Skip to content

wellcast.diagnostics

diagnostics

Diagnostic plots and checks for wells and reservoirs.

  • Chan plot: water-oil ratio and its time derivative on log-log axes, distinguishing water coning from channeling (Chan, 1995).
  • Hall plot: integrated injection pressure against cumulative injection, revealing injectivity changes (Hall, 1963).
  • Havlena-Odeh material balance in straight-line form (Havlena and Odeh, 1963).
  • Anomaly detection combining an Isolation Forest with physical rules.

Units follow the canonical schema: rates in bbl/d (gas Mscf/d), pressures in psi, time in days.

chan_plot_data

chan_plot_data(df: DataFrame, *, by: str | None = 'well', n_bins: int = 40) -> pd.DataFrame

Water-oil ratio and its derivative for a Chan diagnostic plot.

Daily WOR is aggregated into n_bins logarithmically spaced time bins (median per bin) before differentiation. Chan plots are read on log time, and derivatives of raw daily data are dominated by noise.

Parameters:

Name Type Description Default
df DataFrame

Production table with oil_rate and water_rate and a DatetimeIndex.

required
by str or None

Well column. Default "well".

'well'
n_bins int

Number of log-spaced time bins per well. Default 40.

40

Returns:

Type Description
DataFrame

Columns well, t (days since the well's first record, bin median), wor (bin median) and wor_derivative (1/day), one row per non-empty bin with both rates positive. Plot both against t on log-log axes.

Raises:

Type Description
DataValidationError

If columns are missing, the index is not a DatetimeIndex or n_bins < 3.

Notes

\(\mathrm{WOR} = q_w / q_o\) and \(\mathrm{WOR}' = d\,\mathrm{WOR} / dt\). Chan, K. S. (1995), "Water control diagnostic plots", SPE-30775-MS.

Examples:

>>> import numpy as np, pandas as pd
>>> idx = pd.date_range("2024-01-01", periods=101, freq="D")
>>> t = np.arange(101.0)
>>> df = pd.DataFrame({"oil_rate": 100.0, "water_rate": t}, index=idx)
>>> chan = chan_plot_data(df, n_bins=5)
>>> np.allclose(chan["wor_derivative"], 0.01)
True

classify_water_mechanism

classify_water_mechanism(chan: DataFrame, *, slope_threshold: float = 0.3, min_points: int = 10) -> pd.DataFrame

Classify excess water production from Chan plot data.

After breakthrough, the log-log slope of \(\mathrm{WOR}'\) against time separates the mechanisms (Chan, 1995):

  • channeling (high-permeability layer or near-wellbore channel): \(\mathrm{WOR}'\) keeps increasing, slope > slope_threshold;
  • coning (bottom water drawn up to the perforations): \(\mathrm{WOR}'\) decreases after the cone builds, slope < -slope_threshold;
  • otherwise normal displacement.

Parameters:

Name Type Description Default
chan DataFrame

Output of chan_plot_data.

required
slope_threshold float

Minimum absolute log-log slope treated as a trend. Default 0.3.

0.3
min_points int

Minimum points (time bins) with positive derivative needed. Default 10.

10

Returns:

Type Description
DataFrame

Index well; columns mechanism, derivative_slope and n_points. Wells without enough data get "insufficient data".

Notes

This is a screening heuristic. Chan's own guidance is to read the curves together with completion and reservoir information.

Examples:

>>> import numpy as np, pandas as pd
>>> t = np.linspace(10, 1000, 100)
>>> chan = pd.DataFrame(
...     {"well": "A", "t": t, "wor": 1e-4 * t**2, "wor_derivative": 2e-4 * t}
... )
>>> classify_water_mechanism(chan).loc["A", "mechanism"]
'channeling'

hall_plot_data

hall_plot_data(df: DataFrame, *, pressure_column: str = 'bhp', rate_column: str = 'water_inj_rate', reservoir_pressure: float = 0.0) -> pd.DataFrame

Hall plot coordinates for one injection well.

Parameters:

Name Type Description Default
df DataFrame

Injector history with a DatetimeIndex, sorted in time.

required
pressure_column str

Injection pressure, psi. Default "bhp"; "whp" gives the classic wellhead form.

'bhp'
rate_column str

Injection rate, bbl/d. Default "water_inj_rate".

'water_inj_rate'
reservoir_pressure float

Average reservoir pressure subtracted from the injection pressure, psi. Default 0 (the original Hall form).

0.0

Returns:

Type Description
DataFrame

Columns cum_injection (bbl) and hall_integral (psi day), indexed by date.

Raises:

Type Description
DataValidationError

If columns are missing or the index is not a DatetimeIndex.

Notes
\[ \mathrm{Hall} = \int_0^t (p_{wf} - \bar{p}_r)\,dt \quad \text{vs.} \quad W_i = \int_0^t i\,dt \]

The slope equals \(1/I\) (inverse injectivity index) for steady radial flow; an increasing slope indicates plugging or rising skin, a decreasing slope fracturing or stimulation. Hall, H. N. (1963), "How to analyze waterflood injection well performance", World Oil, October, 128-130.

Examples:

>>> import pandas as pd
>>> idx = pd.date_range("2024-01-01", periods=3, freq="D")
>>> df = pd.DataFrame(
...     {"bhp": [5000.0] * 3, "water_inj_rate": [1000.0] * 3}, index=idx
... )
>>> hall_plot_data(df, reservoir_pressure=3000.0)["hall_integral"].tolist()
[2000.0, 4000.0, 6000.0]

hall_slope_change

hall_slope_change(hall: DataFrame, *, min_segment: int = 30) -> pd.Series

Locate the strongest slope change on a Hall plot.

Fits two straight lines meeting at a breakpoint and picks the breakpoint with the smallest total squared error.

Parameters:

Name Type Description Default
hall DataFrame

Output of hall_plot_data.

required
min_segment int

Minimum points on each side of the breakpoint. Default 30.

30

Returns:

Type Description
Series

break_date, slope_before and slope_after (psi day/bbl) and ratio (after / before; above 1 suggests declining injectivity).

Raises:

Type Description
FitError

If there are fewer than 2 * min_segment points.

havlena_odeh

havlena_odeh(pressure: ArrayLike, np_cum: ArrayLike, gp_cum: ArrayLike, wp_cum: ArrayLike, bo: ArrayLike, bg: ArrayLike, rs: ArrayLike, *, boi: float, bgi: float, rsi: float, bw: float = 1.0, winj_cum: ArrayLike = 0.0, gas_cap_ratio: float = 0.0, swi: float = 0.2, cw: float = 3e-06, cf: float = 4e-06) -> pd.DataFrame

Material balance terms in Havlena-Odeh straight-line form.

Parameters:

Name Type Description Default
pressure array_like

Average reservoir pressure at each survey, psia (first value is the initial pressure).

required
np_cum array_like

Cumulative oil (STB), gas (scf) and water (STB) production.

required
gp_cum array_like

Cumulative oil (STB), gas (scf) and water (STB) production.

required
wp_cum array_like

Cumulative oil (STB), gas (scf) and water (STB) production.

required
bo array_like

Oil formation volume factor, rb/STB.

required
bg array_like

Gas formation volume factor, rb/scf.

required
rs array_like

Solution gas-oil ratio, scf/STB.

required
boi float

Initial Bo (rb/STB), Bg (rb/scf) and Rs (scf/STB).

required
bgi float

Initial Bo (rb/STB), Bg (rb/scf) and Rs (scf/STB).

required
rsi float

Initial Bo (rb/STB), Bg (rb/scf) and Rs (scf/STB).

required
bw float

Water formation volume factor, rb/STB. Default 1.0.

1.0
winj_cum array_like

Cumulative water injection, STB. Default 0.

0.0
gas_cap_ratio float

Initial gas cap to oil zone volume ratio m. Default 0.

0.0
swi float

Connate water saturation, fraction. Default 0.2.

0.2
cw float

Water and formation compressibility, 1/psi. Defaults 3e-6, 4e-6.

3e-06
cf float

Water and formation compressibility, 1/psi. Defaults 3e-6, 4e-6.

3e-06

Returns:

Type Description
DataFrame

Columns F (underground withdrawal, rb), Eo, Eg, Efw and Et (expansion terms, rb/STB) and F_over_Et (STB).

Raises:

Type Description
DataValidationError

If array lengths differ.

Notes

With \(R_p = G_p / N_p\):

\[ \begin{aligned} F &= N_p [B_o + (R_p - R_s) B_g] + W_p B_w - W_{inj} B_w \\ E_o &= (B_o - B_{oi}) + (R_{si} - R_s) B_g \\ E_g &= B_{oi} (B_g / B_{gi} - 1) \\ E_{fw} &= (1 + m) B_{oi} \frac{c_w S_{wi} + c_f}{1 - S_{wi}} \Delta p \\ F &= N (E_o + m E_g + E_{fw}) + W_e \end{aligned} \]

Without aquifer influx \(W_e\), \(F\) against \(E_t\) is a straight line through the origin with slope \(N\) (see fit_ooip) and \(F/E_t\) is constant. Since \(F/E_t = N + W_e/E_t\), influx puts the points above \(N\) and makes the ratio vary with time, which signals aquifer support (or a wrong drive mechanism). Havlena, D. and Odeh, A. S. (1963), "The material balance as an equation of a straight line", JPT 15(8), 896-900, SPE-559-PA.

fit_ooip

fit_ooip(mb: DataFrame) -> pd.Series

Original oil in place from a Havlena-Odeh table (no aquifer).

Parameters:

Name Type Description Default
mb DataFrame

Output of havlena_odeh.

required

Returns:

Type Description
Series

ooip (STB, least-squares slope through the origin of F against Et), r2 (uncentered) and n_points.

Raises:

Type Description
FitError

If fewer than two surveys have positive expansion.

detect_anomalies

detect_anomalies(df: DataFrame, *, method: Literal['both', 'rules', 'isolation_forest'] = 'both', columns: Sequence[str] | None = None, by: str | None = 'well', contamination: float = 0.01, flat_run: int = 5, max_gap: int = 1, random_state: int = 0) -> pd.DataFrame

Find anomalous periods with rules and an Isolation Forest.

Rules (physically motivated, always explainable):

  • impossible_<col>: value outside wellcast.clean.IMPOSSIBLE_RANGES;
  • dropout_<col>: pressure exactly zero while the well is on stream;
  • flatline_<col>: at least flat_run identical non-zero pressure readings while flowing (frozen gauge);
  • spike_<col>: Hampel outlier (window 7, 4 sigma) in a rate that is also at least 50 percent above the local median.

The Isolation Forest (Liu, Ting and Zhou, 2008) scores each producing day of each well on standardized signals and their day-to-day changes, and flags the most isolated contamination fraction. It catches multivariate inconsistencies that no single rule covers.

Parameters:

Name Type Description Default
df DataFrame

Production table with a DatetimeIndex, sorted within each well.

required
method ('both', 'rules', 'isolation_forest')

Detectors to run. Default "both"; the forest needs the ml extra.

"both"
columns sequence of str

Signals for the forest. Default: canonical rates and pressures present.

None
by str or None

Well column. Default "well".

'well'
contamination float

Expected anomaly fraction for the forest. Default 0.01.

0.01
flat_run int

Minimum identical readings for a flatline. Default 5.

5
max_gap int

Flagged rows separated by at most this many clean rows are merged into one period. Default 1.

1
random_state int

Seed of the forest. Default 0.

0

Returns:

Type Description
DataFrame

One row per period with well, start, end, n_rows and detector (rule name or "isolation_forest"), sorted by well and start.

Raises:

Type Description
DataValidationError

If the index is not a DatetimeIndex or method is unknown.

MissingDependencyError

If the forest is requested without scikit-learn.

Notes

Slow gauge drift (a few psi per day) is hidden in day-to-day noise and is not reliably found by either detector. Monitor it instead through the residual between the measured value and a virtual flow meter prediction from wellcast.ml.Predictor trained on a trusted period.

Examples:

>>> import pandas as pd
>>> idx = pd.date_range("2024-01-01", periods=6, freq="D")
>>> df = pd.DataFrame({"whp": [300.0, 0.0, 0.0, 305.0, 301.0, 299.0]}, index=idx)
>>> detect_anomalies(df, method="rules")[["start", "end", "detector"]]
       start        end     detector
0 2024-01-02 2024-01-03  dropout_whp