stn 04 · quantil, client engagement
Forecasting Energy Demand Across Three Planning Horizons
Built the model that turns a production plan into the electricity it will need: a regression per operating unit over six years of daily data that had never been assembled in one place, serving three planning horizons from one set of fitted models.
sec 01 · brief
The problem
A national oil and gas operator plans production at three horizons: an operating plan three months out at monthly resolution, a financial plan three years out at monthly resolution, and a long-range plan ten years out at annual resolution. Each plan carries an energy figure beside its production figure, which is the electricity its fields will need. The fields both buy power and generate their own, and the balance between the two is a capital decision.
Those energy figures had no model behind them, and the data to build one had never been put in one place. Consumption was metered daily per frontier, the point where energy is metered, in one file per month. Autogeneration was daily in a different layout. Production came in three incompatible layouts across three overlapping sources. Water was reported monthly while everything else was daily. Nothing maintained the correspondence between the frontiers that meter energy and the units that own the fields, and thirty frontiers had no field assigned at all.
The energy warehouse was the intended source, and on inspection it was incomplete and out of date. The first job was therefore to reconcile six years of raw monthly files into one daily panel per operating unit.
Forecasting energy from its own history would mean rolling a model's past forward for up to ten years. Every plan already states the production volumes it assumes, so the question was: can one set of models, given only the production volumes a plan states, forecast the energy each operating unit will need at all three planning horizons, and with how much error?
sec 02 · approach
What I built
We answered the question with a static regression per operating unit. For a unit on a given day, energy is modelled as a function of that day's production (crude, gas, light hydrocarbons and water) and two calendar terms. The model has no lagged energy terms. Every planning document already states the production volumes it assumes, so a plan supplies the model's inputs directly and the model never has to roll its own past forward. The horizon is set by the input table, and one set of fitted models serves all three plans.
This design assumes that each unit's mapping from production to energy is stationary across the window, because there is no autoregressive term to absorb a change. Where the mapping changed, for example when a frontier moved between units or a plant came online, the model can represent the break only through whatever the production variables carry.
Each unit gets two models, because the plans disagree about water. The operating plan carries no water column. The other two plans do, and water turned out to carry much of the signal. Four feature sets × three algorithms give twelve candidates per unit, selected on test MAE. We kept the best model that uses water (the water model) and the best model that does not (the no-water model). Each ships beside its own fitted preprocessing pipeline, so inference applies the same transformations that training fitted.
sec 03 · method
Method
01
Source reconciliation
This stage produces the target, which is one daily energy series per operating unit. The sources are eleven files covering 2018–2024, and energy arrives in them twice, as consumption and as autogeneration. Consumption is one file per month per frontier: rows carrying an internal ID are the reactive matrix and are dropped, and where a type column exists only active energy is kept. Frontiers are filtered to production, which excludes transport and refining. Autogeneration is concatenated across years and filtered to generating frontiers. Both are mapped to operating units through a correspondence table built for the purpose, because frontier, field and unit names disagree across sources and thirty frontiers carry no field. The unit is therefore the only level at which everything joins, and that is why the models are fitted per unit. Three units meter autogeneration and no purchased power.
energy[u,t] = Σ consumption[f,t] over production frontiers f → u + Σ autogen[g,t] over generating frontiers g → u # consumption: drop reactive-matrix rows; keep type = ACTIVA# dates normalised to %d/%m/%Y, then month → year → all02
Unit conversion and alignment
This stage produces the inputs, which are daily production and water per unit, and joins them to the energy series. Production arrives in three layouts. The 2018–2021 daily files needed header normalisation only. The 2022–2024 gross files are in thousands of barrels of oil equivalent per day, so they are scaled by 1,000 and melted wide-to-long. Where the gross files and the consolidated 2020–2024 file overlap, they disagree, and we took the row-wise maximum. Water is monthly, so each month's volume is spread uniformly across its days and converted from cubic metres to barrels. The result is a stepped daily water series. The step comes from the source's monthly granularity and says nothing about the field. The joined panel of water, production and energy by unit and date goes on to outlier removal.
gross[KBPE/D] × 1000 → BPE/Dprod[u,t] = max(gross[u,t], consolidated[u,t])water[u,t] = water_month[u,m] / days(m) × 6.289 # m³ → bblpanel = water ⋈ production ⋈ energy on (unit, date)03
Outlier removal and interpolation
This stage removes the readings that are reporting errors, and it applies identical treatment in training and inference because it is built as two custom scikit-learn transformers. The first computes a mean and standard deviation per unit per quarter per variable and nulls anything beyond three standard deviations. The window is quarterly because a six-year series with real regime changes would have whole true periods flagged under a global window. For energy it also nulls exact zeros, since a metered zero is a reporting gap and does not mean a day without power. The second reindexes each unit-quarter onto a continuous daily range and interpolates on the time index. Energy and light hydrocarbons needed the most correction. One unit's energy series had roughly 19.5% of its records replaced, against roughly 5% everywhere else.
q = quarter(t)flag(x) = |x − μ[u,q,v]| > n·σ[u,q,v] n = 3 ∨ (v = energy ∧ x = 0)x ← NaN where flag; reindex(u,q) → daily; interpolate(method="time")04
Features, candidates and selection
This stage selects the two models each unit ships. Each unit has four feature sets: water present or absent, crossed with a cyclical day-of-year encoding present or absent. The encoding maps the calendar onto a circle so that 31 December and 1 January are neighbours, where a plain day count would put them 364 units apart. Three algorithms run over each feature set: ordinary least squares, random forest and gradient-boosted trees. That is twelve candidates per unit and 120 in all, scored on a held-out test split. The lowest test MAE wins, separately for the water and no-water families, which gives 20 shipped models and 20 shipped pipelines. Every selected water model is a tree ensemble on the full water-plus-calendar feature set.
x[u,t] = [crude, gas, whites, (water), (sin 2π·d/365, cos 2π·d/365)]E[u,t] ≈ f_u(x[u,t]) # no lagged E: static regression F = {±water} × {±calendar} A = {OLS, RF, XGB}f*[u,water] = argmin MAE_test over F_water × Af*[u,nowater] = argmin MAE_test over F_nowater × A05
Evaluation
This stage defines the error the answer is stated in. Each candidate gets four metrics on train and test: MAE for selection, MAPE for comparison across units whose energy differs by two orders of magnitude, and R² and RMSE for fit. Models were fit and scored daily. The monthly figures are the same daily predictions summed by month and unit and then rescored, so no separate monthly model was fit.
MAE = 1/n Σ |y − ŷ|MAPE = 100/n Σ |y − ŷ| / yRMSE = √(1/n Σ (y − ŷ)²)R² = 1 − Σ(y − ŷ)² / Σ(y − ȳ)² monthly: ŷ[m] = Σ_{t∈m} ŷ[t], then rescore06
Horizon-specific inference
This stage applies the selected models to each plan, and only the input table changes between horizons. Under a year, the models predict monthly from the operating plan, using the no-water models with water opt-in per unit where the plan supplies it. From one to three years, they predict monthly from the financial plan, using the water models. At ten years, they predict annually from the long-range plan. We tested per-project estimation for that plan and abandoned it, because individual project volumes sit far below anything in the training data and a tree ensemble cannot extrapolate outside the range it was fitted on. The unit is predicted whole instead, and its energy is apportioned to projects by production share, weighted by each variable's importance in the unit's model. The shares sum to one by construction.
share[p] = Σ_v w[v] · pct[v,p] v ∈ {crude, whites, gas, water}Σ_v w[v] = 1, Σ_p pct[v,p] = 1 ⇒ Σ_p share[p] = 1E[p] = share[p] · Ê[u]07
Delivery and retraining
This stage puts the forecast in the planners' hands and leaves the client able to retrain. A web tool ingests Excel or CSV, validates it, and returns two formats. The first is the input with a predicted-kWh column appended. The second is a planning-tool export at vice-presidency level in megawatts, carrying medium, high and low scenarios, where high and low are the prediction plus and minus one standard deviation of that unit's training data. Retraining stays in three notebooks (preprocessing, per-unit training and best-model selection). Each serialises models, pipelines and metrics, so the team can inspect the charts behind a selection before accepting it.
reject rows ≤ 1 | populated < 50% | duplicate column namesrequire FECHA, GERENCIA, CRUDO, GAS, BLANCOS (+ water, field, project)reject NaN | negative after group-by unit | non-numeric | date ≠ yyyy-mm-ddhorizon 1–11 consecutive months | 12–120 months | ≥ 10 consecutive years scenario high, low = ŷ ± σ_u(train)
sec 04 · legend
Instruments
legend · modelling
legend · preprocessing
legend · evaluation
legend · platform
legend · delivery
sec 05 · readings
Results
Models trained
120
10 units × 4 feature sets × 3 algorithms
Models shipped
20
2 per unit · with and without water
Monthly MAPE, with water
0.18 – 1.76 %
10 of 10 units under 2 %
Monthly MAPE, without water
0.64 – 25.51 %
9 of 10 units under 2.4 %
Daily test MAPE, with water
1.30 – 14.67 %
8 of 10 units under 5 %
Daily test MAPE, without water
1.70 – 41.21 %
6 of 10 units under 5 %
Test ÷ train error, with water
≈ 2.7× median
range 1.5× – 48× · 10 units, daily MAPE
Monthly R², with / without water
0.56 – 1.00 / 0.60 – 1.00
9 of 10 at 0.96 or above on both
Selected family
RF 6 · XGB 4 · OLS 0
10 water models, lowest test MAE
plate 01
Dropping water costs little in points and a lot in ratio
BARITE
BASALT
GALENA
GYPSUM
JASPER
OLIVINE
PYRITE
QUARTZ
RUTILE
ZIRCON
Monthly MAPE per unit for the selected water model and the selected no-water model, the two models the tool ships. The plate measures what the operating plan loses by stating no water. Eight units lose under one percentage point, which is what makes the short-horizon plan usable. The median unit's error still rises about 2.5×, and one unit's rises from 1.75% to 25.51%, because water is the only variable that carries its regime change.
source
Selected models, daily predictions summed by month and rescored. The axis stops at 3 to keep nine rows legible; the value past it is pinned and printed. Unit names are pseudonyms; the figures are the real ones.
plate 02
Test error against train error, and the one model that memorised
BARITE
BASALT
GALENA
GYPSUM
JASPER
OLIVINE
PYRITE
QUARTZ
RUTILE
ZIRCON
Daily MAPE for each selected water model on the test split against the days it was fit on. The plate measures how far the reported error is from the fitted error. The test error runs a median 2.7× the train error, which is ordinary for tree ensembles. One unit reads 0.07% on train and 3.38% on test, a 48× gap: its boosted model nearly reproduces its training set, and only the test figure is its real error.
source
Selected water models, daily resolution. Test is the solid mark and is named first because it is the result; train is there to measure the gap. The split scheme is not stated in the source, so this gap is a lower bound (see the notes).
plate 03
The cost of dropping water is larger at daily resolution
BARITE
BASALT
GALENA
GYPSUM
JASPER
OLIVINE
PYRITE
QUARTZ
RUTILE
ZIRCON
The same water comparison, scored at the resolution the models were fit at: daily, on the test split. Monthly sums let daily errors cancel, so the cost of dropping water is larger here. Only four units stay within one point, and GALENA nearly doubles from 5.16% to 9.45%. This plate measures the models, and plate 01 measures what the tool delivers.
source
Test split only, selected models. The source's prose says the increase is under one point for most units; its own chart shows four of ten. The chart is used.
plate 04
Nine units are explained; one is not, with or without water
BARITE
BASALT
GALENA
GYPSUM
JASPER
OLIVINE
PYRITE
QUARTZ
RUTILE
ZIRCON
Monthly R² for the same two models per unit: the share of each unit's monthly energy variation the features account for. Nine units sit at 0.96 or above either way. PYRITE sits at 0.56 and 0.60, and water barely moves it, so water is not the missing driver. It also has the lowest daily error on the sheet, which shows that a model can track a level closely without explaining why it moves.
source
Selected models, monthly aggregation as plate 01. Daily R² is not plated: the source's prose and chart name different units, and one chart label is unreadable.
plate 05
The selected model for each unit
| unit | algorithm | features | test MAPE % | test ÷ train |
|---|---|---|---|---|
| BARITE | XGBoost | water + calendar | 2.73 | 2.4× |
| BASALT | Random forest | water + calendar | 2.19 | 5.1× |
| GALENA | Random forest | water + calendar | 5.16 | 3.1× |
| GYPSUM | Random forest | water + calendar | 2.19 | 2.4× |
| JASPER | XGBoost | water + calendar | 3.38 | 48× |
| OLIVINE | XGBoost | water + calendar | 3.97 | 3.2× |
| PYRITE | Random forest | water + calendar | 1.30 | 2.6× |
| QUARTZ | XGBoost | water + calendar | 4.32 | 1.5× |
| RUTILE | Random forest | water + calendar | 14.67 | 2.7× |
| ZIRCON | Random forest | water + calendar | 3.24 | 2.8× |
The selected water model for each unit, chosen from 12 candidates. Every winner is a tree ensemble on the full feature set. OLS won nowhere, and no feature set without both water and the calendar terms won anywhere. The right-hand columns repeat plate 02 as text.
source
Algorithm and feature set read from each best-model chart's title in the source. The no-water winners are not titled there, so they are not listed.
sec 07 · findings
What the data said
finding · result
At monthly resolution the models are accurate for every unit
One set of models forecasts the energy of every operating unit at the resolution the plans use. With water, every unit's monthly error sits between 0.18% and 1.76%, and nine of ten monthly R² values are 0.97 or above. The monthly figures are lower than the daily ones because daily over- and under-predictions cancel inside a month. The daily test figures, 1.30–14.67%, measure the models, and the monthly figures measure what the tool delivers. The plans are monthly and annual documents, so the monthly figure is the one the client uses.
finding · result
Dropping water costs little in points and a lot in ratio
Dropping water costs eight of ten units under one percentage point of monthly error. That is what makes the short horizon usable, since the operating plan states no water. In relative terms the cost is larger: the median unit's monthly error rises about 2.5×. At daily resolution on the test split, only four of ten units stay within one point, and GALENA goes from 5.16% to 9.45%.
finding · result
Tree ensembles won every unit and the linear baseline won none
All ten selected water models are tree ensembles on the full water-plus-calendar feature set: random forest for six units, XGBoost for four. OLS won nowhere. This is consistent with a relationship between energy and production that is non-linear and depends on regime: a single slope per variable cannot represent a unit whose load steps when a plant comes online. The choice has a cost. Trees do not extrapolate, which is why per-project estimation on the ten-year plan failed.
finding · negative result
One unit's energy changed regime, and only water carries the change
RUTILE is the worst unit on every error plate: 1.75% monthly with water and 25.51% without, and 14.67% daily test with water and 41.21% without. Its energy runs between roughly 0.4 and 2.15 million kWh a day from 2019 into 2021, then falls in two steps to a flat ~0.07–0.1 million by late 2021. The report attributes the fall to its energy frontiers being redistributed to other units. That makes it a problem in the data model, and the regression cannot correct it. Two technical readings follow. First, the no-water model does not fit even its training data: train error is 32.29%, so the failure is underfitting. Second, MAPE weighs a level collapse heavily. An error that is 1% at 1.5 million kWh is about 20% at 0.07 million, so the post-break years dominate the percentage however well the model tracks them in kWh.
finding · negative result
One unit's model memorised its training set
JASPER's water model has memorised its training set: it scores 0.07% daily error on train and 3.38% on test, a 48× gap. Every other unit sits between 1.5× and 5.1×. When a boosted ensemble nearly reproduces its training set, the train figure carries no information, so the test figure is the unit's real error. Selection was on test MAE, which kept the train figure from being reported as the result. The source records no depth or regularisation settings.
finding · negative result
One unit's energy is not explained by its production
PYRITE's energy is poorly explained by its inputs: monthly R² is 0.56 with water and 0.60 without, the only unit below 0.96 on either. Water barely moves the figure, so water is not the missing driver. The same unit has the lowest daily test error on the sheet, 1.30%. Both figures can hold because MAPE is scaled by the level and R² by the variance. A unit whose monthly totals barely move has little variance for R² to explain, and a small persistent bias consumes much of it while staying tiny as a percentage. This mechanism is consistent with the figures, and the source does not confirm it.
finding · negative result
The long-horizon allocation was validated and is not in the tool
The ten-year plan is answered at unit level only. The importance-weighted share that apportions a unit's predicted energy to individual projects was validated in analysis. At the close of the MVP it had not been integrated into the tool, so the delivered product runs the ten-year path at unit level.
finding · negative result
The dispatch-level output could not be built
Two of the three designed output formats shipped. The third distributes demand to individual electrical nodes, which requires a field-to-node correspondence. The most recent correspondence file covers 39 fields against 103 in the training data. Most fields could not be mapped, so we deferred the format instead of shipping it partially populated.
finding · negative result
Sequence models were dropped before any was trained
No sequence model was trained. The engagement opened intending recurrent forecasting over the energy history. That plan was dropped on the finding that no unified, regularly updated base integrating production and energy existed to train one on. The work was re-planned around supervised regression that tolerates fragmented, uneven data. The report names building that base as the prerequisite for any advanced method later.
finding · negative result
The warehouse was unusable, so the raw files became the source
The energy data warehouse was the intended source and was rejected on inspection as incomplete and out of date. Six years of per-month raw frontier files were parsed instead, which is most of the first two method stages and most of the engagement's risk.
sec 08 · forward
Recommendations
01
Consolidate the dispersed sources into one maintained base. The report names this as the prerequisite for sequence models, which were dropped for lack of it. It would also reduce the first two method stages from most of the engagement to an ingestion step.
02
Re-split on time. The split behind every test figure is not stated (see the limits below). A forward-chaining split (train on everything before a cutoff, test after it) is the only test that matches how the tool is used, which is to predict dates it has not seen. It would also show whether the test figures on this page survive it.
03
Replace the ±1σ scenarios with prediction intervals. The high and low scenarios describe the spread of the training target (see the limits below). Quantile regression forests or per-unit residual quantiles give a high and low that mean “90% of days fall inside”, which a planner can act on.
04
Re-map the unit whose frontiers moved. RUTILE's regime change is an artifact of the correspondence table, so the fix is in the table, and retraining alone will not remove it.
05
Constrain the memorising model. Cap depth or raise the minimum leaf size on JASPER's ensemble until its train and test errors are on the same order.
06
Extend the field-to-node correspondence past 39 of 103 fields, which is what the deferred dispatch-level output waits on, and finish wiring the long-horizon allocation into the tool.
sec 09 · notes
Notes
disclosure
The client is described by category and never named. The ten operating units on this page are pseudonyms. Their real internal codes and names, the field names, the individuals, the internal systems and the document locations do not appear here in any form. They were dropped, with no pseudonym standing in for them. Every quantitative figure (unit counts, model counts, spans, error and fit) is the real one from the engagement, unchanged.
limits
- The train/test split scheme is not stated. The report says a split was made and does not say how. If it was a random split over days and not a temporal one, each test day has training neighbours on both sides. For a series this autocorrelated, that lowers every test figure on this page, and plate 02's gap is a lower bound on the real one.
- Models were fit at daily resolution only. The monthly figures are daily predictions aggregated by month and unit. No monthly model was fit, and the report says a re-split was not viable without retraining. The monthly figures inherit the daily models' behaviour and are not independent of them.
- The high and low scenarios are ±1 standard deviation of the unit's training target. They describe how much the unit's energy moves and say nothing about how wrong the forecast is likely to be.
- Outlier rates per unit are described and never charted, because the source figure carries no data labels and the values could only be recovered by measuring pixels.
- The report's prose disagrees with its own figures in four places: a daily error digit, a count of units under 5%, how many units lose under a point without water, and which units fall below R² 0.9. The figures were taken as authoritative. Daily R² is omitted entirely, because that disagreement is the one no third source can settle.
- The long-horizon project allocation and the dispatch-level output were not delivered in the tool.
- Every energy series drops to zero at the right-hand edge. That is the data cutoff, and the zero-as-outlier rule excluded it from training.
- The engagement delivered an MVP. Nothing here is a claim about the system in sustained production.