Skip to content

wellcast.clean

clean

Cleaning and quality control for field production data.

Outlier detectors flag suspicious values and return a boolean Series aligned with the input. They never delete or overwrite data: the decision to drop, replace or keep a flagged value belongs to the engineer.

detect_shut_ins

detect_shut_ins(df: DataFrame, rate_columns: Sequence[str] = ('oil_rate', 'gas_rate', 'water_rate'), *, threshold: float = 0.0, hours_column: str = 'on_stream_hours') -> pd.Series

Flag periods when a well is shut in.

A row is a shut-in when its producing hours are zero, or when every rate column present in df is known and at or below threshold. Missing rates are not treated as zero: a gap in reporting is not a shut-in.

Parameters:

Name Type Description Default
df DataFrame

Production table in the canonical schema.

required
rate_columns sequence of str

Candidate rate columns; those absent from df are ignored.

('oil_rate', 'gas_rate', 'water_rate')
threshold float

Rate at or below which the well counts as not flowing. Default 0.

0.0
hours_column str

Producing-hours column, used when present.

'on_stream_hours'

Returns:

Type Description
Series

Boolean flags aligned with df, named shut_in.

Raises:

Type Description
DataValidationError

If none of rate_columns nor hours_column is present.

Examples:

>>> import pandas as pd
>>> df = pd.DataFrame(
...     {"oil_rate": [120.0, 0.0, None], "water_rate": [10.0, 0.0, 5.0]}
... )
>>> detect_shut_ins(df).tolist()
[False, True, False]

hampel_filter

hampel_filter(series: Series, window: int = 7, n_sigmas: float = 3.0) -> pd.Series

Flag outliers with the Hampel identifier.

Parameters:

Name Type Description Default
series Series

Values in time order.

required
window int

Odd length of the centered window. Default 7.

7
n_sigmas float

Threshold in robust standard deviations. Default 3.

3.0

Returns:

Type Description
Series

Boolean flags aligned with series. NaN values are never flagged.

Raises:

Type Description
DataValidationError

If window is not an odd integer >= 3 or n_sigmas <= 0.

Notes

A value \(x_i\) is flagged when

\[ |x_i - m_i| > t \cdot 1.4826 \, \mathrm{MAD}_i \]

where \(m_i\) and \(\mathrm{MAD}_i\) are the median and median absolute deviation of the centered window. Missing values inside the window are ignored. See Pearson, R. K. (2002), "Outliers in process modeling and identification", IEEE Trans. Control Syst. Technol. 10(1).

Examples:

>>> import pandas as pd
>>> s = pd.Series([10.0, 10.2, 9.9, 10.1, 55.0, 10.0, 9.8, 10.1])
>>> hampel_filter(s, window=5).tolist()
[False, False, False, False, True, False, False, False]

rolling_zscore_outliers

rolling_zscore_outliers(series: Series, window: int = 30, threshold: float = 3.0, min_periods: int | None = None) -> pd.Series

Flag values far from a centered rolling mean.

Parameters:

Name Type Description Default
series Series

Values in time order.

required
window int

Rolling window length in samples. Default 30.

30
threshold float

Absolute z-score above which a value is flagged. Default 3.

3.0
min_periods int

Minimum observations in the window. Default window // 2.

None

Returns:

Type Description
Series

Boolean flags aligned with series.

Notes

\(z_i = (x_i - \bar{x}_i) / s_i\) with the rolling mean \(\bar{x}_i\) and standard deviation \(s_i\). Windows with zero spread produce no flags.

Examples:

>>> import numpy as np, pandas as pd
>>> s = pd.Series(np.r_[np.tile([10.0, 11.0], 20), 40.0, np.tile([10.0, 11.0], 20)])
>>> int(rolling_zscore_outliers(s, window=21).sum())
1

iqr_outliers

iqr_outliers(series: Series, k: float = 1.5) -> pd.Series

Flag values outside Tukey's fences.

Parameters:

Name Type Description Default
series Series

Values to test.

required
k float

Fence multiplier. Default 1.5 (3.0 for "far out" values).

1.5

Returns:

Type Description
Series

Boolean flags aligned with series.

Notes

Values below \(Q_1 - k\,\mathrm{IQR}\) or above \(Q_3 + k\,\mathrm{IQR}\) are flagged (Tukey, 1977, Exploratory Data Analysis).

Examples:

>>> import pandas as pd
>>> iqr_outliers(pd.Series([1.0, 2.0, 2.5, 3.0, 50.0])).tolist()
[False, False, False, False, True]

flag_outliers

flag_outliers(df: DataFrame, column: str, method: Literal['hampel', 'zscore', 'iqr'] = 'hampel', *, by: str | None = 'well', **kwargs: Any) -> pd.Series

Apply an outlier detector to one column, separately for each well.

Parameters:

Name Type Description Default
df DataFrame

Production table, sorted by date within each well.

required
column str

Column to test.

required
method ('hampel', 'zscore', 'iqr')

Detector to use. Default "hampel".

"hampel"
by str or None

Grouping column. Default "well"; ignored when absent.

'well'
**kwargs Any

Passed to the detector.

{}

Returns:

Type Description
Series

Boolean flags aligned with df.

Raises:

Type Description
DataValidationError

If column is missing or method is unknown.

Examples:

>>> import pandas as pd
>>> df = pd.DataFrame({"well": ["A"] * 5, "oil_rate": [1.0, 2.0, 2.5, 3.0, 50.0]})
>>> flag_outliers(df, "oil_rate", "iqr").tolist()
[False, False, False, False, True]

resample_regular

resample_regular(df: DataFrame, freq: str = 'D', agg: Literal['mean', 'median', 'sum', 'first', 'last', 'min', 'max'] = 'mean', *, by: str | None = 'well') -> pd.DataFrame

Resample each well onto a regular time grid.

Missing periods become NaN rows so gaps stay visible. Non-numeric columns other than by are dropped.

Parameters:

Name Type Description Default
df DataFrame

Table with a DatetimeIndex.

required
freq str

Pandas offset alias. Default "D" (daily).

'D'
agg str

Aggregation within each period. Default "mean". Use "sum" for volumes, "mean" for rates and pressures.

'mean'
by str or None

Grouping column. Default "well"; ignored when absent.

'well'

Returns:

Type Description
DataFrame

Regularly sampled data, wells stacked in order.

Raises:

Type Description
DataValidationError

If the index is not a DatetimeIndex.

Examples:

>>> import pandas as pd
>>> idx = pd.to_datetime(["2024-01-01", "2024-01-03"])
>>> df = pd.DataFrame({"well": ["A", "A"], "oil_rate": [100.0, 90.0]}, index=idx)
>>> resample_regular(df)["oil_rate"].tolist()
[100.0, nan, 90.0]

fill_gaps

fill_gaps(df: DataFrame, columns: Sequence[str] | None = None, method: Literal['linear', 'ffill', 'bfill'] = 'linear', limit: int = 3, *, by: str | None = 'well') -> pd.DataFrame

Fill short gaps within each well, leaving longer gaps untouched.

Parameters:

Name Type Description Default
df DataFrame

Regularly sampled table with a DatetimeIndex (see resample_regular).

required
columns sequence of str

Columns to fill. Default: all numeric columns.

None
method ('linear', 'ffill', 'bfill')

"linear" interpolates in time between valid neighbours (never extrapolates); "ffill" and "bfill" propagate the last or next valid value. Default "linear".

"linear"
limit int

Maximum number of consecutive missing values to fill. Default 3.

3
by str or None

Grouping column. Default "well".

'well'

Returns:

Type Description
DataFrame

Copy of df with gaps filled.

Raises:

Type Description
DataValidationError

If limit < 1, method is unknown, or the index is not a DatetimeIndex.

Examples:

>>> import numpy as np, pandas as pd
>>> idx = pd.date_range("2024-01-01", periods=5, freq="D")
>>> df = pd.DataFrame({"bhp": [3000.0, np.nan, 2980.0, np.nan, np.nan]}, index=idx)
>>> fill_gaps(df, limit=1)["bhp"].tolist()
[3000.0, 2990.0, 2980.0, nan, nan]

qc_report

qc_report(df: DataFrame, *, by: str | None = 'well', flatline_min_run: int = 5, max_hours: float = 24.0) -> pd.DataFrame

Summarize data quality per well and column.

Parameters:

Name Type Description Default
df DataFrame

Production table in the canonical schema.

required
by str or None

Grouping column. Default "well"; ignored when absent.

'well'
flatline_min_run int

Minimum run of identical non-zero readings counted as a flatline. Default 5.

5
max_hours float

Upper bound for on_stream_hours (24 for daily data). Default 24.

24.0

Returns:

Type Description
DataFrame

Tidy table with one row per (well, column) and the columns well, column, n, missing, missing_pct, negative, flatline and impossible. flatline is NaN for setpoint columns (choke, on_stream_hours), which are constant by design. impossible counts values outside IMPOSSIBLE_RANGES (for example a negative pressure or a water cut outside [0, 1]); it is NaN for columns without a rule.

Examples:

>>> import pandas as pd
>>> df = pd.DataFrame({"well": ["A"] * 4, "bhp": [3000.0, -5.0, None, 2990.0]})
>>> qc_report(df)[["column", "missing", "negative", "impossible"]]
  column  missing  negative  impossible
0    bhp        1         1         1.0