import os
project_dir = os.getcwd()
import random
import numpy as np
# Seed for pseudo-random number generator to control every stochastic model and search.
RANDOM_SEED = 42
random.seed(RANDOM_SEED)
np.random.seed(RANDOM_SEED)
RAW_OPERATIONAL_FEATURES = ['ON_STREAM_HRS', 'AVG_DOWNHOLE_PRESSURE', 'AVG_DOWNHOLE_TEMPERATURE', 'AVG_DP_TUBING', 'AVG_CHOKE_SIZE_P', 'AVG_WHP_P', 'AVG_WHT_P', 'DP_CHOKE_SIZE', 'BORE_GAS_VOL', 'BORE_WAT_VOL', 'BORE_WI_VOL_F4', 'BORE_WI_VOL_F5', 'BORE_WI_VOL_F4_MISSING', 'BORE_WI_VOL_F5_MISSING']Volve Field Production Forecasting using Machine Learning
1. Project Summary
This project develops a time-series forecasting pipeline to estimate daily oil production (BORE_OIL_VOL) for five producing wellbores in the Volve field dataset. Historical operational measurements, past oil production, and the water-injection histories provide the feature information. Cross-validation and scaling within a scikit-learn Pipeline is used to develop the final Random Forest model which is evaluated on production test (holdout) set.
Machine Learning Task
The ML task is to predict future daily oil production volumes based on historical and current well operational parameters. The historical data up to the current day is used to predict the daily oil production for the next day. No data from the next day is used as input.
The final matrix contains 7,798 active-production records and 66 features. Training combines 6,237 records across the five wells; the holdout combines 1,561 records, representing the final 20% of each well’s history. Holdout dates extend from January 12, 2015 to September 17, 2016, with different date ranges for individual wells.
The shared random seed across this project is 42. It controls Python and NumPy seeding, the stochastic estimators, and randomized hyperparameter selection.
Final Model Performance Summary
The model selected and tuned for the forecasting task is a Random Forest model.
| Metric / Parameter | Value | Description / Operational Context |
|---|---|---|
| CV R² Score | 0.7817 | Mean pooled validation R² across five expanding-window folds. |
| Test Set R² Score | 0.8938 | Performance on the pooled per-well 20% holdout. |
| Test Set RMSE | 66.81 Sm³/day | Root Mean Squared Error for daily oil production. |
| Test Set MAE | 41.52 Sm³/day | Mean Absolute Error for daily oil production. |
| Optimal Hyperparameters | max_depth: 20min_samples_leaf: 2min_samples_split: 5n_estimators: 100 |
Random Forest configuration selected by randomized-search cross-validation. |
Forecasted vs Actual oil volume for Well 15/9-F-12 using the tuned Random Forest:

See the section Phase 4: Time-Series Cross-Validation & Hyperparameter Tuning for more details.
2. Data Overview
This dataset captures the daily physical operations of the Volve offshore oil field in the North Sea. It tracks the flow of fluids (oil, gas, and water) from the reservoir through the wellbores and into the surface processing facilities (the Mærsk Inspirer platform).
Official landing page of the Equinor dataset for the Volve field: https://www.equinor.com/energy/volve-data-sharing
Official Volve field description: https://www.norskpetroleum.no/en/facts/field/volve/
Data source (a compact extract from the 40,000-file full release): https://github.com/yohanesnuwara/MLGeo/blob/main/Volve production data.xlsx
Further Context: Waterflooding
The data characterizes the secondary oil recovery process of waterflooding. As an oil reservoir depletes, its natural pressure drops. To keep the oil flowing, operators inject water into the reservoir through dedicated injection wells (which are visible in the data).
This injected water maintains the underground pressure and physically “sweeps” the remaining oil toward the active producing wells. The sensor data (downhole pressures, wellhead temperatures, and choke valve sizes) represents the constant balancing act engineers performed to optimize this extraction as the field ages and the proportion of water (water cut) inevitably increases.
Highlights
- The Daily Production Data worksheet contains 15,634 records and 24 columns, spanning September 2007 to December 2016. The monthly worksheet is not used for ML.
- The raw data includes oil, gas, produced-water and water-injection volumes, on-stream hours, choke settings, wellhead measurements, and downhole measurements.
- There are seven wellbores: five are strictly producing (15/9-F-1 C, 15/9-F-11, 15/9-F-12, 15/9-F-14, and 15/9-F-15 D), without any recorded water injection, and one alternated from injecting to producing (15/9-F-5, or F-5 for short) but never did both simultanously, and one was strictly injecting (15/9-F-4, or F-4 for short).
- The five strictly producing wells were used for ML. F-5’s production records are excluded from ML.
- Both F-5 and F-4’s injection records were used as input features for ML.
Units
The volume channels are in standard cubic metres (Sm³). Daily production values are expressed here as Sm³/day. No unit conversion is performed.
| Quantity | Unit |
|---|---|
| Oil, gas, produced-water and injected-water volume | Sm³ per daily record |
| Daily oil production, RMSE and MAE | Sm³/day |
| On-stream duration | hours |
| Pressure and differential pressure | bar |
| Temperature | °C |
AVG_CHOKE_SIZE_P |
percent open (%) |
3. Exploratory Data Analysis
Pairwise Scatter Plot Analysis
To examine relationships between the production data variables, a pairwise analysis matrix was generated. We highlight key insights below.
Selected Variables
- Activity runtime:
ON_STREAM_HRS - Downhole measurements:
AVG_DOWNHOLE_PRESSURE,AVG_DOWNHOLE_TEMPERATURE,AVG_DP_TUBING - Wellhead and choke measurements:
AVG_WHP_P,AVG_WHT_P,AVG_CHOKE_SIZE_P - Production volumes:
BORE_OIL_VOL,BORE_GAS_VOL,BORE_WAT_VOL
Activities & Implementation Steps
- Converted the selected variables to numeric values and retained rows satisfying
ON_STREAM_HRS > 0andBORE_OIL_VOL > 0. - Created one
seabornpairplot with 55 populated panels: ten diagonal density plots and 45 unique pairwise scatter plots in the lower triangle. - This raw-data EDA includes F-5’s producing records; F-5 is subsequently excluded from the ML target data.
Analytical Purpose & Explanations
- Nonlinear Trend Identification: The plots reveal nonlinear relationships, threshold behaviour, and operational regimes that simple linear correlation metrics may not capture.
- Cluster & Regime Detection: The active-production subset highlights differences among producing conditions and well histories.
- Outlier & Anomaly Verification: The matrix supports visual inspection of unusual readings, and physical outliers prior to ML preparation.
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
# 1. Load dataset
file_path = os.path.join(project_dir, r"Volve production data.xlsx")
df = pd.read_excel(file_path, sheet_name="Daily Production Data")
key_features = [
"ON_STREAM_HRS",
"AVG_DOWNHOLE_PRESSURE",
"AVG_DOWNHOLE_TEMPERATURE",
"AVG_DP_TUBING",
"AVG_WHP_P",
"AVG_WHT_P",
"AVG_CHOKE_SIZE_P",
"BORE_OIL_VOL",
"BORE_GAS_VOL",
"BORE_WAT_VOL",
]
# 2. Filter dataset to available key features and active production days
present_features = [c for c in key_features if c in df.columns]
# Ensure values are numeric and drop non-producing rows
df_active = df.copy()
for col in present_features:
df_active[col] = pd.to_numeric(df_active[col], errors="coerce")
df_active = df_active[
(df_active["ON_STREAM_HRS"] > 0) & (df_active["BORE_OIL_VOL"] > 0)
]
# 3. Create the Pairplot strictly for these features
g = sns.pairplot(
df_active,
vars=present_features,
hue="NPD_WELL_BORE_NAME"
if "NPD_WELL_BORE_NAME" in df_active.columns
else None,
diag_kind="kde", # Clean density curve on diagonal
corner=True, # Drops upper triangle to prevent clutter/overcrowding
height=1.8, # Compact facet size for fast inline display
plot_kws={"alpha": 0.3, "s": 8}, # Transparent small points
)
# 4. Format titles and layout
g.fig.suptitle(
"Pairwise Scatter Plot: Volve Key Operational Features",
y=1.02,
fontsize=14,
fontweight="bold",
)
plt.tight_layout()
plt.show()
Correlation Matrix Analysis
Activities & Implementation Steps
- Loaded the raw daily worksheet and selected nine variables:
ON_STREAM_HRS,AVG_DOWNHOLE_PRESSURE,AVG_DP_TUBING,AVG_WHP_P,AVG_WHT_P,AVG_CHOKE_SIZE_P,BORE_OIL_VOL,BORE_GAS_VOL, andBORE_WAT_VOL. - Converted these columns to numeric values and computed their pairwise Pearson correlations using the available readings.
- Rendered a Seaborn heatmap with a divergent colour map, two-decimal annotations, and a scale from -1.00 to +1.00.
- Exported the figure as
Volve_Correlation_Matrix.pngat 300 DPI.
Analytical Purpose & Explanations
- Multicollinearity Assessment: The matrix characterizes linear associations among operational measurements and production volumes, including the oil and gas channels.
- Key Driver Identification: Relationships between operating hours, pressure, temperature, choke setting, and oil production provide context for the subsequent feature-engineering workflow.
import os
import seaborn as sns
# 1. Load dataset
file_path = os.path.join(project_dir, r"Volve production data.xlsx")
df = pd.read_excel(file_path, sheet_name="Daily Production Data")
if file_path.endswith(".xlsx") or file_path.endswith(".xls"):
df = pd.read_excel(file_path, sheet_name="Daily Production Data")
else:
df = pd.read_csv(file_path)
df.columns = df.columns.str.strip()
# 2. DEFINE RANGE / SUBSET OF KEY VARIABLES
key_variables = [
"ON_STREAM_HRS",
"AVG_DOWNHOLE_PRESSURE",
"AVG_DP_TUBING",
"AVG_WHP_P",
"AVG_WHT_P",
"AVG_CHOKE_SIZE_P",
"BORE_OIL_VOL",
"BORE_GAS_VOL",
"BORE_WAT_VOL",
]
# Ensure selected columns exist in dataframe and convert to numeric
selected_cols = [c for c in key_variables if c in df.columns]
df_subset = df[selected_cols].apply(pd.to_numeric, errors="coerce")
# 3. Calculate Correlation Matrix
corr_matrix = df_subset.corr(method="pearson") # 'pearson' or 'spearman'
# 4. Plot Heatmap
plt.figure(figsize=(10, 8))
sns.heatmap(
corr_matrix,
annot=True, # Display correlation numbers inside cells
fmt=".2f", # Format numbers to 2 decimal places
cmap="coolwarm", # Red = strong positive, Blue = strong negative
vmax=1,
vmin=-1,
linewidths=0.8,
cbar_kws={"label": "Correlation Coefficient"},
)
plt.title(
"Volve Production - Correlation Matrix (Key Variables)",
fontsize=13,
fontweight="bold",
pad=12,
)
plt.xticks(rotation=45, ha="right", fontsize=9)
plt.yticks(fontsize=9)
plt.tight_layout()
# Save output image
output_file = "Volve_Correlation_Matrix.png"
plt.savefig(output_file, dpi=300)
plt.show()
print(f"Correlation heatmap saved as '{output_file}'.")
Correlation heatmap saved as 'Volve_Correlation_Matrix.png'.
Time-Series Workflow & Temporal Structuring
Activities & Implementation Steps
- Datetime Parsing: Converted
DATEPRDto datetime values and sorted the raw daily records into a chronological timeline for the EDA. - Operational History Plotting: Produced seven stacked plots for oil volume, on-stream hours, downhole pressure, downhole temperature, tubing differential pressure, wellhead pressure, and wellhead temperature. The plots share a date axis and use the raw records from the wells together.
- Downstream Per-Well Ordering: Phases 1 and 2 subsequently order histories by wellbore and date. Forward filling is performed within each well before selecting active-production records for historical feature construction.
Analytical Purpose & Explanations
- Temporal Sequence Integrity: The per-well ordering maintains each well’s sequence during lag calculation, rolling-window construction, and expanding-window validation.
- Decline Curve & Lifecycle Mapping: The raw time-series plots provide an overview of production and operational changes over the field’s recorded history, including shut-in and restart periods.
import matplotlib.pyplot as plt
import pandas as pd
# 1. Load dataset
file_path = os.path.join(project_dir, r"Volve production data.xlsx")
df = pd.read_excel(file_path, sheet_name="Daily Production Data")
key_vars = [
"BORE_OIL_VOL",
"ON_STREAM_HRS",
"AVG_DOWNHOLE_PRESSURE",
"AVG_DOWNHOLE_TEMPERATURE",
"AVG_DP_TUBING",
"AVG_WHP_P",
"AVG_WHT_P",
]
# Filter variables to those actually present in the dataframe
selected_vars = [col for col in key_vars if col in df.columns]
# Ensure date column is formatted and dataframe is sorted
time_col = "DATEPRD" if "DATEPRD" in df.columns else df.columns[0]
df[time_col] = pd.to_datetime(df[time_col])
df = df.sort_values(time_col)
# 2. Plot directly in the notebook
fig, axes = plt.subplots(
nrows=len(selected_vars),
ncols=1,
figsize=(12, 2.5 * len(selected_vars)),
sharex=True,
)
# Handle single column edge case
if len(selected_vars) == 1:
axes = [axes]
for ax, col in zip(axes, selected_vars):
ax.plot(df[time_col], df[col], color="#1f77b4", linewidth=1.2)
ax.set_ylabel(col, fontsize=9, fontweight="bold")
ax.grid(True, linestyle="--", alpha=0.5)
ax.tick_params(labelsize=9)
axes[-1].set_xlabel("Date", fontsize=10, fontweight="bold")
fig.suptitle(
"Volve Production - Key Operational Variables Time Series",
fontsize=14,
fontweight="bold",
y=1.01,
)
plt.tight_layout()
plt.show()
# Small preview of the data
df.head()| DATEPRD | WELL_BORE_CODE | NPD_WELL_BORE_CODE | NPD_WELL_BORE_NAME | NPD_FIELD_CODE | NPD_FIELD_NAME | NPD_FACILITY_CODE | NPD_FACILITY_NAME | ON_STREAM_HRS | AVG_DOWNHOLE_PRESSURE | ... | AVG_CHOKE_UOM | AVG_WHP_P | AVG_WHT_P | DP_CHOKE_SIZE | BORE_OIL_VOL | BORE_GAS_VOL | BORE_WAT_VOL | BORE_WI_VOL | FLOW_KIND | WELL_TYPE | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 12328 | 2007-09-01 | NO 15/9-F-5 AH | 5769 | 15/9-F-5 | 3420717 | VOLVE | 369304 | MÆRSK INSPIRER | NaN | NaN | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | injection | WI |
| 9001 | 2007-09-01 | NO 15/9-F-4 AH | 5693 | 15/9-F-4 | 3420717 | VOLVE | 369304 | MÆRSK INSPIRER | NaN | NaN | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | injection | WI |
| 12329 | 2007-09-02 | NO 15/9-F-5 AH | 5769 | 15/9-F-5 | 3420717 | VOLVE | 369304 | MÆRSK INSPIRER | NaN | NaN | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | injection | WI |
| 9002 | 2007-09-02 | NO 15/9-F-4 AH | 5693 | 15/9-F-4 | 3420717 | VOLVE | 369304 | MÆRSK INSPIRER | NaN | NaN | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | injection | WI |
| 9003 | 2007-09-03 | NO 15/9-F-4 AH | 5693 | 15/9-F-4 | 3420717 | VOLVE | 369304 | MÆRSK INSPIRER | NaN | NaN | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | injection | WI |
5 rows × 24 columns
Imputation of Missing Values: Linear Interpolation vs Forward Fill
The figure generated by the code below compares imputation methods for seven of the nine longest missing-data periods of F-4 in BORE_WI_VOL. The two boundary gaps (235 days at the beginning and 73 days at the end) are omitted. The displayed internal gaps last 18, 12, 10, 4, 4, 4, and 3 days, retaining their reference numbering as gaps 3 to 9.
Blue markers show observed injection volumes, pink shading identifies missing periods, grey dashed lines show linear interpolation, and orange horizontal lines show forward filling. Injection volumes are expressed in Sm³.
Linear interpolation connects the observations on both sides of a gap. When injection changes gradually, that connection can provide a smoother and potentially closer approximation to the missing readings. However, it requires the observation after the gap, so that later endpoint would not yet be available when making a forecast during the missing period. Hence linear interpolation is not a realistic imputation scheme, even though it provides potentially better approximation.
Forward filling fills the gap with the most recent observed value. This respects the information-availability conditions of forecasting because it uses only an earlier reading. The cost is that an old injection value can persist while the actual injection rate changes. For example, after a recorded zero, forward filling remains at zero through the missing period, whereas linear interpolation can represent a gradual increase toward the later observation.
Forward filling therefore uses the more realistic information-availability assumption for this project, at the cost of representing less of a possible gradual change within a gap. The comparison in the figure generated by the code below illustrates the different assumptions; the missing values themselves are not observed. Linear interpolation is used only for this diagnostic figure, while the ML preprocessing uses forward filling.
Although the rationale for forward filling is explained here using only BORE_WI_VOL, it’s applied to missing values of all features. Backward filling is never used.
import matplotlib.dates as mdates
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
def plot_injection_gap_comparison(raw_data, well='15/9-F-4', context_days=7):
"""Compare linear interpolation and forward filling over internal gaps."""
series = (raw_data.loc[raw_data['NPD_WELL_BORE_NAME'].eq(well),
['DATEPRD', 'BORE_WI_VOL']]
.assign(DATEPRD=lambda d: pd.to_datetime(d['DATEPRD']))
.set_index('DATEPRD')['BORE_WI_VOL'].sort_index().asfreq('D'))
missing = series.isna()
runs = missing.ne(missing.shift()).cumsum()
gaps = pd.DataFrame([
{'start': values.index.min(), 'end': values.index.max(), 'days': len(values)}
for _, values in series[missing].groupby(runs[missing])
])
# Match the reference's nine gaps; omit its two boundary gaps.
gaps = gaps.sort_values(['days', 'start'], ascending=[False, True]).head(9)
gaps = gaps.loc[(gaps['start'] > series.first_valid_index())
& (gaps['end'] < series.last_valid_index())].copy()
reference_order = pd.to_datetime([
'2009-03-10', '2010-08-17', '2011-06-21', '2011-07-31',
'2009-09-01', '2009-09-27', '2008-09-16',
])
gaps['panel_order'] = gaps['start'].map({date: i for i, date in enumerate(reference_order)})
gaps = gaps.sort_values('panel_order').reset_index(drop=True)
linear = series.interpolate(method='time', limit_area='inside')
forward = series.ffill()
fig, axes = plt.subplots(3, 3, figsize=(17, 12))
for panel, (ax, gap) in enumerate(zip(axes.flat, gaps.itertuples()), start=3):
left, right = gap.start - pd.Timedelta(days=1), gap.end + pd.Timedelta(days=1)
window = series.loc[left - pd.Timedelta(days=context_days):
right + pd.Timedelta(days=context_days)]
ax.axvspan(gap.start - pd.Timedelta(hours=12),
gap.end + pd.Timedelta(hours=12), color='#fca5a5', alpha=0.30)
ax.plot(window.index, window, 'o-', color='#147db3', markersize=4, linewidth=1.5)
# Linear uses the later endpoint; forward filling holds the last known value.
ax.plot(linear.loc[left:right].index, linear.loc[left:right],
'--', color='#777777', linewidth=1.8, zorder=3)
# Hold the last value without drawing a jump to the next observation.
ax.plot([left, right], [forward.loc[left]] * 2,
color='#e07800', linewidth=2.1, zorder=4)
ax.set_title(f'Gap {panel}: {gap.days} days ({gap.start:%Y-%m-%d})', fontsize=11)
ax.set_ylabel('Sm³')
ax.xaxis.set_major_locator(mdates.AutoDateLocator(minticks=4, maxticks=6))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.tick_params(axis='x', labelrotation=45, labelsize=9)
ax.grid(True, linestyle=':', alpha=0.6)
for ax in list(axes.flat)[len(gaps):]:
ax.set_visible(False)
legend = [
Line2D([], [], color='#147db3', marker='o', label='Observed injection'),
Line2D([], [], color='#777777', linestyle='--', label='Linear interpolation'),
Line2D([], [], color='#e07800', linewidth=2, label='Forward fill'),
Patch(facecolor='#fca5a5', alpha=0.30, label='Missing period'),
]
fig.suptitle(f'{well}: Injection Data: Linear Interpolation vs Forward Fill', fontsize=16, y=0.995)
fig.legend(handles=legend, loc='upper center', bbox_to_anchor=(0.5, 0.975), ncol=4, frameon=False)
fig.tight_layout(rect=(0, 0, 1, 0.94), h_pad=2.2)
return fig, gaps
# Diagnostic comparison only; interpolated values never enter the ML pipeline.
raw_injection_data = pd.read_excel(
os.path.join(project_dir, 'Volve production data.xlsx'), sheet_name='Daily Production Data'
)
gap_comparison_fig, gap_comparison_periods = plot_injection_gap_comparison(raw_injection_data)
gap_comparison_fig.savefig('Volve_F4_Imputation_Comparison.png', dpi=300, bbox_inches='tight')
plt.show()
4. Phase 1: Data Ingestion, Cleaning & Well-History Preparation
Overview & Technical Rationale
Phase 1 standardizes the daily production records, trims missing-data boundaries, prepares injection inputs, and retains daily histories for the five production wells.
Detailed Step Breakdown
1. Raw Data Ingestion and Formatting
- Loaded 15,634 records across 24 columns from the Daily Production Data worksheet.
- Parsed
DATEPRD, sorted records byNPD_WELL_BORE_NAMEand date, and converted the operational and volume fields to numeric values. - Standardized the actual choke column,
AVG_CHOKE_SIZE_P, including removal of percent signs where present.
2. Missing Boundary Trimming
For each well’s relevant candidate features, the code retains the common observed date coverage and drops leading or trailing rows outside it.
| History | Boundary rows removed | Retained source-history dates |
|---|---|---|
| F-4 injection | 255 | April 23, 2008 to September 19, 2016 |
| F-5 injection | 196 | March 15, 2008 to September 18, 2016 |
| F-14 production-well measurements | 47 | March 30, 2008 to September 17, 2016 |
| Other four production-well measurement histories | 0 | Their individual observed coverage is retained. |
3. Date-Aligned Injection Inputs
- Built complete daily injection timelines for F-4 and F-5 within their retained coverage.
- Forward filled 82 internal daily gaps for F-4 and 249 for F-5. Missing F-5 injection entries on 145 records explicitly marked as production were assigned zero injection.
- Created new columns/features
BORE_WI_VOL_F4(BORE_WI_VOL of F-4) andBORE_WI_VOL_F5(BORE_WI_VOL of F-5), plus a_MISSINGflag for each channel identifying originally missing readings. - Production records are aligned to both the F-4 and F-5 injection data by date. Only dates within both retained coverage are kept, avoiding an assumption of zero injection outside that coverage.
4. Five-Well Daily Histories
- Excluded F-5’s oil-production records from the ML target data while retaining its injection history as an input.
- Reindexed each of the five production-well histories to daily dates before injection alignment. Daily history includes producing and non-producing records at this stage.
- Removed 95 daily producer-history rows outside the retained injection coverage.
- Exported 9,034 daily history rows across 17 columns to
volve_phase1_cleaned.csv.
| Wellbore | Phase 1 daily history rows |
|---|---|
| 15/9-F-12 | 3,070 |
| 15/9-F-14 | 3,070 |
| 15/9-F-11 | 1,168 |
| 15/9-F-15 D | 980 |
| 15/9-F-1 C | 746 |
| Total | 9,034 |
Retained Columns
The 17 columns comprise two identifiers, the oil target, and 14 operational or injection columns.
| Category | Retained Parameters |
|---|---|
| Identifiers & Time | NPD_WELL_BORE_NAME, DATEPRD |
| Runtime & Production | ON_STREAM_HRS, BORE_OIL_VOL, BORE_GAS_VOL, BORE_WAT_VOL |
| Downhole Measurements | AVG_DOWNHOLE_PRESSURE, AVG_DOWNHOLE_TEMPERATURE, AVG_DP_TUBING |
| Wellhead & Choke Measurements | AVG_WHP_P, AVG_WHT_P, AVG_CHOKE_SIZE_P, DP_CHOKE_SIZE |
| Injection Inputs | BORE_WI_VOL_F4, BORE_WI_VOL_F5, and their two _MISSING flags |
import pandas as pd
import numpy as np
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)
print("=" * 70)
print("PHASE 1: DATA LOADING, CLEANING & WELL FILTERING")
print("=" * 70)
# 1. LOAD DATA
file_path = os.path.join(project_dir, r"Volve production data.xlsx")
print("\nLoading Excel File...")
df = pd.read_excel(file_path, sheet_name="Daily Production Data")
print(f"-> Raw File Loaded: {len(df)} rows across {df.shape[1]} columns.")
# 2. DATE PARSING & CHRONOLOGICAL SORTING PER WELL
print("\n" + "-" * 70)
print("Processing Dates and Well Names...")
if 'DATEPRD' in df.columns:
df['DATEPRD'] = pd.to_datetime(df['DATEPRD'])
if 'NPD_WELL_BORE_NAME' in df.columns:
df = df.sort_values(['NPD_WELL_BORE_NAME', 'DATEPRD']).reset_index(drop=True)
print(f"-> Detected Wells in File: {df['NPD_WELL_BORE_NAME'].unique().tolist()}")
else:
df = df.sort_values('DATEPRD').reset_index(drop=True)
# 3. FORMAT NUMERICAL VALUES
print("\n" + "-" * 70)
print("Cleaning Column Formatting...")
df.columns = df.columns.str.strip()
numeric_cols = [
'ON_STREAM_HRS', 'BORE_OIL_VOL', 'BORE_GAS_VOL', 'BORE_WAT_VOL',
'BORE_WI_VOL', 'AVG_DOWNHOLE_PRESSURE', 'AVG_DOWNHOLE_TEMPERATURE',
'AVG_DP_TUBING', 'AVG_CHOKE_SIZE_P', 'AVG_WHP_P', 'AVG_WHT_P',
'DP_CHOKE_SIZE',
]
for col in numeric_cols:
df[col] = pd.to_numeric(
df[col].astype(str).str.strip().str.rstrip('%'), errors='coerce'
)
# Trim every leading/trailing missing block in the relevant candidate features.
# No boundary records are invented.
def trim_missing_edges(records, columns, label):
records = records.sort_values('DATEPRD').copy()
first_dates, last_dates = [], []
for column in columns:
known = records.loc[records[column].notna(), 'DATEPRD']
if known.empty:
raise ValueError(f'{label}: no observations for required feature {column}')
first_dates.append(known.min())
last_dates.append(known.max())
start, end = max(first_dates), min(last_dates)
if start > end:
raise ValueError(f'{label}: candidate features have no overlapping observed period')
kept = records.loc[records['DATEPRD'].between(start, end)].copy()
print(f'-> {label}: dropped {len(records) - len(kept)} edge rows; '
f'retained {start.date()} to {end.date()}.')
return kept
# Build injection histories before excluding injector/production-mode records.
# Keep each injector only within its observed injection-volume date range.
injection_histories = []
for injector, suffix in [('15/9-F-4', 'F4'), ('15/9-F-5', 'F5')]:
records = df.loc[df['NPD_WELL_BORE_NAME'].eq(injector),
['DATEPRD', 'BORE_WI_VOL', 'FLOW_KIND']].copy()
if records['DATEPRD'].duplicated().any():
raise ValueError(f'Duplicate injection dates for {injector}')
records = trim_missing_edges(records, ['BORE_WI_VOL'], injector)
records = records.set_index('DATEPRD').sort_index()
records = records.reindex(pd.date_range(records.index.min(), records.index.max(), freq='D'))
feature = f'BORE_WI_VOL_{suffix}'
missing = records['BORE_WI_VOL'].isna()
# Production-mode records represent no water injection into this well.
# This is an operational zero, not a blanket assumption about missing data.
production_zero = missing & records['FLOW_KIND'].eq('production')
records.loc[production_zero, 'BORE_WI_VOL'] = 0.0
interior_missing = records['BORE_WI_VOL'].isna().sum()
records['BORE_WI_VOL'] = records['BORE_WI_VOL'].ffill()
if records['BORE_WI_VOL'].isna().any():
raise ValueError(f'Unresolved injection values for {injector}')
history = records[['BORE_WI_VOL']].rename(columns={'BORE_WI_VOL': feature})
history[f'{feature}_MISSING'] = missing.astype(int)
history.index.name = 'DATEPRD'
injection_histories.append(history.reset_index())
print(f'-> {injector}: forward filled {interior_missing} internal daily gaps; '
f'{production_zero.sum()} production-mode injection zeros.')
# The intersection excludes dates outside either injector's retained history;
# dropped edge rows cannot return as zero-filled inputs during alignment.
injection_features = injection_histories[0].merge(
injection_histories[1], on='DATEPRD', how='inner', validate='one_to_one'
)
# 4. RETAIN ONLY THE FIVE OIL-PRODUCTION WELLS
producer_wells = sorted(set(df['NPD_WELL_BORE_NAME']) - {'15/9-F-4', '15/9-F-5'})
if len(producer_wells) != 5:
raise ValueError('Expected exactly five production wells after excluding F-4 and F-5.')
producer_features = [
'ON_STREAM_HRS', 'AVG_DOWNHOLE_PRESSURE', 'AVG_DOWNHOLE_TEMPERATURE',
'AVG_DP_TUBING', 'AVG_CHOKE_SIZE_P', 'AVG_WHP_P', 'AVG_WHT_P',
'DP_CHOKE_SIZE', 'BORE_GAS_VOL', 'BORE_WAT_VOL',
]
trimmed_producers = []
for well in producer_wells:
records = df.loc[df['NPD_WELL_BORE_NAME'].eq(well)].copy()
records = trim_missing_edges(records, producer_features, well)
# Daily history supports forward filling; Phase 2 builds active-record lags.
records = records.set_index('DATEPRD').sort_index().asfreq('D')
records['NPD_WELL_BORE_NAME'] = well
records.index.name = 'DATEPRD'
trimmed_producers.append(records.reset_index())
production_df = pd.concat(trimmed_producers, ignore_index=True)
target_col = 'BORE_OIL_VOL'
before_alignment = len(production_df)
active_df = production_df.merge(
injection_features, on='DATEPRD', how='inner', validate='many_to_one'
)
active_df = active_df.sort_values(['NPD_WELL_BORE_NAME', 'DATEPRD']).reset_index(drop=True)
print('-> Excluded all oil-production records for 15/9-F-5.')
print(f'-> Daily producer rows outside retained injection histories dropped: '
f'{before_alignment - len(active_df)}')
print(f'-> Retained {len(active_df)} daily rows to build historical features.')
print('-> Phase 2 selects active-production records before calculating historical features.')
# 5. SELECT KEY OPERATIONAL FEATURES & WELL IDENTIFIERS
print("\n" + "-" * 70)
print("Selecting Target & Features...")
candidate_features = [
'NPD_WELL_BORE_NAME',
'DATEPRD',
'ON_STREAM_HRS',
'AVG_DOWNHOLE_PRESSURE',
'AVG_DOWNHOLE_TEMPERATURE',
'AVG_DP_TUBING',
'AVG_CHOKE_SIZE_P',
'AVG_WHP_P',
'AVG_WHT_P',
'DP_CHOKE_SIZE',
'BORE_GAS_VOL',
'BORE_WAT_VOL',
'BORE_WI_VOL_F4',
'BORE_WI_VOL_F5',
'BORE_WI_VOL_F4_MISSING',
'BORE_WI_VOL_F5_MISSING',
target_col
]
selected_cols = [c for c in candidate_features if c in active_df.columns]
ml_subset = active_df[selected_cols].copy()
print(f"-> Columns Preserved ({len(selected_cols)} total):\n {selected_cols}")
print("\n--- Daily History Rows Per Producing Well ---")
if 'NPD_WELL_BORE_NAME' in ml_subset.columns:
print(ml_subset['NPD_WELL_BORE_NAME'].value_counts())
# 6. EXPORT CLEANED FILE FOR PHASE 2
print("\n" + "-" * 70)
print("Exporting Cleaned Dataset...")
output_filename = "volve_phase1_cleaned.csv"
ml_subset.to_csv(output_filename, index=False)
print(f"-> Phase 1 Output Saved to '{output_filename}'")
print("\n" + "=" * 70)
print("PHASE 1 COMPLETE: RECOVERED FULL ACTIVE PRODUCTION HISTORY")
print("=" * 70)======================================================================
PHASE 1: DATA LOADING, CLEANING & WELL FILTERING
======================================================================
Loading Excel File...
-> Raw File Loaded: 15634 rows across 24 columns.
----------------------------------------------------------------------
Processing Dates and Well Names...
-> Detected Wells in File: ['15/9-F-1 C', '15/9-F-11', '15/9-F-12', '15/9-F-14', '15/9-F-15 D', '15/9-F-4', '15/9-F-5']
----------------------------------------------------------------------
Cleaning Column Formatting...
-> 15/9-F-4: dropped 255 edge rows; retained 2008-04-23 to 2016-09-19.
-> 15/9-F-4: forward filled 82 internal daily gaps; 0 production-mode injection zeros.
-> 15/9-F-5: dropped 196 edge rows; retained 2008-03-15 to 2016-09-18.
-> 15/9-F-5: forward filled 249 internal daily gaps; 145 production-mode injection zeros.
-> 15/9-F-1 C: dropped 0 edge rows; retained 2014-04-07 to 2016-04-21.
-> 15/9-F-11: dropped 0 edge rows; retained 2013-07-08 to 2016-09-17.
-> 15/9-F-12: dropped 0 edge rows; retained 2008-02-12 to 2016-09-17.
-> 15/9-F-14: dropped 47 edge rows; retained 2008-03-30 to 2016-09-17.
-> 15/9-F-15 D: dropped 0 edge rows; retained 2014-01-12 to 2016-09-17.
-> Excluded all oil-production records for 15/9-F-5.
-> Daily producer rows outside retained injection histories dropped: 95
-> Retained 9034 daily rows to build historical features.
-> Phase 2 selects active-production records before calculating historical features.
----------------------------------------------------------------------
Selecting Target & Features...
-> Columns Preserved (17 total):
['NPD_WELL_BORE_NAME', 'DATEPRD', 'ON_STREAM_HRS', 'AVG_DOWNHOLE_PRESSURE', 'AVG_DOWNHOLE_TEMPERATURE', 'AVG_DP_TUBING', 'AVG_CHOKE_SIZE_P', 'AVG_WHP_P', 'AVG_WHT_P', 'DP_CHOKE_SIZE', 'BORE_GAS_VOL', 'BORE_WAT_VOL', 'BORE_WI_VOL_F4', 'BORE_WI_VOL_F5', 'BORE_WI_VOL_F4_MISSING', 'BORE_WI_VOL_F5_MISSING', 'BORE_OIL_VOL']
--- Daily History Rows Per Producing Well ---
NPD_WELL_BORE_NAME
15/9-F-12 3070
15/9-F-14 3070
15/9-F-11 1168
15/9-F-15 D 980
15/9-F-1 C 746
Name: count, dtype: int64
----------------------------------------------------------------------
Exporting Cleaned Dataset...
-> Phase 1 Output Saved to 'volve_phase1_cleaned.csv'
======================================================================
PHASE 1 COMPLETE: RECOVERED FULL ACTIVE PRODUCTION HISTORY
======================================================================
5. Phase 2: Per-Well Feature Engineering & Sensor Imputation
Overview & Technical Rationale
Phase 2 starts with 9,034 daily history rows and 17 base columns. We then perform per-well sensor forward filling, select active-production records, and construct historical operational features. The final export contains 7,798 active-production rows and 83 columns, including the 66 historical features selected for ML in Phase 3.
Detailed Execution Steps
Step 1: Per-Well Forward Filling and Active-Record Selection
- Forward filled sensor channels separately within each well, filling 1,979 missing sensor values. Injection channels were already prepared in Phase 1.
- Used forward filling only. Available earlier readings provide the replacement values; backward filling is not part of the workflow.
- Applied
ON_STREAM_HRS > 0andBORE_OIL_VOL > 0, retaining 7,808 active-production records and filtering 1,226 non-producing history rows before feature engineering. - Kept the observed oil-production values as targets rather than imputing prediction targets.
Step 2: Historical Lags, Rolling Trends, and Operational Changes
- Calculated
_lag1and_lag2for all 14 operational and injection fields. These represent the previous one and two active-production records for the same well. - Calculated
_roll3_meanand_roll7_meanover up to the previous three and seven active records, excluding the record being predicted. The windows usemin_periods=1. - Created
TARGET_lag1andTARGET_lag2from earlier active-record oil production. No rolling oil-target means are created. - Created the smoothed historical changes
CHOKE_DELTA,WHP_DELTA,DOWNHOLE_PRESS_DELTA, andON_STREAM_DELTA, together withCHOKE_CHANGEDandIS_SHUT_INflags. - Shifted the change features and operational flags to use earlier observations. A lag or rolling window counts retained active records, so it may span more calendar days than its record count.
These features introduce explicit temporal dependencies, enabling the regressors to represent production momentum and operational changes using past information.
Step 3: Physical Interaction Terms
The code calculates two pressure-related interactions and shifts them within each well so that their feature values come from the previous active record:
Tubing Pressure Drop:
\(\Delta P = \mathrm{AVG\_DOWNHOLE\_PRESSURE} - \mathrm{AVG\_WHP\_P}\)
Choke-Pressure Ratio:
\(\mathrm{Ratio} = \frac{\mathrm{AVG\_CHOKE\_SIZE\_P}}{\mathrm{AVG\_DP\_TUBING} + \epsilon}\)
where \(\epsilon\) is a small stabilization constant to avoid division by zero (here, \(\epsilon = 10^{-5}\)).
These interaction terms encode pressure and choke relationships alongside the lagged sensor measurements.
Step 4: Boundary Cleanup and Export
- Removed 10 active records lacking the required initial historical features, leaving 7,798 rows.
- Exported
volve_phase2_engineered.csvwith 83 columns: the 17 retained base columns plus 66 historical features. - The 66 features consist of 56 operational/injection lag and rolling features, two oil lags, four smoothed changes, two flags, and two pressure-related interactions.
- Current-day base channels remain in the CSV for inspection and record selection. Phase 3 excludes those channels, the date, the well identifier, and the target from the feature matrix.
import pandas as pd
import numpy as np
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)
print("=" * 70)
print("PHASE 2: PER-WELL FEATURE ENGINEERING & SENSOR IMPUTATION")
print("=" * 70)
# 0. LOAD PHASE 1 CLEANED DATA
file_path = os.path.join(project_dir, r"volve_phase1_cleaned.csv")
df_p2 = pd.read_csv(file_path)
df_p2['DATEPRD'] = pd.to_datetime(df_p2['DATEPRD'])
well_col = 'NPD_WELL_BORE_NAME' if 'NPD_WELL_BORE_NAME' in df_p2.columns else None
target_col = 'BORE_OIL_VOL'
# Ensure strict chronological order per well
if well_col:
df_p2 = df_p2.sort_values([well_col, 'DATEPRD']).reset_index(drop=True)
else:
df_p2 = df_p2.sort_values('DATEPRD').reset_index(drop=True)
print(f"\n[STEP 0] Base Data Loaded: {len(df_p2)} rows across {df_p2.shape[1]} columns.")
# 1. CAUSAL SENSOR IMPUTATION, SEPARATELY BY WELL
print("\n" + "-" * 70)
print("[STEP 1] Forward Filling Missing Historical Sensor Readings per Well...")
sensor_cols = RAW_OPERATIONAL_FEATURES.copy()
impute_cols = [c for c in sensor_cols if not c.startswith('BORE_WI_VOL_')]
missing_before = int(df_p2[impute_cols].isna().sum().sum())
df_p2[impute_cols] = df_p2.groupby(well_col)[impute_cols].ffill()
print(f'-> Forward filled {missing_before - int(df_p2[impute_cols].isna().sum().sum())} sensor values.')
# Keep active records before all lags, rolling windows, deltas, and interactions.
before_active_filter = len(df_p2)
df_p2 = df_p2.loc[(df_p2['ON_STREAM_HRS'] > 0) & (df_p2[target_col] > 0)].copy()
df_p2 = df_p2.reset_index(drop=True)
print(f'-> Retained {len(df_p2)} active-production records; '
f'filtered {before_active_filter - len(df_p2)} non-producing history rows.')
print('-> Lag1/lag2 and rolling3/rolling7 count active records, not calendar days.')
import warnings
warnings.filterwarnings('ignore', category=DeprecationWarning)
# 2. PER-WELL LAG, ROLLING & SMOOTHED DELTA FEATURES
print("\n" + "-" * 70)
print("[STEP 2] Calculating Per-Well Historical Lags, Rolling Trends & Smoothed Operational Deltas...")
def create_well_features(group):
well_name = group[well_col].iloc[0] if well_col in group.columns else None
# Past active-record lags and rolling averages
for col in sensor_cols:
group[f'{col}_lag1'] = group[col].shift(1)
group[f'{col}_lag2'] = group[col].shift(2)
group[f'{col}_roll3_mean'] = group[col].shift(1).rolling(window=3, min_periods=1).mean()
group[f'{col}_roll7_mean'] = group[col].shift(1).rolling(window=7, min_periods=1).mean()
# Oil lags use earlier active-production records only.
oil_history = group[target_col].ffill()
group['TARGET_lag1'] = oil_history.shift(1)
group['TARGET_lag2'] = oil_history.shift(2)
# --- SMOOTHED OPERATIONAL DELTAS (Rate-of-Change with 3-day rolling smoothing) ---
if 'AVG_CHOKE_SIZE_P' in group.columns:
group['CHOKE_DELTA'] = group['AVG_CHOKE_SIZE_P'].diff().rolling(window=3, min_periods=1).mean().shift(1)
group['CHOKE_CHANGED'] = (group['CHOKE_DELTA'].abs() > 0.01).astype(int)
if 'AVG_WHP_P' in group.columns:
group['WHP_DELTA'] = group['AVG_WHP_P'].diff().rolling(window=3, min_periods=1).mean().shift(1)
if 'AVG_DOWNHOLE_PRESSURE' in group.columns:
group['DOWNHOLE_PRESS_DELTA'] = group['AVG_DOWNHOLE_PRESSURE'].diff().rolling(window=3, min_periods=1).mean().shift(1)
if 'ON_STREAM_HRS' in group.columns:
group['ON_STREAM_DELTA'] = group['ON_STREAM_HRS'].diff().rolling(window=3, min_periods=1).mean().shift(1)
group['IS_SHUT_IN'] = group['ON_STREAM_HRS'].shift(1).eq(0).astype(int)
return group
df_p2 = pd.concat(
[create_well_features(group.copy()) for _, group in df_p2.groupby(well_col, sort=False)],
ignore_index=True,
)
# 3. PHYSICAL INTERACTION TERMS
print("\n" + "-" * 70)
print("[STEP 3] Engineering Reservoir Physics Interactions...")
dhp = 'AVG_DOWNHOLE_PRESSURE'
whp = 'AVG_WHP_P'
if dhp in df_p2.columns and whp in df_p2.columns:
df_p2['TUBING_PRESSURE_DROP'] = (df_p2[dhp] - df_p2[whp]).groupby(df_p2[well_col]).shift(1)
if 'AVG_DP_TUBING' in df_p2.columns and 'AVG_CHOKE_SIZE_P' in df_p2.columns:
df_p2['CHOKE_PRESSURE_RATIO'] = (df_p2['AVG_CHOKE_SIZE_P'] / (df_p2['AVG_DP_TUBING'] + 1e-5)).groupby(df_p2[well_col]).shift(1)
# 4. REMOVE BOUNDARY LAG ROWS
print("\n" + "-" * 70)
print("[STEP 4] Removing Boundary Window NaNs...")
initial_rows = len(df_p2)
# Raw current-day channels are retained for inspection/target filtering only.
historical_cols = [c for c in df_p2.columns
if c not in ['DATEPRD', well_col, target_col] + RAW_OPERATIONAL_FEATURES]
active_target = (df_p2['ON_STREAM_HRS'] > 0) & (df_p2[target_col] > 0)
df_p2_clean = df_p2.loc[active_target].copy()
df_p2_clean[historical_cols] = df_p2_clean[historical_cols].replace([np.inf, -np.inf], np.nan)
df_p2_clean = df_p2_clean.dropna(subset=historical_cols).reset_index(drop=True)
dropped_rows = initial_rows - len(df_p2_clean)
print(f"-> Total Rows Before Cleanup: {initial_rows}")
print(f"-> Non-target / Unavailable-History Rows Removed: {dropped_rows}")
print(f"-> Final Operational Feature Matrix: {df_p2_clean.shape[0]} rows x {df_p2_clean.shape[1]} columns")
print("\n--- Final Row Counts Per Well ---")
print(df_p2_clean[well_col].value_counts())
# EXPORT
output_filename = "volve_phase2_engineered.csv"
df_p2_clean.to_csv(output_filename, index=False)
print(f"\n-> Phase 2 Output Saved to '{output_filename}'")
print("\n" + "=" * 70)
print("PHASE 2 COMPLETE: READY FOR MODELING")
print("=" * 70)======================================================================
PHASE 2: PER-WELL FEATURE ENGINEERING & SENSOR IMPUTATION
======================================================================
[STEP 0] Base Data Loaded: 9034 rows across 17 columns.
----------------------------------------------------------------------
[STEP 1] Forward Filling Missing Historical Sensor Readings per Well...
-> Forward filled 1979 sensor values.
-> Retained 7808 active-production records; filtered 1226 non-producing history rows.
-> Lag1/lag2 and rolling3/rolling7 count active records, not calendar days.
----------------------------------------------------------------------
[STEP 2] Calculating Per-Well Historical Lags, Rolling Trends & Smoothed Operational Deltas...
----------------------------------------------------------------------
[STEP 3] Engineering Reservoir Physics Interactions...
----------------------------------------------------------------------
[STEP 4] Removing Boundary Window NaNs...
-> Total Rows Before Cleanup: 7808
-> Non-target / Unavailable-History Rows Removed: 10
-> Final Operational Feature Matrix: 7798 rows x 83 columns
--- Final Row Counts Per Well ---
NPD_WELL_BORE_NAME
15/9-F-12 2764
15/9-F-14 2721
15/9-F-11 1120
15/9-F-15 D 765
15/9-F-1 C 428
Name: count, dtype: int64
-> Phase 2 Output Saved to 'volve_phase2_engineered.csv'
======================================================================
PHASE 2 COMPLETE: READY FOR MODELING
======================================================================
Engineered Active-Production Row Distribution Per Wellbore
| Wellbore | Rows |
|---|---|
| 15/9-F-12 | 2,764 |
| 15/9-F-14 | 2,721 |
| 15/9-F-11 | 1,120 |
| 15/9-F-15 D | 765 |
| 15/9-F-1 C | 428 |
| Total | 7,798 |
F-5 contributes injection history as a feature but has no oil-production target rows in the ML dataset.
6. Phase 3: Multi-Model Machine Learning Benchmarking
Overview & Technical Rationale
Phase 3 trains six regression models to predict daily oil production using 66 historical features. Chronological boundaries are determined separately within each well. The records from all five wells are then pooled to train and evaluate one shared model of each type.
Detailed Execution Steps
Step 1: Feature Matrix Preparation
- Loaded
volve_phase2_engineered.csvand parsedDATEPRD. - Excluded the date, wellbore identifier, oil target, and all 14 current-day operational/injection fields from the features.
- Checked the engineered inputs for unresolved non-finite values. The resulting ML matrix contains 7,798 active records and 66 features; no secondary median imputation is used.
Step 2: Chronological Per-Well Train/Test Split
- Sorted each well’s records by date and selected the first 80% for training and the final 20% for testing, using integer split boundaries.
- Combined the per-well blocks into 6,237 training samples and 1,561 test samples.
| Wellbore | Training rows | Test rows |
|---|---|---|
| 15/9-F-1 C | 342 | 86 |
| 15/9-F-11 | 896 | 224 |
| 15/9-F-12 | 2,211 | 553 |
| 15/9-F-14 | 2,176 | 545 |
| 15/9-F-15 D | 612 | 153 |
| Total | 6,237 | 1,561 |
The chronological split tests each model on later observations within each well. Historical features use only earlier active-production observations.
Step 3: Scaling and Model Training
StandardScaler is fitted on pooled training data for SVR, k-NN, Polynomial Ridge Regression, and the MLP. Random Forest and Gradient Boosted Trees use unscaled features in this benchmark.
| Model | Benchmark Configuration |
|---|---|
| Random Forest | 100 trees |
| Gradient Boosted Trees | 100 trees; learning rate 0.05 |
| Support Vector Regressor (SVR) | RBF kernel; C=100; epsilon=0.1 |
| k-Nearest Neighbors (k-NN) | 5 neighbours |
| Polynomial Ridge Regression | Degree-2 interaction-only features; Ridge alpha=100.0 |
| Multilayer Perceptron | Hidden layers of 64 and 32 neurons; ReLU; Adam; maximum 1,000 iterations; early stopping |
All six models are evaluated on the same pooled holdout using R², RMSE, and MAE.
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.svm import SVR
from sklearn.neighbors import KNeighborsRegressor
from sklearn.neural_network import MLPRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)
print("=" * 70)
print("PHASE 3: MULTI-MODEL ML BENCHMARK (TEMPORALLY ENCODED)")
print("=" * 70)
# Shared preparation and holdout split used unchanged by Phases 3 and 4.
def prepare_ml_data(file_path):
data = pd.read_csv(file_path)
data['DATEPRD'] = pd.to_datetime(data['DATEPRD'])
well_col = 'NPD_WELL_BORE_NAME'
target_col = 'BORE_OIL_VOL'
data = data.sort_values([well_col, 'DATEPRD']).reset_index(drop=True)
# Only historical features may enter the model; exclude all current-day channels.
ignore_cols = ['DATEPRD', well_col, target_col] + RAW_OPERATIONAL_FEATURES
features = [col for col in data.columns if col not in ignore_cols]
data[features] = data[features].replace([np.inf, -np.inf], np.nan)
if data[well_col].eq('15/9-F-5').any():
raise ValueError('F-5 oil production must be excluded before modeling.')
if data[features + [target_col]].isna().any().any():
raise ValueError('Unresolved non-finite values in engineered ML inputs; inspect Phase 2.')
return data, features
def per_well_holdout(data, train_fraction=0.8):
train_indices, test_indices = [], []
for well, group in data.groupby('NPD_WELL_BORE_NAME', sort=False):
ordered = group.sort_values('DATEPRD').index.to_numpy()
cut = int(len(ordered) * train_fraction)
if cut < 1 or cut >= len(ordered):
raise ValueError(f'Insufficient rows for a holdout split: {well}')
train_indices.extend(ordered[:cut])
test_indices.extend(ordered[cut:])
return (data.loc[train_indices].reset_index(drop=True),
data.loc[test_indices].reset_index(drop=True))
file_path = os.path.join(project_dir, 'volve_phase2_engineered.csv')
df_p3, feature_cols = prepare_ml_data(file_path)
well_col = 'NPD_WELL_BORE_NAME'
target_col = 'BORE_OIL_VOL'
train_data, test_data = per_well_holdout(df_p3)
X_train, y_train = train_data[feature_cols], train_data[target_col]
X_test, y_test = test_data[feature_cols], test_data[target_col]
print(f"-> Predictor Features: {len(feature_cols)}")
print(f"-> Training Set: {len(X_train)} samples")
print(f"-> Testing Set: {len(X_test)} samples")
print(test_data.groupby(well_col).size().rename('Holdout rows'))
# BENCHMARK ALL 6 REQUESTED ML MODELS
print("\n" + "-" * 70)
print("Training Benchmark Machine Learning Models...")
models = {
"Random Forest": (RandomForestRegressor(n_estimators=100, random_state=RANDOM_SEED), False),
"Gradient Boosted Trees": (GradientBoostingRegressor(n_estimators=100, learning_rate=0.05, random_state=RANDOM_SEED), False),
"Support Vector Machine (SVR)": (SVR(kernel='rbf', C=100, epsilon=0.1), True),
"Nearest Neighbors (k-NN)": (KNeighborsRegressor(n_neighbors=5), True),
"Polynomial Ridge Regression": (make_pipeline(PolynomialFeatures(degree=2, interaction_only=True, include_bias=False), Ridge(alpha=100.0)), True),
"Multilayer Perceptron (Neural Net)": (
MLPRegressor(
hidden_layer_sizes=(64, 32),
activation='relu',
solver='adam',
max_iter=1000,
early_stopping=True,
random_state=RANDOM_SEED
),
True
)
}
results = []
for name, (model, requires_scaling) in models.items():
steps = []
if requires_scaling:
steps.append(StandardScaler())
steps.append(model)
model = make_pipeline(*steps)
models[name] = (model, requires_scaling)
print(f"-> Fitting model: {name}...")
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
r2 = r2_score(y_test, y_pred)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
mae = mean_absolute_error(y_test, y_pred)
results.append({
"Model": name,
"R2 Score": round(r2, 4),
"RMSE (Sm³/day)": round(rmse, 2),
"MAE (Sm³/day)": round(mae, 2)
})
# SUMMARY EVALUATION TABLE
print("\n" + "-" * 70)
print("MODEL PERFORMANCE COMPARISON SUMMARY")
print("-" * 70)
summary_df = pd.DataFrame(results).sort_values(by="R2 Score", ascending=False).reset_index(drop=True)
print(summary_df.to_string(index=False))
# FEATURE IMPORTANCES
print("\n" + "-" * 70)
print("Top 10 Feature Importances (Random Forest)")
print("-" * 70)
rf_model = models["Random Forest"][0]
importances = pd.DataFrame({
'Feature': feature_cols,
'Importance': rf_model[-1].feature_importances_
}).sort_values(by='Importance', ascending=False).reset_index(drop=True)
print(importances.head(10).to_string(index=False))
print("\n" + "=" * 70)
print("PHASE 3 COMPLETE: MULTI-MODEL BENCHMARK FINISHED")
print("=" * 70)======================================================================
PHASE 3: MULTI-MODEL ML BENCHMARK (TEMPORALLY ENCODED)
======================================================================
-> Predictor Features: 66
-> Training Set: 6237 samples
-> Testing Set: 1561 samples
NPD_WELL_BORE_NAME
15/9-F-1 C 86
15/9-F-11 224
15/9-F-12 553
15/9-F-14 545
15/9-F-15 D 153
Name: Holdout rows, dtype: int64
----------------------------------------------------------------------
Training Benchmark Machine Learning Models...
-> Fitting model: Random Forest...
-> Fitting model: Gradient Boosted Trees...
-> Fitting model: Support Vector Machine (SVR)...
-> Fitting model: Nearest Neighbors (k-NN)...
-> Fitting model: Polynomial Ridge Regression...
-> Fitting model: Multilayer Perceptron (Neural Net)...
----------------------------------------------------------------------
MODEL PERFORMANCE COMPARISON SUMMARY
----------------------------------------------------------------------
Model R2 Score RMSE (Sm³/day) MAE (Sm³/day)
Gradient Boosted Trees 0.8632 75.84 50.27
Random Forest 0.8536 78.47 52.61
Multilayer Perceptron (Neural Net) -0.2134 225.87 168.67
Support Vector Machine (SVR) -11.6382 728.95 477.44
Polynomial Ridge Regression -20.5199 951.21 475.83
Nearest Neighbors (k-NN) -40.5022 1320.96 853.42
----------------------------------------------------------------------
Top 10 Feature Importances (Random Forest)
----------------------------------------------------------------------
Feature Importance
TARGET_lag1 0.599364
BORE_GAS_VOL_roll7_mean 0.201780
BORE_GAS_VOL_roll3_mean 0.082885
BORE_GAS_VOL_lag1 0.061175
ON_STREAM_HRS_roll3_mean 0.004907
TARGET_lag2 0.003902
ON_STREAM_HRS_lag1 0.002237
BORE_GAS_VOL_lag2 0.002196
AVG_WHT_P_lag1 0.002018
ON_STREAM_HRS_roll7_mean 0.001871
======================================================================
PHASE 3 COMPLETE: MULTI-MODEL BENCHMARK FINISHED
======================================================================
Benchmark Results & Performance Comparison
The unseen per-well 20% holdout produced the following pooled results, ranked by R²:
| Rank | Model Architecture | R² Score | RMSE (Sm³/day) | MAE (Sm³/day) |
|---|---|---|---|---|
| 1 | Gradient Boosted Trees | 0.8632 | 75.84 | 50.27 |
| 2 | Random Forest | 0.8472 | 80.14 | 54.02 |
| 3 | Multilayer Perceptron | -0.2134 | 225.87 | 168.67 |
| 4 | Support Vector Regressor | -11.6382 | 728.95 | 477.44 |
| 5 | Polynomial Ridge Regression | -20.5199 | 951.21 | 475.83 |
| 6 | k-Nearest Neighbors | -40.5022 | 1,320.96 | 853.42 |
Top 10 Feature Importances: Benchmark Random Forest
The code reports feature importances for the benchmark Random Forest, which ranked second in the six-model comparison.
| Rank | Feature Name | Importance Weight | Feature Category |
|---|---|---|---|
| 1 | TARGET_lag1 |
59.93% | Previous active-record oil production |
| 2 | BORE_GAS_VOL_roll7_mean |
20.19% | Gas volume over up to seven prior active records |
| 3 | BORE_GAS_VOL_roll3_mean |
8.30% | Gas volume over up to three prior active records |
| 4 | BORE_GAS_VOL_lag1 |
6.12% | Previous active-record gas volume |
| 5 | ON_STREAM_HRS_roll3_mean |
0.49% | Historical operating duration |
| 6 | TARGET_lag2 |
0.40% | Oil production two active records earlier |
| 7 | ON_STREAM_HRS_lag1 |
0.23% | Previous active-record operating duration |
| 8 | BORE_GAS_VOL_lag2 |
0.20% | Gas volume two active records earlier |
| 9 | AVG_WHT_P_lag1 |
0.20% | Previous active-record wellhead temperature |
| 10 | ON_STREAM_HRS_roll7_mean |
0.19% | Historical operating duration |
Phase 3 Conclusions
Model Accuracy
Gradient Boosted Trees achieved the highest benchmark R² (0.8632) and the lowest benchmark MAE (50.27 Sm³/day). Random Forest followed with R² = 0.8472 and MAE = 54.02 Sm³/day. Phase 4 subsequently tunes the Random Forest.
Dominant Features
The two oil lags account for approximately 60.33% of the benchmark Random Forest’s importance. The four gas-history features listed above contribute approximately 34.81%. Production momentum therefore remains prominent, with historical gas volumes also contributing strongly to the fitted model.
Operational Impact
Historical runtime and wellhead-temperature features also appear among the top ten features. These measurements represent operating conditions alongside the production-history features and pressure/choke interactions.
7. Phase 4: Time-Series Cross-Validation & Hyperparameter Tuning
Technical Rationale & Methodology
Five-Fold Expanding-Window Cross-Validation
Standard K-fold cross-validation (sklearn.model_selection.KFold) randomly shuffles data across folds, which introduces severe temporal data leakage for forecasting (using history and the present to predict the future). The implemented workflow instead uses model_selection.TimeSeriesSplit, which expands historical training windows and validates on the following block within each well.
Phase 4 reuses Phase 3’s preparation and per-well 80%/20% split. Cross-validation uses only the 6,237 training records. Each well’s training block is divided into five expanding-window splits; corresponding blocks are then combined across wells. Each CV fit trains one shared model on pooled records from all five wells, and R² is calculated on the pooled validation records.
| Fold | Pooled training rows | Pooled validation rows | Wells represented |
|---|---|---|---|
| 1 | 1,047 | 1,038 | 5 |
| 2 | 2,085 | 1,038 | 5 |
| 3 | 3,123 | 1,038 | 5 |
| 4 | 4,161 | 1,038 | 5 |
| 5 | 5,199 | 1,038 | 5 |
Randomized Hyperparameter Search
The search explores tree depth and minimum node sizes to regularize the Random Forest’s use of historical features. TARGET_lag1 contributes approximately 59.93% of the benchmark forest’s importance.
max_depth: 10, 15, 20, or Nonemin_samples_split: 2 or 5min_samples_leaf: 1 or 2n_estimators: 100
RandomizedSearchCV samples six configurations with seed 42, producing 30 CV fits across five folds. StandardScaler and Random Forest are combined in a Pipeline, with scaling fitted within each fold’s training subset. The selected pipeline is refitted on the full pooled training set and evaluated on the untouched 1,561-row holdout.
Selected Model and Results
| Item | Result |
|---|---|
| Selected configuration | max_depth=20, min_samples_leaf=2, min_samples_split=5, n_estimators=100 |
| Mean CV R² | 0.7817 |
| Holdout R² | 0.8938 |
| Holdout RMSE | 66.81 Sm³/day |
| Holdout MAE | 41.52 Sm³/day |
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import RandomizedSearchCV, TimeSeriesSplit
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
# --- STEP 1: SAME PER-WELL HOLDOUT AS PHASE 3 ---
file_path = os.path.join(project_dir, 'volve_phase2_engineered.csv')
df, feature_cols = prepare_ml_data(file_path)
well_col = 'NPD_WELL_BORE_NAME'
target_col = 'BORE_OIL_VOL'
train_data, test_data = per_well_holdout(df)
X_train, y_train = train_data[feature_cols], train_data[target_col]
X_test, y_test = test_data[feature_cols], test_data[target_col]
# --- STEP 2: EXPANDING WINDOWS WITHIN EVERY WELL'S TRAINING BLOCK ---
def per_well_expanding_splits(data, n_splits=5):
well_splits = []
for well, group in data.groupby('NPD_WELL_BORE_NAME', sort=False):
positions = group.sort_values('DATEPRD').index.to_numpy()
if len(positions) <= n_splits:
raise ValueError(f'Insufficient training rows for {n_splits} folds: {well}')
splits = []
for train_pos, valid_pos in TimeSeriesSplit(n_splits=n_splits).split(positions):
splits.append((positions[train_pos], positions[valid_pos]))
well_splits.append(splits)
# Pool matching per-well folds. No final holdout row enters CV.
return [
(np.concatenate([splits[fold][0] for splits in well_splits]),
np.concatenate([splits[fold][1] for splits in well_splits]))
for fold in range(n_splits)
]
cv_splits = per_well_expanding_splits(train_data, n_splits=5)
for fold, (train_idx, valid_idx) in enumerate(cv_splits, start=1):
print(f'Fold {fold}: {len(train_idx)} training / {len(valid_idx)} validation rows; '
f"{train_data.iloc[valid_idx][well_col].nunique()} wells")
# Scaler + Random Forest combined into a Pipeline
pipeline = Pipeline(
[
("scaler", StandardScaler()),
("rf", RandomForestRegressor(random_state=RANDOM_SEED)),
]
)
# Parameter grid keys prefixed with 'rf__' for sklearn pipeline.
# See https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html
param_dist = {
"rf__n_estimators": [100],
"rf__max_depth": [10, 15, 20, None],
"rf__min_samples_split": [2, 5],
"rf__min_samples_leaf": [1, 2],
}
# --- STEP 3: EXECUTE HYPERPARAMETER TUNING ---
print("Executing Per-Well Expanding-Window Cross-Validation...")
opt_search = RandomizedSearchCV(
estimator=pipeline,
param_distributions=param_dist,
n_iter=6,
cv=cv_splits,
scoring="r2",
n_jobs=-1, # We set n_jobs to -1 to utilize all available CPU cores for speed
random_state=RANDOM_SEED,
verbose=1,
)
# Fit on X_train. Note that scaling happens inside each CV split independently
opt_search.fit(X_train, y_train)
# --- STEP 4: EVALUATE TUNED MODEL ON UNSEEN TEST SET ---
best_pipeline = opt_search.best_estimator_
y_pred = best_pipeline.predict(X_test)
r2 = r2_score(y_test, y_pred)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
mae = mean_absolute_error(y_test, y_pred)
print("\n" + "=" * 60)
print("HYPERPARAMETER TUNING & CV RESULTS")
print("=" * 60)
print(f"Optimal Hyperparameters : {opt_search.best_params_}")
print(f"Best CV R2 Score : {opt_search.best_score_:.4f}")
print(f"Test Set R2 Score : {r2:.4f}")
print(f"Test Set RMSE : {rmse:.2f} Sm³/day")
print(f"Test Set MAE : {mae:.2f} Sm³/day")
print("=" * 60)Fold 1: 1047 training / 1038 validation rows; 5 wells
Fold 2: 2085 training / 1038 validation rows; 5 wells
Fold 3: 3123 training / 1038 validation rows; 5 wells
Fold 4: 4161 training / 1038 validation rows; 5 wells
Fold 5: 5199 training / 1038 validation rows; 5 wells
Executing Per-Well Expanding-Window Cross-Validation...
Fitting 5 folds for each of 6 candidates, totalling 30 fits
============================================================
HYPERPARAMETER TUNING & CV RESULTS
============================================================
Optimal Hyperparameters : {'rf__n_estimators': 100, 'rf__min_samples_split': 5, 'rf__min_samples_leaf': 2, 'rf__max_depth': 20}
Best CV R2 Score : 0.7808
Test Set R2 Score : 0.8864
Test Set RMSE : 69.10 Sm³/day
Test Set MAE : 43.53 Sm³/day
============================================================
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
# Set visual style
plt.style.use(
"seaborn-v0_8-whitegrid"
if "seaborn-v0_8-whitegrid" in plt.style.available
else "default"
)
fig, ax = plt.subplots(figsize=(8, 6))
# --- ACTUAL VS. PREDICTED SCATTER PLOT ---
sns.scatterplot(
x=y_test,
y=y_pred,
alpha=0.6,
color="#1f77b4",
edgecolor="k",
linewidth=0.5,
ax=ax,
)
# Perfect prediction 1:1 reference line
max_val = max(y_test.max(), y_pred.max())
ax.plot([0, max_val], [0, max_val], "r--", lw=2, label="Perfect Fit (1:1 Line)")
# Plot formatting
ax.set_title("Actual vs. Forecasted Oil Volume", fontsize=13, fontweight="bold")
ax.set_xlabel("Actual BORE_OIL_VOL (Sm³/day)", fontsize=11)
ax.set_ylabel("Predicted BORE_OIL_VOL (Sm³/day)", fontsize=11)
ax.legend(loc="upper left")
ax.grid(True, linestyle="--", alpha=0.6)
plt.tight_layout()
plt.show()
# ==========================================================
# PHASE 4: DIAGNOSTIC VISUALIZATIONS (INDIVIDUAL WELLS - CLEANED)
# ==========================================================
# Reconstruct the test plotting dataframe
test_plot_df = test_data[['DATEPRD', well_col]].rename(
columns={well_col: 'WELL_NAME'}
).copy()
test_plot_df['Actual'] = y_test.to_numpy()
test_plot_df['Predicted'] = y_pred
expected_wells = set(df[well_col].unique())
if set(test_plot_df['WELL_NAME'].unique()) != expected_wells or len(expected_wells) != 5:
raise ValueError('Expected holdout predictions for all five oil-producing wells.')
# Get list of unique wells in the test set
wells = test_plot_df['WELL_NAME'].unique()
n_wells = len(wells)
# Create a figure with a dynamic vertical stack of subplots (one per well)
fig, axes = plt.subplots(n_wells, 1, figsize=(12, 4 * n_wells), sharex=True)
if n_wells == 1:
axes = [axes] # Ensure it's iterable if there's only one well
print(f"Visualization for {n_wells} distinct wells.")
for idx, well_name in enumerate(wells):
ax = axes[idx]
group = test_plot_df[test_plot_df['WELL_NAME'] == well_name].copy()
if len(group) == 0:
continue
# Set DATEPRD as index and sort chronologically
group = group.set_index('DATEPRD').sort_index()
# Reindex to a complete daily date range so missing/shut-in days break lines cleanly instead of sloping ramps
full_range = pd.date_range(start=group.index.min(), end=group.index.max(), freq='D')
group = group.reindex(full_range)
# Plot Actual vs Predicted for this specific well
ax.plot(group.index, group['Actual'], label="Actual Production", color="#2ca02c", linewidth=1.5)
ax.plot(group.index, group['Predicted'], label="Predicted Production", color="#ff7f0e", linestyle="--", linewidth=1.2)
ax.set_title(f"Wellbore Forecast Alignment: {well_name}", fontsize=12, fontweight='bold')
ax.set_ylabel("BORE_OIL_VOL (Sm³/day)")
ax.legend(loc='upper right', fontsize='small')
ax.grid(True, linestyle='--', alpha=0.5)
# Set x-label only on the bottom subplot
axes[-1].set_xlabel("Date", fontsize=11, fontweight='bold')
plt.tight_layout()
plt.savefig("Volve_Individual_Wells_Clean_Forecast.png", dpi=300)
plt.show()Visualization for 5 distinct wells.

Key Findings & Engineering Impact
- Validation Rigor: Five pooled expanding-window folds produced a mean CV R² of 0.7817. The selected Random Forest achieved R² = 0.8938 on the subsequent per-well holdout records.
- Regularization Effect: The selected depth-20 forest with
min_samples_leaf=2andmin_samples_split=5improved holdout performance relative to the benchmark Random Forest. R² increased from 0.8472 to 0.8938, RMSE decreased from 80.14 to 66.81 Sm³/day, and MAE decreased from 54.02 to 41.52 Sm³/day. - Historical Operational Context: The final model combines previous active-record production and sensor histories with date-aligned historical injection inputs from F-4 and F-5.
Discussion of the Plots and Results
The tuned Random Forest is evaluated on 1,561 pooled holdout records from the five production wells. Each well contributes its final 20% of active-production records. Together, the holdout dates span January 12, 2015 to September 17, 2016.
Two visual diagnostics accompany the aggregate scores: an actual-versus-predicted scatter plot and time-series overlays for all five wells. Daily production is discussed in Sm³/day.
Plot 1: Actual vs. Forecasted Oil Volume
Structural Observations
- Line-of-Fit Concordance: Much of the scatter follows the 1:1 reference line, consistent with the holdout R² of 0.8938, RMSE of 66.81 Sm³/day, and MAE of 41.52 Sm³/day.
- Production Range: The holdout includes low-volume producing records and higher-volume observations approaching 1,200 Sm³/day. The scatter shows both overprediction and underprediction around the reference line.
- Possible Engineering Explanation of Transient Departures: Abrupt operational events (such as an unexpected choke adjustment, a shut-in transition, or a rapid pressure change) could explain some positive residual spikes. Such events may cause actual production to fall before historical active-record features reflect the new condition.
Plot 2: Time-Series Forecast Alignment
The figure contains separate actual-versus-predicted overlays for 15/9-F-1 C, 15/9-F-11, 15/9-F-12, 15/9-F-14, and 15/9-F-15 D.
Structural Observations
- Decline Curve Tracking: The model captures broad production trajectories and several rate changes during the 2015 to 2016 holdout period.
- Persistent Offsets: The overlays show sustained underprediction over parts of F-11 and F-12, and overprediction over portions of F-14’s later holdout history. Agreement therefore varies along the individual trajectories even though the pooled R² is high.
- Transient Event Response: Local differences around sharp production changes may reflect operational transitions. Choke adjustments, shut-in transitions, and pressure changes are plausible contributors because production may respond before the historical lag features adjust.
Historical Response Features
The model already includes CHOKE_DELTA, CHOKE_CHANGED, WHP_DELTA, DOWNHOLE_PRESS_DELTA, and ON_STREAM_DELTA. These are shifted historical features derived from earlier active-production records. TARGET_lag1 and TARGET_lag2 similarly represent the previous two active records, so their separation from the predicted date can exceed one or two calendar days.
Key Takeaways
- Predictive Performance: The tuned Random Forest improves the benchmark forest’s pooled holdout scores, reaching R² = 0.8938 and MAE = 41.52 Sm³/day.
- Dynamic Trend Capture: The time-series overlays show the model tracking broad decline patterns and operational changes, together with local departures and sustained offsets in some intervals.
- Operational Interpretation: Past production, runtime, pressure, temperature, choke changes, and injection history provide the operational context used to estimate each retained producing record.
8. Other Works and Recommendations
There are several research papers that have investigated various aspects of the Volve field data. Two of them are briefly discussed below and compared to this porject.
We also summarized recommendations that can further improve this project, and we leave those for future effort.
Other Works
Hyperparameter Tuning of Artificial Neural Networks for Well Production Estimation Considering the Uncertainty in Initialized Parameters [1]
This paper investigates the same data from the Volve field but without specifying which of the seven wells (only states that the data is derived from the daily production records of a “single well belonging to the Volve Field”). The fundamental difference between the paper and this project lies in the treatment of time, data structure and the ML task.
The paper frames well production estimation as a static multivariate regression problem, and it randomly partitions data to predict three outputs using a Multilayer Perceptron (2 hidden layers, 20 units each) without temporal feature engineering. Conversely, this project treats the problem as a dynamic time-series forecasting task focused exclusively on predicting future daily oil volumes.
To prevent temporal data leakage, this project strictly enforces chronological train/test splits. We also utilize physics-informed time-aware features, such as historical lags and rolling averages, to evaluate several machine learning algorithms.
Well production forecast in Volve field: Application of rigorous machine learning techniques and metaheuristic algorithm [2]
This paper also uses Volve daily production data, specifically 1,093 days from well F-14 between July 2013 and July 2016. It predicts oil production using time and operational variables, including pressures, temperatures, choke opening, on-stream hours, and daily gas and water production. The study compares support vector regression, feedforward neural networks, and recurrent models (simple RNN, LSTM, and GRU), with particle swarm optimization applied to the SVR and feedforward models. It reserves the final 274 days for a blind prediction assessment.
Unlike the first paper [1], this paper explicitly considers temporal behavior through recurrent models. The distinction from this project is therefore the forecasting setup: its models use operational inputs for one well, whereas this project pools five producing wells and explicitly shifts features into the past, including oil-production history and separate F-4 and F-5 injection histories. Temporal information here is represented by engineered lags, rolling averages, and changes rather than recurrent networks.
References
[1] M. Jin, Q. Liao, S. Patil, A. Abdulraheem, D. Al-Shehri, and G. Glatz, “Hyperparameter tuning of artificial neural networks for well production estimation considering the uncertainty in initialized parameters,” ACS Omega, vol. 7, no. 28, pp. 24145-24156, Jul. 2022, doi: 10.1021/acsomega.2c00498.
[2] C. S. W. Ng, A. Jahanbani Ghahfarokhi, and M. Nait Amar, “Well production forecast in Volve field: Application of rigorous machine learning techniques and metaheuristic algorithm,” Journal of Petroleum Science and Engineering, vol. 208, Art. no. 109468, Jan. 2022, doi: 10.1016/j.petrol.2021.109468.
Recommendations for Future Work
More Advanced Treatment of Missing Values
Future work could compare forward filling with multivariate, state-space, or learned imputation methods that use relationships among pressures, temperatures, flow measurements, and operating conditions. Candidate methods should be evaluated by masking observed historical values and checking reconstruction error as well as downstream forecasting performance. To preserve the forecasting setup, each estimate must use only information available before the forecast date, with any imputation model fitted within the training portion of each validation fold. Long gaps and missing boundary periods should be assessed separately from short internal gaps.
Separate Validation for Tuning and Model Selection
Phase 4 already tunes the Random Forest using expanding-window validation folds within the training data, keeping the final test records outside that search. Future work should extend this separation to the selection of model families and preprocessing choices, rather than using the Phase 3 test rankings to guide subsequent development. A chronological validation block or nested time-series cross-validation could support these decisions. The final test set would then be reserved for evaluating the completed workflow after its design and hyperparameters have been fixed.
More Rigorous Hyperparameter Tuning Across All Models
The Phase 3 benchmark uses fixed configurations for all six models, while Phase 4 tunes only the Random Forest using six sampled configurations. Future comparisons should tune every model using the same validation splits and a clearly stated search budget. Relevant parameters include tree depth and leaf size, the learning rate and number of estimators for Gradient Boosted Trees, SVR regularization and kernel parameters, neighbor count and distance weighting, polynomial degree and Ridge regularization, and neural-network architecture and learning rate. Broader randomized or Bayesian searches could help distinguish limitations of a model family from limitations of its initial configuration.
Feature Contributions Through Ablation Studies
Retrain the forecasting model after removing defined feature groups, especially the F-4 and F-5 injection histories, gas-production histories, and past oil-production features. Compare each reduced model with the full feature set using identical data rows and chronological validation splits. Removing injection histories separately and together would help assess their incremental predictive value. Because predictors can contain overlapping information, changes in validation performance would complement the current tree-based feature importances. Such results would describe predictive contribution rather than establish a causal relationship between injection and production.
Longer Lags and Rolling Windows for Delayed Effects
The current features emphasize the previous two active-production records and rolling windows of three and seven active records. Future work could explore longer histories for injection, pressure, gas production, and oil production to capture slower responses and longer production trends. Candidate horizons should be selected through chronological validation, with all windows ending before the forecast date. Active-record windows should be distinguished from elapsed calendar time, particularly across shut-ins. Comparing calendar-based injection lags with longer active-record histories could help identify useful response times without assuming that all wells respond at the same delay.