CCUS-Injection-MRV
Monitoring, Reporting and Verification (MRV) calculations for a CO2 injection well: a real, documented equation of state for CO2 density, a real cumulative-mass balance with Monte Carlo uncertainty, and a real, explainable statistical leak/anomaly detector (CUSUM) -- built and tested end to end on synthetic wellhead sensor data.
Why this exists
Large-scale carbon capture, utilization and storage (CCUS) projects -- capturing CO2 from industrial sources and injecting it for permanent geological storage -- are a real, fast-growing, and publicly documented capital investment area across the oil & gas and industrial-emissions sector. Any CO2 injection project needs an MRV (Monitoring, Reporting and Verification) layer for two reasons that are both, fundamentally, engineering problems rather than paperwork:
- Mass accounting: regulators and storage-verification frameworks (e.g. the frameworks referenced by 45Q-style tax credit regimes, EU ETS monitoring, or ISO 27916 for CO2-EOR) require the operator to report the mass of CO2 actually stored, not just a volumetric flow-meter reading. Converting one to the other requires knowing the CO2 density at actual downhole/wellhead pressure and temperature -- and CO2 in an injection well is in a dense supercritical or liquid-like state, not the everyday gas most intuitions are built around, so this conversion is not a trivial unit conversion.
- Containment assurance: a storage site's entire value proposition rests on the CO2 staying where it's put. Wellhead pressure and injection-rate telemetry are the first, cheapest signal available for a developing well-integrity problem (tubing/casing leak, seal degradation), long before any surface or downhole environmental monitoring would catch it -- provided there's a statistically sound way to tell "this deviates from expected behaviour" apart from ordinary process noise.
This project implements both pieces honestly and end to end: a real (if intentionally simplified and clearly qualified) equation of state, a real statistical change-point detector, and a real synthetic-data test harness that measures its own performance rather than asserting it. It stays deliberately general about any specific operator or facility that isn't public and independently verifiable -- see "Honest scope" below.
Why this matters across industries
CCUS is not a niche or speculative technology -- it is a real, fast-growing segment of the energy transition, with regulatory MRV obligations (IPCC guidance on CCUS monitoring and verification, ISO 27916 for CO2-EOR, and jurisdiction-specific frameworks such as 45Q-style tax credit regimes or EU ETS monitoring) already in force wherever CO2 is captured and injected for storage. Any organization operating that kind of injection infrastructure -- across oil & gas, industrial-emissions, or power-generation carbon capture -- needs the same two capabilities this project builds: turning a flow-meter reading into a defensible mass figure via real equation-of-state thermodynamics, and telling a genuine well-integrity problem apart from ordinary process noise via statistically sound anomaly detection. Both skills transfer directly beyond CCUS: equation-of-state thermodynamics and Monte Carlo uncertainty propagation are the same toolkit used for risk and pricing models in quantitative finance, and the CUSUM-based, fully explainable detection approach (every alert traces back to a named statistical rule, not an opaque score) is exactly the kind of auditable monitoring-and-verification tooling that regulated-industry consulting engagements need, in CCUS or any other closely regulated industrial process.
flowchart LR
S[simulator: synthetic wellhead sensors] --> M[mass_balance: EOS density x flow rate]
S --> A[anomaly: CUSUM vs injectivity model]
M --> U["Monte Carlo uncertainty (cumulative mass)"]
A --> D["Alerts + precision/recall vs ground truth"]
M --> API[FastAPI service]
A --> API
What it actually does
1. CO2 density -- Peng-Robinson equation of state (ccus_mrv/eos.py)
CO2 at typical injection conditions (roughly 8-20 MPa, 30-60 C) is a dense supercritical or liquid-like fluid, not an ideal gas -- using the ideal gas law here would understate the injected mass by roughly two orders of magnitude. This project implements the Peng-Robinson (1976) cubic equation of state, the standard textbook real-gas EOS for exactly this kind of calculation, solved via its companion-matrix eigenvalues (mathematically identical to solving the cubic directly, just batchable -- see below).
On top of plain Peng-Robinson, a single Peneloux-style constant volume shift (Peneloux, Rauzy & Freze, 1982) is calibrated against one reference density point computed with CoolProp's Span & Wagner (1996) backend -- the same reference-quality multiparameter EOS behind NIST REFPROP. This is a well-known, simple correction for cubic EOS's tendency to under-predict liquid/dense-phase density; it does not change the model's vapor-liquid equilibrium behaviour.
This is explicitly NOT a reference-quality EOS. Accuracy was measured (not assumed) against 6 independent CoolProp reference points spanning the operating envelope this project cares about (scripts/calibrate_eos.py, reproducible):
| Condition |
CoolProp reference density |
Plain Peng-Robinson error |
+ calibrated volume shift error |
| 12.0 MPa / 35.0 C (calibration point) |
767.072 kg/m3 |
-5.70% |
0.00% |
| 10.0 MPa / 40.0 C (near critical point, Tr=1.01, Pr=1.36 -- hardest case) |
628.612 kg/m3 |
-10.33% |
-6.16% |
| 10.0 MPa / 50.0 C |
384.327 kg/m3 |
-2.34% |
+0.64% |
| 15.0 MPa / 50.0 C |
699.753 kg/m3 |
-6.23% |
-1.11% |
| 8.0 MPa / 20.0 C (dense/liquid-like) |
827.713 kg/m3 |
-4.92% |
+1.37% |
| 0.101 MPa / 15.0 C (near-atmospheric sanity check) |
1.872 kg/m3 |
+0.05% |
+0.07% |
Read this honestly: away from the critical point, the calibrated model is accurate to roughly 1-1.5%; close to the critical point (CO2's critical point is 304.13 K / 7.3773 MPa) any cubic EOS is known to degrade, and here that shows up as a measured ~6% error. Real CCS operations deliberately inject well clear of the critical region for exactly this kind of reason (among others -- near-critical fluid behaviour is also operationally awkward, with large property swings for small P/T changes). CoolProp itself is used only offline, as a validation/calibration tool (pip install ccus-mrv[validation]) -- it is not a runtime dependency of the shipped package.
2. Mass balance with Monte Carlo uncertainty (ccus_mrv/mass_balance.py)
mass_flow_rate(t) = density(P(t), T(t)) * volumetric_flow_rate(t)
cumulative_mass = trapezoidal_integral(mass_flow_rate, timestamps) # scipy.integrate
Measurement uncertainty is propagated to the cumulative mass figure via a Monte Carlo method: each Monte Carlo draw perturbs the pressure, temperature and flow-rate series by a randomly sampled sensor bias (default: correlated across the whole series, i.e. one random calibration-error draw per Monte Carlo sample -- this models systematic instrument bias/drift, which dominates real-world uncertainty over a multi-day campaign far more than high-frequency noise that mostly averages out of a cumulative integral). The 1-sigma sensor uncertainties default to a flow meter at 2% of reading, a pressure transducer at 5 kPa, and an RTD at 0.3 K -- all realistic mid-range industrial-instrumentation figures, adjustable per call.
3. CUSUM leak / anomaly detection (ccus_mrv/anomaly.py)
A first-order injectivity model (expected wellhead pressure as a linear function of injection rate, P = a + b*Q, in the spirit of a real injection-well "Hall plot") is fit on a known-normal baseline period. A two-sided tabular CUSUM (Page, 1954 -- the standard statistical-process-control change-point method, also widely used in pipeline leak detection) then accumulates the standardized residual between measured and expected pressure, and raises an alarm when the cumulative deviation exceeds a threshold h (in residual-sigma units), with a slack k filtering ordinary process noise. Every alarm is explainable: it traces back to "the standardized residual has been persistently k-sigma off the expected model for long enough to accumulate past h" -- not an opaque ML score. k=0.5, h=5.0 are the defaults used throughout this project (standard SPC defaults, Montgomery's Introduction to Statistical Process Control).
4. Synthetic sensor simulator (ccus_mrv/simulator.py)
Generates a labeled wellhead time series (flow rate, pressure, temperature) for a "normal" scenario and a "leak" scenario. The leak scenario models a developing wellbore integrity loss as a progressively ramping wellhead-pressure deficit (fluid escaping upstream of the target formation means less backpressure is needed to sustain the same measured surface injection rate) -- this is a deliberately simple, illustrative model, not a validated wellbore/reservoir simulation. Every generated series carries a ground-truth per-timestamp anomaly label for precision/recall evaluation.
Measured detection results (not hand-picked)
Running ccus-mrv demo (seed=42, the project's default) end to end on this machine:
[mass balance] 48.0 h synthetic normal injection (2.00 days)
cumulative CO2 injected (trapezoidal integral): 3,792,062.6 kg (3,792.063 t)
Monte Carlo uncertainty (1000 samples, correlated-bias sensor model): mean=3,792,150.5 kg, std=80,659.9 kg (+/-2.13%), 90% interval=[3,660,979.2, 3,923,148.7] kg
[anomaly detection] CUSUM (k=0.5 sigma, h=5.0 sigma) on labeled leak scenario
injectivity model fit on first 230 baseline samples: P = 9.9096 MPa + 3.608e+07 Pa/(m3/s) * Q, residual std = 161.23 kPa
true leak onset: t = 24.00 h
false alarms BEFORE leak onset: 2 (first at t = 5.25 h)
first alarm AT/AFTER leak onset: t = 24.83 h (detection delay = +0.83 h)
precision = 0.993, recall = 0.965, false positive rate = 0.0069
confusion: TP=279 FP=2 FN=10 TN=286
Broader, non-cherry-picked sweep across 10 independent random seeds (scripts/run_detector_sweep.py, reproducible -- these are exactly the numbers tests/test_anomaly.py's per-seed assertions are set against, with margin):
|
precision |
recall |
detection delay |
| leak scenarios, 10 seeds |
0.979 - 1.000 |
0.969 - 0.993 |
10 - 45 minutes after leak onset |
|
false-positive rate on pure-normal (no leak) 96h series, 10 seeds |
| range |
0.0% - 4.9% (mean 1.4%, median 0.7%) |
| alarm episodes (contiguous runs, not scattered points) |
0 - 10 per 96h series |
Read the false-positive numbers honestly too: CUSUM false alarms cluster into a handful of distinct episodes rather than being uniformly scattered, and the rate varies noticeably by random seed (i.e. by which particular noise realization the baseline injectivity model happened to be fit on) -- this is a real property of the method on this synthetic data, not a single cherry-picked good run.
Try it
pip install -e ".[dev]"
pytest # 53 tests, ~15-30s on this machine (shared VM, variable load)
ccus-mrv density --pressure-pa 12000000 --temperature-k 308.15
ccus-mrv demo --duration-hours 48 --mc-samples 1000
ccus-mrv serve # FastAPI on http://localhost:8000 (docs at /docs)
Or with Docker:
docker build -t ccus-injection-mrv .
docker run --rm ccus-injection-mrv # runs the demo
docker run --rm -p 8000:8000 ccus-injection-mrv serve --host 0.0.0.0 # API
Docker -- what was actually tested, honestly
docker build was genuinely attempted on the machine this project was built on -- not assumed to work. It failed, with this exact error:
WARNING: Retrying ... SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED]
certificate verify failed: self-signed certificate in certificate chain (_ssl.c:1010)')): /simple/setuptools/
...
Could not fetch URL https://pypi.org/simple/pip/: ... self-signed certificate in certificate chain
ERROR: No matching distribution found for setuptools>=68
This development machine transparently intercepts TLS inside Docker containers (a corporate-proxy-style setup whose root CA is trusted by the host OS but not injected into container images) -- the same documented issue affecting other projects in this portfolio (e.g. CLOUD-NATIVE-OBSERVABILITY-INCIDENT-DIAGNOSIS-PLATFORM, MLOPS-Platform, FRAUD-DECISION-ENGINE). It is an environment limitation, not a Dockerfile bug, and here is the evidence for that distinction rather than just an assertion of it: rebuilding the exact same Dockerfile with pip's certificate validation temporarily disabled for PyPI's hosts (--trusted-host, diagnostic-only, not present in the shipped Dockerfile) completed successfully in 56s, and the resulting container ran correctly:
$ docker run --rm ccus-injection-mrv:diag density --pressure-pa 12000000 --temperature-k 308.15
P = 12.0000 MPa, T = 308.15 K (35.00 C)
Tr = 1.0132, Pr = 1.6266 -> phase: supercritical
Z (compressibility factor) = 0.284975
density = 767.066 kg/m3
$ docker run --rm ccus-injection-mrv:diag demo --duration-hours 12 --mc-samples 200
[mass balance] 12.0 h synthetic normal injection (0.50 days)
cumulative CO2 injected (trapezoidal integral): 961,195.2 kg (961.195 t)
...
[anomaly detection] ... precision = 1.000, recall = 0.890, false positive rate = 0.0000
i.e. the container genuinely builds and runs the real CLI with correct output once the network layer isn't intercepting TLS -- confirming the Dockerfile itself is correct. The --trusted-host workaround is deliberately not shipped in the committed Dockerfile: baking a blanket TLS-verification bypass into a published image would be a bad default for anyone building it from a normal network with no interception. Instead, the committed Dockerfile is verified in CI's docker job, which runs on GitHub-hosted runners with normal, unintercepted internet access -- see the CI badge at the top of this README for its current status.
This was confirmed, not just planned: after pushing, the docker CI job ran docker build on the exact, unmodified, committed Dockerfile plus a real docker run