Skip to content

wellcast.ml

ml

Data-driven prediction of well rates and pressures.

A virtual flow meter (VFM) estimates a quantity that is expensive or unreliable to measure, such as bottomhole pressure after a gauge failure or the rate of a well between well tests, from measurements that are always available (wellhead pressure and temperature, choke opening, and so on).

Predictor wraps a scikit-learn sklearn.pipeline.Pipeline (LightGBM by default), validates it with time-ordered or leave-one-well-out splits, reports metrics per well, provides quantile prediction intervals and explains predictions with SHAP.

Requires the ml extra: pip install 'wellcast[ml]'.

Predictor

Predictor(target: str = 'bhp', features: Sequence[str] | None = None, *, estimator: EstimatorName = 'lightgbm', quantiles: tuple[float, float] | None = (0.1, 0.9), exclude_shut_ins: bool = True, by: str = 'well', random_state: int = 0, params: dict[str, Any] | None = None)

Supervised model for a well rate or pressure (virtual flow metering).

Parameters:

Name Type Description Default
target str

Column to predict, for example "bhp" or "oil_rate". Default "bhp".

'bhp'
features sequence of str

Feature columns. By default every numeric column except the target, the well column and the same-row features derived from the target (see wellcast.features.features_using), which would leak it.

None
estimator ('lightgbm', 'hist_gradient_boosting', 'random_forest', 'ridge')

Point model. Default "lightgbm".

"lightgbm"
quantiles tuple of float or None

Lower and upper quantiles of the prediction interval, fitted as separate quantile-loss models. Default (0.1, 0.9), an 80 percent interval. None disables intervals.

(0.1, 0.9)
exclude_shut_ins bool

Drop rows with zero producing hours from training. Default True.

True
by str

Well column. Default "well".

'well'
random_state int

Seed for the estimators. Default 0.

0
params dict

Extra keyword arguments for the point estimator.

None

Attributes:

Name Type Description
features_ list of str

Feature columns used in the fit.

pipeline_ Pipeline

Fitted point model.

quantile_pipelines_ dict of float to Pipeline

Fitted quantile models.

Examples:

>>> from wellcast.datasets import make_synthetic_field
>>> from wellcast.features import build_features
>>> field = make_synthetic_field(n_wells=2, years=2, n_injectors=0)
>>> data = build_features(field.production)
>>> model = Predictor(target="bhp", quantiles=None).fit(data)
>>> "bhp" in model.features_, "bhp_lag1" in model.features_
(False, True)
>>> bool(model.score(data).loc["all", "mape"] < 5.0)
True

fit

fit(df: DataFrame) -> Predictor

Fit the point model and the quantile models.

Parameters:

Name Type Description Default
df DataFrame

Training data containing the target and the features.

required

Returns:

Type Description
Predictor

self.

Raises:

Type Description
FitError

If fewer than 10 usable rows remain.

DataValidationError

If columns are missing.

MissingDependencyError

If the ml extra is not installed.

predict

predict(df: DataFrame) -> pd.Series

Predict the target.

Parameters:

Name Type Description Default
df DataFrame

Rows with the feature columns.

required

Returns:

Type Description
Series

Predictions aligned with df, named <target>_pred.

Raises:

Type Description
FitError

If the predictor is not fitted.

predict_interval

predict_interval(df: DataFrame) -> pd.DataFrame

Predict with a quantile interval.

Parameters:

Name Type Description Default
df DataFrame

Rows with the feature columns.

required

Returns:

Type Description
DataFrame

Columns lower, prediction and upper. The bounds are sorted per row, because independently fitted quantile models can cross.

Raises:

Type Description
FitError

If the predictor is not fitted or was created with quantiles=None.

score

score(df: DataFrame) -> pd.DataFrame

Per-well metrics of the fitted model on df.

Parameters:

Name Type Description Default
df DataFrame

Rows with the target and the features.

required

Returns:

Type Description
DataFrame

See metrics_by_well.

Raises:

Type Description
FitError

If the predictor is not fitted.

cross_validate

cross_validate(df: DataFrame, method: Literal['timeseries', 'lowo'] = 'timeseries', n_splits: int = 5) -> pd.DataFrame

Out-of-sample validation with per-well metrics.

Parameters:

Name Type Description Default
df DataFrame

Data with the target and the features (a DatetimeIndex for "timeseries").

required
method ('timeseries', 'lowo')

"timeseries": expanding-window splits on calendar dates (sklearn.model_selection.TimeSeriesSplit), testing how the model extrapolates in time. "lowo": leave one well out, testing how it transfers to an unseen well. Default "timeseries".

"timeseries"
n_splits int

Number of time splits. Default 5.

5

Returns:

Type Description
DataFrame

Columns fold, well, n, mae, rmse, mape and r2, one row per (fold, well) plus an "all" row per fold.

Raises:

Type Description
DataValidationError

If the method is unknown or the data cannot be split.

shap_values

shap_values(df: DataFrame, *, max_samples: int = 500) -> pd.DataFrame

SHAP contributions of each feature to each prediction.

Parameters:

Name Type Description Default
df DataFrame

Rows to explain; a random subset of max_samples rows is used when larger.

required
max_samples int

Maximum rows to explain. Default 500.

500

Returns:

Type Description
DataFrame

One column per feature, in target units.

Raises:

Type Description
FitError

If the predictor is not fitted.

MissingDependencyError

If shap is not installed.

Notes

Tree models use the exact TreeSHAP algorithm, the ridge model the linear SHAP solution. Lundberg, S. M. and Lee, S.-I. (2017), "A unified approach to interpreting model predictions", NeurIPS.

explain

explain(df: DataFrame, *, max_samples: int = 500, top: int = 15) -> Any

Bar chart of mean absolute SHAP values (global feature importance).

Parameters:

Name Type Description Default
df DataFrame

Rows to explain.

required
max_samples int

Maximum rows to explain. Default 500.

500
top int

Number of features shown. Default 15.

15

Returns:

Type Description
Figure

Horizontal bar chart, most important feature on top.

Raises:

Type Description
MissingDependencyError

If shap or plotly is not installed.

save

save(path: str | PathLike[str]) -> None

Save the predictor with joblib.

Parameters:

Name Type Description Default
path str or path - like

Output file, conventionally *.joblib.

required

Raises:

Type Description
FitError

If the predictor is not fitted.

load classmethod

load(path: str | PathLike[str]) -> Predictor

Load a predictor saved with save.

Joblib files are pickles: load only files from a trusted source, since unpickling can execute arbitrary code.

Parameters:

Name Type Description Default
path str or path - like

File written by save.

required

Returns:

Type Description
Predictor

The restored predictor.

Raises:

Type Description
DataValidationError

If the file does not contain a wellcast predictor.

regression_metrics

regression_metrics(y_true: ArrayLike, y_pred: ArrayLike) -> dict[str, float]

Mean absolute, root-mean-square and percentage errors and R2.

Parameters:

Name Type Description Default
y_true array_like

Observed and predicted values. Pairs with a missing value are ignored.

required
y_pred array_like

Observed and predicted values. Pairs with a missing value are ignored.

required

Returns:

Type Description
dict of str to float

n, mae, rmse, mape (percent) and r2. MAPE ignores observations equal to zero (for example shut-in rates); R2 is NaN for fewer than two points or a constant target.

Notes
\[ \mathrm{MAPE} = \frac{100}{n} \sum \frac{|y_i - \hat y_i|}{|y_i|}, \quad R^2 = 1 - \frac{\sum (y_i - \hat y_i)^2}{\sum (y_i - \bar y)^2} \]

Examples:

>>> m = regression_metrics([100.0, 200.0], [110.0, 190.0])
>>> m["mae"], m["rmse"], m["mape"]
(10.0, 10.0, 7.5)

metrics_by_well

metrics_by_well(y_true: Series, y_pred: Series, wells: Series | None) -> pd.DataFrame

Compute regression_metrics for each well and for all wells.

Parameters:

Name Type Description Default
y_true Series

Observed and predicted values, aligned by position.

required
y_pred Series

Observed and predicted values, aligned by position.

required
wells Series or None

Well names aligned with the values; None treats the data as one well.

required

Returns:

Type Description
DataFrame

One row per well plus a row "all", columns n, mae, rmse, mape and r2.

Examples:

>>> import pandas as pd
>>> t = pd.Series([1.0, 2.0, 3.0, 4.0])
>>> p = t + 1.0
>>> metrics_by_well(t, p, pd.Series(["A", "A", "B", "B"]))["mae"].tolist()
[1.0, 1.0, 1.0]