diff --git a/.env.example b/.env.example index 6e16b4dd..60ca5cad 100644 --- a/.env.example +++ b/.env.example @@ -35,6 +35,10 @@ FRONTEND_MAX_OLD_SPACE=4096 # Public base URL of the app (optional; e.g. https://qpp.example.com) PUBLIC_URL= +# Cloudflare Named Tunnel token (optional; from Cloudflare Zero Trust -> Networks -> Tunnels). +# Leave blank to use a free temporary *.trycloudflare.com Quick Tunnel instead. +CF_TUNNEL_TOKEN= + # ---- User Access Management (UAM) & Authentication ---- QPP_AUTH_SECRET_KEY=change_this_uam_secret_key QPP_ADMIN_USERNAME=admin diff --git a/.gitignore b/.gitignore index ef2502d3..52e400f5 100644 --- a/.gitignore +++ b/.gitignore @@ -128,3 +128,6 @@ chainlit* docs/tutorials/*.ipynb quick_pp/app/backend/static/reports/* + +# Cloudflare CLI local cache +.cloudflare/ diff --git a/CITATION.cff b/CITATION.cff index a20c4a5b..ded91979 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -15,8 +15,8 @@ authors: email: "imranfadhil@gmail.com" repository-code: "https://github.com/imranfadhil/quick_pp" url: "https://quick-pp.readthedocs.io" -version: 0.3.7 -date-released: "2026-11-22" +version: 0.3.8 +date-released: "2026-11-27" license: MIT keywords: - petrophysics @@ -44,4 +44,4 @@ preferred-citation: orcid: "https://orcid.org/0000-0001-9392-8083" year: 2026 url: "https://github.com/imranfadhil/quick_pp" - version: 0.3.7 + version: 0.3.8 diff --git a/README.md b/README.md index a64371ed..29d73039 100644 --- a/README.md +++ b/README.md @@ -6,32 +6,32 @@ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -Comprehensive Python library and full-stack web platform for deterministic and probabilistic petrophysical evaluation, Special Core Analysis (SCAL) & relative permeability modeling, multi-well Free Water Level (FWL) contact optimization, stratigraphic log normalization, core-log calibration & depth matching, automated FDP report generation, petrophysical handover packaging, rock physics, and static-to-dynamic geomodeling upscaling. +Comprehensive Python library and full-stack web platform for deterministic and probabilistic petrophysical evaluation, unified borehole environmental & radial invasion QC, Special Core Analysis (SCAL) & relative permeability modeling, multi-well Free Water Level (FWL) & Formation Pressure Testing (FPT) contact analysis, stratigraphic log normalization, source-rock TOC geochemistry, core-log calibration & depth matching, automated CPI/FDP report generation with subsurface gate checks, bi-directional petrophysical handover packaging, rock physics, and static-to-dynamic geomodeling upscaling. This repository contains the core `quick_pp` scientific Python package, the FastAPI backend (`quick_pp/app/backend`), and the SvelteKit interactive workstation frontend (`quick_pp/app/frontend`), plus MLflow-integrated machine learning pipelines (`quick_pp/machine_learning`). ## Core Capabilities -- **Multi-Mineral, Clastic & Thomas-Stieber Petrophysics** (`quick_pp.lithology`, `quick_pp.porosity`, `quick_pp.saturation`, `quick_pp.permeability`): - Sand-Silt-Clay (modified Kuttan), Carbonate, multi-mineral inversion solver, and **Thomas-Stieber** laminated sand-shale evaluation (`VSH_LAM`, `VSH_DISP`, `VSH_STR`, `PHIT_TS`, `PHIE_TS`, `PHISAND_TS`) with Simandoux, Indonesian, Dual-Water, Waxman-Smits, Juhasz, and Archie saturation models. -- **Multi-Well Contact, Swirr & Formation Pressure Testing (FPT)** (`quick_pp.saturation`, `quick_pp.fluid_type`, `MultiWellFpt.svelte`, `MultiWellSwirr.svelte`): - Simultaneous multi-well Free Water Level (FWL), Oil-Water Contact (OWC), and Top of Transition Zone (TTZ) solver reconciling resistivity-derived $S_w$, capillary pressure Saturation-Height Models ($S_{w,\text{SHM}}$ via Leverett-$J$, Skelt-Harrison, and Cuddy), multi-well irreducible water saturation (`Swirr` via RQI, Semi-log $k$, and Timur models), and wireline formation tester (MDT/RFT) pressure gradient regression (`FormationPressureAnalyzer` with OLS/Huber/RANSAC, automatic mobility/supercharge flagging, in-situ fluid density, excess pressure, and Monte Carlo P10/P50/P90 GOC/OWC/GWC contact intersections). -- **Rock Typing & Supervised Rock Flag Classification** (`quick_pp.rock_type`, `MultiWellRockTyping.svelte`, `InspectorRockTyping.svelte`): - Hydraulic Flow Unit (`FZI`, `RQI`, `GHE`), Winland $R_{35}$, and Pittman pore-throat rock typing, vuggy/fracture carbonate secondary porosity (`VDL`), and standalone multi-well `RandomForestClassifier` rock-type training, cross-validation, and uncored well inference (`train_and_validate_rock_type_classifier`, `predict_with_saved_rt_classifier`) using raw logs and calculated petrophysical curves (`PHIT`, `VSAND`, `VSHALE`, `VSILT`, `VCLAY`, `VDL`). -- **Special Core Analysis (SCAL), Core Calibration & Depth Matching** (`quick_pp.scal`, `quick_pp.core_analysis`, `CoreDepthShiftPanel.svelte`, `CrossplotCanvas.svelte`): - Laboratory-to-reservoir core plug corrections (hydrostatic/uniaxial overburden compaction, Klinkenberg gas slippage, and Dean-Stark clay-bound water reconciliation preserving raw `CPORE_AMB` and `CPERM_AIR` lineage), interactive core-to-log depth matching with piecewise linear shift tables (`anchors` -> `DEPTH_SHIFTED`) and cross-correlation Automatic Suggested Shift, 1:1 Estimation vs. Core Parity Crossplot (`PHIT` vs `CPORE`, `PERM` vs `CPERM` with RMSE, MAE, $R^2$, Bias, and $\pm 0.5\text{–}1.0$ decade bounds), capillary pressure scaling, two-phase relative permeability models (**Corey**, **Brooks-Corey**, and **LET**), automated SCAL curve fitting (`fit_relperm`), and Eclipse/Intersect `SWOF` table generation (`generate_swof_table`). -- **Probabilistic Uncertainty & Monte Carlo Engine** (`quick_pp.uncertainty`): - Vectorized Latin Hypercube Sampling (`scipy.stats.qmc.LatinHypercube`) for volumetric hydrocarbon in-place uncertainty (`mc_volumetric_uncertainty`), log-level CPI uncertainty propagation (`run_log_uncertainty` producing `P10`/`P50`/`P90` curves), and stochastic reservoir summaries (`calc_stochastic_reservoir_summary`). -- **Log Blocking & Static-to-Dynamic Upscaling** (`quick_pp.upscaling`): - Petrophysically rigorous blocking (`upscale_logs`, `block_logs`) onto cellular geomodel grids with thickness-weighted arithmetic porosity/shale averaging, pore-volume weighted saturation averaging (preserving `BVHC`), directional & Cardwell-Parsons (1945) power-law permeability bounds ($k_h, k_{\text{eff}}, k_v, k_v/k_h$), and majority-vote facies upscaling. -- **Multi-Well QA/QC, Stratigraphic Normalization & Stick Plots** (`quick_pp.qaqc`, `MultiWellQaqc.svelte`, `StickPlotCanvas.svelte`): - Zone-by-zone multi-well quantile and histogram log normalization (`stratigraphic_normalization` / `normalize_by_zone`), borehole environmental and invasion corrections (`apply_environmental_corrections`), neutron-density hydrocarbon corrections, automated washout/bad-hole flagging (`badhole_flagging`), multi-well distribution & conditioning workflows, and interactive multi-well structural/stratigraphic Stick Plot cross-sections flattened on datum or formation tops. +- **Logging Environment, Borehole Corrections, Sensor Confidence & Radial Invasion** (`quick_pp.environment`, `quick_pp.borehole_corrections`, `quick_pp.qaqc`, `quick_pp.conditioning`, `InspectorQaqc.svelte`): + Depth-zoned **Hole Sections** (`BS`, mud system, mud weight, salinity, $R_{mf}$), onshore/offshore BHT-calibrated P&T profiles, generic `WL`/`LWD` borehole environmental corrections (`*_ENV_CORR` with spine-and-ribs `DRHO` double-compensation protection), perturbation-propagated per-sample uncertainty (`*_SIGMA`) and sensor confidence (`*_QC_CONF`), 2/3-curve step-profile radial invasion inversion ($R_t, R_{xo}, d_i$ & $R_{xo}/R_t$ vs. $R_{mf}/R_w$ movable-HC classification), 1D bounded Huber nuclear-log resolution harmonization (`GR_ENH`, `NPHI_ENH`, `RHOB_ENH`), missing-data imputation, and zone-by-zone stratigraphic quantile normalization. +- **Multi-Mineral, Clastic, Thin-Bed & Continuous $\rho_{fl}$ Petrophysics** (`quick_pp.lithology`, `quick_pp.porosity`, `quick_pp.saturation`, `quick_pp.permeability`): + Sand-Silt-Clay (modified Kuttan), Carbonate, selectable-log SLSQP multi-mineral solver, and **Thomas-Stieber** laminated/dispersed/structural thin-bed evaluation (`VSH_LAM`, `VSH_DIS`, `VSH_STR`, `PHIT_SAND`, `RSAND_TS`), 3-tier coupled apparent fluid-density ($\rho_{fl}$) solver, adaptive-shoulder coal detection with reversible interval manual overrides, empirical single-well permeability (`Choo`, `Kozeny-Carman`, `Timur`, `Tixier`, `Coates`), Simandoux / Indonesian / Dual-Water / Waxman-Smits / Juhasz / Archie saturation, water-leg $m$ calibration & continuous $m(\phi)$ (`Borai`, `Shell/Lucia`), and multi-criteria reservoir fluid typing (`GAS`, `OIL`, `UNCONFIRMED`, `WATER`). +- **Source Rock & Total Organic Carbon (TOC) Geochemistry** (`quick_pp.source_rock`, `InspectorToc.svelte`): + Passey et al. (1990) $\Delta\log R$ baseline separation across sonic, density, and neutron logs, automated lean-shale baseline detection, Hood et al. (1975) Level of Organic Metamorphism (`LOM`) maturity conversion from $R_o\,\%$, and core pyrolysis TOC calibration. +- **Rock Typing, Power-Law `PERM_TRANS` & Supervised Classification** (`quick_pp.rock_type`, `MultiWellRockTyping.svelte`, `MultiWellPermTransform.svelte`): + Dual Core (`CPORE`, `CPERM`) and Log (`PHIT`, `PERM`) Discrete Rock Typing (`ROCK_FLAG`) via Amaefule `FZI`/`RQI`, Winland $r_{35}$, and Lucia carbonate `RFN` with GMM, Modified Lorenz, or K-Means cutoff discovery and `ROCK_FLAG = 0` non-reservoir isolation; rock-type partitioned power-law permeability transforms ($k = a_k \cdot \phi^{b_k} \to \text{PERM\_TRANS}$); and standalone supervised `RandomForest` / Gradient Boosting rock-type classification across uncored wells. +- **Multi-Well Contact, SHF, Stick Plot & Formation Pressure Testing (FPT)** (`quick_pp.saturation`, `quick_pp.fluid_type`, `MultiWellShf.svelte`, `MultiWellFpt.svelte`, `StickPlotCanvas.svelte`): + Multi-well Leverett-$J$, Skelt-Harrison, and Cuddy Saturation-Height Models ($S_{w,\text{SHF}}$), global and per-zone Free Water Level (FWL) optimization, interactive `TVDSS` Stick Plot structural/stratigraphic cross-sections (`GR`/`COAL` tracks & fluid limits `GUT`/`GDT`/`GOC`/`GWC`, `OUT`/`ODT`/`OWC`, `WUT`/`FWL`), and zone-filtered MDT/RFT pressure gradient regression on true `TVDSS` (`FormationPressureAnalyzer` with OLS/Huber/RANSAC, automatic mobility/supercharge flagging, in-situ fluid density, excess pressure, and covariance $\pm 1\sigma$ contacts). +- **Special Core Analysis (SCAL), Core Calibration & Multi-Log Grain Density** (`quick_pp.scal`, `quick_pp.core_analysis`, `InspectorScal.svelte`, `MultiWellSwirr.svelte`): + Laboratory-to-reservoir core plug corrections (hydrostatic/uniaxial/log-integrated overburden compaction, Klinkenberg gas slippage, and Dean-Stark clay-bound water reconciliation preserving `CPORE_AMB` and `CPERM_AIR` lineage), interactive core-to-log depth matching, multi-log Huber/ridge core grain-density ($\rho_{ma} \to \text{RHOM}$) calibration, explicit fluid-system lab-to-reservoir $P_c$ scaling, PRT Pore-Throat Size Distributions (`plot_ptsd_by_prt`), field-wide `Swirr` fitting, **Corey** / **Brooks-Corey** / **LET** relative permeability, and Eclipse/Intersect `SWOF` table generation (`generate_swof_table`). +- **Probabilistic Volumetrics, Cutoff Sensitivity & Log Blocking** (`quick_pp.ressum`, `quick_pp.uncertainty`, `quick_pp.upscaling`, `MultiWellVolumetrics.svelte`): + PRMS 95% HCPV empirical cutoff sensitivity sweeps (`cutoffs_analysis`), Iman-Conover correlated Latin Hypercube Sampling (`scipy.stats.qmc.LatinHypercube`) for STOIIP/GIIP (`AREA` & `GRV` modes, Log-Average vs. 1D Hypsometric SHF integration, Tornado ranking), log-level CPI uncertainty propagation (`P10`/`P50`/`P90` curves utilizing `*_SIGMA`), and Cardwell-Parsons (1945) power-law ($\omega \in [-1, 1]$) cellular log blocking (`upscale_logs`, `block_logs`). - **High-Throughput Multi-Format Log & Ancillary Import Engine** (`quick_pp.las_handler`, `BulkImporterModal.svelte`, `BulkAncillaryImporter.svelte`): - Fast two-stage hybrid LAS 2.0/3.0, DLIS and LIS79 (`dlisio`), CSV, and Parquet log importer with automated mnemonic alias mapping, unit standardization, multi-run splicing & depth regularization (preserving raw missing gaps without artificial interpolation by default), and bulk ancillary data ingestion (Formation Tops, Fluid Contacts, Deviation Surveys with minimum-curvature TVD calculation, MDT/RFT Pressure Tests, Core RCA plugs, and SCAL Capillary Pressure & Relative Permeability tables). + Fast two-stage hybrid LAS 2.0/3.0, DLIS and LIS79 (`dlisio`), CSV, and Parquet log importer with automated mnemonic alias mapping, unit standardization, `RAW_*` source preservation, interval-bounded multi-run splicing & depth regularization, and bulk ancillary ingestion (Hole Sections, Formation Tops, Fluid Contacts, Minimum-Curvature Surveys, MDT/RFT Pressure & Mobility Tests, Core RCA plugs, and SCAL $P_c$ & RelPerm tables). - **Automated FDP & Single-Well Report Generation** (`quick_pp/app/backend/services/report.py`, `quick_pp.plotter.report_plots`, `InspectorReport.svelte`, `ReportPreviewCanvas.svelte`): - 10-section Field Development Plan (`FDP_FULL`) and Single-Well CPI (`SINGLE_WELL_CPI`) report generator with publication-grade headless Matplotlib figures, grounded AI narrative synthesis and section enhancement (`executive`, `technical`, `concise`, `audit`), interactive Markdown section editing, and print-ready HTML / multi-page A4 PDF export. -- **Petrophysical Handover Package Builder** (`quick_pp.handover`, `build_handover_archive_bytes`): - Zero-friction `.zip` handover archive generator exporting continuous LAS 2.0 logs with populated `~Well` headers (`EKB`, `EDF`, `EGL`, `WDEP`, coordinates) and `~Parameter` CPI settings, Formation Tops, Fluid Contacts & Perforation Intervals (with interpolated `TVD` and `TVDSS`), Well Headers & Datum summary, Deviation Surveys, Core RCA point-sets (`.csv` and `*_RCA.las` with `RAW_DEPTH`, `SHIFT_M`, `CPORE_AMB`, `CPERM_AIR` lineage), MDT/RFT Pressure Tests (`.csv` and `*_MDT.las`), SCAL Pc & RelPerm tables, Eclipse `SWOF` `.inc` decks, PRMS/SEC Zonal Reservoir Summary & Multi-Tab Master Excel Workbook (`.xlsx`), plus automated `import_to_techlog.py` (SLB Techlog) and `import_to_geolog.tcl` (Emerson Geolog) loader scripts. + 10-section Field Development Plan (`FDP_FULL`), Single-Well CPI (`SINGLE_WELL_CPI`), `QAQC_SUMMARY`, and `RESSUM_ONLY` report generator with Borehole Env/Invasion QC & `*_SIGMA`/`*_QC_CONF` audits, automated subsurface QA/QC gate checks (`CHK-01`+) & anomaly remediation logs, publication-grade headless Matplotlib figures, SSOT-grounded AI narrative synthesis (`executive`, `technical`, `concise`, `audit`), and print-ready HTML / multi-page A4 PDF export. +- **Bi-Directional Petrophysical Handover Package Builder & Importer** (`quick_pp.handover`, `HandoverImporter.svelte`): + Zero-friction `.zip` / `.qpp` handover archive export & persistent project re-hydration preserving LAS 2.0 logs (`~Well` headers + `~Parameter` CPI settings), Hole Sections, Formation Tops, Fluid Contacts & Perforation Intervals (`TVD` & `TVDSS`), Deviation Surveys, Core RCA & MDT LAS point-sets, SCAL tables, Eclipse `SWOF` `.inc` decks, PRMS/SEC Zonal Reservoir Summaries, Multi-Tab Master Excel Workbooks (`.xlsx`), and automated SLB Techlog (`import_to_techlog.py`) & Emerson Geolog (`import_to_geolog.tcl`) loader scripts. - **Rock Physics & Gassmann Fluid Substitution** (`quick_pp.rock_physics`): Elastic moduli, shear-wave velocity ($V_s$) prediction, Gassmann fluid substitution, and seismic rock physics templates. @@ -331,6 +331,6 @@ If you use `quick_pp` in your academic research, coursework, publications, or te publisher = {GitHub}, journal = {GitHub repository}, howpublished = {\url{https://github.com/imranfadhil/quick_pp}}, - version = {0.3.7} + version = {0.3.8} } ``` diff --git a/deploy/README.md b/deploy/README.md index be90ff22..eb1ec2f8 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -6,7 +6,7 @@ Batch scripts that provision and manage the `quick_pp` UI & Backend stack on a D The Docker Compose stack ([`quick_pp/app/docker/docker-compose.yaml`](../quick_pp/app/docker/docker-compose.yaml)) runs: - **`web` (Nginx)**: Unified reverse proxy on port `8080` (and internal `:80`). Routes `/quick_pp/*` to `qpp-backend:6312` and `/` to `qpp-frontend:5469` with a `100 MB` upload limit for LAS files. -- **`quicktunnel` (Cloudflare)**: Runs `cloudflared tunnel --url http://web:80` and prints a free `https://.trycloudflare.com` URL at the end of `sync.bat`. +- **`quicktunnel` (Cloudflare Tunnel)**: Runs `cloudflared` outbound to Cloudflare's edge. Supports a permanent **Named Tunnel** (`https://` + Cloudflare Zero Trust Access when `CF_TUNNEL_TOKEN` is set in `config.bat`), or falls back to a free `https://.trycloudflare.com` Quick Tunnel when `CF_TUNNEL_TOKEN` is blank. - **`qpp-frontend` (SvelteKit / Node 20)**: Builds and serves the SvelteKit UI on `:5469` using relative API paths (`VITE_BACKEND_URL=""`). - **`qpp-backend` (FastAPI / Gunicorn)**: Serves the petrophysical API on `:6312` with in-memory caching for merged well logs. - **`postgres` (pgvector/pg17)**: PostgreSQL 17 database. diff --git a/deploy/config.example.bat b/deploy/config.example.bat index 743954ce..a8717205 100644 --- a/deploy/config.example.bat +++ b/deploy/config.example.bat @@ -29,9 +29,14 @@ set KEY_NAME=%PROJECT_NAME%-do-key set KEY_FILE=%USERPROFILE%\.ssh\%KEY_NAME% set PUB_FILE=%USERPROFILE%\.ssh\%KEY_NAME%.pub -REM ---- App config ---- -REM Your public domain (e.g. qpp.example.com). Leave blank if using Quick Tunnel / IP. +REM ---- App & Cloudflare Tunnel config ---- +REM Your custom domain in Cloudflare (e.g. app.example.com). Leave blank for Quick Tunnel. set DOMAIN= +REM Cloudflare Zero Trust Named Tunnel token (Networks -> Tunnels -> -> Token). +REM Leave blank to fall back to a random *.trycloudflare.com Quick Tunnel. +set CF_TUNNEL_TOKEN= +REM Optional email allowed by Cloudflare Zero Trust Access (used by setup-cloudflare.bat) +set ALLOWED_EMAIL= REM Host port where Nginx unified reverse proxy listens on the droplet set WEB_PORT=8080 diff --git a/deploy/configure-env.sh b/deploy/configure-env.sh index c75986a0..d1a7beac 100644 --- a/deploy/configure-env.sh +++ b/deploy/configure-env.sh @@ -12,6 +12,7 @@ # $5 WEB_PORT # $6 TAVILY_API_KEY # $7 DOMAIN +# $8 CF_TUNNEL_TOKEN set -e REMOTE_DIR="$1"; shift @@ -23,16 +24,17 @@ PG_PASS="$3" WEB_PORT="${4:-8080}" TAVILY_KEY="$5" DOMAIN="$6" +CF_TOKEN="$7" -# Helper to set or append a key=value in .env +# Helper to set or append a key=value in .env safely (handles '/', '+', '=' in tokens) set_kv() { key="$1" val="$2" - if grep -q "^${key}=" .env; then - sed -i "s#^${key}=.*#${key}=${val}#" .env - else - echo "${key}=${val}" >> .env + if [ -f .env ]; then + grep -v "^${key}=" .env > .env.tmp || true + mv .env.tmp .env fi + printf '%s=%s\n' "$key" "$val" >> .env } set_kv POSTGRES_USER "$PG_USER" @@ -70,5 +72,13 @@ if [ -n "$DOMAIN" ]; then set_kv PUBLIC_URL "https://$DOMAIN" fi +if [ -n "$CF_TOKEN" ] && [ "$CF_TOKEN" != "xxx" ]; then + set_kv CF_TUNNEL_TOKEN "$CF_TOKEN" + set_kv CF_TUNNEL_ARG "run" +else + set_kv CF_TUNNEL_TOKEN "" + set_kv CF_TUNNEL_ARG "--url=http://web:80" +fi + echo '--- applied ---' -grep -E '^(POSTGRES_USER|POSTGRES_DB|WEB_PORT|FRONTEND_MODE|VITE_BACKEND_URL|PUBLIC_URL)=' .env || true +grep -E '^(POSTGRES_USER|POSTGRES_DB|WEB_PORT|FRONTEND_MODE|VITE_BACKEND_URL|PUBLIC_URL|CF_TUNNEL_ARG)=' .env || true diff --git a/deploy/demo/Dockerfile.dockerignore b/deploy/demo/Dockerfile.dockerignore index 9ed0c031..6d912244 100644 --- a/deploy/demo/Dockerfile.dockerignore +++ b/deploy/demo/Dockerfile.dockerignore @@ -35,12 +35,13 @@ quick_pp/app/frontend/.svelte-kit/ quick_pp/app/frontend/.output/ quick_pp/app/frontend/build/ -# Data, outputs, ML runs (very large) +# Data, outputs, ML runs, local dev reports (very large / local-only) data/ mlruns/ uploads/ output/ outputs/ +quick_pp/app/backend/static/reports/** notebooks/** !notebooks/data/01_raw/36_7-3.las !notebooks/data/01_raw/formation_pressure_data.csv diff --git a/deploy/demo/README.md b/deploy/demo/README.md index 704051ca..c00bcc7c 100644 --- a/deploy/demo/README.md +++ b/deploy/demo/README.md @@ -10,13 +10,17 @@ Because Hugging Face Spaces now requires a paid plan for Docker SDK Spaces, this Unlike the full production stack (which runs PostgreSQL 17, persistent volumes, and live `npm run build` on container start), the **Live Demo stack** ([`deploy/demo/docker-compose.yaml`](./docker-compose.yaml)) is self-contained and lightweight: - **No PostgreSQL or Celery containers**: Uses the pre-seeded read-only SQLite database (`quick_pp.db`, `chmod 444`) + pre-trained Conformal PIML bundle (`pretrained_models.joblib`). -- **Single Application Container (`qpp-demo-app`)**: Bundles Nginx (`:7860`), FastAPI (`127.0.0.1:6312`), and the pre-built SvelteKit Node server (`127.0.0.1:5469`). Steady-state RAM usage is **~220–280 MB**. +- **Single Application Container (`qpp-demo-app`)**: Bundles Nginx (`:7860`), FastAPI (`127.0.0.1:6312`), and the pre-built SvelteKit Node server (`127.0.0.1:5469`). Steady-state RAM usage is **~220–280 MB**, with hard Docker resource ceilings (`DEMO_MEM_LIMIT=2g`, `DEMO_CPU_LIMIT=0.85`, `pids_limit=128`, `cap_drop=ALL`, 256 MB `/tmp` tmpfs, rotated `3×10m` container logs) and tiered Nginx rate limiting (`60 req/min` general, `10 req/min` heavy compute/LLM/PDF). +- **Live Occupancy, Idle Pause, & 3-Tier Storage Cleanup**: + - Displays a real-time **online users badge** in the top bar (amber lag warning at `3+` concurrent visitors) and enforces a soft active-session gate (`DEMO_MAX_USERS=6`) plus a `2`-job heavy-compute semaphore. + - Pauses inactive browser tabs (`10 min` idle / `5 min` hidden tab) to release capacity for other visitors. + - Automatically purges committed log uploads immediately after parsing, removes session reports/staged files on tab exit, and runs a 5-minute TTL + ring-buffer sweep so disk usage stays bounded. - **Complete Isolation on Shared Droplets**: - Remote folder: `/opt/quick_pp_demo` (never touches `/opt/quick_pp`) - Compose project: `quick_pp_demo` (`qpp-demo-app` & `qpp-demo-tunnel`) - Host port: `127.0.0.1:7860` (never collides with `:80`, `:443`, or `:8080`) - Automatic 2 GB `/swapfile` provisioning so multi-stage Docker builds never hit OOM on 1 GB / 2 GB droplets. -- **Instant HTTPS Public Link**: Includes `demo-quicktunnel` (`cloudflared`) which prints a live `https://.trycloudflare.com` URL at the end of `deploy.bat` / `sync.bat`, or you can proxy your own subdomain (e.g. `demo.yourdomain.com`) to `127.0.0.1:7860`. +- **Custom Domain or Instant HTTPS Public Link**: Includes `demo-quicktunnel` (`cloudflared`) which connects to your permanent Cloudflare Named Tunnel (`https://`) when `CF_TUNNEL_TOKEN` is set in `deploy\demo\config.bat`, or prints a free `https://.trycloudflare.com` Quick Tunnel URL when left blank. --- diff --git a/deploy/demo/config.example.bat b/deploy/demo/config.example.bat index edcc2d1d..94dc850b 100644 --- a/deploy/demo/config.example.bat +++ b/deploy/demo/config.example.bat @@ -37,11 +37,23 @@ set KEY_NAME=quick-pp-do-key set KEY_FILE=%USERPROFILE%\.ssh\%KEY_NAME% set PUB_FILE=%USERPROFILE%\.ssh\%KEY_NAME%.pub -REM ---- Demo Networking ---- +REM ---- Demo Networking, Resource Limits & Cloudflare Tunnel ---- REM Host port on the droplet (7860 avoids colliding with 80, 443, or 8080) set DEMO_PORT=7860 -REM Bind to 127.0.0.1 when using Cloudflare Quick Tunnel or host Nginx reverse proxy. +REM Bind to 127.0.0.1 when using Cloudflare Tunnel or host Nginx reverse proxy. REM Set to 0.0.0.0 if you want http://:7860 accessible directly. set DEMO_BIND=127.0.0.1 +REM Hard container memory & CPU limits for qpp-demo-app (protects shared droplets from OOM/starvation) +set DEMO_MEM_LIMIT=2g +set DEMO_CPU_LIMIT=0.85 +REM Concurrent active visitor cap, lag-indicator threshold, and browser idle pause (seconds) +set DEMO_MAX_USERS=6 +set DEMO_LAG_WARNING_USERS=3 +set DEMO_IDLE_TIMEOUT_SECONDS=600 +set DEMO_MAX_CONCURRENT_COMPUTE=2 +REM Custom domain for the public demo in Cloudflare (e.g. demo.example.com) set DOMAIN= +REM Cloudflare Zero Trust Named Tunnel token (Networks -> Tunnels -> -> Token). +REM Leave blank to fall back to a random *.trycloudflare.com Quick Tunnel. +set CF_TUNNEL_TOKEN= diff --git a/deploy/demo/docker-compose.yaml b/deploy/demo/docker-compose.yaml index 9c16a629..99300add 100644 --- a/deploy/demo/docker-compose.yaml +++ b/deploy/demo/docker-compose.yaml @@ -6,31 +6,64 @@ services: context: ../.. dockerfile: deploy/demo/Dockerfile restart: unless-stopped + # Enforce hard memory, CPU, PID, and privilege ceilings (protects shared droplets) + mem_limit: ${DEMO_MEM_LIMIT:-2g} + memswap_limit: ${DEMO_MEM_LIMIT:-2g} + cpus: ${DEMO_CPU_LIMIT:-0.85} + pids_limit: 128 + security_opt: + - no-new-privileges:true + cap_drop: + - ALL + tmpfs: + - /tmp:size=256m,mode=1777 + logging: + driver: json-file + options: + max-size: "10m" + max-file: "3" environment: - QPP_DEMO_MODE=true - QPP_DISABLE_TRAINING=true - QPP_DATABASE_URL=sqlite:////code/data/quick_pp.db - QPP_PRETRAINED_MODELS_PATH=/code/data/seed/pretrained_models.joblib + - QPP_DEMO_MAX_USERS=${DEMO_MAX_USERS:-6} + - QPP_DEMO_LAG_WARNING_USERS=${DEMO_LAG_WARNING_USERS:-3} + - QPP_DEMO_IDLE_TIMEOUT_SECONDS=${DEMO_IDLE_TIMEOUT_SECONDS:-600} + - QPP_DEMO_HIDDEN_IDLE_TIMEOUT_SECONDS=${DEMO_HIDDEN_IDLE_TIMEOUT_SECONDS:-300} + - QPP_DEMO_MAX_CONCURRENT_COMPUTE=${DEMO_MAX_CONCURRENT_COMPUTE:-2} - PUBLIC_URL=${PUBLIC_URL:-} - # Bound to localhost by default so public access goes through Cloudflare Quick Tunnel - # or an existing host Nginx/Caddy reverse proxy. Set DEMO_BIND=0.0.0.0 to expose directly. + # Bound to localhost by default so public access goes through Cloudflare Tunnel + # or an existing host Nginx/Caddy reverse proxy. Keep 127.0.0.1 when trusting CF-Connecting-IP. ports: - "${DEMO_BIND:-127.0.0.1}:${DEMO_PORT:-7860}:7860" networks: - qpp-demo-network - # Cloudflare Quick Tunnel — free random *.trycloudflare.com HTTPS URL for the demo. + # Cloudflare Tunnel — uses permanent Named Tunnel (e.g. https://demo.quick-pp.com) + # when CF_TUNNEL_TOKEN is set, or falls back to a free *.trycloudflare.com Quick Tunnel. demo-quicktunnel: image: cloudflare/cloudflared:latest container_name: qpp-demo-tunnel restart: unless-stopped depends_on: - qpp-demo - command: tunnel --no-autoupdate --url http://qpp-demo:7860 + security_opt: + - no-new-privileges:true + logging: + driver: json-file + options: + max-size: "10m" + max-file: "3" + environment: + - TUNNEL_TOKEN=${CF_TUNNEL_TOKEN:-} + command: + - tunnel + - --no-autoupdate + - ${CF_TUNNEL_ARG:---url=http://qpp-demo:7860} networks: - qpp-demo-network networks: qpp-demo-network: driver: bridge - diff --git a/deploy/demo/nginx.conf b/deploy/demo/nginx.conf index 4fc7ad94..a738db57 100644 --- a/deploy/demo/nginx.conf +++ b/deploy/demo/nginx.conf @@ -1,14 +1,15 @@ -worker_processes auto; +worker_processes 1; pid /tmp/nginx.pid; -error_log /tmp/nginx_error.log warn; +error_log /dev/stderr warn; events { - worker_connections 1024; + worker_connections 512; } http { include /etc/nginx/mime.types; default_type application/octet-stream; + server_tokens off; client_body_temp_path /tmp/client_temp; proxy_temp_path /tmp/proxy_temp_path; @@ -16,40 +17,100 @@ http { uwsgi_temp_path /tmp/uwsgi_temp; scgi_temp_path /tmp/scgi_temp; - access_log /tmp/nginx_access.log; + # Disable disk access_log so public demo traffic never fills container storage + access_log off; sendfile on; keepalive_timeout 65; - # Guardrail: Enforce 5 MB max upload payload in the public Interactive Live Demo + # Guardrail 1: Enforce 5 MB max upload payload in the public Interactive Live Demo client_max_body_size 5m; + # Guardrail 2: Real visitor IP via Cloudflare Tunnel (keep DEMO_BIND=127.0.0.1 when using CF) + map $http_cf_connecting_ip $client_real_ip { + "" $remote_addr; + default $http_cf_connecting_ip; + } + limit_req_zone $client_real_ip zone=demo_rate_limit:5m rate=180r/m; + limit_req_zone $client_real_ip zone=demo_telemetry_limit:2m rate=30r/m; + limit_req_zone $client_real_ip zone=demo_heavy_limit:2m rate=10r/m; + limit_req_status 429; + limit_req_log_level warn; + server { listen 7860; server_name _; - # Proxy API requests and OpenAPI docs to the FastAPI backend - location ~ ^/(quick_pp|docs|redoc|openapi\.json|static|qpp_assistant) { + # Standard browser hardening headers + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; + + # Guardrail 3: Hide Swagger/ReDoc/OpenAPI schema from public internet scanners + location ~ ^/(docs|redoc|openapi\.json) { + return 404; + } + + # Isolated rate-limit bucket for lightweight session heartbeats so they never starve API calls + location /quick_pp/demo/ { + limit_req zone=demo_telemetry_limit burst=12 nodelay; proxy_pass http://127.0.0.1:6312; proxy_http_version 1.1; proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Real-IP $client_real_ip; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 15s; + proxy_send_timeout 15s; + } + + # Guardrail 4: Stricter rate limit on CPU/LLM/PDF-heavy endpoints + location ~ ^/(quick_pp/(assistant/chat|mcp)|(?:quick_pp|api/v1)/projects/[^/]+/reports/(generate|[^/]+/(enhance|pdf))) { + limit_req zone=demo_heavy_limit burst=6 nodelay; + proxy_pass http://127.0.0.1:6312; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $client_real_ip; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_read_timeout 180s; proxy_send_timeout 180s; } + # Proxy API requests and static report assets to the FastAPI backend + location ~ ^/(quick_pp|api/v1|static|qpp_assistant) { + limit_req zone=demo_rate_limit burst=60 nodelay; + proxy_pass http://127.0.0.1:6312; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $client_real_ip; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 180s; + proxy_send_timeout 180s; + } + + # Serve immutable SvelteKit JS/CSS bundles & static icons without rate-limit overhead + location ~ ^/(_app/|favicon\.ico|robots\.txt) { + proxy_pass http://127.0.0.1:5469; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $client_real_ip; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + # Proxy everything else to the SvelteKit frontend server location / { + limit_req zone=demo_rate_limit burst=60 nodelay; proxy_pass http://127.0.0.1:5469; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Real-IP $client_real_ip; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } } - diff --git a/deploy/demo/start_demo.sh b/deploy/demo/start_demo.sh index 17f84773..f2fbf8fa 100644 --- a/deploy/demo/start_demo.sh +++ b/deploy/demo/start_demo.sh @@ -21,12 +21,19 @@ export QPP_DISABLE_TRAINING=true export QPP_DATABASE_URL="sqlite:////code/data/quick_pp.db" export QPP_PRETRAINED_MODELS_PATH="/code/data/seed/pretrained_models.joblib" -# 1. Launch FastAPI backend on 127.0.0.1:6312 -uvicorn quick_pp.app.backend.main:app --host 127.0.0.1 --port 6312 --workers 1 & +# Keep glibc & OpenMP/BLAS thread pools lean inside 1-vCPU / 2 GB containers +export MALLOC_ARENA_MAX="${MALLOC_ARENA_MAX:-2}" +export MALLOC_TRIM_THRESHOLD_="${MALLOC_TRIM_THRESHOLD_:-65536}" +export OMP_NUM_THREADS="${OMP_NUM_THREADS:-1}" +export OPENBLAS_NUM_THREADS="${OPENBLAS_NUM_THREADS:-1}" +export MKL_NUM_THREADS="${MKL_NUM_THREADS:-1}" + +# 1. Launch FastAPI backend on 127.0.0.1:6312 (no access-log spam) +uvicorn quick_pp.app.backend.main:app --host 127.0.0.1 --port 6312 --workers 1 --no-access-log --limit-concurrency 64 & BACKEND_PID=$! -# 2. Launch SvelteKit Node adapter build on 127.0.0.1:5469 -HOST=127.0.0.1 PORT=5469 BODY_SIZE_LIMIT=5242880 node /code/quick_pp/app/frontend/build & +# 2. Launch SvelteKit Node adapter build on 127.0.0.1:5469 with bounded 256 MB V8 heap +NODE_OPTIONS="--max-old-space-size=256" HOST=127.0.0.1 PORT=5469 BODY_SIZE_LIMIT=5242880 node /code/quick_pp/app/frontend/build & FRONTEND_PID=$! # 3. Launch Nginx reverse proxy in foreground on port 7860 @@ -37,4 +44,3 @@ trap "kill -TERM $BACKEND_PID $FRONTEND_PID $NGINX_PID 2>/dev/null || true" SIGI wait -n $BACKEND_PID $FRONTEND_PID $NGINX_PID exit $? - diff --git a/deploy/demo/sync.bat b/deploy/demo/sync.bat index 50ef6d10..5f64a063 100644 --- a/deploy/demo/sync.bat +++ b/deploy/demo/sync.bat @@ -123,26 +123,34 @@ if %ERRORLEVEL% neq 0 ( set "PUBLIC_URL_VAL=" if not "%DOMAIN%"=="" set "PUBLIC_URL_VAL=https://%DOMAIN%" +if "%DEMO_MEM_LIMIT%"=="" set "DEMO_MEM_LIMIT=2g" -call :ssh_run "printf 'QPP_DEMO_MODE=true\nQPP_DISABLE_TRAINING=true\nDEMO_PORT=%DEMO_PORT%\nDEMO_BIND=%DEMO_BIND%\nPUBLIC_URL=%PUBLIC_URL_VAL%\n' > %REMOTE_DIR%/.env" -if %ERRORLEVEL% neq 0 ( +set "DEMO_ENV_TMP=%TEMP%\%PROJECT_NAME%-demo.env" +powershell -NoProfile -Command "$t = if ($env:CF_TUNNEL_TOKEN) { $env:CF_TUNNEL_TOKEN.Trim() } else { '' }; $arg = if ($t) { 'run' } else { '--url=http://qpp-demo:7860' }; $lines = @('QPP_DEMO_MODE=true','QPP_DISABLE_TRAINING=true',('DEMO_PORT='+$env:DEMO_PORT),('DEMO_BIND='+$env:DEMO_BIND),('DEMO_MEM_LIMIT='+$env:DEMO_MEM_LIMIT),('PUBLIC_URL='+$env:PUBLIC_URL_VAL),('CF_TUNNEL_TOKEN='+$t),('CF_TUNNEL_ARG='+$arg)) -join [char]10; Set-Content -NoNewline -LiteralPath $env:DEMO_ENV_TMP -Value ($lines + [char]10) -Encoding ascii" + +call :ssh_pipe "%DEMO_ENV_TMP%" "cat > %REMOTE_DIR%/.env" +set DEMO_ENV_RC=%ERRORLEVEL% +if defined DEMO_ENV_TMP if exist "%DEMO_ENV_TMP%" del "%DEMO_ENV_TMP%" 2>nul +if not %DEMO_ENV_RC% equ 0 ( echo [ERROR] Failed to write remote .env. exit /b 1 ) -echo [OK] Demo environment configured. +echo [OK] Demo environment configured ^(Memory limit: %DEMO_MEM_LIMIT%^). REM -- Build & Start isolated demo compose stack ----------------------- echo [5/5] Starting isolated demo stack ^(project: %COMPOSE_PROJECT%^)... set "COMPOSE_CMD=docker compose -p %COMPOSE_PROJECT% --env-file %REMOTE_DIR%/.env -f %REMOTE_DIR%/deploy/demo/docker-compose.yaml" -REM Rebuild/update only `qpp-demo` (--no-deps) and keep `demo-quicktunnel` running (--no-recreate --no-deps) -REM so the *.trycloudflare.com HTTPS URL does not change across sync.bat / sync.bat --restart runs. +set "DEMO_TUNNEL_FLAGS=--no-recreate --no-deps" +if defined CF_TUNNEL_TOKEN set "DEMO_TUNNEL_FLAGS=--no-deps" + +REM Rebuild/update `qpp-demo` and manage `demo-quicktunnel`: if "%1"=="--from-deploy" ( set "REMOTE_CMD=!COMPOSE_CMD! up -d --build" ) else if %BUILD% equ 1 ( - set "REMOTE_CMD=!COMPOSE_CMD! up -d --build --no-deps qpp-demo && !COMPOSE_CMD! up -d --no-recreate --no-deps demo-quicktunnel" + set "REMOTE_CMD=!COMPOSE_CMD! up -d --build --no-deps qpp-demo && !COMPOSE_CMD! up -d !DEMO_TUNNEL_FLAGS! demo-quicktunnel" ) else ( - set "REMOTE_CMD=!COMPOSE_CMD! up -d --no-recreate --no-deps qpp-demo demo-quicktunnel" + set "REMOTE_CMD=!COMPOSE_CMD! up -d --no-deps qpp-demo && !COMPOSE_CMD! up -d !DEMO_TUNNEL_FLAGS! demo-quicktunnel" ) call :ssh_run "!REMOTE_CMD!" @@ -160,7 +168,19 @@ echo. echo [OK] Demo stack running: call :ssh_run "!COMPOSE_CMD! ps" -REM -- Retrieve Cloudflare Quick Tunnel URL ---------------------------- +REM -- Retrieve Cloudflare Tunnel URL ---------------------------------- +if defined CF_TUNNEL_TOKEN ( + echo. + if not "%DOMAIN%"=="" ( + echo =============================================================== + echo LIVE DEMO URL ^(Cloudflare Tunnel^): https://%DOMAIN% + echo =============================================================== + ) else ( + echo [OK] Cloudflare Named Tunnel active ^(CF_TUNNEL_TOKEN configured^). + ) + goto :sync_end +) + set QUICK_URL= echo. echo [INFO] Resolving Cloudflare Quick Tunnel HTTPS URL... diff --git a/deploy/seed-config.ps1 b/deploy/seed-config.ps1 index 6e3873b0..0b5b1f7f 100644 --- a/deploy/seed-config.ps1 +++ b/deploy/seed-config.ps1 @@ -61,7 +61,8 @@ $direct = @( 'POSTGRES_DB', 'POSTGRES_PASSWORD', 'TAVILY_API_KEY', - 'WEB_PORT' + 'WEB_PORT', + 'CF_TUNNEL_TOKEN' ) $values = @{} diff --git a/deploy/setup-cloudflare.bat b/deploy/setup-cloudflare.bat new file mode 100644 index 00000000..33fbf079 --- /dev/null +++ b/deploy/setup-cloudflare.bat @@ -0,0 +1,3 @@ +@echo off +cd /d "%~dp0" +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0setup-cloudflare.ps1" %* diff --git a/deploy/setup-cloudflare.ps1 b/deploy/setup-cloudflare.ps1 new file mode 100644 index 00000000..9f174f7a --- /dev/null +++ b/deploy/setup-cloudflare.ps1 @@ -0,0 +1,382 @@ +<# + setup-cloudflare.ps1 — Automate Cloudflare Tunnel routes, DNS CNAMEs, + Zero Trust Access policy, and WAF Rate Limiting from local config.bat files. + + Reads Account ID, Tunnel IDs, DOMAIN, and ALLOWED_EMAIL directly from: + - deploy\config.bat (gitignored private app settings) + - deploy\demo\config.bat (gitignored demo app settings) + + Usage: + powershell -ExecutionPolicy Bypass -File deploy\setup-cloudflare.ps1 [-AllowedEmail you@example.com] +#> +[CmdletBinding()] +param( + [string]$ZoneName = '', + [string]$PrivateHostname = '', + [string]$PrivateService = 'http://web:80', + [string]$DemoHostname = '', + [string]$DemoService = 'http://qpp-demo:7860', + [string]$AllowedEmail = '' +) + +$ErrorActionPreference = 'Stop' +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + +function Get-BatVar { + param([string]$ConfigPath, [string]$VarName) + if (-not (Test-Path -LiteralPath $ConfigPath)) { return '' } + $raw = Get-Content -LiteralPath $ConfigPath -Raw + $m = [regex]::Match($raw, "(?m)^\s*set\s+`"?$([regex]::Escape($VarName))=([^`"\r\n]*)") + if ($m.Success) { return $m.Groups[1].Value.Trim() } + return '' +} + +function Get-TunnelInfoFromConfig { + param([string]$ConfigPath, [string]$Label) + if (-not (Test-Path -LiteralPath $ConfigPath)) { + throw "Config file not found: $ConfigPath" + } + $tok = Get-BatVar -ConfigPath $ConfigPath -VarName 'CF_TUNNEL_TOKEN' + if ([string]::IsNullOrWhiteSpace($tok)) { + throw "CF_TUNNEL_TOKEN is empty in $ConfigPath. Paste your $Label tunnel token first." + } + $padLen = (4 - ($tok.Length % 4)) % 4 + $padded = $tok + ('=' * $padLen) + $jsonBytes = [Convert]::FromBase64String($padded) + $jsonText = [System.Text.Encoding]::UTF8.GetString($jsonBytes) + $parsed = $jsonText | ConvertFrom-Json + if (-not $parsed.a -or -not $parsed.t) { + throw "CF_TUNNEL_TOKEN in $ConfigPath is not a valid Cloudflare Tunnel token." + } + return @{ + AccountId = [string]$parsed.a + TunnelId = [string]$parsed.t + Domain = (Get-BatVar -ConfigPath $ConfigPath -VarName 'DOMAIN') + Email = (Get-BatVar -ConfigPath $ConfigPath -VarName 'ALLOWED_EMAIL') + } +} + +$deployDir = $PSScriptRoot +$privateInfo = Get-TunnelInfoFromConfig -ConfigPath (Join-Path $deployDir 'config.bat') -Label 'private' +$demoInfo = Get-TunnelInfoFromConfig -ConfigPath (Join-Path $deployDir 'demo\config.bat') -Label 'demo' + +if ([string]::IsNullOrWhiteSpace($PrivateHostname)) { $PrivateHostname = $privateInfo.Domain } +if ([string]::IsNullOrWhiteSpace($DemoHostname)) { $DemoHostname = $demoInfo.Domain } +if ([string]::IsNullOrWhiteSpace($AllowedEmail)) { $AllowedEmail = $privateInfo.Email } +if ([string]::IsNullOrWhiteSpace($PrivateHostname)) { throw 'DOMAIN is empty in deploy\config.bat.' } +if ([string]::IsNullOrWhiteSpace($DemoHostname)) { throw 'DOMAIN is empty in deploy\demo\config.bat.' } +if ([string]::IsNullOrWhiteSpace($ZoneName)) { + $parts = $PrivateHostname.Split('.') + if ($parts.Length -ge 2) { + $ZoneName = ($parts[($parts.Length - 2)..($parts.Length - 1)] -join '.') + } else { + throw 'Could not infer root ZoneName from DOMAIN; pass -ZoneName explicitly.' + } +} +if ([string]::IsNullOrWhiteSpace($AllowedEmail)) { + $AllowedEmail = (Read-Host -Prompt "Enter email address to allow in Zero Trust Access for $PrivateHostname").Trim() +} +if ([string]::IsNullOrWhiteSpace($AllowedEmail)) { + throw 'AllowedEmail is required for Cloudflare Zero Trust Access policy.' +} + +if ($privateInfo.AccountId -ne $demoInfo.AccountId) { + throw "Account ID mismatch between deploy\config.bat ($($privateInfo.AccountId)) and deploy\demo\config.bat ($($demoInfo.AccountId))." +} + +$accountId = $privateInfo.AccountId +$privateTunnelId = $privateInfo.TunnelId +$demoTunnelId = $demoInfo.TunnelId + +Write-Host '' +Write-Host '===============================================================' -ForegroundColor Cyan +Write-Host " CLOUDFLARE PROVISIONING - $ZoneName" -ForegroundColor Cyan +Write-Host '===============================================================' -ForegroundColor Cyan +Write-Host " Account ID : $accountId" +Write-Host " Private Tunnel : $privateTunnelId -> $PrivateHostname ($PrivateService)" +Write-Host " Demo Tunnel : $demoTunnelId -> $DemoHostname ($DemoService)" +Write-Host " Access Policy : Allow $AllowedEmail on $PrivateHostname" +Write-Host '' + +# Resolve Cloudflare API / OAuth Token (env var -> cf CLI login -> interactive prompt) +$apiToken = $env:CLOUDFLARE_API_TOKEN +if ([string]::IsNullOrWhiteSpace($apiToken)) { + $apiToken = $env:CF_API_TOKEN +} +if ([string]::IsNullOrWhiteSpace($apiToken)) { + $cfConfigPaths = @( + (Join-Path $env:APPDATA 'xdg.config\cloudflare\config\default.json'), + (Join-Path $env:USERPROFILE '.config\cloudflare\config\default.json') + ) + foreach ($cfCfg in $cfConfigPaths) { + if ($cfCfg -and (Test-Path -LiteralPath $cfCfg)) { + try { + $cfgObj = Get-Content -LiteralPath $cfCfg -Raw | ConvertFrom-Json + if ($cfgObj.oauth_token) { + $apiToken = [string]$cfgObj.oauth_token + Write-Host ' [Auth] Using authenticated session from Cloudflare CLI (cf auth login).' -ForegroundColor DarkGray + break + } + } catch {} + } + } +} +if ([string]::IsNullOrWhiteSpace($apiToken)) { + Write-Host 'Create a Cloudflare API Token at: https://dash.cloudflare.com/profile/api-tokens' -ForegroundColor Yellow + Write-Host 'Required permissions:' -ForegroundColor Yellow + Write-Host ' - Account | Cloudflare Tunnel (or Cloudflare One Connectors) | Edit' + Write-Host ' - Account | Access: Apps and Policies | Edit' + Write-Host ' - Account | Access: Organizations, Identity Providers, Groups| Edit' + Write-Host ' - Zone | DNS | Edit' + Write-Host ' - Zone | Zone WAF | Edit' + Write-Host ' - Zone | Zone Settings | Edit' + Write-Host ' - Zone | Zone | Read' + Write-Host '' + $sec = Read-Host -Prompt 'Paste Cloudflare API Token (input hidden)' -AsSecureString + $bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($sec) + try { + $apiToken = [Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr).Trim() + } finally { + [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) + } +} + +if ([string]::IsNullOrWhiteSpace($apiToken)) { + throw 'No Cloudflare API Token provided.' +} + +$headers = @{ + 'Authorization' = "Bearer $apiToken" + 'Content-Type' = 'application/json' +} + +function Invoke-CfApi { + param( + [Parameter(Mandatory)][string]$Method, + [Parameter(Mandatory)][string]$Path, + [object]$Body = $null, + [switch]$Allow404 + ) + $uri = "https://api.cloudflare.com/client/v4$Path" + $params = @{ + Method = $Method + Uri = $uri + Headers = $headers + ErrorAction = 'Stop' + } + if ($null -ne $Body) { + $params['Body'] = ($Body | ConvertTo-Json -Depth 20 -Compress) + } + try { + $resp = Invoke-RestMethod @params + if (-not $resp.success) { + $errMsg = ($resp.errors | ForEach-Object { "[$($_.code)] $($_.message)" }) -join '; ' + throw "Cloudflare API error on $Method $Path : $errMsg" + } + return $resp + } catch { + $statusCode = $null + if ($_.Exception.Response) { + $statusCode = [int]$_.Exception.Response.StatusCode + } + if ($Allow404 -and $statusCode -eq 404) { + return $null + } + $detail = $_.ErrorDetails.Message + if ($detail) { + throw "HTTP $statusCode on $Method $Path : $detail" + } + throw + } +} + +# ---- 1. Resolve Zone & Ensure SSL=Full ------------------------------------- +Write-Host "[1/5] Looking up zone '$ZoneName'..." +$zonesResp = Invoke-CfApi -Method GET -Path "/zones?name=$([uri]::EscapeDataString($ZoneName))" +if (-not $zonesResp.result -or $zonesResp.result.Count -eq 0) { + throw "Zone '$ZoneName' not found in Cloudflare account $accountId." +} +$zone = $zonesResp.result[0] +$zoneId = $zone.id +$planId = [string]$zone.plan.legacy_id +$isFreePlan = ($planId -eq 'free' -or $zone.plan.name -match 'Free') +Write-Host " [OK] Zone ID: $zoneId (Plan: $($zone.plan.name), Status: $($zone.status))" -ForegroundColor Green + +try { + $sslResp = Invoke-CfApi -Method GET -Path "/zones/$zoneId/settings/ssl" + if ($sslResp.result.value -eq 'flexible' -or $sslResp.result.value -eq 'off') { + [void](Invoke-CfApi -Method PATCH -Path "/zones/$zoneId/settings/ssl" -Body @{ value = 'full' }) + Write-Host ' [OK] Updated Zone SSL/TLS encryption mode to Full.' -ForegroundColor Green + } +} catch { + Write-Host " [SKIP] Could not inspect/update SSL setting (non-fatal): $($_.Exception.Message)" -ForegroundColor DarkYellow +} + +# ---- 2. Configure Both Tunnel Ingress Routes ------------------------------- +Write-Host '[2/5] Configuring Cloudflare Tunnel ingress routes...' + +$privateTunnelBody = @{ + config = @{ + ingress = @( + @{ hostname = $PrivateHostname; service = $PrivateService }, + @{ service = 'http_status:404' } + ) + } +} +[void](Invoke-CfApi -Method PUT -Path "/accounts/$accountId/cfd_tunnel/$privateTunnelId/configurations" -Body $privateTunnelBody) +Write-Host " [OK] Private tunnel ($privateTunnelId) -> $PrivateHostname -> $PrivateService" -ForegroundColor Green + +$demoTunnelBody = @{ + config = @{ + ingress = @( + @{ hostname = $DemoHostname; service = $DemoService }, + @{ service = 'http_status:404' } + ) + } +} +[void](Invoke-CfApi -Method PUT -Path "/accounts/$accountId/cfd_tunnel/$demoTunnelId/configurations" -Body $demoTunnelBody) +Write-Host " [OK] Demo tunnel ($demoTunnelId) -> $DemoHostname -> $DemoService" -ForegroundColor Green + +# ---- 3. Upsert Proxied CNAME DNS Records ----------------------------------- +Write-Host '[3/5] Upserting proxied CNAME DNS records...' + +function Set-TunnelCname { + param([string]$Hostname, [string]$TunnelId) + $target = "$TunnelId.cfargotunnel.com" + $existing = Invoke-CfApi -Method GET -Path "/zones/$zoneId/dns_records?name=$([uri]::EscapeDataString($Hostname))" + $recordBody = @{ + type = 'CNAME' + name = $Hostname + content = $target + proxied = $true + ttl = 1 + comment = "Managed by quick_pp Cloudflare Tunnel ($TunnelId)" + } + if ($existing.result -and $existing.result.Count -gt 0) { + $recId = $existing.result[0].id + [void](Invoke-CfApi -Method PUT -Path "/zones/$zoneId/dns_records/$recId" -Body $recordBody) + Write-Host " [OK] Updated DNS CNAME: $Hostname -> $target (Proxied)" -ForegroundColor Green + } else { + [void](Invoke-CfApi -Method POST -Path "/zones/$zoneId/dns_records" -Body $recordBody) + Write-Host " [OK] Created DNS CNAME: $Hostname -> $target (Proxied)" -ForegroundColor Green + } +} + +Set-TunnelCname -Hostname $PrivateHostname -TunnelId $privateTunnelId +Set-TunnelCname -Hostname $DemoHostname -TunnelId $demoTunnelId + +# ---- 4. Zero Trust Access Policy & Self-Hosted App ------------------------- +Write-Host "[4/5] Configuring Cloudflare Zero Trust Access for $PrivateHostname..." + +$orgResp = Invoke-CfApi -Method GET -Path "/accounts/$accountId/access/organizations" -Allow404 +if (-not $orgResp -or -not $orgResp.result -or -not $orgResp.result.auth_domain) { + throw "Zero Trust Organization is not initialized yet. Open https://one.dash.cloudflare.com/ once to pick your team name (Free plan), then re-run this script." +} +Write-Host " [OK] Zero Trust Team Domain: $($orgResp.result.auth_domain)" -ForegroundColor Green + +# Ensure One-Time PIN IdP exists +$idpsResp = Invoke-CfApi -Method GET -Path "/accounts/$accountId/access/identity_providers" +$otpIdp = $idpsResp.result | Where-Object { $_.type -eq 'onetimepin' } | Select-Object -First 1 +if (-not $otpIdp) { + $otpCreated = Invoke-CfApi -Method POST -Path "/accounts/$accountId/access/identity_providers" -Body @{ + name = 'One-time PIN' + type = 'onetimepin' + config = @{} + } + $otpIdp = $otpCreated.result + Write-Host ' [OK] Enabled One-time PIN Identity Provider.' -ForegroundColor Green +} else { + Write-Host ' [OK] One-time PIN Identity Provider already active.' -ForegroundColor Green +} + +# Upsert Reusable Access Policy (cloudflare-one best practice) +$policyName = 'Allow Owner Only (quick_pp)' +$policiesResp = Invoke-CfApi -Method GET -Path "/accounts/$accountId/access/policies" +$existingPolicy = $policiesResp.result | Where-Object { $_.name -eq $policyName } | Select-Object -First 1 +$policyBody = @{ + name = $policyName + decision = 'allow' + include = @( + @{ email = @{ email = $AllowedEmail } } + ) + session_duration = '168h' +} +if ($existingPolicy) { + $polUpdated = Invoke-CfApi -Method PUT -Path "/accounts/$accountId/access/policies/$($existingPolicy.id)" -Body $policyBody + $policyId = $polUpdated.result.id + Write-Host " [OK] Updated reusable Access policy '$policyName' ($policyId) -> $AllowedEmail" -ForegroundColor Green +} else { + $polCreated = Invoke-CfApi -Method POST -Path "/accounts/$accountId/access/policies" -Body $policyBody + $policyId = $polCreated.result.id + Write-Host " [OK] Created reusable Access policy '$policyName' ($policyId) -> $AllowedEmail" -ForegroundColor Green +} + +# Upsert Self-Hosted Access Application for private.quick-pp.com +$appsResp = Invoke-CfApi -Method GET -Path "/accounts/$accountId/access/apps" +$existingApp = $appsResp.result | Where-Object { $_.domain -eq $PrivateHostname } | Select-Object -First 1 +$appBody = @{ + name = 'quick_pp Private' + domain = $PrivateHostname + type = 'self_hosted' + session_duration = '168h' + app_launcher_visible = $true + http_only_cookie_attribute = $true + same_site_cookie_attribute = 'lax' + allowed_idps = @([string]$otpIdp.id) + auto_redirect_to_identity = $true + policies = @( + @{ id = $policyId; precedence = 1 } + ) +} +if ($existingApp) { + [void](Invoke-CfApi -Method PUT -Path "/accounts/$accountId/access/apps/$($existingApp.id)" -Body $appBody) + Write-Host " [OK] Updated Access Application 'quick_pp Private' ($PrivateHostname)" -ForegroundColor Green +} else { + [void](Invoke-CfApi -Method POST -Path "/accounts/$accountId/access/apps" -Body $appBody) + Write-Host " [OK] Created Access Application 'quick_pp Private' ($PrivateHostname)" -ForegroundColor Green +} + +# ---- 5. WAF Rate Limiting Rule for demo.quick-pp.com ----------------------- +Write-Host "[5/5] Configuring WAF Rate Limiting rule on $DemoHostname..." + +$rlPeriod = if ($isFreePlan) { 10 } else { 60 } +$rlRequests = if ($isFreePlan) { 20 } else { 60 } +$rlMitigation = if ($isFreePlan) { 10 } else { 60 } + +$demoRuleDesc = 'quick_pp Demo Rate Limit' +$demoRule = @{ + description = $demoRuleDesc + expression = "(http.host eq `"$DemoHostname`" and not starts_with(http.request.uri.path, `"/_app/`"))" + action = 'block' + enabled = $true + ratelimit = @{ + characteristics = @('cf.colo.id', 'ip.src') + period = $rlPeriod + requests_per_period = $rlRequests + mitigation_timeout = $rlMitigation + } +} + +$existingRuleset = Invoke-CfApi -Method GET -Path "/zones/$zoneId/rulesets/phases/http_ratelimit/entrypoint" -Allow404 +$rulesToPut = @() +if ($existingRuleset -and $existingRuleset.result -and $existingRuleset.result.rules -and -not $isFreePlan) { + foreach ($r in $existingRuleset.result.rules) { + if ($r.description -ne $demoRuleDesc) { + $rulesToPut += $r + } + } +} +$rulesToPut += $demoRule + +[void](Invoke-CfApi -Method PUT -Path "/zones/$zoneId/rulesets/phases/http_ratelimit/entrypoint" -Body @{ + rules = $rulesToPut +}) +Write-Host " [OK] Active WAF Rate Limit: $rlRequests req / ${rlPeriod}s (block ${rlMitigation}s) on $DemoHostname (+ 60 req/min sustained in Nginx)" -ForegroundColor Green + +Write-Host '' +Write-Host '===============================================================' -ForegroundColor Cyan +Write-Host ' CLOUDFLARE CONFIGURATION COMPLETE!' -ForegroundColor Cyan +Write-Host '===============================================================' -ForegroundColor Cyan +Write-Host " Private App : https://$PrivateHostname (Zero Trust: $AllowedEmail)" +Write-Host " Public Demo : https://$DemoHostname (2 GB cap + WAF & Nginx rate limits)" +Write-Host '' diff --git a/deploy/sync.bat b/deploy/sync.bat index 0f2d5047..3b8c02b1 100644 --- a/deploy/sync.bat +++ b/deploy/sync.bat @@ -126,7 +126,7 @@ if not exist "%ENV_TMP%" ( exit /b 1 ) -call :ssh_pipe "%ENV_TMP%" "bash -s -- '%REMOTE_DIR%' '%POSTGRES_USER%' '%POSTGRES_DB%' '%POSTGRES_PASSWORD%' '%WEB_PORT%' '%TAVILY_API_KEY%' '%DOMAIN%'" +call :ssh_pipe "%ENV_TMP%" "bash -s -- '%REMOTE_DIR%' '%POSTGRES_USER%' '%POSTGRES_DB%' '%POSTGRES_PASSWORD%' '%WEB_PORT%' '%TAVILY_API_KEY%' '%DOMAIN%' '%CF_TUNNEL_TOKEN%'" set ENV_RC=%ERRORLEVEL% if defined ENV_TMP if exist "%ENV_TMP%" del "%ENV_TMP%" 2>nul if not %ENV_RC% equ 0 ( @@ -146,13 +146,18 @@ if not "%1"=="--from-deploy" ( call :ssh_run "!COMPOSE_CMD! stop qpp-frontend" >nul 2>&1 ) -REM Keep `web` and `quicktunnel` running (--no-recreate --no-deps) so the *.trycloudflare.com URL never changes on sync/--restart. +REM Keep `web` running (--no-recreate --no-deps). When using Quick Tunnel (no CF_TUNNEL_TOKEN), +REM also keep `quicktunnel` --no-recreate so the *.trycloudflare.com URL never changes on sync. +REM When CF_TUNNEL_TOKEN is set, allow `quicktunnel` to recreate automatically if the token changed. +set "TUNNEL_UP_FLAGS=--no-recreate --no-deps" +if defined CF_TUNNEL_TOKEN set "TUNNEL_UP_FLAGS=--no-deps" + if "%1"=="--from-deploy" ( set "REMOTE_CMD=!COMPOSE_CMD! up -d --build" ) else if %BUILD% equ 1 ( - set "REMOTE_CMD=!COMPOSE_CMD! up -d --no-recreate --no-deps postgres && !COMPOSE_CMD! up -d --build --no-deps qpp-backend qpp-frontend && !COMPOSE_CMD! up -d --no-recreate --no-deps web quicktunnel" + set "REMOTE_CMD=!COMPOSE_CMD! up -d --no-recreate --no-deps postgres && !COMPOSE_CMD! up -d --build --no-deps qpp-backend qpp-frontend && !COMPOSE_CMD! up -d --no-recreate --no-deps web && !COMPOSE_CMD! up -d !TUNNEL_UP_FLAGS! quicktunnel" ) else ( - set "REMOTE_CMD=!COMPOSE_CMD! up -d --no-recreate --no-deps postgres web quicktunnel qpp-backend qpp-frontend && !COMPOSE_CMD! restart qpp-backend" + set "REMOTE_CMD=!COMPOSE_CMD! up -d --no-recreate --no-deps postgres web qpp-backend qpp-frontend && !COMPOSE_CMD! up -d !TUNNEL_UP_FLAGS! quicktunnel && !COMPOSE_CMD! restart qpp-backend" ) call :ssh_run "!REMOTE_CMD!" @@ -190,7 +195,19 @@ echo. echo [INFO] Container status: call :ssh_run "!COMPOSE_CMD! ps" -REM -- Quick tunnel URL (random *.trycloudflare.com) ------------------- +REM -- Tunnel URL (Named Cloudflare Tunnel or random *.trycloudflare.com) --- +if defined CF_TUNNEL_TOKEN ( + echo. + if not "%DOMAIN%"=="" ( + echo =============================================================== + echo PRIVATE APP URL ^(Cloudflare Tunnel^): https://%DOMAIN% + echo =============================================================== + ) else ( + echo [OK] Cloudflare Named Tunnel active ^(CF_TUNNEL_TOKEN configured^). + ) + goto :sync_end +) + set QUICK_URL= echo. echo [INFO] Waiting for the Cloudflare Quick Tunnel URL... diff --git a/docs/api/qaqc.md b/docs/api/qaqc.md index fdf96180..c4378ba6 100644 --- a/docs/api/qaqc.md +++ b/docs/api/qaqc.md @@ -1,20 +1,12 @@ -# Multi-Well QA/QC & Stratigraphic Normalization (`quick_pp.qaqc`) +# Logging Environment, Borehole Corrections, QA/QC & Normalization (`quick_pp.environment`, `quick_pp.borehole_corrections`, `quick_pp.qaqc`) -Borehole environmental corrections, neutron-density hydrocarbon corrections, bad-hole flagging, and multi-well zone-by-zone quantile/histogram normalization. +Unified logging-environment physics, tool-profile (`WL` / `LWD`) borehole environmental corrections with per-sample uncertainty (`*_SIGMA`) and sensor confidence (`*_QC_CONF`), 2/3-curve radial resistivity invasion inversion, neutron-density hydrocarbon corrections, 4-criterion bad-hole flagging, and multi-well zone-by-zone quantile/histogram normalization. -Environmental correction outputs use distinct `*_ENV_CORR` mnemonics. Density reconstruction -has its own `RHOB_DEN_CORR` output. -They remain preview/derived curves; downstream calculations do not select them automatically. +Environmental correction outputs use distinct `*_ENV_CORR` mnemonics alongside `*_CORR_DELTA`, `*_SIGMA`, `*_QC_CONF`, `*_QC_STATUS`, `HOLE_SEVERITY`, `ENV_QC_REASON`, and radial invasion curves (`INVASION_FLAG`, `INVASION_PROFILE`, `DI_IN`). Density reconstruction has its own `RHOB_DEN_CORR` output. Downstream calculations use raw curves unless `use_env_corrected` / `confidence_weighting` (`confidence_weighted_curve`) is enabled. -## Mud system metadata +## Well Header & Hole Sections metadata -The QAQC Well Header panel stores the run-level mud system used by the -continuous fluid-density engine: `mud_type` (`WBM`/`OBM`/`SBM`) and -`obm_base_density` (g/cc), alongside the existing `rmf`, -`mud_filtrate_salinity`, and `mud_filtrate_density` fields. These are read from -the LAS header where present and can be overridden per well. See -[Porosity Evaluation](porosity.md#continuous-apparent-fluid-density-rho_fl) for -how they feed the $\rho_{fl}$ solver. +The **Well & Ancillary** step (`InspectorAncillary.svelte`, Step 1 in the Single-Well workflow) manages both the Well Header metadata (`mud_type` `WBM`/`OBM`/`SBM`, `obm_base_density`, `rm`, `rmf`, `rmc`, `mud_filtrate_salinity`, `mud_filtrate_density`, water depth, air gap, and BHT records) and depth-zoned **Hole Sections** (`top`, `bottom`, `bit_size`, `mud_type`, `mud_weight`, `mud_salinity`, `rmf`, `rmf_temp`). These synthesize nominal bit size (`BS`) and depth-specific mud properties for `badhole_flagging`, `apply_environmental_corrections`, and the continuous apparent fluid-density ($\rho_{fl}$) solver in [Porosity Evaluation](porosity.md#continuous-apparent-fluid-density-rho_fl). ## Hydrocarbon correction targets @@ -42,16 +34,21 @@ hydrogen index, and lithology-scaled excavation term follow the supplied method equations. The selected saturation is returned as `SHC_INV`. The method requires well-header `mud_filtrate_density` (g/cc) and -`mud_filtrate_salinity` (ppm), editable in the QAQC Well Header panel. Lithology +`mud_filtrate_salinity` (ppm), editable in the Well Header panel in **Well & Ancillary**. Lithology coefficient `K` defaults to 1. Density porosity is estimated from the dry-sand density endpoint and mud-filtrate density; corrected `VSH_DN` is evaluated in the -matrix/clay/mud-filtrate crossplot triangle. These are explicit implementation -conventions where the supplied excerpts did not define `phi_D` or the exact -`VSH_DN` calculation. - -This is an effective invaded-zone saturation correction, not a radial invasion -simulator: separate neutron and density investigation radii and radial saturation -profiles are not modeled. The separate “Default method” in the supplied screenshots -is not implemented because its `NFAC` and `HCORR` equations were not provided. +matrix/clay/mud-filtrate crossplot triangle. + +--- + +## Unified Logging Environment (`quick_pp.environment`) + +::: quick_pp.environment + +## Borehole Corrections, Sensor Confidence & Radial Invasion (`quick_pp.borehole_corrections`) + +::: quick_pp.borehole_corrections + +## Bad-Hole Flagging, Normalization & Curve Reconstruction (`quick_pp.qaqc`) ::: quick_pp.qaqc diff --git a/docs/api/source_rock.md b/docs/api/source_rock.md new file mode 100644 index 00000000..55418e5e --- /dev/null +++ b/docs/api/source_rock.md @@ -0,0 +1,5 @@ +# Source Rock & Total Organic Carbon (`quick_pp.source_rock`) + +Organic-rich source rock identification and continuous Total Organic Carbon (`TOC`, wt%) quantification via Passey et al. (1990) $\Delta\log R$ resistivity-porosity separation (`passey_delta_log_r`), automated lean-shale baseline detection (`auto_detect_shale_baseline`), Hood et al. (1975) Level of Organic Metamorphism (`LOM`) thermal maturity conversion (`hood_ro_to_lom`, `hood_lom_to_ro`), and linear core pyrolysis TOC calibration (`calibrate_toc_to_core`). + +::: quick_pp.source_rock diff --git a/docs/community/changelog.md b/docs/community/changelog.md index 90b79f56..fedfa004 100644 --- a/docs/community/changelog.md +++ b/docs/community/changelog.md @@ -2,6 +2,29 @@ ## Unreleased +## 0.3.8 (2026-11-27) +- Added **Unified Logging Environment, Borehole Environmental Corrections, Sensor Confidence ($\sigma$) & Step-Profile Radial Invasion** (`quick_pp/environment.py`, `quick_pp/borehole_corrections.py`, `InspectorQaqc.svelte`, `CrossplotCanvas.svelte`, `envCorrQc.ts`, `tempPressureProfile.ts`, `tests/test_borehole_corrections.py`): + - Unified SI-internal `Environment` and `MudInterval` models supporting onshore and offshore (`water_depth_m`, `air_gap_m`, `seabed_temp_c`) temperature profiles calibrated to BHT records, hydrostatic/mud-column pressure profiles, and Arps / Bateman-Konen downhole fluid resistivities ($R_m, R_{mf}, R_w$). + - Tool-profile (`WL` and `LWD`) borehole corrections (`GR_ENV_CORR` mud-annulus attenuation & KCl potassium stripping, `NPHI_ENV_CORR` multi-term environmental adjustment, `RHOB_ENV_CORR` spine-and-ribs `DRHO` double-compensation guard, and `RT_ENV_CORR` conductive washout stripping) emitting perturbation-propagated per-sample uncertainty (`*_SIGMA`), sensor confidence (`*_QC_CONF`), status (`*_QC_STATUS`), `HOLE_SEVERITY`, bitmask `ENV_QC_REASON` (washout, high DRHO, badhole, invasion, isolated MAD spike, flatline, Gardner-checked sonic cycle-skip), and optional downstream confidence-weighted input blending (`confidence_weighted_curve`). + - 2- and 3-curve Gaussian step-profile radial resistivity invasion inversion (`invert_invasion_profile`, `classify_invasion_profile`) solving true $R_t$, flushed $R_{xo}$, and invasion diameter $d_i$ (`DI_IN`), and classifying $\log_{10}(R_{xo}/R_t)$ vs. $\log_{10}(R_{mf}/R_w)$ into water-like, movable hydrocarbon-like, tight/uninvaded, or anomalous intervals (`INVASION_FLAG`, `INVASION_PROFILE`). + - Added three dedicated right-pane diagnostic views in Single-Well **Data & QAQC**: **Borehole Env Correction QC**, **Invasion Profile**, and **P&T Profile**. +- Added **Depth-Zoned Hole Sections, Single-Well Step 1/2 Reordering & Header $R_{mf}$ Wiring** (`InspectorAncillary.svelte`, `WorkflowStepper.svelte`, `quick_pp/database/models.py`, `quick_pp/database/objects.py`, `quick_pp/app/backend/services/ancillary.py`, `InspectorLithoPoro.svelte`, `tests/test_ancillary.py`): + - Added persistent depth-zoned **Hole Sections** (`top`, `bottom`, `bit_size`, `mud_type`, `mud_weight`, `mud_salinity`, `rmf`, `rmf_temp`) in Ancillary Data and bulk ancillary imports, automatically synthesizing continuous `BS` curves and depth-specific mud programs for downstream QA/QC. + - Swapped Single-Well **Step 1 (`Well & Ancillary`)** and **Step 2 (`Data & QAQC`)** so well headers, Hole Sections, tops, and minimum-curvature `TVD`/`TVDSS` trajectories are established prior to log conditioning. + - Added bidirectional Well Header $R_{mf} \leftrightarrow$ mud-filtrate salinity conversion (`fluidUnits.ts`) wired directly into Lithology & Porosity continuous fluid density ($\rho_{fl}$). +- Overhauled **Automated FDP & Single-Well CPI Report Generation** (`quick_pp/app/backend/services/report.py`, `quick_pp/plotter/report_plots.py`, `InspectorReport.svelte`, `quick_pp/app/backend/template/reports/sections/*.md.j2`, `report_print.css`, `tests/test_report_generation.py`): + - Integrated Borehole Mud-Program Hole Sections, per-sensor Environmental Correction & Uncertainty (`*_SIGMA`, `*_QC_CONF`) tables, Step-Profile Radial Invasion ($R_{xo}/R_t$ vs. $R_{mf}/R_w$) movable-hydrocarbon summaries, and high-DPI Borehole Environment QC figures into Single-Well CPI and Multi-Well FDP reports. + - Added automated **Subsurface QA/QC Gate-Check & Peer-Review Audit (`CHK-01`+)** and **Detected Subsurface Anomalies & Handover Remediation** tables (`10_gate_checks.md.j2`) with interactive pre-render audit checks in `InspectorReport.svelte`. + - Delivered Phases 1–4 physics, contact reconciliation, FPT gradient, uncertainty, upscaling, editorial, and print-ready A4 PDF export enhancements. +- Added **PRMS Cutoff Sensitivity Analysis, Optional Perm Cutoffs & Multi-Well Volumetrics Improvements** (`quick_pp/ressum.py`, `InspectorResSum.svelte`, `MultiWellVolumetrics.svelte`, `VolumetricsCanvas.svelte`, `tests/test_ressum_perm_cutoff.py`, `tests/test_multi_well_volumetrics_wiring.py`): + - Added empirical **Cutoff Sensitivity Analysis** (`cutoffs_analysis`, default $95\%$ HCPV recovery threshold across $V_{\text{sh}}, \phi_t, S_{wt}$) to both Single-Well **Reservoir Summary** and Multi-Well **Volumetric Assessment**, plus optional permeability cutoffs (`PERM`) in Reservoir Summary and log blocking. + - Improved Multi-Well Volumetrics fluid-contact inheritance (`OWC`, `GOC`, `GWC`, global/zonal `FWL`) from Step 5 SHF and Standalone FPT, 1D Hypsometric SHF integration, and interactive volumetric visual panels. +- Added **Reversible Interval Manual Overrides & Multi-Well SCAL / FPT / Stick Plot Refinements** (`InspectorLithoPoro.svelte`, `InspectorSaturation.svelte`, `MultiWellSwirr.svelte`, `MultiWellFpt.svelte`, `StickPlotCanvas.svelte`, `tests/test_litho_overrides.py`, `tests/test_scal_swirr.py`, `tests/test_fpt_api.py`): + - Added well-isolated, reversible interval **Manual Overrides** for `COAL_FLAG` and `BADHOLE` in Lithology & Porosity (preserving `COAL_BASE` / `BADHOLE_BASE`) and hardened compact scrollable `SWT` / `FLUID_TYPE` overrides in Saturation. + - Removed hardcoded $>200\,\text{psi}$ MICP scaling assumptions in SCAL capillary pressure conversion, synchronized Petrophysical Rock Type (`PRT`) assignments across Rock Typing, SCAL, and Stick Plot, persisted fitted $J$/$P_c$ parameters across SHF runs, improved Stick Plot zoning and hover inspection, and fixed FPT zone filtering, saved-parameter restoration, and strict `TVDSS` resolution. +- Hardened **Handover Package Persistence, Live Demo Security, Cloudflare Deployment & SSOT Reference** (`quick_pp/handover.py`, `demo_guard.py`, `deploy/setup-cloudflare.ps1`, `docs/workflows/*.md`, `ssot_reference.py`, `WorkflowGuideSheet.svelte`, `tests/test_handover.py`, `tests/test_live_demo.py`, `tests/test_ssot_reference.py`): + - Fixed full database persistence when importing `.zip` / `.qpp` Petrophysical Handover Packages, added configurable Live Demo rate/upload/session guardrails (`demo_guard.py`, `DemoSessionOverlays.svelte`) and Cloudflare deployment automation, and synchronized the Petrophysical SSOT Reference across Single-Well and Multi-Well workflows (reflecting the Step 1/2 swap, exact `Choo`/`Kozeny-Carman`/`Timur`/`Tixier`/`Coates` permeability equations, and Multi-Well FZI & power-law `PERM_TRANS` alignment). + ## 0.3.7 (2026-11-22) - Added **Standalone Source Rock & Total Organic Carbon (TOC) Evaluation Module** (`quick_pp/source_rock.py`, `InspectorToc.svelte`, `POST /workspace/wells/{well_name}/source_rock`, `LogTrackCanvas.svelte`, `WorkflowStepper.svelte`, `tests/test_source_rock.py`) providing end-to-end source rock geochemical quantification: - Implements the Passey et al. (1990) $\Delta\log R$ baseline separation technique across sonic transit time ($50\,\mu\text{s/ft}/\text{dec}$), bulk density ($-2.5\,\text{g/cm}^3/\text{dec}$), and neutron porosity ($0.25\,\text{v/v}/\text{dec}$) logs (`passey_delta_log_r`). diff --git a/docs/getting-started/ai-assistant.md b/docs/getting-started/ai-assistant.md index d06beaa6..fc816640 100644 --- a/docs/getting-started/ai-assistant.md +++ b/docs/getting-started/ai-assistant.md @@ -1,31 +1,33 @@ # Petrophysical AI Assistant & MCP Server -The `quick_pp` backend includes a built-in **Petrophysical AI Assistant** and **Model Context Protocol (MCP) Server** (`quick_pp/app/backend/mcp_server.py` and `quick_pp/app/backend/services/chat.py`) for interactive subsurface evaluation and automated FDP report synthesis. +The `quick_pp` backend includes a built-in **Petrophysical AI Assistant** and **Model Context Protocol (MCP) Server** (`quick_pp/app/backend/mcp_server.py` and `quick_pp/app/backend/services/chat.py`) for interactive subsurface evaluation, SSOT-grounded technical guidance, and automated CPI / FDP report synthesis. ## Features - **Zero-API-Key Built-in Agent (`native_mcp`)**: Runs deterministic and conformal petrophysical workflows and synthesizes grounded Lead Petrophysicist report commentary directly against project wells without requiring external API keys. +- **SSOT Grounding & Epistemic Confidence Grading**: Automatically grounds step-specific questions against the authoritative [Petrophysical SSOT Reference](../workflows/index.md) (`ssot_reference.py`) and explicitly grades every response with **High**, **Medium**, or **Low** confidence callouts based on direct tool evidence vs. uncalibrated assumptions. - **Multi-Provider LLM Support**: Switch between `native_mcp`, `openai`, `gemini`, `anthropic`, and local `ollama` directly from the workbench AI Assistant drawer or Report Workbench. - **In-Process Petrophysical MCP Tools**: - - `inspect_well`: Inspect available curves, depth intervals, formation tops, fluid contacts, core plug counts, and zonal statistics. - - `run_well_qaqc`: Execute outer-limit checks, washout/badhole flagging (`BADHOLE`), coal detection, and NPHI/RHOB hydrocarbon corrections (`NPHI_HC`, `RHOB_HC`, `HC_FLAG`). + - `inspect_well`: Inspect available curves, depth intervals, Hole Sections, formation tops, fluid contacts, core plug counts, and zonal statistics. + - `run_well_qaqc`: Execute outer-limit checks, 4-criterion washout/badhole flagging (`BADHOLE`), borehole environmental & radial invasion corrections (`*_ENV_CORR`, `*_SIGMA`, `*_QC_CONF`), coal detection, and NPHI/RHOB hydrocarbon corrections. - `run_multi_mineral`: Run `MultiMineral` or `SandSiltClay` lithology and porosity solvers. - - `run_shf_evaluation`: Run FZI rock typing, Leverett-J / Skelt-Harrison / Cuddy Saturation Height Function (`SHF`), and Free Water Level (`FWL`) optimization. + - `run_shf_evaluation`: Run FZI / Winland / Lucia rock typing, `PERM_TRANS` transforms, Leverett-$J$ / Skelt-Harrison / Cuddy Saturation-Height Function (`SHF`), and Free Water Level (`FWL`) optimization. - `evaluate_with_conformal_bounds`: Generate calibrated P10–P90 conformal prediction intervals (`PHIT_P10`/`P90`, `SW_P10`/`P90`, `PERM_P10`/`P90`). - - `control_workbench_ui`: Navigate workbench tabs, filter zones/depths, or scroll the log track canvas to a target depth. - - `get_project_report_context`: Retrieve compact project-level QA/QC, rock typing, FWL, and P10/P50/P90 reservoir summaries for grounded report commentary. - - `generate_petrophysical_report`: Generate 10-section `FDP_FULL` or `SINGLE_WELL_CPI` evaluation reports with high-DPI Matplotlib figures and open the Report Workbench. + - `get_workflow_technical_reference`: Query authoritative petrophysical equations, curve contracts, parameter bounds, and diagnostic guidelines from `docs/workflows/`. + - `control_workbench_ui`: Navigate workbench steps/modules, filter zones/depths, or scroll the log track canvas to a target depth. + - `get_project_report_context`: Retrieve compact project-level QA/QC, environmental/invasion audit, rock typing, FWL/FPT, P10/P50/P90 reservoir summaries, and subsurface gate checks (`CHK-01`+) for grounded report commentary. + - `generate_petrophysical_report`: Generate `FDP_FULL`, `SINGLE_WELL_CPI`, `QAQC_SUMMARY`, or `RESSUM_ONLY` evaluation reports with high-DPI Matplotlib figures and open the Report Workbench. - `update_report_section`: Rewrite or refine specific Markdown report sections in-place. - - `export_report_to_pdf`: Compile the active petrophysical report into a downloadable A4 PDF document. + - `export_report_to_pdf`: Compile the active petrophysical report into a downloadable multi-page A4 PDF document. ## API Endpoints - `GET /quick_pp/assistant/providers`: List supported LLM providers and models -- `POST /quick_pp/assistant/chat`: Execute an agentic chat turn with live tool calls and computed curves +- `POST /quick_pp/assistant/chat`: Execute an agentic chat turn with live tool calls, SSOT grounding, and computed curves - `GET /quick_pp/assistant/mcp/tools`: List registered Petrophysical MCP tools and JSON schemas - `POST /quick_pp/assistant/mcp/call`: Directly invoke a Petrophysical MCP tool - `POST /quick_pp/assistant/mcp`: Standard MCP JSON-RPC 2.0 Streamable HTTP endpoint -- `GET /quick_pp/projects/{project_id}/reports/context`: Retrieve compact report context JSON +- `GET /quick_pp/projects/{project_id}/reports/context`: Retrieve pre-render gate-check & report context JSON - `POST /quick_pp/projects/{project_id}/reports/generate`: Generate an FDP or Single-Well CPI report - `POST /quick_pp/projects/{project_id}/reports/{report_id}/enhance`: AI-enhance a report section (`executive`, `technical`, `concise`, `audit`) - `GET /quick_pp/projects/{project_id}/reports/{report_id}/pdf`: Download compiled multi-page A4 PDF report diff --git a/docs/index.md b/docs/index.md index 9d956949..cbb3fe37 100644 --- a/docs/index.md +++ b/docs/index.md @@ -3,28 +3,28 @@ [![PyPI version](https://img.shields.io/pypi/v/quick_pp.svg)](https://pypi.org/project/quick-pp/) [![Documentation Status](https://readthedocs.org/projects/quick-pp/badge/?version=latest)](https://quick-pp.readthedocs.io/en/latest/?version=latest) -**`quick_pp`** is a comprehensive Python package and full-stack web platform for deterministic and probabilistic petrophysical evaluation, Special Core Analysis (SCAL) & relative permeability modeling, multi-well Free Water Level (FWL) & Formation Pressure Testing (FPT) contact analysis, stratigraphic log normalization, core-log calibration & depth matching, automated FDP report generation, and static-to-dynamic geomodeling upscaling. +**`quick_pp`** is a comprehensive Python package and full-stack web platform for deterministic and probabilistic petrophysical evaluation, unified borehole environmental & radial invasion QC, Special Core Analysis (SCAL) & relative permeability modeling, multi-well Free Water Level (FWL) & Formation Pressure Testing (FPT) contact analysis, stratigraphic log normalization, source-rock TOC geochemistry, automated CPI/FDP report generation with subsurface gate checks, and static-to-dynamic geomodeling upscaling. --- ## Core Capabilities -- **Multi-Mineral, Clastic & Thomas-Stieber Petrophysics** ([`quick_pp.lithology`](api/lithology.md), [`quick_pp.porosity`](api/porosity.md), [`quick_pp.saturation`](api/saturation.md), [`quick_pp.permeability`](api/permeability.md)): - Sand-Silt-Clay (modified Kuttan), Carbonate, optimization-based Multi-Mineral solver, and Thomas-Stieber laminated sand-shale evaluation (`VSH_LAM`, `VSH_DISP`, `VSH_STR`, `PHIT_TS`, `PHIE_TS`, `PHISAND_TS`) with Simandoux, Indonesian, Dual-Water, Waxman-Smits, Juhasz, and Archie saturation models. -- **Multi-Well Contact, Swirr & Formation Pressure Testing (FPT)** ([`quick_pp.saturation`](api/saturation.md), [`quick_pp.fluid_type`](api/rock_type.md)): - Simultaneous multi-well Free Water Level ($\text{FWL}$), Oil-Water Contact ($\text{OWC}$), and Top of Transition Zone ($\text{TTZ}$) solver reconciling resistivity-derived $S_w$, capillary pressure Saturation-Height Models ($S_{w,\text{SHM}}$ via Leverett-$J$, Skelt-Harrison, and Cuddy), multi-well irreducible water saturation (`Swirr` via RQI, Semi-log $k$, and Timur correlations), and wireline formation tester (MDT/RFT) pressure gradient regression (`FormationPressureAnalyzer` with OLS/Huber/RANSAC, automatic supercharge/tight flagging, in-situ fluid density, and Monte Carlo P10/P50/P90 GOC/OWC/GWC contact intersections). -- **Rock Typing & Supervised Rock Flag Classification** ([`quick_pp.rock_type`](api/rock_type.md)): - Hydraulic Flow Unit (`FZI`, `RQI`, `GHE`), Winland $R_{35}$, and Pittman pore-throat rock typing, plus standalone multi-well `RandomForestClassifier` rock-type training, cross-validation, and uncored well prediction (`train_and_validate_rock_type_classifier`, `predict_with_saved_rt_classifier`) using both raw logs and calculated petrophysical curves (`PHIT`, `VSAND`, `VSHALE`, `VSILT`, `VCLAY`, `VDL`). -- **Special Core Analysis (SCAL), Core Calibration & Depth Matching** ([`quick_pp.scal`](api/scal.md), [`quick_pp.core_analysis`](api/core_analysis.md)): - Laboratory-to-reservoir core plug corrections (hydrostatic/uniaxial overburden compaction, Klinkenberg gas slippage, and Dean-Stark clay-bound water reconciliation preserving ambient `CPORE_AMB`/`CPERM_AIR` lineage), interactive core-to-log depth shifting (piecewise linear anchor tables & automated cross-correlation shift suggestion), 1:1 Estimation vs. Core parity crossplots (`PHIT` vs `CPORE`, `PERM` vs `CPERM`), capillary pressure scaling, two-phase relative permeability models (**Corey**, **Brooks-Corey**, and **LET**), automated SCAL curve fitting (`fit_relperm`), and Eclipse/Intersect `SWOF` table generation (`generate_swof_table`). -- **Probabilistic Uncertainty & Monte Carlo Engine** ([`quick_pp.uncertainty`](api/uncertainty.md)): - Vectorized Latin Hypercube Sampling (`scipy.stats.qmc.LatinHypercube`) for volumetric hydrocarbon in-place uncertainty (`mc_volumetric_uncertainty`), log-level CPI uncertainty propagation (`run_cpi_uncertainty` producing `P10`/`P50`/`P90` curves), and stochastic reservoir summaries (`calc_stochastic_reservoir_summary`). -- **Log Blocking & Static-to-Dynamic Upscaling** ([`quick_pp.upscaling`](api/upscaling.md)): - Petrophysically rigorous blocking (`upscale_logs`, `block_logs`) onto cellular geomodel grids with thickness-weighted arithmetic porosity/shale averaging, pore-volume weighted saturation averaging (preserving `BVHC`), directional & Cardwell-Parsons (1945) power-law permeability bounds ($k_h, k_{\text{eff}}, k_v, k_v/k_h$), and majority-vote facies upscaling. -- **Multi-Well QA/QC, Stratigraphic Normalization & Stick Plots** ([`quick_pp.qaqc`](api/qaqc.md)): - Zone-by-zone multi-well quantile and histogram log normalization (`stratigraphic_normalization` / `normalize_by_zone`), borehole environmental and invasion corrections (`apply_environmental_corrections`), neutron-density hydrocarbon corrections, automated washout/bad-hole flagging (`badhole_flagging`), and multi-well structural/stratigraphic Stick Plot cross-sections. -- **High-Throughput Multi-Format Log Import, Handover Packages & Automated FDP Reports** ([`quick_pp.las_handler`](api/plotter.md), [`quick_pp.handover`](api/plotter.md), [`quick_pp.plotter.report_plots`](api/plotter.md)): - Fast hybrid LAS 2.0/3.0, DLIS, LIS79, CSV, and Parquet ingestion with mnemonic mapping, unit standardization, and multi-run splicing; zero-friction `.zip` handover package generation (`build_handover_archive_bytes`) with LAS 2.0 exports (`~Well` headers + `~Parameter` CPI settings), Formation Tops, Fluid Contacts & Perforations (with `TVD` and `TVDSS`), Core RCA & MDT LAS point-sets, multi-tab Excel workbooks, Eclipse `SWOF` decks, and ready-to-run SLB Techlog (`import_to_techlog.py`) & Emerson Geolog (`import_to_geolog.tcl`) loader scripts; plus automated 10-section FDP & Single-Well CPI report generation with publication-grade figures and A4 PDF / print HTML export. +- **Logging Environment, Borehole Corrections, Sensor Confidence & Radial Invasion** ([`quick_pp.environment`](api/qaqc.md), [`quick_pp.borehole_corrections`](api/qaqc.md), [`quick_pp.qaqc`](api/qaqc.md), [`quick_pp.conditioning`](api/conditioning.md)): + Depth-zoned **Hole Sections** (`BS`, mud system, mud weight, salinity, $R_{mf}$), onshore/offshore BHT-calibrated P&T profiles, generic `WL`/`LWD` borehole environmental corrections (`*_ENV_CORR` with spine-and-ribs `DRHO` double-compensation protection), perturbation-propagated per-sample uncertainty (`*_SIGMA`) and sensor confidence (`*_QC_CONF`), 2/3-curve step-profile radial invasion inversion ($R_t, R_{xo}, d_i$ & $R_{xo}/R_t$ vs. $R_{mf}/R_w$ movable-HC classification), 1D bounded Huber nuclear-log resolution harmonization (`GR_ENH`, `NPHI_ENH`, `RHOB_ENH`), missing-data imputation, and zone-by-zone stratigraphic quantile normalization. +- **Multi-Mineral, Clastic, Thin-Bed & Continuous $\rho_{fl}$ Petrophysics** ([`quick_pp.lithology`](api/lithology.md), [`quick_pp.porosity`](api/porosity.md), [`quick_pp.saturation`](api/saturation.md), [`quick_pp.permeability`](api/permeability.md)): + Sand-Silt-Clay, Carbonate, selectable-log SLSQP Multi-Mineral solver, and Thomas-Stieber laminated/dispersed/structural thin-bed evaluation (`VSH_LAM`, `VSH_DIS`, `VSH_STR`, `PHIT_SAND`, `RSAND_TS`), 3-tier coupled apparent fluid-density ($\rho_{fl}$) solver, adaptive-shoulder coal detection with reversible interval manual overrides, empirical single-well permeability (`Choo`, `Kozeny-Carman`, `Timur`, `Tixier`, `Coates`), Archie / Waxman-Smits / Simandoux / Indonesian / Dual-Water saturation, water-leg $m$ calibration & continuous $m(\phi)$ (`Borai`, `Shell/Lucia`), and multi-criteria reservoir fluid typing (`GAS`, `OIL`, `UNCONFIRMED`, `WATER`). +- **Source Rock & Total Organic Carbon (TOC) Geochemistry** ([`quick_pp.source_rock`](api/source_rock.md)): + Passey et al. (1990) $\Delta\log R$ baseline separation across sonic, density, and neutron logs, automated lean-shale baseline detection, Hood et al. (1975) Level of Organic Metamorphism (`LOM`) maturity conversion from $R_o\,\%$, and core pyrolysis TOC calibration. +- **Rock Typing, Power-Law `PERM_TRANS` & Supervised Classification** ([`quick_pp.rock_type`](api/rock_type.md)): + Dual Core (`CPORE`, `CPERM`) and Log (`PHIT`, `PERM`) Discrete Rock Typing (`ROCK_FLAG`) via Amaefule `FZI`/`RQI`, Winland $r_{35}$, and Lucia carbonate `RFN` with GMM, Modified Lorenz, or K-Means cutoff discovery and `ROCK_FLAG = 0` non-reservoir isolation; rock-type partitioned power-law permeability transforms ($k = a_k \cdot \phi^{b_k} \to \text{PERM\_TRANS}$); and supervised Random Forest / Gradient Boosting rock-type classification across uncored wells. +- **Multi-Well Contact, SHF, Stick Plot & Formation Pressure Testing (FPT)** ([`quick_pp.saturation`](api/saturation.md), [`quick_pp.fluid_type`](api/rock_type.md)): + Multi-well Leverett-$J$, Skelt-Harrison, and Cuddy Saturation-Height Functions ($S_{w,\text{SHF}}$), global and per-zone Free Water Level ($\text{FWL}$) optimization, `TVDSS` Stick Plot geological correlation (`GR`/`COAL` tracks & fluid limits `GUT`/`GDT`/`GOC`/`GWC`, `OUT`/`ODT`/`OWC`, `WUT`/`FWL`), and zone-filtered MDT/RFT pressure gradient regression on true `TVDSS` (`FormationPressureAnalyzer` with OLS/Huber/RANSAC, excess pressure, in-situ densities, and covariance $\pm 1\sigma$ contacts). +- **Special Core Analysis (SCAL), Core Calibration & Multi-Log Grain Density** ([`quick_pp.scal`](api/scal.md), [`quick_pp.core_analysis`](api/core_analysis.md)): + Interactive core-to-log depth shifting, overburden stress (scalar or log-integrated `SV_EST`/`NCS_EST`) and Klinkenberg corrections, multi-log Huber/ridge core grain-density ($\rho_{ma} \to \text{RHOM}$) calibration, explicit fluid-system lab-to-reservoir $P_c$ scaling, PRT Pore-Throat Size Distributions (`plot_ptsd_by_prt`), field-wide $S_{\text{wirr}}$ fitting, **Corey** / **Brooks-Corey** / **LET** relative permeability, and Eclipse `SWOF` deck export. +- **Probabilistic Volumetrics, Cutoff Sensitivity & Log Blocking** ([`quick_pp.ressum`](api/ressum.md), [`quick_pp.uncertainty`](api/uncertainty.md), [`quick_pp.upscaling`](api/upscaling.md)): + PRMS 95% HCPV empirical cutoff sensitivity sweeps (`cutoffs_analysis`), Iman-Conover correlated Latin Hypercube Monte Carlo STOIIP/GIIP (`AREA` & `GRV` modes, Log-Average vs. 1D Hypsometric SHF integration, Tornado ranking), log-level CPI uncertainty propagation (`P10`/`P50`/`P90` utilizing `*_SIGMA`), and Cardwell-Parsons ($\omega \in [-1, 1]$) cellular log blocking. +- **Multi-Format Log Import, Bi-Directional Handover Packages & Automated CPI/FDP Reports** ([`quick_pp.las_handler`](api/plotter.md), [`quick_pp.handover`](api/plotter.md), [`quick_pp.plotter.report_plots`](api/plotter.md)): + Hybrid LAS 2.0/3.0, DLIS, LIS79, CSV, and Parquet ingestion with multi-run splicing; bi-directional `.zip` / `.qpp` handover archive export & persistent project import (with SLB Techlog & Emerson Geolog loader scripts, Excel workbooks, LAS point-sets & `SWOF` decks); and automated 10-section `FDP_FULL`, `SINGLE_WELL_CPI`, `QAQC_SUMMARY`, and `RESSUM_ONLY` reports with Borehole Env/Invasion QC audits, automated subsurface gate checks (`CHK-01`+), SSOT-grounded AI commentary, and multi-page A4 PDF export. - **Physics-Informed ML & Conformal Prediction** ([`quick_pp.machine_learning`](api/machine_learning.md)): Domain physics features (`RHOMA_APP`, `AI`, Burke's `M_LITH` & `N_LITH`), locally weighted split/cross-conformal intervals (`ConformalRegressor`, `ConformalMultiOutputRegressor`), and mineral volumetric closure (`EnforceMineralSum`). diff --git a/docs/workflows/index.md b/docs/workflows/index.md index 5d0a71d7..38a5005b 100644 --- a/docs/workflows/index.md +++ b/docs/workflows/index.md @@ -1,6 +1,6 @@ # Domain Workflows & Technical Foundations -`quick_pp` provides a dual-space architecture that bridges single-well deterministic petrophysics with field-scale multi-well reservoir characterization. Both spaces distinguish between **Primary Sequential Workflow Steps** (numbered 1 through 7) and **Standalone Specialized Modules**. +`quick_pp` provides a dual-space architecture that bridges single-well deterministic petrophysics with field-scale multi-well reservoir characterization. Both spaces distinguish between **Primary Sequential Workflow Steps** (numbered 1 through 7) and **Standalone Specialized Modules**, with full project state, curves, ancillary records, hole sections, and calibrated models portable via `.qpp` Handover Packages. --- @@ -11,7 +11,7 @@ flowchart TD subgraph SingleWellSpace["Single-Well Space (Trajectory / Log Scale)"] direction TB subgraph SW_Seq["Primary Sequential Workflow (Steps 1–7)"] - SW1["1. Data & QA/QC"] --> SW2["2. Tops & Ancillary"] + SW1["1. Well & Ancillary"] --> SW2["2. Data & QA/QC"] SW2 --> SW3["3. Lithology & Porosity"] SW3 --> SW4["4. Permeability"] SW4 --> SW5["5. Saturation"] @@ -19,10 +19,10 @@ flowchart TD SW6 --> SW7["7. Well CPI Report"] end subgraph SW_Stand["Standalone Specialized Modules"] - SW_LAB["Core & Pc Prep\n(Depth Shift, Stress Corrections, Lab Pc)"] + SW_LAB["Core & Pc Prep\n(Depth Shift, Stress Corrections, Lab Pc, Grain Density)"] SW_TOC["Source Rock & TOC\n(Passey Delta Log R, LOM & Maturity)"] end - SW_LAB -.->|Calibrated Core & Pc| SW3 + SW_LAB -.->|Calibrated Core & Rho_ma| SW3 SW_LAB -.->|Calibrated Core Perm| SW4 SW_TOC -.->|TOC & Source Flags| SW3 end @@ -31,8 +31,8 @@ flowchart TD direction TB subgraph MW_Seq["Primary Sequential Workflow (Steps 1–7)"] MW1["1. Field Inventory"] --> MW2["2. Data & Field QA/QC (Norm)"] - MW2 --> MW3["3. Rock Typing (FZI)"] - MW3 --> MW4["4. Perm Transform"] + MW2 --> MW3["3. Rock Typing (FZI / r35 / RFN)"] + MW3 --> MW4["4. Perm Transform (PERM_TRANS)"] MW4 --> MW5["5. Saturation Height (SHF)"] MW5 --> MW6["6. Volumetric Assessment"] MW6 --> MW7["7. FDP Report"] @@ -45,13 +45,14 @@ flowchart TD MW_PIML["Conformal ML Trainer\n(P10–P90 Physics ML Bounds)"] end MW_FPT -.->|FWL & Fluid Densities| MW5 + MW_FPT -.->|Contacts & Uncertainties| MW6 MW_SCAL -.->|Swirr & Capillary Parameters| MW5 MW_RT -.->|Predicted RTs| MW4 MW_PIML -.->|Conformal Bounds| MW6 end - SingleWellSpace -.->|Calibrated Key Wells & Parameters| MultiWellSpace - MultiWellSpace -.->|Field Normalization & Fluid Contacts| SingleWellSpace + SingleWellSpace -.->|Calibrated Key Wells, Curves & Cutoffs| MultiWellSpace + MultiWellSpace -.->|Normalized Logs, PERM_TRANS & Contacts| SingleWellSpace style SingleWellSpace fill:#f8fafc,stroke:#0284c7,stroke-width:2px style MultiWellSpace fill:#f0fdf4,stroke:#16a34a,stroke-width:2px @@ -73,39 +74,39 @@ The right-pane crossplot selector shows only plots supported by the active singl | Step Category | Stepper ID | UI Component | Markdown Anchor | Primary Petrophysical Function | | :--- | :--- | :--- | :--- | :--- | -| **Step 1** | `qaqc` | `InspectorQaqc.svelte` | [`#sw-step-1-qaqc`](single_well.md#sw-step-1-qaqc) | Outer limits, bad-hole flagging, resolution enhancement & curve repair | -| **Step 2** | `ancillary` | `InspectorAncillary.svelte` | [`#sw-step-2-ancillary`](single_well.md#sw-step-2-ancillary) | Minimum curvature trajectory & tops ingestion | -| **Step 3** | `litho-poro` | `InspectorLithoPoro.svelte` | [`#sw-step-3-litho-poro`](single_well.md#sw-step-3-litho-poro) | $V_{\text{sh}}$, SSC ternary, multi-mineral SLSQP, $\phi_e$, $\phi_t$ & $\rho_{fl}$ | -| **Step 4** | `perm` | `InspectorPerm.svelte` | [`#sw-step-4-perm`](single_well.md#sw-step-4-perm) | Choo, Timur-Coates, Tixier & Morris-Biggs permeability | -| **Step 5** | `saturation` | `InspectorSaturation.svelte` | [`#sw-step-5-saturation`](single_well.md#sw-step-5-saturation) | Archie, Waxman-Smits ($Q_v, B$), Dual Water, Indonesian, water-leg $m$ calibration, empirical $m(\phi)$ & fluid typing | -| **Step 6** | `ressum` | `InspectorResSum.svelte` | [`#sw-step-6-ressum`](single_well.md#sw-step-6-ressum) | Net Pay cutoffs, zonal summation & log blocking upscaling | -| **Step 7** | `report` | `InspectorReport.svelte` | [`#sw-step-7-report`](single_well.md#sw-step-7-report) | Automated CPI well report compilation | -| **Standalone** | `scal` | `InspectorScal.svelte` | [`#sw-standalone-core-pc`](single_well.md#sw-standalone-core-pc) | **Core & Pc Prep**: Depth shifting, stress corrections & lab-to-res $P_c$ | +| **Step 1** | `ancillary` | `InspectorAncillary.svelte` | [`#sw-step-1-ancillary`](single_well.md#sw-step-1-ancillary) | Well header ($R_{mf}$, BHT, datum), depth-zoned Hole Sections (`BS`, mud program), tops, core/SCAL/FPT tables & minimum curvature trajectory (`TVD`, `TVDSS`) | +| **Step 2** | `qaqc` | `InspectorQaqc.svelte` | [`#sw-step-2-qaqc`](single_well.md#sw-step-2-qaqc) | 4-criterion bad-hole flagging, borehole environmental & radial invasion corrections (`*_ENV_CORR`, `*_SIGMA`, `*_QC_CONF`), P&T/Invasion QC plots, imputation, resolution enhancement & curve splicing | +| **Step 3** | `litho-poro` | `InspectorLithoPoro.svelte` | [`#sw-step-3-litho-poro`](single_well.md#sw-step-3-litho-poro) | $V_{\text{sh}}$, SSC ternary, Thomas-Stieber ($V_{\text{lam}}, V_{\text{disp}}, V_{\text{str}}$), multi-mineral SLSQP, $\phi_t$, $\phi_e$, continuous $\rho_{fl}$, coal flagging & reversible manual overrides | +| **Step 4** | `perm` | `InspectorPerm.svelte` | [`#sw-step-4-perm`](single_well.md#sw-step-4-perm) | Empirical single-well permeability: Choo, Kozeny-Carman, Timur, Tixier & Coates-Dumanoir (with optional Thomas-Stieber thin-bed weighting & core calibration) | +| **Step 5** | `saturation` | `InspectorSaturation.svelte` | [`#sw-step-5-saturation`](single_well.md#sw-step-5-saturation) | Archie, Waxman-Smits ($Q_v, B$), Simandoux, Indonesian, Dual Water, water-leg $m$ calibration, continuous $m(\phi)$, fluid typing & manual overrides | +| **Step 6** | `ressum` | `InspectorResSum.svelte` | [`#sw-step-6-ressum`](single_well.md#sw-step-6-ressum) | Net Reservoir / Net Pay cutoffs (optional $k_{\text{cut}}$), PRMS 95% HCPV cutoff sensitivity, zonal summation, Cardwell-Parsons log blocking & stochastic log uncertainty | +| **Step 7** | `report` | `InspectorReport.svelte` | [`#sw-step-7-report`](single_well.md#sw-step-7-report) | Automated Single-Well CPI report with log QC/invasion audit, subsurface gate checks (`CHK-01`+) & A4 PDF export | +| **Standalone** | `scal` | `InspectorScal.svelte` | [`#sw-standalone-core-pc`](single_well.md#sw-standalone-core-pc) | **Core & Pc Prep**: Core depth shifting, overburden/Klinkenberg corrections, lab-to-res $P_c$ scaling & multi-log grain-density ($\rho_{ma}$) correlation | | **Standalone** | `toc` | `InspectorToc.svelte` | [`#sw-standalone-source-rock`](single_well.md#sw-standalone-source-rock) | **Source Rock & TOC**: Passey $\Delta\log R$, Hood LOM maturity, core geochemical calibration & log overlays | ### Multi-Well Space | Step Category | Stepper ID | UI Component | Markdown Anchor | Primary Field Petrophysical Function | | :--- | :--- | :--- | :--- | :--- | -| **Step 1** | `inventory` | `MultiWellInventory.svelte` | [`#mw-step-1-inventory`](multi_well.md#mw-step-1-inventory) | Multi-well completeness audit & canonical mnemonic aliasing | -| **Step 2** | `qaqc` | `MultiWellQaqc.svelte` | [`#mw-step-2-qaqc`](multi_well.md#mw-step-2-qaqc) | Key-well designation & stratigraphic quantile normalization | -| **Step 3** | `rock-typing` | `MultiWellRockTyping.svelte` | [`#mw-step-3-rock-typing`](multi_well.md#mw-step-3-rock-typing) | Core Hydraulic Flow Units (FZI), Winland $r_{35}$ & Lucia RFN | -| **Step 4** | `perm-transform` | `MultiWellPermTransform.svelte` | [`#mw-step-4-perm-transform`](multi_well.md#mw-step-4-perm-transform) | Rock-type partitioned poro-perm regression ($k = a \cdot e^{b\phi}$) | -| **Step 5** | `shf` | `MultiWellShf.svelte` | [`#mw-step-5-shf`](multi_well.md#mw-step-5-shf) | Saturation-Height Modeling (Leverett $J$ / Skelt-Harrison), fluid contacts & log reconciliation | -| **Step 6** | `volumetrics` | `MultiWellVolumetrics.svelte` | [`#mw-step-6-volumetrics`](multi_well.md#mw-step-6-volumetrics) | Probabilistic Monte Carlo LHS STOIIP/GIIP (P90/P50/P10) & Tornado | -| **Step 7** | `report` | `InspectorReport.svelte` | [`#mw-step-7-report`](multi_well.md#mw-step-7-report) | Field Development Plan (FDP) comprehensive report generation | +| **Step 1** | `inventory` | `MultiWellInventory.svelte` | [`#mw-step-1-inventory`](multi_well.md#mw-step-1-inventory) | Multi-well completeness audit, canonical mnemonic aliasing & bulk LAS/ancillary ingestion | +| **Step 2** | `qaqc` | `MultiWellQaqc.svelte` | [`#mw-step-2-qaqc`](multi_well.md#mw-step-2-qaqc) | Key-well stratigraphic quantile normalization, multi-well bad-hole/environmental conditioning & pooled missing-data imputation | +| **Step 3** | `rock-typing` | `MultiWellRockTyping.svelte` | [`#mw-step-3-rock-typing`](multi_well.md#mw-step-3-rock-typing) | Discrete Rock Typing (`ROCK_FLAG`) on Core or Logs via Amaefule FZI / RQI, Winland $r_{35}$, Lucia RFN & GMM/Lorenz cutoffs | +| **Step 4** | `perm-transform` | `MultiWellPermTransform.svelte` | [`#mw-step-4-perm-transform`](multi_well.md#mw-step-4-perm-transform) | Rock-type partitioned power-law poro-perm regressions ($k = a_k \cdot \phi^{b_k}$) generating field-wide `PERM_TRANS` | +| **Step 5** | `shf` | `MultiWellShf.svelte` | [`#mw-step-5-shf`](multi_well.md#mw-step-5-shf) | Saturation-Height Modeling (Leverett $J$ / Skelt-Harrison), Stick Plot geological correlation, fluid contacts/limits & log reconciliation | +| **Step 6** | `volumetrics` | `MultiWellVolumetrics.svelte` | [`#mw-step-6-volumetrics`](multi_well.md#mw-step-6-volumetrics) | Probabilistic LHS STOIIP/GIIP (`AREA` / `GRV`, Log-Average vs. 1D Hypsometric SHF), PRMS cutoff sensitivity, inherited contacts & Tornado | +| **Step 7** | `report` | `InspectorReport.svelte` | [`#mw-step-7-report`](multi_well.md#mw-step-7-report) | Field Development Plan (`FDP_FULL`, `QAQC_SUMMARY`, `RESSUM_ONLY`) dossier, subsurface gate-check audit & A4 PDF export | | **Standalone** | `batch-evaluation` | `MultiWellEvaluation.svelte` | [`#mw-standalone-batch-evaluation`](multi_well.md#mw-standalone-batch-evaluation) | Preview and apply isolated single-well calculations by well and zone | -| **Standalone** | `swirr-corr` | `MultiWellSwirr.svelte` | [`#mw-standalone-scal-relperm`](multi_well.md#mw-standalone-scal-relperm) | **SCAL & Rel-Perm**: Field Swirr fit, Brooks-Corey, LET & SWOF decks | -| **Standalone** | `fpt` | `MultiWellFpt.svelte` | [`#mw-standalone-fpt`](multi_well.md#mw-standalone-fpt) | **Pressure & Contacts**: MDT/RFT gradients, excess pressure, FWL/OWC/GOC | -| **Standalone** | `rt-classifier` | `MultiWellRtClassifierTrainer.svelte` | [`#mw-standalone-rt-classifier`](multi_well.md#mw-standalone-rt-classifier) | **RT Classifier**: Supervised classification (Random Forest / XGBoost) | -| **Standalone** | `ml-training` | `MultiWellMlTrainer.svelte` | [`#mw-standalone-ml-training`](multi_well.md#mw-standalone-ml-training) | **Conformal ML Trainer**: Physics-informed continuous ML with P10–P90 bounds | +| **Standalone** | `swirr-corr` | `MultiWellSwirr.svelte` | [`#mw-standalone-scal-relperm`](multi_well.md#mw-standalone-scal-relperm) | **SCAL & Rel-Perm**: Field $S_{\text{wirr}}$ fit, PRT pore-throat distributions, Brooks-Corey, LET & ECLIPSE `SWOF` decks | +| **Standalone** | `fpt` | `MultiWellFpt.svelte` | [`#mw-standalone-fpt`](multi_well.md#mw-standalone-fpt) | **Pressure & Contacts**: Zone-filtered MDT/RFT gradients on `TVDSS`, excess pressure & `FWL`/`OWC`/`GOC` $\pm 1\sigma$ | +| **Standalone** | `rt-classifier` | `MultiWellRtClassifierTrainer.svelte` | [`#mw-standalone-rt-classifier`](multi_well.md#mw-standalone-rt-classifier) | **RT Classifier**: Supervised discrete rock-type classification (Random Forest / Gradient Boosting) & model registry | +| **Standalone** | `ml-training` | `MultiWellMlTrainer.svelte` | [`#mw-standalone-ml-training`](multi_well.md#mw-standalone-ml-training) | **Conformal ML Trainer**: Physics-informed continuous ML with distribution-free P10–P90 bounds | --- ## Detailed Technical References - [**Single-Well Petrophysical Workflow**](single_well.md): - Covers the 7-step deterministic evaluation pipeline and standalone modules (Core & Pc Prep, Source Rock & TOC). + Covers the 7-step deterministic evaluation pipeline (starting from Well & Ancillary setup through Data & QA/QC to CPI reporting) and the 2 standalone modules (Core & Pc Prep, Source Rock & TOC). - [**Multi-Well Field Evaluation Workflow**](multi_well.md): - Covers the 7-step field characterization pipeline and the 5 standalone specialized modules (Multi-Well Evaluation, SCAL & Rel-Perm, Formation Pressure & Contacts, RT Classifier, Conformal PIML). + Covers the 7-step field characterization pipeline (including FZI/Winland/Lucia rock typing and power-law `PERM_TRANS` transforms) and the 5 standalone specialized modules (Multi-Well Evaluation, SCAL & Rel-Perm, Formation Pressure & Contacts, RT Classifier, Conformal PIML). diff --git a/docs/workflows/multi_well.md b/docs/workflows/multi_well.md index c7bdc6d5..b3a89679 100644 --- a/docs/workflows/multi_well.md +++ b/docs/workflows/multi_well.md @@ -1,16 +1,16 @@ # Multi-Well Field Evaluation Workflow -The Multi-Well workspace harmonizes multi-vintage logging suites across the entire field, establishes consistent stratigraphic baselines, models core-calibrated Petrophysical Rock Types and permeability transforms, calculates field-wide Saturation-Height Functions ($\text{SHF}$), and runs Monte Carlo volumetric uncertainty. +The Multi-Well workspace harmonizes multi-vintage logging suites across the entire field, establishes consistent stratigraphic baselines, models discrete Petrophysical Rock Types (`ROCK_FLAG`) and power-law permeability transforms (`PERM_TRANS`), calculates field-wide Saturation-Height Functions ($\text{SHF}$), and runs probabilistic Monte Carlo volumetric uncertainty. In Field QA/QC, **Missing Data Imputation** uses selected wells and the active depth and zone filters. Mean, median, most frequent, KNN, and iterative models fit pooled samples; KNN scales curves before computing distances. Forward/backward fill and depth-based linear interpolation operate independently within each well; interpolation leaves end gaps missing. Results are saved as separate `_IMP` curves by default. Alternatively, replace existing curves while preserving a full-well `_ORI` backup; existing backups are never overwritten. Replacement requires the source curve to exist in every selected well. Existing `_IMP` outputs must be renamed or deleted before re-running in new-curve mode, and curves with no observed values across the selected wells cannot be imputed. The right-pane **Missing Matrix** displays one selected well at a time, with deeper depths at the top and colors showing the missing fraction in each depth bin. -The workflow is structured into **7 Primary Sequential Steps** for end-to-end field evaluation, complemented by **5 Standalone Specialized Modules** (Multi-Well Evaluation, SCAL & Dynamic Relative Permeability, Formation Pressure & Contacts, Discrete Rock Type Classifier Trainer, and Conformal Physics-Informed ML Trainer). +The workflow is structured into **7 Primary Sequential Steps** for end-to-end field evaluation, complemented by **5 Standalone Specialized Modules** (Multi-Well Evaluation, SCAL & Dynamic Relative Permeability, Formation Pressure & Contacts, Discrete Rock Type Classifier Trainer, and Conformal Physics-Informed ML Trainer). Project-scoped module parameters and curves persist seamlessly into `.qpp` Handover Packages. --- ## 1. Workflow Architecture (Level 1 & Level 2) {#mw-level-1-2-diagrams} -### Level 1: Macro Workflow +#### Level 1: Macro Workflow High-level progression from field data ingestion to probabilistic reserves, showing the 7 sequential steps and the 5 standalone modules. @@ -18,27 +18,28 @@ High-level progression from field data ingestion to probabilistic reserves, show flowchart TD subgraph Primary ["Primary Sequential Workflow (Steps 1 to 7)"] direction LR - S1["1. Field Inventory\n(Multi-LAS, Surveys, Tops)"] --> S2["2. Field QA/QC\n(Stratigraphic Normalization)"] - S2 --> S3["3. Rock Typing (FZI)\n(Amaefule, Winland, Lucia)"] - S3 --> S4["4. Perm Transform\n(RT-Partitioned k-phi)"] - S4 --> S5["5. Saturation Height\n(Leverett J, Skelt-Harrison)"] - S5 --> S6["6. Volumetrics\n(Monte Carlo LHS STOIIP/GIIP)"] - S6 --> S7["7. FDP Report\n(Comprehensive Synthesis)"] + S1["1. Field Inventory\n(Multi-LAS, Hole Sections, Surveys, Tops)"] --> S2["2. Field QA/QC\n(Norm, Env/Badhole Conditioning, Imputation)"] + S2 --> S3["3. Rock Typing\n(Amaefule FZI, Winland r35, Lucia RFN)"] + S3 --> S4["4. Perm Transform\n(Power-Law k = a·φ^b → PERM_TRANS)"] + S4 --> S5["5. Saturation Height\n(Leverett J, Skelt-Harrison, Stick Plot)"] + S5 --> S6["6. Volumetrics\n(LHS STOIIP/GIIP, Hypsometric SHF, Cutoffs)"] + S6 --> S7["7. FDP Report\n(Executive Dossier, Gate Checks, PDF)"] end subgraph Standalone ["Standalone Specialized Modules"] direction TB M_BATCH["Multi-Well Evaluation\n(Shared single-well models)"] - M_SCAL["SCAL & Rel-Perm\n(Swirr Fit, Brooks-Corey, LET, SWOF)"] - M_FPT["Pressure & Contacts (FPT)\n(MDT/RFT, Fluid Densities, FWL/OWC/GOC)"] - M_CLF["RT Classifier\n(Supervised RF/XGBoost, Model Registry)"] + M_SCAL["SCAL & Rel-Perm\n(Swirr Fit, PRT PTSD, Corey, LET, SWOF)"] + M_FPT["Pressure & Contacts (FPT)\n(Zone-Filtered MDT/RFT on TVDSS, FWL/OWC/GOC)"] + M_CLF["RT Classifier\n(Supervised RF/GBM, Model Registry)"] M_ML["Conformal ML Trainer\n(PIML Continuous Regressors, P10-P90)"] end + M_BATCH -.->|"Evaluated PHIT, PERM & SWT"| S3 M_FPT -.->|"FWL & In-Situ Densities"| S5 - M_SCAL -.->|"Calibrated Swirr & RelPerm"| S4 - M_SCAL -.->|"Capillary J-Functions"| S5 - M_CLF -.->|"Propagated Rock Types"| S4 + M_FPT -.->|"Contacts & Uncertainties"| S6 + M_SCAL -.->|"Calibrated Swirr & Pc Fits"| S5 + M_CLF -.->|"Propagated ROCK_FLAG_ML"| S4 M_ML -.->|"Conformal Uncertainty Bounds"| S6 style S1 fill:#f8fafc,stroke:#475569,stroke-width:1.5px @@ -49,108 +50,94 @@ flowchart TD style S6 fill:#fef3c7,stroke:#d97706,stroke-width:1.5px style S7 fill:#eff6ff,stroke:#2563eb,stroke-width:2px + style M_BATCH fill:#f0fdfa,stroke:#0d9488,stroke-dasharray: 4 4 style M_SCAL fill:#fffbeb,stroke:#b45309,stroke-dasharray: 4 4 style M_FPT fill:#fff1f2,stroke:#be123c,stroke-dasharray: 4 4 style M_CLF fill:#f0fdfa,stroke:#0f766e,stroke-dasharray: 4 4 style M_ML fill:#faf5ff,stroke:#7e22ce,stroke-dasharray: 4 4 ``` -### Level 2: Data Flow, Integration & Reconciliation Architecture +#### Level 2: Data Flow, Integration & Reconciliation Architecture Detailed interaction showing how primary steps interact with the standalone modules to produce field-wide petrophysical evaluations. ```mermaid flowchart TD subgraph S1_BOX["Step 1: Multi-Well Inventory (MultiWellInventory)"] - LAS_IN["Multi-Well LAS Catalog & Surveys"] + LAS_IN["Multi-Well LAS/DLIS Catalog, Hole Sections & Surveys"] ALIAS["Mnemonic Aliasing & Canonical Mapping\n(GR, RHOB, NPHI, RT, DTC, CALI, PEF)"] LAS_IN --> ALIAS end subgraph S2_BOX["Step 2: Field QA/QC & Normalization (MultiWellQaqc)"] - MARKER["Stratigraphic Anchor Selection\n(Marine Condensed Shale / Regional Aquifer)"] - QUANTILE["Quantile Evaluation (P05/P95 or P10/P90)"] - NORM["Two-Point Rescaling to Reference Key Well\nX_norm = P_low_ref + ((X - P_low) / (P_high - P_low)) * ΔP_ref"] - MARKER --> QUANTILE --> NORM + COND["Field Bad-Hole & Borehole Env Conditioning"] + MARKER["Stratigraphic Anchor Selection\n(Key Well & Marker Zone Quantiles)"] + NORM["Two-Point Quantile Rescaling\n(GR_NORM, NPHI_NORM, RHOB_NORM)"] + COND --> MARKER --> NORM end - subgraph S3_BOX["Step 3: Core Rock Typing (MultiWellRockTyping)"] - RCA_DB["Core Database (Porosity, Permeability, Grain Density)"] - FZI_M["Amaefule FZI & RQI Log-Normal Probability"] - WIN_M["Winland r35 & Pittman Pore-Throat Radii"] - LUC_M["Lucia Rock Fabric Number (RFN)"] - RCA_DB --> FZI_M & WIN_M & LUC_M - FZI_M & WIN_M & LUC_M --> DISCRETE_RTS["Discrete Petrophysical Rock Types (RT_1 ... RT_K)"] + subgraph S3_BOX["Step 3: Core & Log Rock Typing (MultiWellRockTyping)"] + PHI_K_SRC["Dual Input Source: Core (CPORE, CPERM)\nor Calculated Logs (PHIT, PERM)"] + FZI_M["Amaefule FZI & RQI"] + WIN_M["Winland r35 Pore-Throat Radius"] + LUC_M["Lucia RFN (Interparticle φ_ip)"] + PHI_K_SRC --> FZI_M & WIN_M & LUC_M + FZI_M & WIN_M & LUC_M --> DISCRETE_RTS["GMM / Lorenz / K-Means Cutoffs\nROCK_FLAG (RT 1..K + RT 0 Non-Res)"] end subgraph S4_BOX["Step 4: Field Permeability Transforms (MultiWellPermTransform)"] - RT_REGS["RT-Specific Poro-Perm Regressions\nlog10(k) = a_k * PHIE + b_k"] - GLOBAL_REG["Global Mean Permeability Transforms"] - RT_REGS & GLOBAL_REG --> PERM_FIELD["Continuous Permeability Field (PERM_FIELD)"] + RT_REGS["RT-Partitioned Power-Law Regressions\nk = a_k · φ^(b_k) (Interactive a, b Edits)"] + PROP_MODE["Propagation Mode: Cutoff-Only, Hybrid, or Full ML"] + RT_REGS & PROP_MODE --> PERM_TRANS["Continuous Field Permeability (PERM_TRANS)"] end subgraph S5_BOX["Step 5: Saturation Height Function (MultiWellShf)"] - LEV_J["Leverett J-Function Modeling\nJ = A_J * (Sw*)^(-B_J)"] - SKELT["Skelt-Harrison 4-Parameter Model\nSw = 1 - A * exp(-(B / (h + D))^C)"] - RECON["Resistivity Log vs Capillary Sw Reconciliation\n(Depth Crossplots, Error Metrics, FWL Fine-Tuning)"] - LEV_J & SKELT --> RECON + LEV_J["Leverett J-Function & Skelt-Harrison Models"] + STICK["Multi-Well Stick Plot\n(TVDSS Zonal Correlation, GR/Coal, Contacts)"] + RECON["Log Sw vs Capillary Sw_SHF Reconciliation\n& Fluid Limits (GUT/GDT/GOC/GWC, OUT/ODT/OWC, WUT/FWL)"] + LEV_J & STICK --> RECON end subgraph S6_BOX["Step 6: Volumetrics & Uncertainty (MultiWellVolumetrics)"] - PAY_ROLLUP["Zonal Net Pay Rollups Across All Wells"] - LHS_SIM["Latin Hypercube Monte Carlo Simulation\n(Iman-Conover Rank Correlation Induction)"] - RESERVES["Probabilistic Reserves (P90 / P50 / P10)\nSTOIIP, GIIP, Recoverable Hydrocarbons"] - TORNADO["Spearman Sensitivity Tornado Ranking"] - PAY_ROLLUP --> LHS_SIM --> RESERVES & TORNADO + CUT_SENS["Multi-Well PRMS 95% HCPV Cutoff Sensitivity"] + SAT_MODE["Log-Average vs 1D Hypsometric SHF Integration\n(AREA or GRV · Inherited Contacts)"] + LHS_SIM["Latin Hypercube Monte Carlo + Iman-Conover\nP90 / P50 / P10 STOIIP, GIIP & Tornado"] + CUT_SENS & SAT_MODE --> LHS_SIM end subgraph S7_BOX["Step 7: Field FDP Report (InspectorReport)"] - DOSSIER["Multi-Well Technical Dossier & FDP Deliverable\n(Markdown, JSON & Print Ready PDF)"] + DOSSIER["FDP_FULL / QAQC_SUMMARY / RESSUM_ONLY Dossier,\nSubsurface Gate Checks (CHK-01+) & A4 PDF"] end - subgraph SA_FPT["Standalone Module: Pressure & Contacts (MultiWellFpt)"] - FPT_SURVEYS["MDT / RFT / RCI Pressure Survey Points"] - FPT_GRAD["Phase Regressions: P = m*z + c\nFluid Densities: ρ = m / 0.433527"] - FPT_EXCESS["Excess Pressure: ΔP = P - (0.4335 · ρ_w · z)"] - FPT_CONTACT["Phase Intersections & Covariance Error\nFWL, GOC, OWC with ±1σ confidence"] - FPT_SURVEYS --> FPT_GRAD --> FPT_EXCESS --> FPT_CONTACT + subgraph SA_FPT["Standalone: Pressure & Contacts (MultiWellFpt)"] + FPT_CONTACT["Zone-Filtered MDT/RFT on TVDSS\nGradients, Excess Pressure & FWL/GOC/OWC ±1σ"] end - subgraph SA_SCAL["Standalone Module: SCAL & Rel-Perm (MultiWellSwirr)"] - SCAL_PLUGS["Centrifuge / Porous Plate Pc Plug Curves"] - SWIRR_FIT["Swirr Correlation Fit (Power-Law, Exponential, FZI)"] - RELPERM_MODELS["Brooks-Corey & LET Dynamic Rel-Perm Models\nFractional Flow fw(Sw) Calculation"] - SWOF_DECK["ECLIPSE Simulation SWOF Keyword Table Export"] - SCAL_PLUGS --> SWIRR_FIT --> RELPERM_MODELS --> SWOF_DECK + subgraph SA_SCAL["Standalone: SCAL & Rel-Perm (MultiWellSwirr)"] + SWOF_DECK["Swirr Fit, PRT PTSD, Corey/LET Rel-Perm\n& ECLIPSE SWOF Deck"] end - subgraph SA_CLF["Standalone Module: RT Classifier (MultiWellRtClassifierTrainer)"] - CLF_TRAIN["Supervised Ensemble Training (Random Forest / XGBoost)"] - CLF_CONF["Confusion Matrix, Multiclass F1 & Precision Audit"] - CLF_REG["Model Registry & Field-Wide RT_PRED Inference"] - CLF_TRAIN --> CLF_CONF --> CLF_REG + subgraph SA_CLF["Standalone: RT Classifier (MultiWellRtClassifierTrainer)"] + CLF_REG["Supervised RF / GBM Training,\nConfusion Matrix & ROCK_FLAG_ML Registry"] end - subgraph SA_ML["Standalone Module: Conformal ML Trainer (MultiWellMlTrainer)"] - PIML_TRAIN["Physics-Informed Continuous Property Regressor"] - CONFORMAL_ENGINE["Split Conformal Residual Engine\nFinite-Sample Coverage Guarantee"] - INTERVALS["Distribution-Free [P10, P90] Prediction Bounds"] - PIML_TRAIN --> CONFORMAL_ENGINE --> INTERVALS + subgraph SA_ML["Standalone: Conformal ML Trainer (MultiWellMlTrainer)"] + INTERVALS["Physics-Informed Regressors &\nSplit Conformal [P10, P90] Bounds"] end - ALIAS --> NORM - NORM --> CLF_TRAIN - NORM --> PIML_TRAIN - DISCRETE_RTS --> CLF_TRAIN + ALIAS --> COND + NORM --> CLF_REG + NORM --> INTERVALS + DISCRETE_RTS --> CLF_REG DISCRETE_RTS --> RT_REGS - CLF_REG -.->|"RT_PRED"| RT_REGS - FPT_CONTACT -.->|"FWL (z_FWL) & Phase Densities"| LEV_J - SWIRR_FIT -.->|"Asymptotic Swirr Parameters"| S4_BOX - SWIRR_FIT -.->|"Swirr Limit"| LEV_J - PERM_FIELD --> LEV_J - RECON --> PAY_ROLLUP - INTERVALS -.->|"PHIE & Perm Uncertainty Ranges"| LHS_SIM - RESERVES & TORNADO --> DOSSIER + CLF_REG -.->|"ROCK_FLAG_ML"| PROP_MODE + FPT_CONTACT -.->|"FWL & Fluid Densities"| LEV_J + FPT_CONTACT -.->|"Contacts"| SAT_MODE + SWOF_DECK -.->|"Swirr & Pc Fits"| LEV_J + PERM_TRANS --> LEV_J + RECON --> SAT_MODE + INTERVALS -.->|"Property Uncertainty"| LHS_SIM + LHS_SIM --> DOSSIER ``` --- @@ -159,7 +146,7 @@ flowchart TD ### Step 1: Multi-Well Inventory & Mnemonic Standardization (`MultiWellInventory`) {#mw-step-1-inventory} -* **Objective:** Ingest heterogeneous well databases, resolve vendor curve mnemonics into canonical families, harmonize physical units, and perform spatial audit of survey, core, top, and pressure tables. +* **Objective:** Ingest heterogeneous well databases, resolve vendor curve mnemonics into canonical families, harmonize physical units, and perform a field-wide spatial and completeness audit across log suites, Hole Sections, surveys, tops, core, SCAL, and pressure tables. * **Technical Foundation:** Enforces deterministic mapping into `quick_pp` canonical curve families: @@ -174,175 +161,187 @@ flowchart TD $$\text{Compressional Sonic: } \{\text{DTC, DT, DTCO, AC, ITT}\} \to \text{DTC (}\mu\text{s/ft)}$$ -* **Input Data:** LAS 2.0/3.0 files, Deviation surveys (MD, Inclination, Azimuth), Formation marker tops. -* **Output Data:** Canonical multi-well data tree, completeness coverage matrix, TVD trajectory grid. +* **Input Data:** Bulk LAS 2.0/3.0, DLIS & LIS79 files, Hole Sections, Deviation surveys (`MD`, `INC`, `AZI`), Formation tops, Core/SCAL/FPT CSVs, or `.qpp` Handover Packages. +* **Output Data:** Canonical multi-well data tree, completeness coverage matrix, `TVD`/`TVDSS` trajectory grids. --- ### Step 2: Field QA/QC & Stratigraphic Normalization (`MultiWellQaqc`) {#mw-step-2-qaqc} -* **Objective:** Eliminate tool calibration drift, mud salinity variations, and service vendor biases across multi-decade drilling campaigns prior to field-wide rock typing and ML modeling. +* **Objective:** Harmonize borehole conditioning across project wells and eliminate tool calibration drift, mud salinity variations, and service vendor biases across multi-decade drilling campaigns prior to field-wide rock typing and ML modeling. * **Technical Foundation:** + * **Multi-Well Bad-Hole Flagging & Borehole Environmental Conditioning:** + Executes batch bad-hole detection (`BADHOLE`, `BS`, `DCALI` honoring per-well Hole Sections), generic `WL`/`LWD` borehole environmental and radial invasion corrections (`*_ENV_CORR`, `*_SIGMA`, `*_QC_CONF`), and pooled/per-well missing-data imputation across selected field wells. + * **Key-Well Reference Marker Distribution:** - A cored, high-integrity reference well ("Key Well") is selected within a regionally extensive, lithologically stable stratigraphic marker zone (e.g. marine condensed section shale or regional clean aquifer sand) to establish target percentiles $(P_{\text{low}}^{\text{ref}}, P_{\text{high}}^{\text{ref}})$, typically $(P_{05}, P_{95})$ or $(P_{10}, P_{90})$. + A cored, high-integrity reference well ("Key Well") is selected within a regionally extensive, lithologically stable stratigraphic marker zone (e.g., marine condensed shale or regional clean aquifer sand) to establish target percentiles $(P_{\text{low}}^{\text{ref}}, P_{\text{high}}^{\text{ref}})$, typically $(P_{05}, P_{95})$ or $(P_{10}, P_{90})$. * **Two-Point Quantile Linear Rescaling:** For each subject well $w$ with marker percentiles $(P_{\text{low}}^{(w)}, P_{\text{high}}^{(w)})$: $$X_{w,\text{norm}} = P_{\text{low}}^{\text{ref}} + \left( \frac{X_w - P_{\text{low}}^{(w)}}{P_{\text{high}}^{(w)} - P_{\text{low}}^{(w)}} \right) \cdot \left( P_{\text{high}}^{\text{ref}} - P_{\text{low}}^{\text{ref}} \right)$$ -* **Input Data:** Multi-well raw curves, Reference key-well selection, Marker top/base boundaries. -* **Output Data:** `GR_NORM`, `NPHI_NORM`, `RHOB_NORM`, Multi-well quantile diagnostic histograms. +* **Input Data:** Multi-well raw curves, Hole Sections, Reference key-well selection, Stratigraphic marker zones. +* **Output Data:** `GR_NORM`, `NPHI_NORM`, `RHOB_NORM`, field-wide `BADHOLE` & `*_ENV_CORR` curves, `*_IMP` imputed logs, multi-well quantile diagnostic distributions. --- -### Step 3: Core Rock Typing & Hydraulic Flow Units (`MultiWellRockTyping`) {#mw-step-3-rock-typing} +### Step 3: Core & Log Rock Typing & Hydraulic Flow Units (`MultiWellRockTyping`) {#mw-step-3-rock-typing} -* **Objective:** Partition core plug measurements into discrete Petrophysical Rock Types ($RT_1, \dots, RT_K$) that share consistent pore-throat size distributions, flow geometry, and capillary behavior. +* **Objective:** Partition multi-well **Core Plugs (`CPORE`, `CPERM`)** or **Calculated Logs (`PHIT`, `PERM`)** into discrete Petrophysical Rock Types (`ROCK_FLAG`: $RT_1, \dots, RT_K$ plus optional $RT_0$ Non-Reservoir) that share consistent pore-throat geometry and flow behavior. * **Technical Foundation:** - * **Hydraulic Flow Units (Amaefule FZI):** + * **Hydraulic Flow Units — Amaefule FZI / RQI (`fzi`):** - $$\text{RQI} = 0.0314 \sqrt{\frac{k}{\phi_e}}, \qquad \phi_z = \frac{\phi_e}{1 - \phi_e}, \qquad \text{FZI} = \frac{\text{RQI}}{\phi_z}$$ + $$\text{RQI} = 0.0314 \sqrt{\frac{k}{\phi}}, \qquad \phi_z = \frac{\phi}{1 - \phi}, \qquad \text{FZI} = \frac{\text{RQI}}{\phi_z}$$ - Rock types appear as distinct normal distributions on probability plots of $\log_{10}(\text{FZI})$ or clusters identified via Ward's hierarchical agglomerative clustering. + Rearranging yields the Kozeny-Carman hydraulic unit permeability relation $k = 1014 \cdot \text{FZI}^2 \cdot \frac{\phi^3}{(1 - \phi)^2}$. Distinct flow units manifest as log-normal populations of $\log_{10}(\text{FZI})$. - * **Winland $r_{35}$ & Pittman Pore-Throat Radii:** - Pore-throat radius at $35\%$ mercury saturation (apical pore opening): + * **Winland $r_{35}$ Pore-Throat Radius (`winland`):** + Estimates pore-throat radius ($\mu\text{m}$) at $35\%$ mercury saturation from permeability (mD) and porosity ($\phi_{\%} = 100\phi$): - $$\log_{10}(r_{35}) = 0.732 + 0.588 \log_{10}(k) - 0.864 \log_{10}(\phi_{\%})$$ + $$\log_{10}(r_{35}) = 0.732 + 0.588 \log_{10}(k) - 0.864 \log_{10}(100\phi)$$ - * **Megaporous:** $r_{35} > 10\,\mu\text{m}$ - * **Macroporous:** $r_{35} \in [2, 10]\,\mu\text{m}$ - * **Mesoporous:** $r_{35} \in [0.5, 2]\,\mu\text{m}$ - * **Microporous:** $r_{35} \in [0.1, 0.5]\,\mu\text{m}$ - * **Nanoporous:** $r_{35} < 0.1\,\mu\text{m}$ - - * **Lucia Rock Fabric Number (RFN, Carbonates):** - Links interparticle porosity ($\phi_{ip}$) and permeability to grain-dominated vs mud-dominated fabrics: + Classifies pore systems into Megaporous ($>10\,\mu\text{m}$), Macroporous ($2\text{–}10\,\mu\text{m}$), Mesoporous ($0.5\text{–}2\,\mu\text{m}$), Microporous ($0.1\text{–}0.5\,\mu\text{m}$), and Nanoporous ($<0.1\,\mu\text{m}$). + + * **Lucia Rock Fabric Number — Carbonates (`lucia`):** + Links interparticle porosity ($\phi_{ip} = \phi_t - \phi_{\text{sec}}$, stripped via sonic Wyllie porosity when available) and permeability to grain-dominated vs. mud-dominated carbonate fabrics ($\text{RFN} \in [0.5, 4.0]$, where lower $\text{RFN}$ indicates superior rock quality): $$\log_{10}(k) = (9.7982 - 12.0838 \log_{10} \text{RFN}) + (8.6711 - 8.2965 \log_{10} \text{RFN}) \log_{10}(\phi_{ip})$$ + + Supports automatic Lucia RFN override in carbonate-dominated intervals (`VCALC + VDOLO`). - * **Modified Lorenz Plot ($F_m$ vs $\Phi_m$):** - Plots cumulative flow capacity $F_m = \frac{\sum (k \cdot h)_i}{\sum k \cdot h}$ against cumulative storage capacity $\Phi_m = \frac{\sum (\phi \cdot h)_i}{\sum \phi \cdot h}$ to diagnose reservoir heterogeneity and identify high-conductivity thief zones. + * **Automated Cutoff Discovery & Non-Reservoir Isolation (`ROCK_FLAG = 0`):** + Discovers optimal rock-type boundaries via **Gaussian Mixture Models (`GMM`)** with BIC/AIC cluster selection, **Modified Lorenz Plot** ($F_m = \frac{\sum k_i h_i}{\sum k h}$ vs. $\Phi_m = \frac{\sum \phi_i h_i}{\sum \phi h}$) inflection segmentation, or **K-Means**. Optionally isolates tight/shaly/coal intervals (`PHIT`, `VSHALE`, `PERM` cutoffs & `COAL_FLAG`) into `ROCK_FLAG = 0` so non-reservoir rock does not distort reservoir poro-perm regressions. -* **Input Data:** Core porosity ($\phi_{\text{core}}$), Permeability ($k_{\text{core}}$), Grain density. -* **Output Data:** Core rock type labels ($RT_1, \dots, RT_K$), FZI cutoffs, Winland classes. +* **Input Data:** Multi-well Core (`CPORE`, `CPERM`) or Calculated Logs (`PHIT`, `PERM`), optional Sonic (`DTC`) and Carbonate volumes. +* **Output Data:** `ROCK_FLAG` ($0, 1, \dots, K$), `FZI`, `R35`, `RFN`, GMM/Lorenz cutoffs, synchronized SCAL plug rock-type tags. --- ### Step 4: Field Permeability Transforms (`MultiWellPermTransform`) {#mw-step-4-perm-transform} -* **Objective:** Establish Rock-Type-specific porosity-permeability transforms and generate continuous permeability curves across all field wells. +* **Objective:** Fit Rock-Type-partitioned power-law porosity-permeability regressions across cored or evaluated wells and apply them across all project wells to generate the continuous **`PERM_TRANS`** curve. -* **Technical Foundation:** +* **Technical Foundation (`workspace_perm_transform_compute`):** - * **Rock-Type Partitioned Poro-Perm Regressions:** - Within each propagated Rock Type $RT_k$: + * **Rock-Type Partitioned Power-Law Regressions:** + Within each reservoir Discrete Rock Type ($RT_k$, `ROCK_FLAG >= 1`), fits a log-log linear (power-law) relationship on either **Core Data (`CPORE`, `CPERM`)** or **Calculated Logs (`PHIT`, `PERM`)**: + + $$k = a_k \cdot \phi^{b_k} \quad \Longleftrightarrow \quad \log_{10}(k) = b_k \log_{10}(\phi) + \log_{10}(a_k)$$ - $$\log_{10}(k) = a_k \cdot \phi_e + b_k \quad \lor \quad k = 1014 \cdot \overline{\text{FZI}}_k^2 \cdot \frac{\phi_e^3}{(1 - \phi_e)^2}$$ + Coefficients $a_k$ and exponents $b_k$ can be interactively edited per DRT in the workbench with live $R^2$ recalculation, crossplot line updates, and Track 5 previewing. - * **Global vs Partitioned Blending:** - For intervals where rock typing is ambiguous or unclassified, a fallback regression or harmonic mean blending is applied to ensure continuity without unphysical permeability spikes. + * **Rock-Flag Propagation & Non-Reservoir Handling:** + Applies fitted equations to continuous well porosity (`PHIT`) using the selected rock-flag source (`cutoff_only`, `hybrid` core + ML classifier, or `full_ml` from `ROCK_FLAG_ML`). Intervals flagged as non-reservoir (`ROCK_FLAG = 0`) are masked so tight shales and coals do not receive unphysical permeability extrapolations. Downstream modules (Single-Well Reservoir Summary, Multi-Well SHF, Volumetrics, and Reports) automatically prioritize `PERM_TRANS` when saved. -* **Input Curves:** `RT_PRED` (from classification) or `FZI_ZONE`, `PHIE`. -* **Output Curves:** `PERM_FIELD` (permeability log populated across all active wells). +* **Input Curves:** `ROCK_FLAG` / `ROCK_FLAG_ML`, Core (`CPORE`, `CPERM`) or Logs (`PHIT`, `PERM`). +* **Output Curves:** `PERM_TRANS` (continuous field-calibrated permeability in mD saved across project wells), per-RT power-law coefficients $(a_k, b_k, R^2)$. --- ### Step 5: Saturation-Height Function (SHF) & Reconciliation (`MultiWellShf`) {#mw-step-5-shf} -* **Objective:** Construct a capillary-equilibrium water saturation profile $S_{w,\text{SHF}}(h)$ above the Free Water Level ($\text{FWL}$) and reconcile it with resistivity log saturation ($S_{w,\text{log}}$). +* **Objective:** Construct a capillary-equilibrium water saturation profile $S_{w,\text{SHF}}(h)$ above the Free Water Level ($\text{FWL}$), correlate fluid contacts across wells on the **Multi-Well Stick Plot**, and reconcile capillary saturation against resistivity log saturation ($S_{w,\text{log}}$). Requires true `TVD` / `TVDSS` (`TVD` is never assumed equal to `MD`). * **Technical Foundation:** * **Height Above FWL & Capillary Pressure:** + Supports global $z_{\text{FWL}}$ or per-zone `fwlByZone`: - $$h = \max\left(0, \;\; z_{\text{FWL}} - \text{TVDSS}\right)$$ - - $$P_{c,\text{res}}(h) = 0.433527 \cdot (\rho_w - \rho_{\text{hc}}) \cdot h \quad (\text{psi})$$ + $$h = \max\left(0, \;\; z_{\text{FWL}} - \text{TVDSS}\right), \qquad P_{c,\text{res}}(h) = 0.433527 \cdot (\rho_w - \rho_{\text{hc}}) \cdot h \quad (\text{psi})$$ * **Leverett $J$-Function Model:** - Collapses multi-rock-type capillary pressure curves into a dimensionless function: + Collapses multi-rock-type capillary pressure curves into a dimensionless function using `PERM_TRANS` (or `PERM`) and porosity: - $$J(S_w) = \frac{0.2166 \cdot P_{c,\text{res}}}{\sigma_{\text{res}} \cos\theta_{\text{res}}} \sqrt{\frac{k}{\phi_e}}$$ + $$J(S_w) = \frac{0.2166 \cdot P_{c,\text{res}}}{\sigma_{\text{res}} \cos\theta_{\text{res}}} \sqrt{\frac{k}{\phi}}$$ - Fitting the power-law $J = A_J \cdot (S_w^*)^{-B_J}$ (where $S_w^* = \frac{S_w - S_{\text{wirr}}}{1 - S_{\text{wirr}}}$) yields saturation at any elevation: + Fitting the power-law $J = A_J \cdot (S_w^*)^{-B_J}$ (where $S_w^* = \frac{S_w - S_{\text{wirr}}}{1 - S_{\text{wirr}}}$) yields continuous saturation at any structural elevation, with fitted $P_c$/$J$ parameters persisted to the project configuration: - $$S_{w,\text{SHF}}(h, k, \phi_e) = S_{\text{wirr}} + (1 - S_{\text{wirr}}) \cdot \left( \frac{J(h, k, \phi_e)}{A_J} \right)^{-\frac{1}{B_J}}$$ + $$S_{w,\text{SHF}}(h, k, \phi) = S_{\text{wirr}} + (1 - S_{\text{wirr}}) \cdot \left( \frac{J(h, k, \phi)}{A_J} \right)^{-\frac{1}{B_J}}$$ - * **Skelt-Harrison Analytical Model:** - Provides a smooth 4-parameter continuous saturation profile: - - $$S_{w,\text{SHF}}(h) = 1 - A \cdot \exp\left( - \left( \frac{B}{h + D} \right)^C \right)$$ + * **Skelt-Harrison Analytical Model & FWL Inverse Optimization:** + Provides a smooth 4-parameter saturation-height profile $S_{w,\text{SHF}}(h) = 1 - A \cdot \exp\!\left( - \left( \frac{B}{h + D} \right)^C \right)$ and nonlinear least-squares optimization (`workspace_optimize_fwl`) to invert $z_{\text{FWL}}$ against deep-resistivity log saturations across wells. - * **FWL Inverse Optimization:** - When pressure survey points are ambiguous, $z_{\text{FWL}}$ and SHF parameters are inverted simultaneously by minimizing the residual against deep resistivity log saturation across all wells: - - $$\min_{z_{\text{FWL}}, \mathbf{\theta}_{\text{SHF}}} \sum_{w=1}^{N_w} \sum_{i=1}^{M_w} \left( S_{w,\text{SHF}}(z_{w,i}; z_{\text{FWL}}, \mathbf{\theta}) - S_{w,\text{log},i} \right)^2$$ + * **Multi-Well Stick Plot & Fluid Contact / Limits Delineation (`extract_fluid_contacts_and_limits`):** + Displays multi-well `TVDSS` structural stick tracks with stratigraphic zone correlation lines, optional `GR` and `COAL` lithology tracks, rich hover inspection readouts, and fluid contact markers: + * **Gas Limits & Contacts:** `GUT` (Gas Up To), `GDT` (Gas Down To), `GOC` (Gas-Oil Contact), `GWC` (Gas-Water Contact) + * **Oil Limits & Contacts:** `OUT` (Oil Up To), `ODT` (Oil Down To), `OWC` (Oil-Water Contact) + * **Water Limits & Contacts:** `WUT` (Water Up To), `FWL` (Free Water Level) — *`WDT` is excluded as petrophysically uninformative.* - * **Fluid Contact & Transition Limits Delineation (`extract_fluid_contacts_and_limits`):** - Automatically establishes petrophysical fluid boundaries across all wells and zones: - * **Gas Limits & Contacts:** GUT (Gas Up To), GDT (Gas Down To), GOC (Gas-Oil Contact), GWC (Gas-Water Contact) - * **Oil Limits & Contacts:** OUT (Oil Up To), ODT (Oil Down To), OWC (Oil-Water Contact) - * **Water Limits & Contacts:** WUT (Water Up To), FWL (Free Water Level) — *Note: WDT (Water Down To) is explicitly excluded as it carries no petrophysical utility.* - * **Net Sand & Pay Conditioning:** Declared contacts require contiguous reservoir sand samples ($V_{\text{sh}} \le V_{\text{sh,cutoff}}$, $\phi_e \ge \phi_{\text{cutoff}}$, $h_{\text{sand}} \ge 1.0\,\text{m}$) and saturation discrimination ($S_w \le S_{w,\text{pay}}$ for hydrocarbon, $S_w \ge S_{w,\text{water}}$ for water). - -* **Input Data:** `TVDSS`, `PERM_FIELD`, `PHIE`, $z_{\text{FWL}}$, In-situ fluid densities ($\rho_w, \rho_{\text{hc}}$). -* **Output Data:** `SW_SHF`, Reconciliation crossplots, Residual error statistics ($\text{RMSE}, R^2$). +* **Input Data:** `TVDSS`, `PERM_TRANS`/`PERM`, `PHIT`/`PHIE`, `SWT`, `FLUID_TYPE`, $z_{\text{FWL}}$ (global or per-zone), In-situ fluid densities ($\rho_w, \rho_{\text{hc}}$). +* **Output Data:** `SW_SHF`, Persisted fluid contacts & limits table, Stick Plot structural correlation, Reconciliation crossplots & error metrics ($\text{RMSE}, R^2$). --- ### Step 6: Probabilistic Field Volumetrics & Uncertainty (`MultiWellVolumetrics`) {#mw-step-6-volumetrics} -* **Objective:** Combine multi-well net-pay distributions, structural geometry, and fluid properties to evaluate P90 (1P/Proven), P50 (2P), and P10 (3P) Hydrocarbons Initially In Place (STOIIP / GIIP) and identify primary subsurface risks. +* **Objective:** Integrate multi-well zonal net-pay properties, inherited or custom fluid contacts (`FWL`, `OWC`, `GOC`, `GWC`), structural geometry (`AREA` or `GRV`), and PVT distributions in a correlated Latin Hypercube Sampling ($\text{LHS}$) Monte Carlo simulation to quantify PRMS P90 (1P), P50 (2P), and P10 (3P) Oil & Gas In Place and Recoverable Reserves. * **Technical Foundation:** - * **Governing Volumetric Equations:** + * **Multi-Well Empirical Cutoff Sensitivity (`workspace_multi_well_cutoffs_sensitivity`):** + Pools evaluated logs across selected project wells and zones to sweep $V_{\text{sh}}$, $\phi_t$, and $S_{wt}$ cutoffs against cumulative $\text{HCPV}$ recovery (default $95\%$ PRMS threshold) before volumetric rollup. + + * **Governing Volumetric Equations (`AREA` vs. `GRV` Modes):** + Supports Oil (`STOIIP`, Recoverable Oil via $RF_o$), Free Gas (`GIIP`, Recoverable Gas via $RF_g$), and Associated Solution Gas ($R_s$): - $$\text{STOIIP (bbl)} = \frac{7758 \cdot A \cdot H_{\text{gross}} \cdot \text{NTG} \cdot \phi_e \cdot (1 - S_w)}{B_o}$$ + $$\text{STOIIP (bbl)} = \frac{7758 \cdot A_{\text{acres}} \cdot H_{\text{gross,ft}} \cdot \text{NTG} \cdot \phi \cdot (1 - S_w)}{B_o}$$ - $$\text{GIIP (scf)} = \frac{43560 \cdot A \cdot H_{\text{gross}} \cdot \text{NTG} \cdot \phi_e \cdot (1 - S_w)}{B_g}$$ + $$\text{GIIP (scf)} = \frac{43560 \cdot A_{\text{acres}} \cdot H_{\text{gross,ft}} \cdot \text{NTG} \cdot \phi \cdot (1 - S_w)}{B_g}$$ - $$\text{Metric (m}^3\text{): } V = \frac{10^6 \cdot A_{\text{km}^2} \cdot H_{\text{net}} \cdot \phi_e \cdot (1 - S_w)}{B}$$ + $$\text{GRV Mode (m}^3\text{): } V_{hc} = \frac{10^6 \cdot \text{GRV}_{10^6\text{m}^3} \cdot \text{NTG} \cdot \phi \cdot (1 - S_w)}{B}$$ - * **Monte Carlo / Latin Hypercube Sampling (LHS):** - Draws $N_{\text{sim}} \ge 10,000$ stratifying samples across distributions (Normal, Log-Normal, Triangular, PERT) for Area, Gross Thickness, NTG, $\phi_e$, $S_w$, and $B_o/B_g$. + * **Dual Saturation Assessment (`log_average` vs. `shf` 1D Hypsometric Integration):** + * `log_average`: Samples lumped well-log porosity and pore-volume-weighted saturation distributions partitioned by fluid contacts (`inherit` from Step 5 SHF / FPT database contacts, or `custom` global/zonal overrides). + * `shf`: Integrates capillary $S_{w,\text{SHF}}(h)$ across structural elevation slices from crest to contact using either a `structural_dome` conical/dome area-depth curve or `well_tracks` multi-well track integration, incorporating `fwl_uncertainty` ($\pm 1\sigma$ m) directly into each LHS realization. - * **Iman-Conover Rank Correlation Induction:** - Prevents unphysical realizations by enforcing the empirical rank correlation matrix $\mathbf{C}$ (e.g. negative correlation between $\phi_e$ and $S_w$) on the sampled matrix: - - $$\mathbf{X}^* = \mathbf{X} \cdot \mathbf{L}^T \quad \text{where } \mathbf{C} = \mathbf{L}\mathbf{L}^T$$ - - * **PRMS Oilfield Percentiles & Sensitivity Tornado:** - Extracts cumulative exceedance percentiles: - * **P90 (Proven / 1P):** $90\%$ probability that actual volume equals or exceeds this estimate ($Q_{0.10}$) - * **P50 (Probable / 2P):** Median expectation ($Q_{0.50}$) - * **P10 (Possible / 3P):** $10\%$ upside expectation ($Q_{0.90}$) - - Computes Spearman rank correlation coefficients $\rho_s(\theta_j, \text{STOIIP})$ to generate the Tornado chart ranking uncertainty drivers. + * **Latin Hypercube Sampling (LHS), Iman-Conover Correlation & PRMS Tornado:** + Draws $N_{\text{sim}}$ stratified realizations across Normal, Log-Normal, Triangular, or PERT distributions with Iman-Conover Cholesky rank-correlation induction ($\mathbf{X}^* = \mathbf{X}\mathbf{L}^T$, e.g., negative $\phi$–$S_w$ correlation). Extracts PRMS exceedance percentiles—**P90 (1P / Proven)**, **P50 (2P / Probable)**, and **P10 (3P / Possible)**—and Spearman rank-correlation Tornado sensitivity charts. -* **Input Data:** Zonal summaries across all wells, Structural area distributions, Fluid PVT ($B_o, B_g$). -* **Output Data:** P90/P50/P10 STOIIP & GIIP, Cumulative exceedance curves, Tornado sensitivity chart. +* **Input Data:** Multi-well curves & cutoffs, Inherited/custom zonal contacts (`OWC`, `GOC`, `GWC`, `FWL`), Zonal `AREA` or `GRV` & PVT distributions ($B_o, B_g, R_s, RF_o, RF_g$), SHF parameters. +* **Output Data:** P90/P50/P10 `STOIIP`, `GIIP`, Associated Gas & Recoverable Reserves by zone and field total, Exceedance S-curves, Tornado sensitivity rankings. --- ### Step 7: Field FDP Report (`InspectorReport` / Multi-Well Dossier) {#mw-step-7-report} -* **Objective:** Synthesize multi-well data inventory, stratigraphic normalization results, pressure gradients, rock typing distributions, SHF models, and probabilistic volumetric reserve estimates into an executive Field Development Plan (FDP) report. +* **Objective:** Synthesize multi-well data inventory, borehole environmental & invasion QC audits, stratigraphic normalization shifts, FZI/Winland/Lucia rock typing, `PERM_TRANS` regressions, FPT pressure gradients, SHF & SCAL models, probabilistic volumetric reserves, cellular upscaling, and peer-review gate checks into an executive Field Development Plan (`FDP`) deliverable. -* **Technical Foundation:** - Automated multi-well dossier compilation featuring executive summaries, zonal net pay rollups, fluid contact determinations, and volumetric risk distributions in Markdown, JSON, and print-ready PDF formats. +* **Report Presets & Audit Capabilities:** + * **Multi-Well Presets:** `FDP_FULL` (complete 10-section Field Development Plan dossier + CPI appendices), `QAQC_SUMMARY` (Executive Summary, Data Inventory & Multi-Well Conditioning/Normalization Audit), and `RESSUM_ONLY` (Executive Summary, Zonal Reservoir Summary, Probabilistic Volumetrics & Upscaling). + * **Automated Subsurface Gate-Check & Anomaly Remediation Log (`CHK-01`+):** Pre-render and in-report verification matrix auditing borehole conditioning, sensor confidence (`*_QC_CONF`), core parity, contact consistency across FPT/SHF/logs, and volumetric uncertainty bounds, paired with severity-graded remediation actions and paginated A4 PDF export. --- ## 3. Standalone Specialized Modules -### Multi-Well Evaluation {#mw-standalone-batch-evaluation} +The Multi-Well workspace provides 5 standalone specialized modules accessible at any point during field evaluation. + +```mermaid +graph LR + subgraph Standalone_Modules ["Multi-Well Standalone Specialized Modules"] + direction TB + M0["Multi-Well Evaluation\n(MultiWellEvaluation.svelte)\n#mw-standalone-batch-evaluation"] + M1["SCAL & Rel-Perm\n(MultiWellSwirr.svelte)\n#mw-standalone-scal-relperm"] + M2["Pressure & Contacts (FPT)\n(MultiWellFpt.svelte)\n#mw-standalone-fpt"] + M3["RT Classifier Trainer\n(MultiWellRtClassifierTrainer.svelte)\n#mw-standalone-rt-classifier"] + M4["Conformal ML Trainer\n(MultiWellMlTrainer.svelte)\n#mw-standalone-ml-training"] + end + + style M0 fill:#f0fdfa,stroke:#0f766e,stroke-width:1.5px + style M1 fill:#fffbeb,stroke:#b45309,stroke-width:1.5px + style M2 fill:#fff1f2,stroke:#be123c,stroke-width:1.5px + style M3 fill:#f0fdfa,stroke:#0f766e,stroke-width:1.5px + style M4 fill:#faf5ff,stroke:#7e22ce,stroke-width:1.5px +``` + +--- + +### Multi-Well Evaluation (`MultiWellEvaluation`) {#mw-standalone-batch-evaluation} This optional utility repeats the current single-well lithology, porosity, permeability and saturation settings independently for selected well/zone pairs. It is not a pooled field @@ -357,74 +356,37 @@ lithology, porosity, optional Thomas-Stieber analysis, permeability, and saturat order. Preview calculations are isolated: they do not save curves or alter the well data used by other evaluations. Zone labels must be available for each selected well, and duplicate depths prevent reliable evaluation. A run may use only one correction; invaded-zone -correction and crossplot-calibrated Qv are excluded because they require well-specific inputs. +correction, continuous apparent fluid density, and crossplot-calibrated $Q_v$ are excluded because they require well-specific inputs. When a correction is selected, the lithology and porosity settings must use its corrected logs. Thomas-Stieber settings are required when permeability or saturation requests that model. -The preview reports failures per well/zone and compares paired valid values for VCLAY, PHIT, -PERM and SWT. The right-hand evaluation grid includes coverage and failures; select a +The preview reports failures per well/zone and compares paired valid values for `VCLAY`, `PHIT`, +`PERM` and `SWT`. The right-hand evaluation grid includes coverage and failures; select a successful well/zone to load its full-resolution existing and preview curves in the center depth tracks. -PHIT, PERM and SWT can be shown together or individually, and VCLAY individually. PERM -uses a logarithmic track and changes are shown as a median ratio. Zoom and scroll the -depth tracks to inspect details. The separate Reservoir Summary grid shows only an +`PHIT`, `PERM` and `SWT` can be shown together or individually, and `VCLAY` individually. `PERM` +uses a logarithmic track and changes are shown as a median ratio. The separate Reservoir Summary grid shows only an in-session summary previously calculated for the active single well, not batch-preview results; it can be stale and must be recomputed after curve changes. Only checked successful results are applied, with parameter snapshots saved per zone. Apply saves the previously calculated preview without recalculating, after checking the input fingerprint against the current well data and settings; if input -data changed, preview again. Full-resolution curve profiles are loaded on demand, rather -than being included with every preview result. Preview data is -held temporarily in the backend process for 30 minutes and is released on leaving or changing -scope. If it expires, the server restarts, or a request reaches a different worker, preview -again. Deployments with multiple backend workers need sticky routing to the preview's worker. -Well/zone saves are independent, -so review each apply status. The results are calculated using the workspace's current merged -well data, which can include unsaved single-well previews. - -Invaded-zone hydrocarbon correction and crossplot-calibrated Qv are not supported in this -utility because they require well-specific metadata or calibration validation. Recompute -reservoir summaries and dependent field interpretations after applying results, and reload -the active well view to see saved curves. - -The Multi-Well workspace provides 5 standalone specialized modules accessible at any point during field evaluation. - -```mermaid -graph LR - subgraph Standalone_Modules ["Multi-Well Standalone Specialized Modules"] - direction TB - M0["Multi-Well Evaluation\n(MultiWellEvaluation.svelte)\n#mw-standalone-batch-evaluation"] - M1["SCAL & Rel-Perm\n(MultiWellSwirr.svelte)\n#mw-standalone-scal-relperm"] - M2["Pressure & Contacts (FPT)\n(MultiWellFpt.svelte)\n#mw-standalone-fpt"] - M3["RT Classifier Trainer\n(MultiWellRtClassifierTrainer.svelte)\n#mw-standalone-rt-classifier"] - M4["Conformal ML Trainer\n(MultiWellMlTrainer.svelte)\n#mw-standalone-ml-training"] - end - - style M0 fill:#f0fdfa,stroke:#0f766e,stroke-width:1.5px - style M1 fill:#fffbeb,stroke:#b45309,stroke-width:1.5px - style M2 fill:#fff1f2,stroke:#be123c,stroke-width:1.5px - style M3 fill:#f0fdfa,stroke:#0f766e,stroke-width:1.5px - style M4 fill:#faf5ff,stroke:#7e22ce,stroke-width:1.5px -``` +data changed, preview again. Preview data is held temporarily in the backend process for 30 minutes and is released on leaving or changing scope. Recompute reservoir summaries and dependent field interpretations after applying results. --- ### Standalone Module 1: SCAL & Dynamic Relative Permeability (`MultiWellSwirr`) {#mw-standalone-scal-relperm} -* **Objective:** Ingest field-wide Special Core Analysis ($\text{SCAL}$) capillary pressure plug experiments, fit irreducible water saturation ($S_{\text{wirr}}$) correlations, model dynamic Relative Permeability ($k_r$) curves, compute fractional flow ($f_w$), and export ECLIPSE simulation `SWOF` keyword decks. +* **Objective:** Ingest field-wide Special Core Analysis ($\text{SCAL}$) capillary pressure plug experiments (MICP, Porous Plate, Centrifuge), synchronize Petrophysical Rock Type (`PRT`) classifications with Step 3 Rock Typing, fit irreducible water saturation ($S_{\text{wirr}}$) and Leverett $J$/$P_c$ correlations, model dynamic Relative Permeability ($k_r$) curves, compute fractional flow ($f_w$), and export ECLIPSE `SWOF` simulation decks. * **Technical Foundation:** - * **Multi-Well $S_{\text{wirr}}$ Extraction & Correlation:** - Extracts $S_{\text{wirr}}$ from porous plate, centrifuge, or MICP capillary pressure curves at a designated reservoir displacement threshold pressure $P_{c,\text{threshold}}$ (e.g. $100\,\text{psi}$). - - Fits parametric regressions across plugs globally and by Petrophysical Rock Type ($RT$): - * **Power-Law Permeability / Porosity Model:** - $$S_{\text{wirr}} = c_1 \cdot \phi_e^{c_2} \cdot k^{c_3}$$ - * **FZI Hydraulic Flow Unit Model:** - $$S_{\text{wirr}} = 1 - \frac{1}{a_{\text{FZI}} + b_{\text{FZI}} \cdot \text{FZI}^{-c_{\text{FZI}}}}$$ - * **Logarithmic / Polynomial Fits:** - $$S_{\text{wirr}} = a \cdot \ln(k) + b$$ + * **Lab-to-Reservoir $P_c$ Conversion & Multi-Well $S_{\text{wirr}}$ Correlation:** + Converts plug capillary pressures using explicit laboratory test fluid-system parameters ($\sigma_{\text{lab}} \cos\theta_{\text{lab}}$ vs. $\sigma_{\text{res}} \cos\theta_{\text{res}}$, without assuming high-pressure curves $>200\,\text{psi}$ are automatically MICP) and extracts $S_{\text{wirr}}$ at a designated threshold pressure or asymptotic limit. Fits parametric models globally or per Rock Type (`PRT`): + * **Power-Law Porosity / Permeability Model:** $S_{\text{wirr}} = c_1 \cdot \phi^{c_2} \cdot k^{c_3}$ + * **FZI Hydraulic Flow Unit Model:** $S_{\text{wirr}} = 1 - \frac{1}{a_{\text{FZI}} + b_{\text{FZI}} \cdot \text{FZI}^{-c_{\text{FZI}}}}$ + * **Logarithmic / Polynomial Fits:** $S_{\text{wirr}} = a \cdot \ln(k) + b$ + Applies calibrated continuous `SWIRR` curves across project wells (`workspace_swirr_apply`) and persists $J$/$P_c$ fit parameters for seamless Step 5 SHF consumption. * **Normalized Effective Phase Saturation:** @@ -432,153 +394,78 @@ graph LR * **Pore Throat Size Distribution by PRT:** In the right-hand crossplot, select **Pore Throat by PRT** to display individual plug curves grouped - by rock type. The plot follows `plot_ptsd_by_prt`: Washburn radius is - calculated from reservoir Pc, IFT, and contact angle, and the vertical - axis is the finite-difference derivative of normalized water saturation - with respect to $\log_{10} R$. Normalization uses the selected plug - Swirr or porosity-permeability correlation, as in the SCAL curve fit. - Well, zone, depth, rock-type, and sample-focus filters apply. Curves - require at least two distinct positive Pc values; duplicate pressures - are represented by their first point. All curve points remain visible - even when excluded from fitting, and plugs not included in the Swirr - fit are dotted. Synthetic samples, if generated by the SCAL loader, - are identified by their `SYN_` sample names. Set IFT and contact angle - in **SCAL J / Pc Curve Fit** and use **Reset Auto-Fit** after changing - them to reload converted Pc values; this also resets manual Swirr fits. - - * **Dynamic Relative Permeability Models:** - * **Brooks-Corey Model:** - $$k_{rw}(S_{wn}) = k_{rw,\max} \cdot S_{wn}^{n_w}$$ - $$k_{ro}(S_{wn}) = k_{ro,\max} \cdot (1 - S_{wn})^{n_o}$$ - * **Modified Corey Formulation:** - Accounts for pore-size distribution index $\lambda$: - $$n_w = \frac{2 + 3\lambda}{\lambda}, \qquad n_o = 2 + \lambda$$ - * **LET Model (Lomeland, Ebeltoft, Thomas):** - Provides flexible S-shaped relative permeability curves without artificial end-point artifacts: - $$k_{rw}(S_{wn}) = k_{rw,\max} \cdot \frac{S_{wn}^{L_w}}{S_{wn}^{L_w} + E_w (1 - S_{wn})^{T_w}}$$ - $$k_{ro}(S_{wn}) = k_{ro,\max} \cdot \frac{(1 - S_{wn})^{L_o}}{(1 - S_{wn})^{L_o} + E_o S_{wn}^{T_o}}$$ - where $L$ governs the lower slope/entry, $E$ elevates the central plateau, and $T$ governs the upper approach to the end-point. + by rock type (`plot_ptsd_by_prt`): Washburn pore-throat radius is + calculated from reservoir $P_c$, IFT, and contact angle, and the vertical + axis plots $dS_{wn} / d(\log_{10} R)$. Well, zone, depth, rock-type, and sample-focus filters apply; plugs excluded from fitting remain visible as dotted curves. - * **Fractional Flow Curve ($f_w$):** - Calculates the fractional water cut as a function of water saturation and oil/water viscosity ratio $M = \frac{\mu_o}{\mu_w}$: - - $$f_w(S_w) = \frac{1}{1 + \left(\frac{k_{ro}(S_w)}{k_{rw}(S_w)}\right) \cdot \left(\frac{\mu_w}{\mu_o}\right)}$$ + * **Dynamic Relative Permeability Models & Fractional Flow ($f_w$):** + * **Brooks-Corey & Modified Corey:** $k_{rw} = k_{rw,\max} S_{wn}^{n_w}$, $k_{ro} = k_{ro,\max} (1 - S_{wn})^{n_o}$ (with $n_w = \frac{2+3\lambda}{\lambda}, n_o = 2+\lambda$ for Modified Corey). + * **LET Model (Lomeland, Ebeltoft, Thomas):** + $$k_{rw}(S_{wn}) = k_{rw,\max} \cdot \frac{S_{wn}^{L_w}}{S_{wn}^{L_w} + E_w (1 - S_{wn})^{T_w}}, \qquad k_{ro}(S_{wn}) = k_{ro,\max} \cdot \frac{(1 - S_{wn})^{L_o}}{(1 - S_{wn})^{L_o} + E_o S_{wn}^{T_o}}$$ + * **Fractional Flow Curve:** $f_w(S_w) = \left[1 + \frac{k_{ro}(S_w)}{k_{rw}(S_w)} \cdot \frac{\mu_w}{\mu_o}\right]^{-1}$. * **Reservoir Simulation Export (ECLIPSE `SWOF` Deck):** - Formats monotonic tables of $(S_w, k_{rw}, k_{row}, P_{cow})$ with automated end-point validation conforming to ECLIPSE and CMG black-oil simulator syntax: - - ```text - -- ECLIPSE 100 / 300 RELPERM & CAPILLARY TABLE - SWOF - -- Sw Krw Krow Pcow (psi) - 0.150 0.00000 0.85000 150.00 - 0.200 0.00125 0.72410 45.20 - ... - 0.800 0.35000 0.00000 0.00 - / - ``` - -* **Input Data:** SCAL capillary pressure curves, Reservoir endpoint parameters ($S_{\text{wirr}}, S_{or}, k_{rw,\max}, k_{ro,\max}$), Fluid viscosities ($\mu_o, \mu_w$). -* **Output Data:** Fitted $S_{\text{wirr}}$ models, Relative permeability tables, Fractional flow diagnostic plots, Formatted `SWOF` text decks. + Formats monotonic validated tables of $(S_w, k_{rw}, k_{row}, P_{cow})$ per Rock Type (`SATNUM`) conforming to ECLIPSE / CMG black-oil simulator syntax. + +* **Input Data:** SCAL capillary pressure curves, Rock Type (`PRT`) assignments, Endpoints ($S_{\text{wirr}}, S_{or}, k_{rw,\max}, k_{ro,\max}$), Fluid viscosities ($\mu_o, \mu_w$). +* **Output Data:** Fitted $S_{\text{wirr}}$ & $J$/$P_c$ models, Continuous `SWIRR` well curves, Pore-throat distributions, Relative permeability & fractional flow plots, Formatted `SWOF` decks. --- ### Standalone Module 2: Formation Pressure Testing (FPT) & Fluid Contacts (`MultiWellFpt`) {#mw-standalone-fpt} -* **Objective:** Determine in-situ fluid phase pressure gradients, calculate in-situ fluid densities ($\rho_g, \rho_o, \rho_w$), identify hydraulic communication across fault blocks, and calculate the Free Water Level ($\text{FWL}$), Gas-Oil Contact ($\text{GOC}$), and producible contacts ($\text{OWC}, \text{GWC}$) with covariance uncertainty bounds. +* **Objective:** Regress zone-filtered MDT / RFT / RCI formation pressure measurements against true sub-sea elevation (`TVDSS`), determine in-situ phase densities ($\rho_g, \rho_o, \rho_w$), diagnose overpressure or depletion via excess pressure, and locate equilibrium fluid contacts ($\text{FWL}, \text{GOC}, \text{GWC}, \text{OWC}$) with covariance uncertainty bounds. * **Technical Foundation:** - * **Hydrostatic Phase Linear Regression:** - In each mobile phase $p \in \{\text{gas, oil, water}\}$, pressure $P$ varies linearly with depth $z = \text{TVDSS}$: + * **Hydrostatic Phase Linear Regression on True `TVDSS`:** + Resolves true `TVDSS` from directional surveys and datum elevations (never inflating `TVDSS` with raw `MD` in deviated wells) and honors active stratigraphic zone filters and persisted per-zone regression settings. In each mobile phase $p \in \{\text{gas, oil, water}\}$: - $$P_p(z) = m_p \cdot z + c_p$$ - - where the gradient $m_p = \frac{dP_p}{dz}$ (in $\text{psi/ft}$) is converted to in-situ fluid density $\rho_p$ (in $\text{g/cm}^3$): - - $$\rho_p = \frac{m_p}{0.433527}$$ + $$P_p(z) = m_p \cdot z + c_p, \qquad \rho_p = \frac{m_p}{0.433527} \quad (\text{g/cm}^3 \text{ from psi/ft})$$ * **Diagnostic Excess Pressure:** - Identifies pressure regime anomalies (supercharging, drawdown, depleted reservoirs): $$P_{\text{excess}}(z) = P(z) - \left( 0.433527 \cdot \rho_{\text{water,datum}} \cdot z \right)$$ - * **Equilibrium Fluid Contact Intersection Mathematics:** - Phase contacts occur at the exact intersection of phase lines ($P_c = P_{\text{non-wet}} - P_{\text{wet}} = 0$): - - $$\text{FWL (Oil-Water): } z_{\text{FWL}} = \frac{c_w - c_o}{m_o - m_w}$$ + * **Equilibrium Fluid Contact Intersections, Covariance Error & OWC Offset:** - $$\text{GOC (Gas-Oil): } z_{\text{GOC}} = \frac{c_o - c_g}{m_g - m_o}$$ + $$z_{\text{FWL}} = \frac{c_w - c_o}{m_o - m_w}, \qquad z_{\text{GOC}} = \frac{c_o - c_g}{m_g - m_o}, \qquad z_{\text{GWC}} = \frac{c_w - c_g}{m_g - m_w}$$ - $$\text{GWC (Gas-Water): } z_{\text{GWC}} = \frac{c_w - c_g}{m_g - m_w}$$ + $$\sigma_{z_{\text{contact}}}^2 = \mathbf{J} \cdot \boldsymbol{\Sigma}_{(m,c)} \cdot \mathbf{J}^T, \qquad z_{\text{OWC}} = z_{\text{FWL}} - \frac{P_{d,\text{res}}}{0.433527 \cdot (\rho_w - \rho_o)}$$ - * **Contact Uncertainty Propagation:** - Using the covariance matrix $\boldsymbol{\Sigma}_{(m, c)}$ from least-squares regression, the contact depth variance is: - - $$\sigma_{z_{\text{contact}}}^2 = \mathbf{J} \cdot \boldsymbol{\Sigma} \cdot \mathbf{J}^T \quad \text{where } \mathbf{J} = \left[ \frac{\partial z}{\partial m_1}, \frac{\partial z}{\partial c_1}, \frac{\partial z}{\partial m_2}, \frac{\partial z}{\partial c_2} \right]$$ - - * **Displacement Threshold Offset (OWC vs FWL):** - In rocks with non-zero entry capillary pressure $P_d$, the producible Oil-Water Contact ($\text{OWC}$) sits above the $\text{FWL}$ by: - - $$z_{\text{OWC}} = z_{\text{FWL}} - \frac{P_{d,\text{res}}}{0.433527 \cdot (\rho_w - \rho_o)}$$ - -* **Input Data:** MDT / RFT / RCI pressure survey table $(\text{TVDSS}, P_{\text{form}}, \text{QualityFlag})$. -* **Output Data:** Fluid gradients ($m_g, m_o, m_w$), In-situ densities ($\rho_g, \rho_o, \rho_w$), Contact depths ($z_{\text{FWL}}, z_{\text{GOC}}, z_{\text{OWC}}$) $\pm \sigma$. +* **Input Data:** MDT / RFT / RCI pressure survey table (`MD` / `TVDSS`, $P_{\text{form}}$, Fluid/Quality flags, Zone labels). +* **Output Data:** Phase gradients ($m_g, m_o, m_w$), In-situ densities ($\rho_g, \rho_o, \rho_w$), Contact depths ($z_{\text{FWL}}, z_{\text{GOC}}, z_{\text{GWC}}, z_{\text{OWC}}$) $\pm 1\sigma$ persisted for SHF & Volumetrics. --- ### Standalone Module 3: Supervised Petrophysical Rock Type (DRT) Classifier (`MultiWellRtClassifierTrainer`) {#mw-standalone-rt-classifier} -* **Objective:** Train supervised machine learning models on cored Key Wells to predict discrete Petrophysical Rock Types across uncored field wells, validating performance via cross-validation and confusion matrices. +* **Objective:** Train supervised machine learning models on cored Key Wells to predict discrete Petrophysical Rock Types (`ROCK_FLAG_ML`) across uncored field wells, validating performance via cross-validation and contingency/confusion matrices. * **Technical Foundation:** + * **Multi-Scale Feature Engineering:** Normalized logs (`GR_NORM`, `RHOB_NORM`, `NPHI_NORM`, `RT`, `DTC`), acoustic impedance surrogate $\text{AI} = \text{RHOB} \cdot (10^6 / \text{DTC})$, neutron-density separation $\Delta\phi_{ND}$, Burke $M$/$N$ indices, and multi-scale rolling standard deviations/gradients ($\pm 1\,\text{m}, \pm 3\,\text{m}$). + * **Classifier Architectures & Registry:** Random Forest (with OOB error) and Gradient Boosting (XGBoost / LightGBM) evaluated via stratified $k$-fold cross-validation, multiclass confusion matrices, and Macro-F1 scores, saved into the project model registry for field-wide inference into Step 4 `PERM_TRANS`. - * **Multi-Scale Feature Engineering:** - Extracts feature vectors from normalized log curves: - * Normalized primary curves: $\text{GR\_NORM}, \text{RHOB\_NORM}, \text{NPHI\_NORM}, \text{RT}, \text{DTC}$ - * Mineral indicators: Apparent acoustic impedance surrogate $\text{AI} = \text{RHOB} \cdot (10^6 / \text{DTC})$ - * Porosity separation: $\Delta \phi_{ND} = \text{NPHI} - \phi_D$ - * Multi-scale rolling standard deviations and vertical gradients ($\pm 1\,\text{m}, \pm 3\,\text{m}$) to capture bed boundary transitions. - - * **Classifier Architectures:** - * **Random Forest Classifier:** Ensembles decorrelated decision trees with out-of-bag (OOB) validation. - * **Gradient Boosting (XGBoost / LightGBM):** Minimizes multiclass log-loss with regularization against overfitting. - - * **Model Diagnostics & Registry:** - * Stratified k-fold cross-validation - * Multi-class confusion/contingency matrix, precision, recall, and Macro-F1 scores - * Model persistence into the project registry for on-demand inference across any uncored well. - -* **Input Data:** Normalized logs on cored Key Wells, Core Rock Type labels ($RT_1, \dots, RT_K$). -* **Output Data:** Trained classifier artifact, feature importance ranking, predicted rock type curves (`RT_PRED`). +* **Input Data:** Normalized logs on cored Key Wells, Core Rock Type labels (`ROCK_FLAG`). +* **Output Data:** Registered classifier model, feature importances, confusion matrix audit, propagated `ROCK_FLAG_ML` curves. --- ### Standalone Module 4: Conformal Physics-Informed ML Trainer (`MultiWellMlTrainer`) {#mw-standalone-ml-training} -* **Objective:** Train continuous petrophysical property regressors ($\phi_e, k, S_w$) regularized with physical constraints, generating distribution-free P10–P90 uncertainty prediction intervals via conformal prediction. +* **Objective:** Train continuous petrophysical property regressors ($\phi, k, S_w$) regularized with physical domain constraints, generating distribution-free P10–P90 uncertainty prediction intervals via Split Conformal Prediction. * **Technical Foundation:** * **Physics-Informed Machine Learning (PIML) Regularization:** - Enforces physical domain laws during model training: - * **Strict Monotonicity:** $\frac{\partial k}{\partial \phi_e} \ge 0$, $\frac{\partial k}{\partial V_{\text{clay}}} \le 0$ - * **Physical Bounds:** $\phi_e \in [0, \phi_{\max}]$, $S_w \in [S_{\text{wirr}}, 1.0]$. - * **Physics Loss Penalty:** - $$\mathcal{L}_{\text{total}} = \mathcal{L}_{\text{MSE}} + \lambda_{\text{phys}} \sum \max\left(0, -\frac{\partial \hat{y}}{\partial x_{\text{phys}}}\right)$$ - - * **Split Conformal Prediction Engine (Distribution-Free Coverage Guarantee):** - Given calibration samples $\mathcal{D}_{\text{cal}} = \{(\mathbf{x}_i, y_i)\}_{i=1}^n$, computes absolute non-conformity scores: + Enforces domain monotonicity ($\frac{\partial k}{\partial \phi} \ge 0$, $\frac{\partial k}{\partial V_{\text{clay}}} \le 0$) and physical clamping ($\phi \in [0, \phi_{\max}]$, $S_w \in [S_{\text{wirr}}, 1.0]$): - $$s_i = |y_i - \hat{f}(\mathbf{x}_i)|$$ - - For target error rate $\alpha$ (e.g. $\alpha = 0.10$ for $90\%$ confidence), the empirical quantile $\hat{q}_{1-\alpha}$ defines prediction intervals on uncored wells: - - $$\hat{q}_{1-\alpha} = \text{Quantile}\left( \{s_i\}_{i=1}^n, \;\; \frac{\lceil(n+1)(1-\alpha)\rceil}{n} \right)$$ - - $$\mathcal{C}(\mathbf{x}_{\text{new}}) = \left[ \hat{f}(\mathbf{x}_{\text{new}}) - \hat{q}_{1-\alpha}, \;\; \hat{f}(\mathbf{x}_{\text{new}}) + \hat{q}_{1-\alpha} \right]$$ + $$\mathcal{L}_{\text{total}} = \mathcal{L}_{\text{MSE}} + \lambda_{\text{phys}} \sum \max\left(0, -\frac{\partial \hat{y}}{\partial x_{\text{phys}}}\right)$$ + + * **Split Conformal Prediction Engine (Finite-Sample Coverage Guarantee):** + Computes calibration non-conformity residuals $s_i = |y_i - \hat{f}(\mathbf{x}_i)|$ and empirical quantile $\hat{q}_{1-\alpha} = \operatorname{Quantile}\!\left(\{s_i\}_{i=1}^n, \frac{\lceil(n+1)(1-\alpha)\rceil}{n}\right)$: - Guarantees marginal coverage $\mathbb{P}\left(Y_{\text{new}} \in \mathcal{C}(\mathbf{X}_{\text{new}})\right) \ge 1 - \alpha$ without parametric Gaussian assumptions. + $$\mathcal{C}(\mathbf{x}_{\text{new}}) = \left[ \hat{f}(\mathbf{x}_{\text{new}}) - \hat{q}_{1-\alpha}, \;\; \hat{f}(\mathbf{x}_{\text{new}}) + \hat{q}_{1-\alpha} \right], \qquad \mathbb{P}\!\left(Y_{\text{new}} \in \mathcal{C}(\mathbf{X}_{\text{new}})\right) \ge 1 - \alpha$$ -* **Input Data:** Multi-well normalized logs, Core calibration target properties. -* **Output Data:** Continuous prediction curves with rigorous $[\text{P10}, \text{P90}]$ conformal prediction bands. +* **Input Data:** Multi-well normalized logs, Core or key-well calibration targets. +* **Output Data:** Saved PIML model suites, continuous predicted curves with rigorous $[\text{P10}, \text{P90}]$ conformal uncertainty bands. diff --git a/docs/workflows/single_well.md b/docs/workflows/single_well.md index 1c1dc501..41188d30 100644 --- a/docs/workflows/single_well.md +++ b/docs/workflows/single_well.md @@ -1,137 +1,183 @@ # Single-Well Petrophysical Workflow -The Single-Well space delivers deterministic, optimization-driven, and core-calibrated formation evaluation along a single wellbore trajectory. It is structured into **7 Primary Sequential Workflow Steps** culminating in a Computer Processed Interpretation (CPI) report, accompanied by a **Standalone Core & Pc Prep Lab Module**. +The Single-Well space delivers deterministic, optimization-driven, and core-calibrated formation evaluation along a single wellbore trajectory. It is structured into **7 Primary Sequential Workflow Steps** culminating in a Computer Processed Interpretation (CPI) report, accompanied by **2 Standalone Specialized Modules**: **Core & Pc Prep** (`InspectorScal`) and **Source Rock & TOC** (`InspectorToc`). When importing LAS logs, check the depth curve's **Source Unit** in the uploader. Feet are converted to meters by multiplying the depth values by 0.3048; edit the source unit if the LAS curve header is incorrect. Previously imported wells are not automatically corrected, and importing into an existing well merges data rather than replacing it. -For LAS imports through **Review / Commit**, renamed log curves retain a separate copy of their source values and unit alongside the standardized curve. Name collisions receive a `RAW_` prefix or a numeric suffix. The import summary and Data & QAQC well header show each source file, mnemonic, stored curve, and raw copy; these records describe the import, not subsequent edits. Depth remains the shared, converted index rather than a separate raw curve. Optional grid regularization also applies to the raw copies. Existing imports are not backfilled. +For LAS imports through **Review / Commit**, renamed log curves retain a separate copy of their source values and unit alongside the standardized curve. Name collisions receive a `RAW_` prefix or a numeric suffix. The import summary and Well Header show each source file, mnemonic, stored curve, and raw copy; these records describe the import, not subsequent edits. Depth remains the shared, converted index rather than a separate raw curve. Optional grid regularization also applies to the raw copies. Existing imports are not backfilled. -The same log uploader also accepts DLIS and LIS79 (`.lis`) files. LIS Enhanced LIS/LIS84 variants are not supported by the current parser. +The same log uploader also accepts DLIS and LIS79 (`.lis`) files. LIS Enhanced LIS/LIS84 variants are not supported by the current parser. Full project state—including well curves, headers, hole sections, tops, surveys, core/SCAL/FPT tables, per-zone module parameters, and trained models—can be exported and re-imported via `.qpp` Handover Packages with full database persistence. The **Log / interval** unit selector (m or ft) affects the single-well log plot and readouts, working interval and top-bar depth filter, and shared tables whose values are in meters. Table edits, pasted values, and ancillary quick-entry depths are converted back to meters for processing. The preference is saved in the browser; it does not change stored data. Other plots, reports, and exports retain their existing units. -Zone-filtered workspace calculations require resolved zone labels for the selected well, normally from its zone data or formation tops. If zone labels are unavailable, the calculation reports an error instead of evaluating the entire well. - -In Data & QAQC, **Missing Data Imputation** saves selected logs as new `_IMP` curves by default. Alternatively, replace the selected curves while preserving a full-well `_ORI` backup; existing backups are never overwritten. Choose mean, median, most frequent, forward/backward fill, depth-based linear interpolation, KNN, or iterative imputation; multivariate methods require at least two curves. Linear interpolation fills only gaps between observed samples, without extrapolating end gaps. Directional fills follow increasing depth and may also leave end gaps unfilled. Active depth and zone filters apply; existing `_IMP` curves must be renamed or deleted before re-running in new-curve mode. The right-pane **Missing Matrix** shows binned missing fractions by curve, with deeper depths at the top and grey bins indicating no samples. +Zone-filtered workspace calculations require resolved zone labels for the selected well, normally from its zone data or formation tops. If zone labels are unavailable, the calculation reports an error instead of evaluating the entire well. Module parameters are persisted per interval (`well`, `zone:`, or `depth:-`) and restored automatically when switching wells or active filters. Calculated curve groups can be selectively cleared via **Clear Calc** in the top stepper across `Top–Bottom`, `By Formation`, or the `Active Filter`. --- ## 1. Workflow Architecture (Level 1 & Level 2) {#sw-level-1-2-diagrams} -### Level 1: Macro Workflow +#### Level 1: Macro Workflow ```mermaid flowchart LR subgraph PrimarySeq["Primary Sequential Workflow (Steps 1–7)"] - A["1. Data & QA/QC\n(Bad-Hole, Repair, Normalization)"] --> B["2. Tops & Ancillary\n(Min. Curvature, Tops Ingestion)"] - B --> C["3. Lithology & Porosity\n(Vsh, SSC, Multi-Mineral, Phie)"] - C --> D["4. Permeability\n(Choo, Coates, Tixier, FZI)"] - D --> E["5. Saturation\n(Archie, Waxman-Smits, Dual Water)"] - E --> F["6. Reservoir Summary\n(Cutoffs, Net Pay, Log Blocking)"] - F --> G["7. Well CPI Report\n(Automated Dossier, FDP Export)"] + A["1. Well & Ancillary\n(Header, Hole Sections, Tops, Trajectory)"] --> B["2. Data & QA/QC\n(Bad-Hole, Env & Invasion Corr, Deconv, Repair)"] + B --> C["3. Lithology & Porosity\n(Vsh, SSC, Thomas-Stieber, Multi-Mineral, Phit/Phie)"] + C --> D["4. Permeability\n(Choo, Kozeny-Carman, Timur, Tixier, Coates)"] + D --> E["5. Saturation\n(Archie, Waxman-Smits, Simandoux, Indonesian, Dual Water)"] + E --> F["6. Reservoir Summary\n(Cutoffs, Sensitivity, Zonal Sums, Log Blocking)"] + F --> G["7. Well CPI Report\n(Automated CPI Dossier, QC Gate Checks, PDF)"] end - subgraph StandaloneLab["Standalone Lab Module"] - LAB["Core & Pc Prep\n(Depth Shift, Stress Corrections, Lab Pc)"] + subgraph StandaloneMods["Standalone Specialized Modules"] + LAB["Core & Pc Prep\n(Depth Shift, Stress & Klinkenberg, Lab Pc, Grain Density)"] + TOC["Source Rock & TOC\n(Passey Delta Log R, Hood LOM & Core Calibration)"] end - LAB -.->|Depth-Aligned Core| C + LAB -.->|Depth-Aligned Core & Rho_ma| C LAB -.->|Stress-Corrected Perm| D + TOC -.->|TOC & Source Flags| C - style A fill:#f0f9ff,stroke:#0284c7,stroke-width:1.5px - style B fill:#f8fafc,stroke:#475569,stroke-width:1.5px + style A fill:#f8fafc,stroke:#475569,stroke-width:1.5px + style B fill:#f0f9ff,stroke:#0284c7,stroke-width:1.5px style C fill:#f0fdf4,stroke:#16a34a,stroke-width:1.5px style D fill:#fefce8,stroke:#ca8a04,stroke-width:1.5px style E fill:#fff1f2,stroke:#e11d48,stroke-width:1.5px style F fill:#fef3c7,stroke:#d97706,stroke-width:1.5px style G fill:#eff6ff,stroke:#2563eb,stroke-width:2px style LAB fill:#faf5ff,stroke:#9333ea,stroke-width:1.5px,stroke-dasharray: 4 4 + style TOC fill:#ecfdf5,stroke:#059669,stroke-width:1.5px,stroke-dasharray: 4 4 ``` -### Level 2: Sub-Process & Curve Handoff Architecture +#### Level 2: Sub-Process & Curve Handoff Architecture ```mermaid flowchart TD - subgraph S1["1. Data & QA/QC (InspectorQaqc)"] - LAS["Raw LAS Curves\n(GR, RHOB, NPHI, RT, DTC, CALI)"] - CALI["CALI & Bit Size (BS)"] --> BAD["Bad-Hole Flag (BADHOLE)\nDifferential Caliper & Rugosity σ_RHOB"] - LAS --> BAD - BAD --> REPAIR["Synthetic Curve Repair\nML / Multi-Log Reconstruction"] + subgraph S1["1. Well & Ancillary Data (InspectorAncillary)"] + HDR["Well Header & Datum\n(KB/DF, Water Depth, BHT, Mud Type, Rmf ↔ Salinity)"] + HSEC["Hole Sections Table\n(Interval BS, Mud Type/Weight/Salinity, Rmf)"] + SURV["Directional Survey\n(MD, INC, AZI)"] --> MINCURV["Minimum Curvature Solver\nTVD, TVDSS, DX, DY, DLS"] + TOPS["Stratigraphic Tops, Fluid Contacts,\nRCA Core, SCAL Pc & FPT Mobility"] end - subgraph S2["2. Tops & Ancillary Data (InspectorAncillary)"] - SURV["Directional Survey\n(MD, INC, AZI)"] --> MINCURV["Minimum Curvature Solver\nTVD, TVDSS, Northing, Easting"] - TOPS["Stratigraphic Tops & Zones"] - MINCURV --> TVD_GRID["Continuous TVDSS Depth Grid"] + subgraph S2["2. Data & QA/QC (InspectorQaqc)"] + LAS["Raw LAS/DLIS Curves\n(GR, RHOB, DRHO, NPHI, RT, RMED, RXO, DTC, CALI)"] + HSEC & LAS --> BAD["4-Criterion Bad-Hole Flag (BADHOLE)\nΔCALI, |DRHO|, RHOB/NPHI Bounds & Rugosity"] + HDR & HSEC & LAS --> ENVCORR["Borehole Env & Invasion Corrections\n(*_ENV_CORR, *_SIGMA, *_QC_CONF, RT/RXO/DI_IN)"] + LAS --> DECONV["1D Bounded Huber Deconvolution\n(GR_ENH, NPHI_ENH, RHOB_ENH)"] + BAD & LAS --> REPAIR["Imputation, Splice Runs & Curve Repair\n(*_IMP, *_ORI, Multi-Log Reconstruction)"] end subgraph S3["3. Lithology & Porosity Evaluation (InspectorLithoPoro)"] - REPAIR --> VSH_MOD["Shale Volume (VSH_GR)\nLinear, Larionov, Clavier, Stieber"] - REPAIR & VSH_MOD --> LITHO_SOLVER{"Lithology Engine"} + ENVCORR & DECONV & REPAIR --> VSH_MOD["Shale Volume (VSH_GR)\nLinear, Larionov, Clavier, Stieber (GR/CGR/SGR/CGR_SYN)"] + ENVCORR & VSH_MOD --> LITHO_SOLVER{"Lithology Engine"} LITHO_SOLVER -->|Sand-Silt-Clay| SSC["SSC Ternary Model\n(VSAND, VSILT, VCLAY)"] - LITHO_SOLVER -->|Thin Beds| TB["Thomas-Stieber Tensor Model\n(V_lam, V_disp, Sand Phie)"] - LITHO_SOLVER -->|Carbonate| CARB["Carbonate Partitioning\n(VCALC, VDOLO, VANHY)"] - LITHO_SOLVER -->|Multi-Mineral| MM["SLSQP Matrix Inversion\nMin ||Av - b||^2"] - SSC & TB & CARB & MM --> PORO_CALC["Total & Effective Porosity\n(PHIT, PHIE) via Density/Neutron/Sonic"] - PORO_CALC <-->|Gas / Condensate| HCCORR["Hydrocarbon Correction\nExcavation & Density Adjustment"] + LITHO_SOLVER -->|Thin Beds| TB["Thomas-Stieber Tensor Model\n(VSH_LAM, VSH_DIS, VSH_STR, PHIT_SAND)"] + LITHO_SOLVER -->|Multi-Mineral| MM["SLSQP Matrix Inversion\nSelectable Input Logs"] + SSC & TB & MM --> PORO_CALC["Total & Effective Porosity\n(PHIT, PHIE) + Continuous RHO_FL & Coal/Badhole Overrides"] end subgraph S4["4. Permeability Estimation (InspectorPerm)"] - PORO_CALC & VSH_MOD --> PERM_ENGINE{"Permeability Model"} - PERM_ENGINE -->|Shaly Clastics| CHOO["Choo Model: f(PHIT, VCLAY, VSILT)"] - PERM_ENGINE -->|Free Fluid NMR| COATES["Timur-Coates / Free Fluid Model"] - PERM_ENGINE -->|Empirical Clastics| TIXIER["Tixier / Morris-Biggs Gas & Oil"] - PERM_ENGINE -->|Hydraulic Units| HFU_PERM["Amaefule FZI / RQI Transform"] + PORO_CALC & SSC & TB --> PERM_ENGINE{"Single-Well Empirical Perm"} + PERM_ENGINE -->|Sand-Silt-Clay| CHOO["Choo Model: f(PHIT, VCLAY, VSILT, m, A, B, C)"] + PERM_ENGINE -->|Clean Sand| KC["Kozeny-Carman: f(PHIT, S)"] + PERM_ENGINE -->|Swirr Empirical| TIM_TIX_COA["Timur / Tixier / Coates-Dumanoir: f(PHIT, Swirr)"] end subgraph S5["5. Fluid Saturation Evaluation (InspectorSaturation)"] - TVD_GRID --> TEMP_GRAD["Geothermal Gradient & Rw(T)\nArps Temperature Conversion"] - PORO_CALC & TEMP_GRAD --> SAT_ENGINE{"Saturation Model"} - SAT_ENGINE -->|Clean / Carbonate| ARCHIE["Archie Equation\n(Swt, Swe via m, n, a, Rw)"] - SAT_ENGINE -->|Dispersed Shaly Sand| WS["Waxman-Smits Model\n(CEC, Qv, B Counter-Ion Mobility)"] - SAT_ENGINE -->|Dual Conductivity| DW["Dual Water Model\n(Bound Water Swb & Free Water Swf)"] - SAT_ENGINE -->|Total Shale Clastic| SIM_IND["Simandoux / Indonesian Model"] + MINCURV & HDR --> TEMP_GRAD["Geothermal Gradient & Rw(T)\nArps / Bateman-Konen Conversion"] + PORO_CALC & TB & TEMP_GRAD --> SAT_ENGINE{"Saturation & Fluid Typing"} + SAT_ENGINE -->|Clean / Carbonate| ARCHIE["Archie + Continuous m(φ)\n(Calibrated Water-Leg, Borai, Shell/Lucia)"] + SAT_ENGINE -->|Shaly Sand| SHALY["Waxman-Smits / Simandoux / Indonesian / Dual Water"] + ARCHIE & SHALY --> FTYPE["Fluid Typing & Manual Overrides\n(FLUID_TYPE, SWT Overrides, Segregation)"] end subgraph S6["6. Reservoir Summary & Log Blocking (InspectorResSum)"] - PORO_CALC & PERM_ENGINE & SAT_ENGINE & TOPS --> CUTOFFS["Net Pay Cutoffs\n(Vsh_cut, Phie_cut, Sw_cut, Perm_cut)"] - CUTOFFS --> SUMMARY["Zonal Net Reservoir / Net Pay Sum\n(Gross, Net, NTG, Phie_avg, Sw_avg, HCPV)"] - CUTOFFS --> BLOCKING["Log Upscaling (Blocking)\nArithmetic, Geometric, Harmonic"] + PORO_CALC & PERM_ENGINE & FTYPE & TOPS --> CUTOFFS["Rock, Reservoir & Pay Cutoffs\n+ PRMS 95% HCPV Cutoff Sensitivity"] + CUTOFFS --> SUMMARY["Zonal Summary & Stochastic MC Uncertainty\n(Gross, Net, NTG, Phit, Swt, BVHC, Perm Proxies)"] + CUTOFFS --> BLOCKING["Cardwell-Parsons Log Blocking\nArithmetic, Geometric, Harmonic, Power-Law ω"] end subgraph S7["7. Well CPI Report (InspectorReport)"] - SUMMARY & BLOCKING --> DOSSIER["CPI Composite Plot, Property Tables\n& Automated FDP Markdown/PDF"] + ENVCORR & SUMMARY & BLOCKING --> DOSSIER["Single-Well CPI Dossier, Env/Invasion QC Audit,\nSubsurface Gate Checks (CHK-01+) & A4 PDF"] end subgraph S_LAB["Standalone: Core & Pc Prep (InspectorScal)"] - CORE_RAW["Routine Core Analysis (RCA)\n(CPOR, CPERM, Grain Density)"] --> SHIFT["Core-to-Log Warping\nInteractive Depth Alignment Δz(MD)"] - CORE_RAW --> STRESS["Overburden & Klinkenberg Corrections\nNet Confining Stress Compaction"] - PC_LAB["Lab Capillary Pressure (Pc)"] --> PC_SCALE["Lab-to-Reservoir Pc Scaling\nInterfacial Tension & Contact Angle"] + CORE_RAW["RCA Core Plugs\n(CPORE, CPERM, CGD)"] --> SHIFT["Core-to-Log Depth Shift Δz(MD)"] + CORE_RAW --> STRESS["Overburden Stress & Klinkenberg Slippage"] + CORE_RAW --> RHO_MA["Multi-Log Huber/Ridge Grain Density (RHOM)"] + PC_LAB["Lab Capillary Pressure (Pc)"] --> PC_SCALE["Lab-to-Reservoir Pc Scaling"] + end + + subgraph S_TOC["Standalone: Source Rock & TOC (InspectorToc)"] + TOC_IN["RT + Sonic/Density/Neutron\n+ Ro% / LOM + Core TOC"] --> PASSEY["Passey ΔlogR & Continuous TOC (wt%)"] end - SHIFT -.->|Shifted Core Porosity| PORO_CALC - STRESS -.->|Liquid-Equiv Perm| PERM_ENGINE + SHIFT & RHO_MA -.-> PORO_CALC + STRESS -.-> PERM_ENGINE + PASSEY -.-> LITHO_SOLVER ``` --- ## 2. Primary Sequential Steps (1 to 7) -### Step 1: Data & Log QA/QC (`InspectorQaqc`) {#sw-step-1-qaqc} +### Step 1: Well Header, Hole Sections, Ancillary & Trajectory (`InspectorAncillary`) {#sw-step-1-ancillary} -* **Objective:** Identify intervals where borehole washout or severe rugosity invalidates shallow-reading pad tools ($\text{RHOB}, \text{NPHI}, \text{PEF}$), perform environmental corrections, and reconstruct missing or corrupted log intervals using multi-log regressions. +* **Objective:** Establish well header metadata, depth-zoned borehole casing/bit-size and drilling-fluid intervals (**Hole Sections**), stratigraphic formation tops, fluid contacts, core/SCAL/pressure datasets, and the True Vertical Depth ($\text{TVD}$ / $\text{TVDSS}$) trajectory frame before log conditioning and petrophysical evaluation. -* **Technical Foundation:** +* **Well Header & Mud Filtrate Wiring:** + Configures surface/offshore elevation datums ($\text{KB}, \text{DF}, \text{GL}$, water depth, air gap), Bottom-Hole Temperature ($\text{BHT}$) records, mud system (`WBM`, `OBM`, `SBM`), mud weight, base-oil density, and mud/filtrate/mudcake resistivities ($R_m, R_{mf}, R_{mc}$) with measurement temperatures. Editing $R_{mf}$ and temperature or mud filtrate salinity synchronizes the counterpart via Bateman-Konen and Arps temperature conversion, feeding directly into Step 2 environmental/invasion corrections and Step 3 continuous apparent fluid density ($\rho_{fl}$). - * **Differential Caliper & Rugosity Flagging:** - Differential caliper $\Delta \text{CALI} = \text{CALI} - \text{BS}$ measures borehole enlargement relative to bit size. A rolling window of standard deviation $\sigma_{\text{RHOB}}$ evaluates micro-rugosity. The boolean `BADHOLE` flag is triggered if: - - $$\Delta \text{CALI} > \tau_{\text{cali}} \quad \lor \quad \sigma_{\text{RHOB}} > \tau_{\sigma} \quad \lor \quad \rho_b < 1.95\,\text{g/cm}^3 \quad \lor \quad \rho_b > 3.05\,\text{g/cm}^3$$ +* **Hole Sections (`hole_sections`):** + Defines depth-zoned wellbore intervals (`top`, `bottom`, `bit_size`, `mud_type`, `mud_weight`, `mud_salinity`, `rmf`, `rmf_temp`). When enabled in Step 2, Hole Sections synthesize a continuous nominal Bit Size (`BS`) curve and depth-specific mud program automatically across casing shoes, eliminating single-scalar bit-size errors across multi-section wells. - * **Borehole Environmental Corrections:** - Mudcake buildup and borehole temperature/pressure effects are compensated analytically: - - $$\Delta \rho_{\text{mudcake}} = -0.015 \cdot (\text{CALI} - \text{BS}) \cdot \frac{\rho_m - 1.0}{\rho_m}$$ +* **Formation-test mobility:** Enter or import optional drawdown mobility with formation pressure + tests. The well plot displays positive mobility values as pink triangles at measured depth in + Track 5, with a separate 0.01–10,000 mD/cP logarithmic scale and an FPT mobility toggle. + Points outside that scale are counted as off-scale; depth and zone filters apply. Hover a + point for its value, depth, and available fluid, quality, and remarks. Mobility is not + permeability: matching numerical positions on the two scales do not imply equivalent + properties, and no viscosity or permeability conversion is assumed. + +* **Technical Foundation (Minimum Curvature Directional Survey Inversion):** + Converts directional survey stations $(\text{MD}_i, I_i, A_i)$ (Measured Depth, Inclination, Azimuth) into continuous spatial coordinates $(\text{TVD}, \text{DX}, \text{DY})$ and dogleg severity using dogleg angle $\beta_i$ and ratio factor $RF_i$: + + $$\beta_i = \arccos\left(\cos I_{i-1} \cos I_i + \sin I_{i-1} \sin I_i \cos(A_i - A_{i-1})\right)$$ + + $$RF_i = \frac{2}{\beta_i} \tan\left(\frac{\beta_i}{2}\right) \quad (\text{with } RF_i \to 1 \text{ as } \beta_i \to 0)$$ + + $$\Delta \text{TVD}_i = \frac{\Delta \text{MD}_i}{2} (\cos I_{i-1} + \cos I_i) \cdot RF_i, \qquad \text{TVDSS} = \text{TVD} - \text{KB}$$ + +* **Input Data:** Well Header metadata, Hole Sections table, Stratigraphic Tops & Fluid Contacts, Directional survey (`MD`, `INC`, `AZI`), Routine Core (`CPORE`, `CPERM`, `CGD`), SCAL $P_c$ tables, FPT pressure/mobility points +* **Output Data:** Synthesized `BS` & mud program, continuous `TVD`, `TVDSS`, `DX`, `DY`, Dogleg Severity (`DLS`), registered formation `ZONES` + +--- + +### Step 2: Data & Log QA/QC (`InspectorQaqc`) {#sw-step-2-qaqc} + +* **Objective:** Audit curve coverage and missingness, flag borehole washouts and pad-standoff intervals (`BADHOLE`), apply physics-based borehole environmental and radial invasion corrections with per-sample uncertainty ($\sigma$) and sensor confidence (`*_QC_CONF`), harmonize vertical resolution via 1D deconvolution, and edit, splice, or impute log curves. + +* **Technical Foundation:** + + * **Four-Criterion Bad-Hole Flagging (`badhole_flagging`):** + Combines Hole Section bit sizes (`BS`), `ruptures` KDE change-point auto-estimated bit sizes (when `BS` is absent), or nominal fallback bit size with four configurable criteria: + 1. *Differential Caliper:* $|\text{CALI} - \text{BS}| \ge \tau_{\text{cali}}$ (outputs `DCALI` and `BS`). + 2. *Density Compensation Standoff:* $|\text{DRHO}| > \tau_{\text{drho}}$ (default $0.15\,\text{g/cm}^3$). + 3. *Bulk Density / Neutron Pad-Standoff Bounds:* $\rho_b < \rho_{\min} \;\lor\; \rho_b > \rho_{\max} \;\lor\; \phi_N > \phi_{N,\max}$ (excluding coal seams when `exclude_coal=True`). + 4. *Local Rugosity & Caliper Spikes:* Flags sharp drops of $\rho_b$ below its rolling mean (`rhob_trend_factor`) or $|\text{CALI} - \operatorname{median}_w(\text{CALI})| > \tau_{\text{spike}}$. + Emits `BADHOLE` and baseline `BADHOLE_BASE`. + + * **Unified Logging Environment, Borehole Corrections & Radial Invasion (`quick_pp.environment` & `quick_pp.borehole_corrections`):** + Constructs a continuous onshore or offshore (`water_depth`, `air_gap`, `seabed_temp`) temperature $T(z)$ (anchored to BHT records when provided) and mud/hydrostatic pressure $P(z)$ profile, converting $R_m, R_{mf}, R_w$ to formation temperature via Arps' equation. Evaluates generic Wireline (`WL`) and Logging-While-Drilling (`LWD`) tool profiles: + * *Gamma Ray (`GR_ENV_CORR`):* Compensates exponential mud-annulus attenuation across $d_{\text{hole}} - d_{\text{tool}}$ and strips KCl mud potassium background ($\approx 16\,\text{gAPI}/\%\text{K}$ scaled by annulus area fraction). + * *Thermal Neutron (`NPHI_ENV_CORR`):* Additive borehole washout, temperature, pressure, mud weight, borehole/formation salinity, and tool standoff corrections. + * *Bulk Density (`RHOB_ENV_CORR`):* Preserves vendor spine-and-ribs compensated `RHOB` when `DRHO` is present to avoid double-correcting mudcake; applies two-layer wall-gap compensation only for uncompensated density logs (with large $|\text{DRHO}|$ penalizing confidence). + * *Resistivity Borehole & Step-Profile Radial Invasion (`RT_ENV_CORR`, `RXO_INV`, `DI_IN`, `INVASION_FLAG`, `INVASION_PROFILE`):* Removes conductive washout-annulus mixing in `WBM`, then inverts 2- or 3-curve radial resistivity suites (`RT`, `RMED`, `RXO`) via a Gaussian step-profile geometric factor $J_k(d_i) = 1 - \exp(-(d_i/r_k)^2)$ for true $R_t$, flushed $R_{xo}$, and invasion diameter $d_i$ ($6\text{–}120\,\text{in}$ grid for 3 curves; $35\,\text{in}$ fixed for 2 curves). Compares $\log_{10}(R_{xo}/R_t)$ against $\log_{10}(R_{mf}/R_w)$ to classify water-like, movable hydrocarbon-like, anomalous, or tight/uninvaded intervals. + * *Per-Sample Uncertainty ($\sigma$) & Sensor Confidence:* Perturbation root-sum-square propagation combines sensor precision, $25\%$ model error, assumed-parameter uncertainty, and hole-severity penalties into `_SIGMA`, `_QC_CONF` $\in [0, 1]$, `_QC_STATUS` (`GOOD`, `CORRECTED`, `UNRELIABLE`), `HOLE_SEVERITY`, and bitmask `ENV_QC_REASON` (including isolated MAD `SPIKE`, stuck `FLATLINE`, and Gardner-checked sonic `CYCLE_SKIP`). Downstream modules can consume `*_ENV_CORR` with confidence-weighted blending (`QcWeightedInputsMixin`), and `*_SIGMA` propagates into stochastic Monte Carlo log uncertainty. + + * **Right-Pane Environmental, Invasion & P&T QC Views:** + Provides dedicated right-pane diagnostic views—**Borehole Env Correction QC** ($\pm 1\sigma$ ribbons, $\Delta$-correction tracks, confidence & reason flags), **Invasion Profile** ($R_t / R_m / R_{xo}$ radial separation, $d_i$, and $R_{xo}/R_t$ vs. $R_{mf}/R_w$ classification), and **P&T Profile** (formation temperature, BHT anchors, hydrostatic vs. mud-column pressure, and depth-varying $R_m / R_{mf} / R_w$). * **Raw Log Resolution Enhancement & Nuclear Log Harmonization:** Intrinsic sensor vertical resolutions differ (`GR` ≈ 0.76 m, `NPHI` ≈ 0.55 m, `RHOB` ≈ 0.40 m FWHM for legacy strings), creating inter-sensor footprint mismatches that scatter thin-bed laminated points on the Thomas-Stieber crossplot into unphysical boomerang loops. A 1D bounded deconvolution operator harmonizes all three logs onto a common target vertical resolution $\text{FWHM}_{\text{target}}$ subject to the Shannon-Nyquist limit ($2 \cdot \Delta z$). The forward model couples true formation property $\mathbf{x}$ to log response $\mathbf{y}$ through effective Gaussian Vertical Response Function (VRF) kernels: @@ -144,82 +190,41 @@ flowchart TD with normalized Huber edge-preserving penalty $\phi_\delta$, edge-replicate boundary padding, rolling bulk-volume conservation tether $\mathbf{H}_v$, and Morozov discrepancy parameter auto-tuning based on second-difference MAD sensor noise $\hat{\sigma}_n = \operatorname{MAD}(\mathbf{D}_2\mathbf{y}) / (0.6745\sqrt{6})$, capped at `noise_cap_mult` (default 3.0×) tool noise floor to protect against dense thin-bed inflation. - * **Synthetic Curve Repair:** - Corrupted pad readings are reconstructed via multivariate regression or Random Forest models trained on in-gauge intervals ($\text{BADHOLE} = 0$) using deep-reading, borehole-insensitive logs ($\text{GR}, \text{DTC}, \ln(\text{RT})$). - -* **Input Curves:** `CALI`, `BS`, `GR`, `RHOB`, `NPHI`, `DTC`, `RT` -* **Output Curves:** `BADHOLE` (flag), `GR_ENV_CORR`, `NPHI_ENV_CORR`, `RHOB_ENV_CORR`, `RT_ENV_CORR`, `GR_ENH`, `NPHI_ENH`, `RHOB_ENH`, `GR_RECON`, `NPHI_RECON`, `RHOB_RECON`, `DECONV_WEIGHT`. - Environmental-correction and enhanced-log outputs are non-destructive preview curves; downstream calculations use raw or enhanced inputs based on explicit selection. + * **Missing Data Imputation & Synthetic Curve Repair:** + **Missing Data Imputation** saves selected logs as new `_IMP` curves by default, or replaces selected curves while preserving a full-well `_ORI` backup (existing backups are never overwritten). Supports mean, median, most frequent, forward/backward fill, depth-based linear interpolation (interior gaps only), KNN, or iterative multivariate imputation (requiring $\ge 2$ curves). Active depth and zone filters apply; the right-pane **Missing Matrix** shows binned missing fractions by curve. Corrupted washout intervals can also be reconstructed via multivariate regression or Random Forest models trained on in-gauge intervals ($\text{BADHOLE} = 0$). * **Curve editing and splicing:** In Curve Editor & Management, select **View log vs depth in right pane** to compare the selected curve with its original backup or edit source. In **Splice Runs**, optionally enter a top and/or bottom depth in metres for each run; blank limits use the - full run and both limits include their boundary samples. For example, set Run 1's bottom to the - end of its good data and Run 2's top to the start of its good data. The overlap mode resolves + full run and both limits include their boundary samples. The overlap mode resolves samples covered by both intervals; uncovered depths stay empty unless gap interpolation is enabled. Auto-level uses only overlap within the selected intervals. Diagnostics compare the first two runs. Click **Apply Splice** after changing the settings to update the preview, then - **Save** to persist it. The selected runs are shown alongside the applied splice result. - The plot follows the active depth and zone filters and preserves gaps. - Use the plot selector to return to the histogram or another view. Log-versus-depth plots lock - the horizontal scale; the mouse wheel zooms depth, while selection tools remain available. - ---- - -### Step 2: Tops & Ancillary Data (`InspectorAncillary`) {#sw-step-2-ancillary} + **Save** to persist it. Log-versus-depth plots lock the horizontal scale; the mouse wheel zooms depth. -* **Objective:** Establish the True Vertical Depth Sub-Sea ($\text{TVDSS}$) coordinate frame, ingest stratigraphic formation tops, and manage wellbore survey geometry. - -* **Formation-test mobility:** Enter or import optional drawdown mobility with formation pressure - tests. The well plot displays positive mobility values as pink triangles at measured depth in - Track 5, with a separate 0.01–10,000 mD/cP logarithmic scale and an FPT mobility toggle. - Points outside that scale are counted as off-scale; depth and zone filters apply. Hover a - point for its value, depth, and available fluid, quality, and remarks. Mobility is not - permeability: matching numerical positions on the two scales do not imply equivalent - properties, and no viscosity or permeability conversion is assumed. - -* **Technical Foundation:** - - * **Minimum Curvature Directional Survey Inversion:** - Converts directional survey stations $(\text{MD}_i, I_i, A_i)$ (Measured Depth, Inclination, Azimuth) into continuous spatial coordinates $(\text{TVD}, N, E)$ using the dogleg angle $\beta_i$ and ratio factor $RF_i$: - - $$\beta_i = \arccos\left(\cos I_{i-1} \cos I_i + \sin I_{i-1} \sin I_i \cos(A_i - A_{i-1})\right)$$ - - $$RF_i = \frac{2}{\beta_i} \tan\left(\frac{\beta_i}{2}\right) \quad (\text{with } RF_i \to 1 \text{ as } \beta_i \to 0)$$ - - $$\Delta \text{TVD}_i = \frac{\Delta \text{MD}_i}{2} (\cos I_{i-1} + \cos I_i) \cdot RF_i$$ - - $$\text{TVDSS} = \text{TVD} - \text{KB}$$ - -* **Input Data:** Directional survey CSV, Kelly Bushing elevation ($\text{KB}$), Stratigraphic Tops -* **Output Data:** Continuous `TVD`, `TVDSS`, `DX`, `DY`, Formation tops depth registration +* **Input Curves:** `CALI`, `BS`, `GR`, `RHOB`, `DRHO`, `NPHI`, `RT`, `RMED`, `RXO`, `DTC`, Hole Sections & Header Environment +* **Output Curves:** `BADHOLE`, `BADHOLE_BASE`, `BS`, `DCALI`, `*_ENV_CORR`, `*_CORR_DELTA`, `*_SIGMA`, `*_QC_CONF`, `*_QC_STATUS`, `ENV_QC_REASON`, `HOLE_SEVERITY`, `ENV_TEMP_C`, `INVASION_FLAG`, `INVASION_PROFILE`, `DI_IN`, `GR_ENH`, `NPHI_ENH`, `RHOB_ENH`, `DECONV_WEIGHT`, `*_IMP`, `*_ORI`, `*_RECON` --- ### Step 3: Lithology & Porosity Evaluation (`InspectorLithoPoro`) {#sw-step-3-litho-poro} -* **Objective:** Partition the rock solid volume into mineral volumes ($V_{\text{sh}}, V_{\text{sand}}, V_{\text{silt}}, V_{\text{clay}}, V_{\text{calc}}, V_{\text{dolo}}$) and calculate Total Porosity ($\phi_t$) and Effective Porosity ($\phi_e$) corrected for shale and light hydrocarbon effects. +* **Objective:** Partition the rock matrix into mineral volumes ($V_{\text{sh}}, V_{\text{sand}}, V_{\text{silt}}, V_{\text{clay}}, V_{\text{calc}}, V_{\text{dolo}}$) and calculate Total Porosity ($\phi_t$) and Effective Porosity ($\phi_e$) corrected for shale, coal seams, bad-hole intervals, and light hydrocarbon effects. * **Technical Foundation:** - * **Gamma Ray Index & Empirical $V_{\text{sh}}$ Models:** + * **Gamma Ray Index & Empirical $V_{\text{sh}}$ Models (`vsh_gr`):** $$I_{GR} = \text{clip}\left(\frac{\text{GR} - \text{GR}_{\text{clean}}}{\text{GR}_{\text{shale}} - \text{GR}_{\text{clean}}}, 0, 1\right)$$ - $$\text{Linear: } V_{\text{sh}} = I_{GR}$$ - - $$\text{Larionov (Tertiary): } V_{\text{sh}} = 0.083 \left( 2^{3.7 \cdot I_{GR}} - 1 \right)$$ + $$\text{Linear: } V_{\text{sh}} = I_{GR}, \qquad \text{Larionov (Tertiary): } V_{\text{sh}} = 0.083 \left( 2^{3.7 \cdot I_{GR}} - 1 \right)$$ $$\text{Larionov (Older / Mesozoic): } V_{\text{sh}} = 0.33 \left( 2^{2 \cdot I_{GR}} - 1 \right)$$ - $$\text{Clavier (1971): } V_{\text{sh}} = 1.7 - \sqrt{3.38 - (I_{GR} + 0.7)^2}$$ - - $$\text{Stieber (1970): } V_{\text{sh}} = \frac{I_{GR}}{3 - 2 \cdot I_{GR}}$$ + $$\text{Clavier (1971): } V_{\text{sh}} = 1.7 - \sqrt{3.38 - (I_{GR} + 0.7)^2}, \qquad \text{Stieber (1970): } V_{\text{sh}} = \frac{I_{GR}}{3 - 2 \cdot I_{GR}}$$ - * **Sand-Silt-Clay (SSC) Ternary Model:** - Partitioning resolves the barycentric triangle of Clean Quartz Sand $(\text{NPHI}_{\text{sd}}, \rho_{\text{sd}})$, Dry Silt $(\text{NPHI}_{\text{slt}}, \rho_{\text{slt}})$, and Dry Clay $(\text{NPHI}_{\text{cl}}, \rho_{\text{cl}})$: - - $$V_{\text{sand}} + V_{\text{silt}} + V_{\text{clay}} + \phi_t = 1$$ + * **Sand-Silt-Clay (SSC) Ternary & Sand-Shale Models:** + Resolves the barycentric triangle of Clean Quartz Sand $(\text{NPHI}_{\text{sd}}, \rho_{\text{sd}})$, Dry Silt $(\text{NPHI}_{\text{slt}}, \rho_{\text{slt}})$, and Dry Clay $(\text{NPHI}_{\text{cl}}, \rho_{\text{cl}})$. Saved lithology fractions (`VSAND`, `VSILT`, `VCLAY`, `VCALC`, `VDOLO`, etc.) are **matrix-relative** ($\sum V_{\text{mineral}} = 1$); the composite log plot scales them by $(1 - \phi_t)$ for bulk-volume visualization. * **Neutron-Density Crossplot Shale Volume ($V_{\text{sh,ND}}$):** Calculated from parametric projection along the matrix line in $(\phi_N, \rho_b)$ crossplot space from clean sand endpoint $\mathbf{A} = (\phi_{N,\text{sd}}, \rho_{\text{sd}})$ to dry clay endpoint $\mathbf{C} = (\phi_{N,\text{cl}}, \rho_{\text{cl}})$: @@ -235,343 +240,247 @@ flowchart TD Standard endpoints (Quartz: $M=0.810, N=0.898$; Calcite: $M=0.827, N=0.585$; Dolomite: $M=0.778, N=0.524$; Anhydrite: $M=0.702, N=0.505$) establish diagnostic ternary triangles and feed the dynamic `M_LITH`/`N_LITH` drivers for core grain-density calibration. - * **Thin-Bed Thomas-Stieber & Tensor Resistivity:** - Partitions shale into laminated ($V_{\text{lam}}$), dispersed ($V_{\text{disp}}$), and structural ($V_{\text{struct}}$) forms. On the $\phi_t$ vs. $V_{\text{sh}}$ crossplot, points below the laminated line $\phi_{\text{lam}} = \phi_{\text{sd}} + (\phi_{\text{sh}} - \phi_{\text{sd}}) V_{\text{sh}}$ fall in the dispersed triangle and split shale into $V_{\text{lam}} + V_{\text{disp}}$; points above it fall in the structural triangle bounded by the grain-replacing line $\phi_{\text{str}} = \phi_{\text{sd}} + \phi_{\text{sh}} V_{\text{sh}}$ and split shale into $V_{\text{lam}} + V_{\text{struct}}$: + * **Thin-Bed Thomas-Stieber & Hagiwara Tensor Resistivity:** + Partitions shale into laminated ($V_{\text{lam}}$), dispersed ($V_{\text{disp}}$), and structural ($V_{\text{struct}}$) forms (`VSH_LAM`, `VSH_DIS`, `VSH_STR`, `PHIT_SAND`, `RSAND_TS`). On the $\phi_t$ vs. $V_{\text{sh}}$ crossplot, points below the laminated line $\phi_{\text{lam}} = \phi_{\text{sd}} + (\phi_{\text{sh}} - \phi_{\text{sd}}) V_{\text{sh}}$ fall in the dispersed triangle ($V_{\text{lam}} + V_{\text{disp}}$); points above it fall in the structural triangle bounded by $\phi_{\text{str}} = \phi_{\text{sd}} + \phi_{\text{sh}} V_{\text{sh}}$ ($V_{\text{lam}} + V_{\text{struct}}$): $$V_{\text{lam}} = \begin{cases} \dfrac{\phi_t - \phi_{\text{sd}} + V_{\text{sh}}(1-\phi_{\text{sh}})}{1-\phi_{\text{sd}}} & \phi_t \le \phi_{\text{lam}} \\[2ex] \dfrac{\phi_{\text{sd}} + V_{\text{sh}}\,\phi_{\text{sh}} - \phi_t}{\phi_{\text{sd}}} & \phi_t > \phi_{\text{lam}} \end{cases}, \quad V_{\text{disp}} + V_{\text{struct}} = V_{\text{sh}} - V_{\text{lam}}$$ - $$R_h^{-1} = \frac{1 - V_{\text{lam}}}{R_{\text{sand}}} + \frac{V_{\text{lam}}}{R_{\text{shale}}}, \qquad R_v = (1 - V_{\text{lam}}) R_{\text{sand}} + V_{\text{lam}} R_{\text{shale}}$$ + $$R_h^{-1} = \frac{1 - V_{\text{lam}}}{R_{\text{sand}}} + \frac{V_{\text{lam}}}{R_{h,\text{shale}}}, \qquad R_v = (1 - V_{\text{lam}}) R_{\text{sand}} + V_{\text{lam}} R_{v,\text{shale}}$$ * **Multi-Mineral Constrained Optimization (SLSQP):** - Given log measurements $\mathbf{b}$ and mineral response matrix $\mathbf{A}$: + Given selectable log measurements $\mathbf{b}$ (`input_logs`, minimum 2 curves among `GR`, `NPHI`, `RHOB`, `PEF`, `DTC`, `POTA`, `THOR`, `URAN`) and mineral response matrix $\mathbf{A}$: $$\min_{\mathbf{v}} \sum_{j=1}^N w_j \left( \frac{\sum_{i=1}^M A_{ji} v_i - b_j}{\sigma_j} \right)^2 \quad \text{s.t.} \quad \sum_{i=1}^{M+1} v_i = 1, \quad 0 \le v_i \le 1$$ * **Total Porosity ($\phi_t$) & Effective Porosity ($\phi_e$):** - $$\text{Density Porosity: } \phi_{D} = \frac{\rho_{\text{ma}} - \rho_b}{\rho_{\text{ma}} - \rho_{\text{fl}}}$$ - - $$\text{Sonic Porosity (Wyllie): } \phi_S = \frac{\Delta t - \Delta t_{\text{ma}}}{\Delta t_{\text{fl}} - \Delta t_{\text{ma}}}$$ + $$\text{Density Porosity: } \phi_{D} = \frac{\rho_{\text{ma}} - \rho_b}{\rho_{\text{ma}} - \rho_{\text{fl}}}, \qquad \text{Sonic (Wyllie): } \phi_S = \frac{\Delta t - \Delta t_{\text{ma}}}{\Delta t_{\text{fl}} - \Delta t_{\text{ma}}}$$ $$\text{Hunt-Raymer: } \phi_S = -c - \sqrt{c^2 + \frac{\Delta t_{\text{ma}}}{\Delta t} - 1}, \quad c = \frac{\Delta t_{\text{ma}}}{2\Delta t_{\text{fl}}} - 1$$ - $$\phi_e = \phi_t - V_{\text{clay}} \cdot \phi_{\text{clay}} \quad \text{or} \quad \phi_e = \phi_t (1 - V_{\text{sh}})$$ - -* **Input Curves:** `GR`, `RHOB`, `NPHI`, `PEF`, `DTC`, `POTA`, `THOR`, `URAN` -* **Output Curves:** `VSH`, `VSAND`, `VSILT`, `VCLAY`, `VCALC`, `VDOLO`, `PHIT`, `PHIE` - -* **Continuous fluid density ($\rho_{fl}$):** The **Fluid Density** selector offers - three modes. `Static` keeps the single scalar fluid density used by the classic - density-porosity equation. `Mud & Zonal Profile` builds a continuous - $\rho_{mf}(z)$ from the mud system (Batzle & Wang brine for WBM, thermal/pressure - corrected base oil for OBM/SBM) and applies a static zonal residual hydrocarbon - saturation across the fluid contacts. `Auto Iterative (Rxo / Sw^0.2)` runs the - full 3-tier coupled solver, iterating $\rho_{fl}$ and $\phi_D$ to convergence and - degrading per depth sample from shallow-resistivity $S_{xo}$ to the Poupon - $S_w^{c}$ fallback to a zonal $S_{hr}$ constant. - - The non-static modes add diagnostic curves: `RHO_FL` (continuous apparent fluid - density), `RHO_MF` (filtrate profile), `SXO_EST` (estimated flushed-zone - saturation), `PHID_RAW_100` (density porosity at $\rho_{fl} = 1.0$), and - `RHO_FL_TIER` (solver tier per sample). These are QC outputs, so they are not - drawn on the well log: they appear in the **Porosity Methods vs Core** comparison - plot, where `RHO_FL` and `RHO_MF` share the density axis with `RHOM` and the - scalar fluid density line, while `PHID_RAW_100` and the corrected `PHID` are drawn - on the porosity axis so the porosity shift ($\Delta\phi_D$) is directly visible. - - Mud system and base-oil density come from the QAQC Well Header (`mud_type`, - `obm_base_density`); filtrate salinity or surface `Rmf` and the flushing exponent - are set in the inspector. The engine is not available in batch evaluation. - See [Porosity Evaluation](../api/porosity.md#continuous-apparent-fluid-density-rho_fl) - for the tier logic, the physics, and the documented implementation conventions. - -* **Selectable input logs:** The multi-mineral inversion accepts any subset of the - available curves via `input_logs` (UI: *Input Logs* checkboxes). Leaving the selection - empty auto-uses every loaded curve among `GR`, `NPHI`, `RHOB`, `PEF`, `DTC`, `POTA`, - `THOR`, `URAN`. Exclude curves distorted by the mineralogy — for example drop `GR`, - `NPHI`, and `RHOB` in heavy-mineral or hot-sand intervals and invert on `PEF`, `THOR`, - and `POTA` instead. At least two curves are required, and each depth row must carry - enough finite measurements to constrain the solve. The selection is persisted as - `litho_input_logs` in the well config and reported in the generated report. - -* **Porosity method:** Alongside density and the neutron-density crossplot, choose - Wyllie or Hunt-Raymer sonic porosity, or a neutron-density weighted - $(2\phi_D+\phi_N)/3$, arithmetic $(\phi_D+\phi_N)/2$, or RMS - $\sqrt{(\phi_D^2+\phi_N^2)/2}$ average. The library's Gaymard and gas - averaging options use the same RMS formula. Averages use the selected fluid - density and lithology-derived matrix density; they are empirical corrections, - not substitutes for calibration to local lithology and core. - Sonic methods require `DTC` (or `DT`) as well as the neutron and density logs - required by the lithology workflow. Matrix transit time is the matrix-volume - weighted sum of configured mineral DTC values; silt uses quartz. The fluid - transit time is adjustable (default 190 µs/ft). Samples with missing or - non-positive sonic transit time, fluid transit time not exceeding matrix transit - time, or an invalid Hunt-Raymer result are null. Badhole interpolation may - interpolate flagged samples; coal and GR-based badhole handling retain their - existing special treatment. Effective porosity uses the existing shale correction. - The new methods are not available in batch evaluation. - -* **Porosity comparison:** Run Lithology & Porosity, then select **Porosity Methods - vs Depth + Core** from the Crossplot dropdown. The first track shows matrix - density (`RHOM`) and the configured fluid density; the second track overlays the - method curves with core markers. Toggle the methods to overlay - their total-porosity curves; the active method is emphasized. - Calculations use the current parameters and most recently calculated lithology and - corrected logs, but never overwrite the working or saved PHIT. Run the module - again after editing inputs. The fixed porosity scale is 0–0.5 v/v; use the mouse - wheel to zoom depth. RMSE and bias are computed - from depth-matched core porosity and each method's valid results, excluding flagged - coal and badhole samples. Core is matched to a log sample within 0.5 m, and markers - appear at the matched log depth. Different log/core scales, depth alignment and - laboratory conditions can affect the comparison. Depth and zone filters apply; - brushed calculation selections are not supported. + $$\phi_e = \max\left(0, \;\phi_t - V_{\text{clay}} \cdot \phi_{\text{clay}}\right) \quad \text{or} \quad \phi_e = \phi_t (1 - V_{\text{sh}})$$ -* **Vsh from gamma:** Select GR, an available gamma curve such as SGR or CGR, - or estimated `CGR_SYN = a_Th × THOR + a_K × POTA`. Verify thorium and potassium - units (ppm and percent) and coefficients against the tool calibration. The - provisional coefficients (4 gAPI/ppm and 16 gAPI/%) are not universal. - Calibrate endpoints independently for each response; imported GR aliases may - already refer to CGR. The gamma index is a shale proxy, not a mineralogical - clay measurement. - Select the response in **Vshale Calibration** and adjust its clean and shale - sliders there. The calibration comparison, auto-calibration, and P10/P90 reset - use the selected response. GR-based log correction and badhole fallback retain - their separate GR endpoints. - - Saved lithology fractions are matrix-relative and are not scaled by PHIT. - Multi-mineral inversion still jointly solves mineral and fluid volumes, then - reports mineral fractions relative to their sum. PHIT is computed separately; - the well plot scales mineral fractions to `1 − PHIT` for visualization only. - Recalculate previously saved lithology before comparing results or applying - cutoffs, because earlier versions saved PHIT-scaled volumes. - -* **Spectral crossplots:** The right pane also offers thorium vs potassium, PEF vs potassium, - and PEF vs Th/K. These use `THOR` in ppm, `POTA` in percent and `PEF` in b/e; - verify the input units before interpreting them. Potassium values are used as - stored, including values below 0.5%; no magnitude-based conversion is applied. - Curves stored as fractions must be converted to percent before use. The Th/K plot uses a logarithmic - ratio axis and excludes non-positive K or Th. Ratios are unstable at low K. - Th/K guide lines and the scatter are interpretive aids, not mineral classifications. - Diamond markers are illustrative configured mineral response endpoints, not - calibrated field boundaries. Selected Th and K curves are shared with the - derived-CGR controls. - PEF plots initially display 0–20 b/e and report the number of paired samples - above that range; zoom out to inspect them. Values are not clipped or modified. - The plots do not alter the GR-based shale calculation. +* **Continuous fluid density ($\rho_{fl}$):** Offers `Static` scalar $\rho_{fl}$, `Mud & Zonal Profile` (Batzle & Wang brine for WBM or P-T corrected base oil for OBM/SBM, wired to Well Header & Hole Section `mud_type`, `rmf`, and `mud_salinity`), and `Auto Iterative (Rxo / Sw^0.2)` (3-tier coupled $\rho_{fl}$–$\phi_D$ solver degrading gracefully from $S_{xo}$ to Poupon $S_w^c$ to zonal $S_{hr}$). Emits QC curves `RHO_FL`, `RHO_MF`, `SXO_EST`, `PHID_RAW_100`, and `RHO_FL_TIER` displayed on the **Porosity Methods vs Depth + Core** plot. + +* **Coal Seam Flagging, Badhole Mitigation & Reversible Manual Overrides:** + Detects low-density, high-neutron coal beds (`COAL_FLAG`) using threshold bounds (`RHOB`, `NPHI`), rolling-trend deviation, seam gap bridging, and adaptive gradient shoulder recovery so adjacent reservoir sand boundaries are not over-flagged. Supports `badhole_treatment` (`none`, `vsh_gr`, `interpolate`, `ignore`) and well-scoped, interval-based **Manual Overrides** to force or clear `COAL_FLAG` and `BADHOLE` non-destructively while preserving `COAL_BASE` and `BADHOLE_BASE` so overrides can be edited or reverted at any time. + +* **Vsh from gamma, Porosity Comparison & Spectral Crossplots:** + Select `GR`, `SGR`, `CGR`, or synthetic `CGR_SYN = a_Th × THOR + a_K × POTA` in **Vshale Calibration**. Use **Porosity Methods vs Depth + Core** to compare density, neutron-density crossplot, Wyllie/Hunt-Raymer sonic, and weighted/arithmetic/RMS (`avg_gaymard`) porosity methods against core porosity (`CPORE`, matched within 0.5 m, excluding flagged coal and badhole samples). Spectral right-pane crossplots (`THOR` vs `POTA`, `PEF` vs `POTA`, `PEF` vs `Th/K`) provide clay mineralogical diagnostics. + +* **Input Curves:** `GR`, `CGR`, `SGR`, `RHOB`, `NPHI`, `PEF`, `DTC`, `POTA`, `THOR`, `URAN`, optional `*_ENV_CORR` / `*_ENH` +* **Output Curves:** `VSHALE`, `VSAND`, `VSILT`, `VCLAY`, `VCALC`, `VDOLO`, `PHIT`, `PHIE`, `RHOM`, `COAL_FLAG`, optional `VSH_LAM`, `VSH_DIS`, `VSH_STR`, `PHIT_SAND`, `RSAND_TS`, `RHO_FL`, `RHO_MF` --- ### Step 4: Permeability Estimation (`InspectorPerm`) {#sw-step-4-perm} -* **Objective:** Generate continuous absolute permeability ($k$) profiles calibrated against core measurements. +* **Objective:** Generate continuous single-well absolute permeability (`PERM`, in mD) profiles from evaluated porosity, clay/silt fractions, or irreducible water saturation ($S_{\text{wirr}}$), calibrated against routine core permeability (`CPERM`). -* **Technical Foundation:** +> [!NOTE] +> **Scope Boundary — Single-Well Empirical Perm vs. Multi-Well Rock-Type Perm:** Single-Well Step 4 evaluates continuous log-based empirical correlations (`Choo`, `Kozeny-Carman`, `Timur`, `Tixier`, `Coates`). Discrete Hydraulic Flow Units (**Amaefule FZI / RQI**, **Winland $r_{35}$**, **Lucia RFN**) and rock-type-partitioned power-law regressions ($k = a_k \cdot \phi^{b_k} \to \text{PERM\_TRANS}$) belong to the **Multi-Well Workflow** ([Step 3: Rock Typing](multi_well.md#mw-step-3-rock-typing) and [Step 4: Field Permeability Transforms](multi_well.md#mw-step-4-perm-transform)), where multi-well core datasets establish statistically representative flow units across the field. + +* **Technical Foundation (`quick_pp.permeability`):** - * **Choo Model (Shaly Clastics):** + * **Choo (2010) Sand-Silt-Clay Shaly Clastic Model (`choo_permeability`):** + Relates total porosity ($\phi_t$) and grain-size tortuosity penalties from clay ($V_{\text{clay}}$) and silt ($V_{\text{silt}}$) fractions: + + $$k_{\text{Choo}} = \frac{A \cdot \phi_t^B}{10^{\left(6 V_{\text{clay}} + 3 V_{\text{silt}}\right)}}$$ - $$k_{\text{Choo}} = A \cdot \frac{\phi_t^B}{10^{\left(C \cdot V_{\text{clay}} + D \cdot V_{\text{silt}}\right)}}$$ + where $A$ is the grain-size constant ($A \approx 0.125 \cdot r_{\text{grain}}^2 / 10$, library default $1.65 \times 10^7$, UI default $10^6$), and $B$ is the porosity compaction/cementation exponent. When $B$ is not explicitly specified, it is derived from cementation exponent $m$ (default $2.0$) and constant $C$ (default $1.78$) via: - where $A \approx 0.125 \cdot r_{\text{grain}}^2 \times 10^8$, $B \in [5.5, 6.0]$, and $C, D$ weight the surface area tortuosity penalties of clay and silt. + $$B = m \left( \frac{2}{C} + 1 \right) + 2$$ - * **Timur-Coates Free-Fluid Model:** + * **Kozeny-Carman Clean / Unconsolidated Sand Model (`kozeny_carman_permeability`):** - $$k_{\text{Coates}} = C_{\text{TC}}^2 \cdot \phi_e^4 \cdot \left( \frac{1 - S_{\text{wirr}}}{S_{\text{wirr}}} \right)^2$$ + $$k_{\text{KC}} = \frac{\phi_t^3}{5 S^2 (1 - \phi_t)^2}$$ + + where $S$ is the specific grain surface area factor (default $0.01$). - * **Tixier & Morris-Biggs Models:** + * **Timur (1968) Empirical Sandstone Model (`timur_permeability`):** + + $$k_{\text{Timur}} = \frac{0.136 \cdot \phi_t^{4.4}}{S_{\text{wirr}}^2}$$ - $$k_{\text{Tixier}} = \left( 250 \cdot \frac{\phi_e^3}{S_{\text{wirr}}} \right)^2, \qquad k_{\text{gas}} = \left( 62.5 \cdot \frac{\phi_e^3}{S_{\text{wirr}}} \right)^2$$ + with $\phi_t$ and $S_{\text{wirr}}$ expressed as decimal fractions ($\text{v/v}$). - * **Amaefule Hydraulic Flow Unit (FZI / RQI) Transform:** + * **Tixier (1949) Irreducible Saturation Model (`tixier_permeability`):** - $$\text{RQI} = 0.0314 \sqrt{\frac{k}{\phi_e}}, \qquad \phi_z = \frac{\phi_e}{1 - \phi_e}, \qquad \text{FZI} = \frac{\text{RQI}}{\phi_z}$$ + $$k_{\text{Tixier}} = \frac{62.5 \cdot \phi_t^6}{S_{\text{wirr}}^2}$$ + + * **Coates (1974) / Coates-Dumanoir Free-Fluid Model (`coates_permeability`):** - $$k = 1014 \cdot \text{FZI}^2 \cdot \frac{\phi_e^3}{(1 - \phi_e)^2}$$ + $$k_{\text{Coates}} = \left( \frac{\phi^2}{a} \cdot \frac{1 - S_{\text{wirr}}}{S_{\text{wirr}}} \right)^2 \quad (a = 1 \text{ default})$$ -* **Input Curves:** `PHIE`, `PHIT`, `VCLAY`, `VSILT`, `SWIRR` -* **Output Curves:** `PERM`, `PERM_CHOO`, `PERM_COATES`, `RQI`, `FZI` + * **Python Library API Additional Correlations:** + `quick_pp.permeability` also provides `morris_biggs_permeability` ($k = (C \cdot \phi_t^3 / S_{\text{wirr}})^2$, $C=250$ medium oil, $C=79$ gas), `morris_biggs_modified_permeability`, and Park Jones / Pirson relative-permeability & water-cut screening utilities (`estimate_krw`, `estimate_kro`, `estimate_wor`, `estimate_wc`) for scripting workflows. + + * **Thomas-Stieber Thin-Bed Permeability Option (`use_thomas_stieber=True`):** + When Thomas-Stieber curves (`PHIT_SAND`, `VSH_LAM`, `VSH_DIS`) are present, evaluates clean sand-lamina permeability $k_{\text{sand}}(\phi_{t,\text{sand}}, V_{\text{sh,dis}})$ and scales horizontal thin-bed permeability by net sand fraction: + + $$k_h = (1 - V_{\text{sh,lam}}) \cdot k_{\text{sand}}$$ + + Flagged coal beds (`COAL_FLAG` or `VCOAL >= 0.5`) and non-porous intervals ($\phi_t \le 0$) are clamped to $0.001\,\text{mD}$. + +* **Input Curves:** `PHIT`, `VCLAY`, `VSILT` (or `VSHALE` fallback), `SWIRR` parameter, optional `PHIT_SAND`, `VSH_LAM`, `VSH_DIS`, Core `CPERM` +* **Output Curves:** `PERM` (mD), Core calibration metrics ($\log_{10}\text{RMSE}$, $\log_{10}\text{MAE}$, Factor Error $10^{\text{RMSE}}$, $R^2$) * **Permeability comparison:** Run Permeability, then select **Permeability Methods vs Depth + Core** from the Crossplot dropdown to overlay Choo, Kozeny-Carman, Timur, - Tixier and Coates-Dumanoir curves against `CPERM` on a logarithmic + Tixier, and Coates-Dumanoir curves against `CPERM` on a logarithmic permeability axis (fixed at 0.1–100,000 mD). The first track shows `VSHALE` (clay plus silt for the SSC model), matching the saturation comparison plot. Use the mouse wheel to zoom depth. Toggle methods and use the emphasized active method as a reference. The comparison uses the current model parameters, porosity and lithology inputs, including Thomas-Stieber inputs when enabled, without changing working or saved `PERM`. Only positive values are displayed or - included in the matched-core metrics. RMSE and bias are in log10 permeability - units; bias is log10(PERM) − log10(CPERM). Coal and badhole samples are + included in the matched-core metrics. RMSE and bias are in $\log_{10}$ permeability + units; bias is $\log_{10}(\text{PERM}) - \log_{10}(\text{CPERM})$. Coal and badhole samples are excluded from metrics. Core is matched to the nearest log sample within 0.5 m, with markers at matched log depths. Depth and zone filters apply; - brushed calculation selections are not supported. Core/log scale, depth - alignment and measurement conditions can influence the comparison. + brushed calculation selections are not supported. --- ### Step 5: Fluid Saturation Evaluation (`InspectorSaturation`) {#sw-step-5-saturation} -* **Objective:** Quantify Total Water Saturation ($S_{wt}$) and Effective Water Saturation ($S_{we}$) across clean sands, carbonates, and conductive shaly formations. +* **Objective:** Quantify Total Water Saturation ($S_{wt}$) and Effective Water Saturation ($S_{we}$) across clean sands, carbonates, laminated thin beds, and conductive shaly formations, paired with multi-criteria reservoir fluid typing. * **Technical Foundation:** - * **Geothermal Gradient & Arps Brine Resistivity ($R_w(T)$):** + * **Geothermal Gradient, Bateman-Konen Salinity & Arps Brine Resistivity ($R_w(T)$):** $$T(z) = T_{\text{surf}} + g_T \cdot \text{TVD}(z), \qquad R_w(T) = R_w(T_{\text{ref}}) \cdot \frac{T_{\text{ref}} + 21.5}{T(z) + 21.5} \quad (^\circ\text{C})$$ * **Archie Equation (Clean Sands & Carbonates):** - $$S_w = \left( \frac{a \cdot R_w}{\phi^m \cdot R_t} \right)^{\frac{1}{n}}$$ + $$S_{wt} = \left( \frac{a \cdot R_w}{\phi_t^m \cdot R_t} \right)^{\frac{1}{n}}$$ * **Waxman-Smits Shaly Sand Model:** - Solves for excess electrical conduction via Cation Exchange Capacity ($Q_v$, in $\text{meq/mL}$) and counter-ion mobility ($B$, in $\text{mho}\cdot\text{m}^2/\text{meq}$): - - $$Q_v = \frac{\text{CEC} \cdot (1 - \phi_t) \cdot \rho_{\text{ma,clay}} \cdot V_{\text{clay}}}{\phi_t}$$ + Solves for excess electrical conduction via Cation Exchange Capacity ($Q_v$, in $\text{meq/mL}$, derived from clay CEC & $\rho_{\text{dry,clay}}$, Juhasz normalized $Q_{vn}$, or crossplot calibration) and counter-ion mobility ($B$, in $\text{mho}\cdot\text{m}^2/\text{meq}$): - $$\frac{1}{R_t} = \frac{\phi_t^{m^*} S_{wt}^{n^*}}{a^*} \left( \frac{1}{R_w} + \frac{B \cdot Q_v}{S_{wt}} \right)$$ + $$Q_v = \frac{\text{CEC} \cdot (1 - \phi_t) \cdot \rho_{\text{ma,clay}} \cdot V_{\text{clay}}}{\phi_t}, \qquad \frac{1}{R_t} = \frac{\phi_t^{m^*} S_{wt}^{n^*}}{a^*} \left( \frac{1}{R_w} + \frac{B \cdot Q_v}{S_{wt}} \right)$$ Solved via Newton-Raphson iteration for $S_{wt}$, followed by clay-bound water stripping: $$S_{we} = \text{clip}\left(\frac{S_{wt} \cdot \phi_t - V_{\text{clay}} \phi_{\text{clay}}}{\phi_e}, 0, 1\right)$$ - * **Dual Water & Indonesian Models:** + * **Simandoux, Indonesian & Dual Water Shaly Sand Models:** - $$\text{Dual Water: } C_t = \phi_t^m S_{wt}^n \left( C_{wf} + \frac{S_{wb}}{S_{wt}} (C_{wb} - C_{wf}) \right)$$ + $$\text{Simandoux: } \frac{1}{R_t} = \frac{V_{\text{sh}}}{R_{\text{sh}}} S_w + \frac{\phi_e^m}{a \cdot R_w} S_w^n$$ $$\text{Indonesian: } \frac{1}{\sqrt{R_t}} = \left( \sqrt{\frac{V_{\text{sh}}^{2 - V_{\text{sh}}}}{R_{\text{sh}}}} + \sqrt{\frac{\phi_e^m}{a \cdot R_w}} \right) \cdot S_w^{n/2}$$ - - * **Cementation Exponent Calibration in 100% Water Leg ($m$):** - Inverts Archie (clean water sand) or Indonesian (shaly water sand) assuming $S_w = 1.0$ across depth- or zone-filtered water zones: - - $$\text{Archie: } m = \frac{\ln(R_w / R_t)}{\ln(\phi_t)}$$ - $$\text{Indonesian: } m = \frac{2}{\ln(\phi_t)} \ln\left(\sqrt{R_w}\left(\frac{1}{\sqrt{R_t}} - \frac{V_{\text{sh}}^{1 - 0.5 V_{\text{sh}}}}{\sqrt{R_{\text{sh}}}}\right)\right)$$ + $$\text{Dual Water: } C_t = \phi_t^m S_{wt}^n \left( C_{wf} + \frac{S_{wb}}{S_{wt}} (C_{wb} - C_{wf}) \right)$$ - Computes distribution metrics (mean, median, P10, P90) and calibrated linear regression $m = a \cdot \phi_t + b$ across valid physical points ($1.0 \le m \le 3.5$). + Supports Thomas-Stieber thin-bed evaluation (`use_thomas_stieber=True`) using sand-lamina porosity `PHIT_SAND`, dispersed shale `VSH_DIS`, and Hagiwara horizontal/vertical tensor-inverted sand resistivity `RSAND_TS`. - * **Continuous Depth-Variable Cementation Exponent Models ($m(\phi)$):** - Supports continuous calculation of $m(z)$ via: - 1. *Calibrated Trend*: $m(z) = a \cdot \phi_t(z) + b$ from water-leg calibration. - 2. *Borai (1987) Correlation (Low Porosity / Tight Formations)*: - $$m = 2.2 - \frac{0.035}{\phi_t + 0.042}$$ - 3. *Shell / Lucia (1983) Correlation (Carbonate & Fractured Systems)*: - $$m = 1.87 + \frac{0.019}{\phi_t}$$ + * **Cementation Exponent Calibration in 100% Water Leg ($m$) & Continuous $m(\phi)$:** + Inverts Archie or Indonesian assuming $S_w = 1.0$ across depth- or zone-filtered water legs: + + $$\text{Archie: } m = \frac{\ln(R_w / R_t)}{\ln(\phi_t)}, \qquad \text{Indonesian: } m = \frac{2}{\ln(\phi_t)} \ln\left(\sqrt{R_w}\left(\frac{1}{\sqrt{R_t}} - \frac{V_{\text{sh}}^{1 - 0.5 V_{\text{sh}}}}{\sqrt{R_{\text{sh}}}}\right)\right)$$ + + Supports continuous $m(z)$ via calibrated linear trend ($m = a\phi_t + b$), **Borai (1987)** tight-rock model ($m = 2.2 - \frac{0.035}{\phi_t + 0.042}$), or **Shell / Lucia (1983)** carbonate model ($m = 1.87 + \frac{0.019}{\phi_t}$). - * **Reservoir Fluid Typing & Phase Discrimination (`classify_fluid_types`, `fix_fluid_segregation`):** - Differentiates Gas, Oil, Unconfirmed Hydrocarbon, and Water phases across reservoir pay: - 1. *Neutron-Density Porosity Crossover*: $\Delta\phi = \phi_D - \phi_N$. Gas: $\Delta\phi \ge \Delta\phi_{\text{gas}}$; Oil: $\Delta\phi \le \Delta\phi_{\text{oil}}$; Unconfirmed: buffer interval between cutoffs. - 2. *Apparent Hydrocarbon Density ($\rho_{hc}$)*: - $$\rho_{hc} = \frac{\rho_b - (1-\phi_t)\rho_{ma} - \phi_t S_{wt}\rho_w}{\phi_t (1 - S_{wt})}$$ - Gas: $\rho_{hc} \le 0.40\,\text{g/cm}^3$; Oil: $\rho_{hc} \ge 0.55\,\text{g/cm}^3$. - 3. *Dipole Sonic Velocity Ratio ($V_p/V_s$)*: Gas: $V_p/V_s \le 1.60$; Oil: $V_p/V_s \ge 1.70$. - 4. *Haworth (1985) Mud Gas Chromatography*: Gas Wetness ($W_h$), Light-to-Heavy Balance ($B_h$), and Character ($C_h$) from $C_1\text{–}C_5$ mud-gas readings. - 5. *Physical Fluid Segregation*: Enforces gravity segregation (`fix_fluid_segregation`) ensuring lighter gas caps overlie oil legs within continuous stratigraphic zones or hydraulic flow compartments. - 6. *Interactive Manual Overrides*: Allows point- or interval-specific overrides for $S_{wt}$ and fluid type flags (`FLUID_TYPE`). + * **Reservoir Fluid Typing, Segregation & Manual Overrides (`classify_fluid_types`, `fix_fluid_segregation`):** + Differentiates `GAS`, `OIL`, `UNCONFIRMED`, and `WATER` intervals via Neutron-Density crossover ($\Delta\phi = \phi_D - \phi_N$), apparent hydrocarbon density ($\rho_{hc}$), dipole sonic $V_p/V_s$, Haworth $C_1\text{–}C_5$ mud-gas ratios, or `oil_only`/`gas_only` constraints. Enforces gravity segregation (`fix_fluid_segregation`) within continuous compartments and supports well-scoped, compact scrollable interval **Manual Overrides** for both `SWT` and `FLUID_TYPE`. -* **Input Curves:** `RT`, `PHIT`, `PHIE`, `VSH`, `VCLAY`, `TVD`, `NPHI`, `RHOB`, optional `DTC`, `DTS`, `C1`–`NC5` -* **Output Curves:** `SWT`, `SWE`, `BVW` ($\phi_e \cdot S_{we}$), `BVW_IRR`, `M_CALC`, `FLUID_TYPE`, `HC_FLAG`, `GAS_FLAG`, `OIL_FLAG`, `UNC_FLAG`, `RHO_HC`, `VOIL`, `VGAS`, `VUNC`, `BVHC` +* **Input Curves:** `RT`, `PHIT`, `PHIE`, `VSHALE`, `VCLAY`, `TVDSS`/`TVD`, `NPHI`, `RHOB`, optional `RSAND_TS`, `DTC`, `DTS`, `C1`–`NC5` +* **Output Curves:** `SWT`, `SWE`, `BVW`, `BVW_IRR`, `M_CALC`, `FLUID_TYPE`, `HC_FLAG`, `GAS_FLAG`, `OIL_FLAG`, `UNC_FLAG`, `RHO_HC`, `VOIL`, `VGAS`, `VUNC`, `BVHC` --- ### Step 6: Reservoir Summary & Log Blocking (`InspectorResSum`) {#sw-step-6-ressum} -* **Objective:** Apply petrophysical cutoffs to delineate Net Reservoir and Net Pay, compute zonal property averages, and upscale fine logs into coarse simulation layers. +* **Objective:** Apply petrophysical cutoffs (including optional permeability cutoffs) and empirical cutoff sensitivity analysis to delineate Net Rock, Net Reservoir, and Net Pay, compute PRMS/SEC-compliant zonal averages, quantify stochastic log uncertainty, and upscale fine logs onto cellular simulation grids. -* **Technical Foundation:** +* **Technical Foundation (`quick_pp.ressum` & `quick_pp.upscaling`):** - * **Rock & Pay Delineation:** + * **Rock, Reservoir & Pay Interval Flagging (`flag_interval`):** + Evaluates shale volume (`VCLAY` or `VSHALE`), total porosity (`PHIT`), water saturation (`SWT`), and permeability (`PERM_TRANS` when present, otherwise `PERM`): - $$\text{RES\_FLAG} = \mathbb{I}\left(V_{\text{sh}} \le V_{\text{sh,cut}} \;\land\; \phi_e \ge \phi_{e,\text{cut}} \;\land\; k \ge k_{\text{cut}}\right)$$ + $$\text{ROCK\_FLAG} = \mathbb{I}\left(V_{\text{sh}} \le V_{\text{sh,cut}}\right), \qquad \text{RES\_FLAG} = \text{ROCK\_FLAG} \;\land\; \mathbb{I}\left(\phi_t \ge \phi_{\text{cut}}\right) \;\land\; \mathbb{I}\left(k \ge k_{\text{cut}} \text{ if enabled}\right)$$ - $$\text{PAY\_FLAG} = \text{RES\_FLAG} \;\land\; \mathbb{I}\left(S_{we} \le S_{w,\text{cut}}\right)$$ + $$\text{PAY\_FLAG} = \text{RES\_FLAG} \;\land\; \mathbb{I}\left(S_{wt} \le S_{w,\text{cut}}\right)$$ - * **Zonal Integration:** - - $$H_{\text{gross}} = \sum_{i \in \text{Zone}} \Delta \text{TVD}_i, \qquad H_{\text{net}} = \sum_{i \in \text{Pay}} \Delta \text{TVD}_i, \qquad \text{NTG} = \frac{H_{\text{net}}}{H_{\text{gross}}}$$ + * **Empirical Cutoff Sensitivity Analysis (`cutoffs_analysis`):** + Sweeps candidate $V_{\text{sh}}$, $\phi_t$, and $S_{wt}$ cutoffs against cumulative Hydrocarbon Pore Volume ($\text{HCPV}$) and Net Pay thickness to identify inflection knees at a target PRMS HCPV recovery percentile (default $95\%$). + + * **PRMS/SEC-Compliant Zonal Integration (`calc_reservoir_summary`):** - $$\overline{\phi_e} = \frac{\sum_{i \in \text{Pay}} \phi_{e,i} \Delta \text{TVD}_i}{H_{\text{net}}}, \qquad \overline{S_w} = \frac{\sum_{i \in \text{Pay}} S_{w,i} \phi_{e,i} \Delta \text{TVD}_i}{\sum_{i \in \text{Pay}} \phi_{e,i} \Delta \text{TVD}_i}$$ + $$H_{\text{gross}} = \sum_{i \in \text{Zone}} h_i, \qquad H_{\text{net}} = \sum_{i \in \text{Pay}} h_i, \qquad \text{NTG} = \frac{H_{\text{net}}}{H_{\text{gross}}}$$ - $$\text{HCPV} = \sum_{i \in \text{Pay}} \phi_{e,i} (1 - S_{w,i}) \Delta \text{TVD}_i$$ + $$\overline{\phi_t} = \frac{\sum_{i \in \text{Pay}} \phi_{t,i} h_i}{H_{\text{net}}}, \qquad \overline{S_{wt}} = \frac{\sum_{i \in \text{Pay}} S_{wt,i} \phi_{t,i} h_i}{\sum_{i \in \text{Pay}} \phi_{t,i} h_i}, \qquad \overline{\text{BVHC}} = \frac{\sum_{i \in \text{Pay}} \phi_{t,i} (1 - S_{wt,i}) h_i}{H_{\text{net}}}$$ - * **Log Blocking / Upscaling Averaging Laws:** + * **Cardwell-Parsons Directional Log Blocking & Upscaling (`upscale_logs`):** + Upscales fine-scale logs onto fixed cell thicknesses or geological zones using thickness-weighted arithmetic averaging ($\phi, V_{\text{sh}}, \text{NTG}$), pore-volume-weighted saturation averaging ($\overline{S_w}$, strictly conserving $\text{BVHC}$), majority-vote discrete rock-type upscaling, and Cardwell-Parsons (1945) permeability laws: - $$\text{Arithmetic (Porosity, Volume): } \bar{x}_A = \frac{1}{\Delta z}\int_{z_a}^{z_b} x(z) \, dz$$ + $$\bar{k}_{\text{arith}} = \frac{\sum h_i k_i}{\sum h_i} \;(\omega=1), \qquad \bar{k}_{\text{geom}} = \exp\!\left(\frac{\sum h_i \ln k_i}{\sum h_i}\right) \;(\omega \to 0), \qquad \bar{k}_{\text{harm}} = \frac{\sum h_i}{\sum h_i / k_i} \;(\omega=-1)$$ - $$\text{Geometric (Heterogeneous Horizontal Perm): } \bar{k}_G = \exp\left( \frac{1}{\Delta z}\int_{z_a}^{z_b} \ln k(z) \, dz \right)$$ - - $$\text{Harmonic (Layered Vertical Perm): } \bar{k}_H = \left( \frac{1}{\Delta z}\int_{z_a}^{z_b} \frac{1}{k(z)} \, dz \right)^{-1}$$ + $$\bar{k}_{\omega} = \left( \frac{\sum h_i k_i^{\omega}}{\sum h_i} \right)^{1/\omega} \quad (\omega \in [-1, 1]), \qquad \frac{k_v}{k_h} = \frac{\bar{k}_{\text{harm}}}{\bar{k}_{\text{arith}}}$$ + + * **Stochastic Single-Well Monte Carlo Uncertainty (`calc_stochastic_reservoir_summary`):** + Propagates input log uncertainties (including per-sample `*_SIGMA` from Step 2 environmental corrections when present) across $N$ realizations to produce P10/P50/P90 curves (`PHIT_P10..P90`, `SW_P10..P90`, `BVHC_P10..P90`) and probabilistic zonal summaries. -* **Input Data:** `VSH`, `PHIE`, `SWE`, `PERM`, `TVD`, Stratigraphic Tops -* **Output Data:** `RES_FLAG`, `PAY_FLAG`, Zonal summary table, Blocked curves (`PHIE_BLK`, `PERM_BLK`, `SWE_BLK`) +* **Input Data:** `VCLAY`/`VSHALE`, `PHIT`, `SWT`, `PERM_TRANS`/`PERM`, `FLUID_TYPE`, Stratigraphic `ZONES` +* **Output Data:** `RES_FLAG`, `PAY_FLAG`, Zonal rollup table, Cutoff sensitivity curves, Blocked cellular & step-profile logs, Stochastic P10/P50/P90 CPI bands --- ### Step 7: Well CPI Report & Dossier Generation (`InspectorReport`) {#sw-step-7-report} -* **Objective:** Assemble evaluated curves, cutoffs, zonal summaries, composite log plots, and crossplots into a Computer Processed Interpretation (CPI) report in Markdown, PDF, and interactive HTML. +* **Objective:** Assemble all continuous single-well evaluations, borehole environmental & radial invasion QC audits, crossplots, core calibration metrics, cutoffs, zonal summaries, and subsurface gate checks into a publishable Single-Well CPI Dossier (`SINGLE_WELL_CPI`) in Markdown, interactive preview, and print-ready A4 PDF. + +* **Key Capabilities:** + * **Borehole QC & Invasion Audit Integration:** Automatically tabulates mud-program Hole Sections, bad-hole percentages, per-sensor environmental correction deltas, `*_SIGMA` uncertainty, `*_QC_CONF` sensor reliability, documented assumptions, and radial invasion ($R_{xo}/R_t$ vs. $R_{mf}/R_w$) movable-hydrocarbon statistics alongside high-DPI QC plots. + * **Pre-Render Subsurface Gate-Check Audit (`CHK-01`+):** Executes automated QA/QC verification gates across borehole conditioning, depth alignment, core parity, saturation physics, and uncertainty propagation, flagging anomalies with severity ratings and required handover remediation actions. + * **Customizable Sections & Export:** Supports per-section petrophysicist notes, optional AI narrative synthesis, high-DPI composite CPI plots, and paginated A4 PDF compilation. --- ## 3. Standalone Lab Module: Core & Pc Prep (`InspectorScal`) {#sw-standalone-core-pc} > [!NOTE] -> **Architecture Note:** In `quick_pp`, dynamic multiphase **Relative Permeability modeling and ECLIPSE `SWOF` deck generation have been consolidated into the Multi-Well Space** ([MultiWellSwirr](multi_well.md#mw-standalone-scal-relperm)), where rock-type partitioned $S_{\text{wirr}}$ fits and Corey/LET functions are calibrated consistently across the entire field. The Single-Well `InspectorScal` module serves as the **dedicated laboratory conditioning workbench** for core depth alignment, stress corrections, and lab capillary pressure scaling. +> **Architecture Note:** Dynamic multiphase **Relative Permeability modeling and ECLIPSE `SWOF` deck generation are consolidated into the Multi-Well Space** ([MultiWellSwirr](multi_well.md#mw-standalone-scal-relperm)), where rock-type partitioned $S_{\text{wirr}}$ fits and Corey/LET functions are calibrated consistently across the field. The Single-Well `InspectorScal` module serves as the **dedicated laboratory conditioning workbench** for core depth alignment, stress/Klinkenberg corrections, lab capillary pressure scaling, and core grain-density ($\rho_{ma}$) calibration. -* **Objective:** Condition Routine Core Analysis ($\text{RCA}$) ground-truth samples, apply overburden stress and gas slippage corrections, and scale laboratory mercury injection / porous plate capillary pressure measurements to in-situ reservoir conditions. +* **Objective:** Condition Routine Core Analysis ($\text{RCA}$) ground-truth samples, apply overburden stress and gas slippage corrections, scale laboratory MICP / porous plate / centrifuge capillary pressure measurements to in-situ reservoir conditions, and calibrate multi-log matrix density trends. * **Technical Foundation:** * **Interactive Core-to-Log Dynamic Depth Shifting:** - Aligns core plugs ($\phi_{\text{core}}, k_{\text{core}}$) to wireline logs ($\rho_b, \text{GR}$) by applying depth warping shifts $\Delta z(\text{MD})$: + Aligns core plugs ($\phi_{\text{core}}, k_{\text{core}}$) to wireline logs ($\rho_b, \text{GR}$) via piece-wise depth warping shifts $\Delta z(\text{MD})$: $$\text{MD}_{\text{shifted}} = \text{MD}_{\text{core}} + \Delta z(\text{MD})$$ * **Overburden Confining Stress Corrections:** Converts ambient laboratory porosity ($\phi_{\text{amb}}$) and permeability ($k_{\text{amb}}$) to effective reservoir confining stress $\sigma_{\text{net}}$: - $$\phi_{\text{res}} = \phi_{\text{amb}} \cdot (1 - C_\phi \cdot \sigma_{\text{net}})$$ + $$\phi_{\text{res}} = \phi_{\text{amb}} \cdot (1 - C_\phi \cdot \sigma_{\text{net}}), \qquad k_{\text{res}} = k_{\text{amb}} \cdot \exp(-C_k \cdot \sigma_{\text{net}})$$ - $$k_{\text{res}} = k_{\text{amb}} \cdot \exp(-C_k \cdot \sigma_{\text{net}})$$ - - where $C_\phi$ and $C_k$ are rock-specific compaction coefficients (sandstone, friable sandstone, carbonate). - - **Log-derived option:** Integrates bulk density over positive-down TVD to calculate vertical stress, estimates pore pressure from a user-selected gradient, and applies Biot's coefficient. When both DTC and DTS are available, dynamic Poisson's ratio is calculated from their velocity ratio; otherwise a configured fallback is used. Equivalent effective confining stress is the mean of vertical and two uniaxial-strain horizontal effective stresses. The profile assumes density at the shallowest valid sample continues to the depth datum; measured depth is only a TVD approximation when no TVD curve is available. It does not infer pore pressure from sonic compaction trends. + **Log-derived option:** Integrates bulk density over positive-down TVD to calculate vertical stress (`SV_EST`), estimates pore pressure (`PP_EST`) from a user-selected gradient, computes dynamic Poisson's ratio (`NU_DYN`) from `DTC`/`DTS` when available, and derives mean effective confining stress (`NCS_EST`). * **Klinkenberg Gas Slippage Correction:** - Corrects air permeability ($k_{\text{air}}$) to equivalent liquid permeability ($k_{\infty}$): + Corrects air permeability ($k_{\text{air}}$) to equivalent liquid permeability ($k_{\infty}$) using either the Jones or Heithaus formulation: $$k_{\infty} = \frac{k_{\text{air}}}{1 + \frac{b_K}{P_{\text{mean}}}}$$ - - using either the Jones or Heithaus formulation. * **Lab-to-Reservoir Capillary Pressure ($P_c$) Scaling:** - Rescales laboratory air-mercury or air-brine capillary pressures ($P_{c,\text{lab}}$) to reservoir fluid fluid system conditions ($P_{c,\text{res}}$): + Rescales laboratory air-mercury, air-brine, or oil-water capillary pressures ($P_{c,\text{lab}}$) to reservoir fluid conditions ($P_{c,\text{res}}$) using explicit lab fluid-system interfacial tension and contact angle without hardcoded pressure-threshold assumptions: $$P_{c,\text{res}} = P_{c,\text{lab}} \cdot \frac{(\sigma \cos\theta)_{\text{res}}}{(\sigma \cos\theta)_{\text{lab}}}$$ - * **Core-Calibrated Grain / Matrix Density ($\rho_{ma}$) Correlation:** - Calibrates a project-wide matrix density trend from core grain density (CGD) that overrides the mineral-model $\rho_{ma}$ in the Lithology & Porosity density-porosity calculation. Two forms are available: - - **Single anchored gamma driver:** - - $$\rho_{ma}(z) = \rho_{ma,\text{clean}} + k \cdot \left(\text{driver}(z) - \text{driver}_{\text{clean}}\right)$$ - - **Multi-log ridge / Huber (default):** - - $$\rho_{ma}(z) = b_0 + \sum_j \beta_j \frac{\text{log}_j(z) - c_j}{s_j}$$ - - Gamma logs are heteroscedastic — GR, CGR and SGR mix K/Th/U sources, so a single-log OLS slope is dominated by radioactive and heavy-mineral outliers (mica, glauconite). The multi-log form jointly regresses GR/CGR/SGR with RHOB, NPHI, Burke's $M$-parameter or acoustic impedance, standardizing each driver with a robust median/IQR and fitting by ridge regression with optional Huber IRLS reweighting. The fit reports $R^2$/RMSE, robust residual spread, per-driver variance inflation factors (collinearity), a Breusch-Pagan heteroscedasticity test, and the per-driver slopes in **native log units** so the model reads as a familiar regression equation, e.g. - - $$\hat{\rho}_{ma} = b_0 + \beta_1 \cdot \text{CGR} + \beta_2 \cdot \text{RHOB} + \beta_3 \cdot M_{\text{lith}}$$ - - Characterizing the correlation in the UI: - - * **Crossplot X-axis selector** — the "Grain Density vs. GR/CGR" crossplot header exposes an *X axis* dropdown so CGD can be plotted against any calibrated driver (CGR, GR, RHOB, NPHI, M_LITH, AI, …). When a multi-log fit is active the red trend line is the marginal 1-D slice: the plotted driver is swept while the remaining drivers are held at their fitted centers. - * **Weightage panel** — besides the standardized $\beta_j$ and VIF, each driver row shows the swing in $\rho_{ma}$ across that driver's observed interquartile range ($|\beta_j \cdot \text{IQR}_j| / s_j$), i.e. how much each log actually moves the predicted matrix density. - * **Burke $M$/$N$ drivers** — `M_LITH`+ / `N_LITH`+ chips are offered whenever `RHOB` and `NPHI` are loaded; selecting one *generates* the curve from RHOB/NPHI (with a Gardner slowness estimate when no sonic log exists), mirroring `quick_pp.machine_learning.feature_engineering.mn_lithology_parameters`. - * **Porosity provenance** — because the correlation overrides the mineral-model $\rho_{ma}$ fed to the density porosity, the porosity response reports how many points were replaced, the mean $\rho_{ma}$ and the mean $\Delta\rho_{ma}$ vs. the mineral model, and the result is persisted as the `RHOM` curve. Lithology & Porosity displays this as a "Grain-density correlation applied in Porosity" panel. + * **Core-Calibrated Grain / Matrix Density ($\rho_{ma}$) Correlation:** + Calibrates a project-wide matrix density trend from core grain density (`CGD`) that overrides the mineral-model $\rho_{ma}$ in Step 3 density porosity and persists `RHOM`. Supports a single anchored gamma driver: + + $$\rho_{ma}(z) = \rho_{ma,\text{clean}} + k \cdot \left(\text{driver}(z) - \text{driver}_{\text{clean}}\right)$$ + + or the default **multi-log ridge / Huber IRLS regression** across `GR`/`CGR`/`SGR`, `RHOB`, `NPHI`, Burke's `M_LITH`/`N_LITH`, and acoustic impedance `AI`: + + $$\rho_{ma}(z) = b_0 + \sum_j \beta_j \frac{\text{log}_j(z) - c_j}{s_j}$$ + + reporting $R^2$, RMSE, per-driver VIF collinearity, Breusch-Pagan heteroscedasticity, IQR swing weightage, and native-unit slopes. - * **Input Data:** Core plugs table (`DEPTH`, `CPORE`, `CPERM`, `CGRAIN_DENSITY`), Overburden stress parameters, Lab IFT and contact angle, driver logs (`GR`, `CGR`, `SGR`, `RHOB`, `NPHI`, `M_LITH`, `N_LITH`, `AI`) - * **Output Data:** `CPOR_SHIFTED`, `CPERM_SHIFTED`, `SV_EST`, `PP_EST`, `NU_DYN`, `NCS_EST`, Stress-corrected core properties, Scaled $P_c$ curves, Calibrated grain density correlation (project-scoped) +* **Input Data:** Core plugs table (`DEPTH`, `CPORE`, `CPERM`, `CGRAIN_DENSITY`), Overburden stress parameters, Lab/Reservoir IFT and contact angles, driver logs (`GR`, `CGR`, `SGR`, `RHOB`, `NPHI`, `M_LITH`, `N_LITH`, `AI`) +* **Output Data:** `CPOR_SHIFTED`, `CPERM_SHIFTED`, `SV_EST`, `PP_EST`, `NU_DYN`, `NCS_EST`, Stress/Klinkenberg-corrected core properties, Scaled $P_c$ curves, Project-scoped grain-density correlation (`RHOM`) --- @@ -582,37 +491,23 @@ flowchart TD * **Technical Foundation:** * **Passey et al. (1990) $\Delta\log R$ Technique:** - Overlays a properly scaled porosity log ($\Delta t$, $\rho_b$, or $\phi_N$) on deep resistivity ($R_t$) such that one logarithmic resistivity decade corresponds to $50\,\mu\text{s/ft}$ sonic transit time, $-0.25\,\text{g/cm}^3$ (or $-2.5$ scaling) bulk density, or $0.25\,\text{v/v}$ ($4.0$ scaling) neutron porosity: + Overlays a scaled porosity log ($\Delta t$, $\rho_b$, or $\phi_N$) on deep resistivity ($R_t$) such that one logarithmic resistivity decade corresponds to $50\,\mu\text{s/ft}$ sonic transit time ($0.02$), $-0.25\,\text{g/cm}^3$ ($-2.5$ scaling) bulk density, or $0.25\,\text{v/v}$ ($+4.0$ scaling) neutron porosity: $$\Delta\log R = \log_{10}(R_t / R_{\text{baseline}}) + \text{coeff} \cdot (\text{Poro\_log} - \text{Poro\_baseline})$$ - where $R_{\text{baseline}}$ and $\text{Poro\_baseline}$ represent the baseline response in lean, non-source, water-saturated shale. In organically lean rocks, the two curves track together ($\Delta\log R \approx 0$). In organic-rich source rocks, kerogen lowers the bulk density, increases acoustic transit time, and raises formation resistivity due to generated hydrocarbons, creating a pronounced positive separation ($\Delta\log R > 0$). + where $R_{\text{baseline}}$ and $\text{Poro\_baseline}$ represent lean, water-saturated non-source shale (selectable manually or via auto-detection). - * **Hood et al. (1975) Level of Organic Metamorphism (LOM):** - Converts measured Vitrinite Reflectance ($R_o\,\%$) to the continuous Hood maturity scale: + * **Hood et al. (1975) Level of Organic Metamorphism (LOM) & Continuous TOC:** - $$\text{LOM} = 10.59 + 4.54 \cdot \ln(R_o)$$ + $$\text{LOM} = 10.59 + 4.54 \cdot \ln(R_o), \qquad \text{TOC} = \Delta\log R \cdot 10^{\left(2.297 - 0.1688 \cdot \text{LOM}\right)} + \text{TOC}_{\text{baseline}}$$ - Spanning Immature ($R_o \approx 0.4 \implies \text{LOM} \approx 6.0$), Oil Window ($R_o \approx 0.8 \implies \text{LOM} \approx 9.6$), Condensate ($R_o \approx 1.0 \implies \text{LOM} \approx 10.6$), to Dry Gas ($\text{LOM} > 13.0$). - - * **Continuous TOC Quantification:** - - $$\text{TOC} = \Delta\log R \cdot 10^{\left(2.297 - 0.1688 \cdot \text{LOM}\right)} + \text{TOC}_{\text{baseline}}$$ - - where $\text{TOC}_{\text{baseline}}$ is background organic carbon in lean shale (default $0.8\,\text{wt}\%$). Negative $\Delta\log R$ separations in non-source rocks are clamped to $\text{TOC}_{\text{baseline}}$. + Negative $\Delta\log R$ separations in non-source rocks are clamped to $\text{TOC}_{\text{baseline}}$ (default $0.8\,\text{wt}\%$) when `clamp_negative=True`. * **Core Geochemical Calibration (`calibrate_toc_to_core`):** - Regresses measured core pyrolysis TOC points against log-derived $\Delta\log R$: - - $$\text{TOC}_{\text{core}} = a \cdot \Delta\log R + b$$ - - allowing direct derivation of the implied Level of Organic Metamorphism: - - $$\text{LOM}_{\text{implied}} = \frac{2.297 - \log_{10}(a)}{0.1688}$$ + Regresses measured core TOC (`CTOC`) against log-derived $\Delta\log R$ ($\text{TOC}_{\text{core}} = a \cdot \Delta\log R + b$), deriving implied maturity $\text{LOM}_{\text{implied}} = (2.297 - \log_{10} a) / 0.1688$. - * **Composite Log Display & Overlays:** - - **Track 2**: Overlays deep resistivity ($R_t$) and the Passey porosity-equivalent resistivity $R_{\text{poro}} = R_{\text{baseline}} \cdot 10^{-\text{coeff}\cdot(\text{log} - \text{log}_{\text{baseline}})}$ on a logarithmic scale (0.2–2000 ohm.m), visually highlighting source rock separation. - - **Track 4**: Displays continuous TOC (0–10 wt%) with high-grade source rock threshold shading ($\text{TOC} \ge 2.0\,\text{wt}\%$). + * **Composite Log & Crossplot Diagnostics:** + Track 2 overlays $R_t$ and porosity-equivalent resistivity $R_{\text{poro}}$ ($0.2\text{–}2000\,\Omega\cdot\text{m}$); Track 4 displays `TOC` ($0\text{–}10\,\text{wt}\%$) with source-rock shading ($\text{TOC} \ge 2.0\,\text{wt}\%$), paired with right-pane $\Delta\log R$ vs. core calibration crossplots. -* **Input Data:** `RT`, Porosity Log (`DT`, `RHOB`, or `NPHI`), $R_{\text{baseline}}$, $\text{Poro\_baseline}$, $R_o\,\%$ or LOM, background $\text{TOC}_{\text{baseline}}$, optional Core TOC (`CTOC`) +* **Input Data:** `RT`, Porosity Log (`DT`, `RHOB`, or `NPHI`), $R_{\text{baseline}}$, $\text{Poro\_baseline}$, $R_o\,\%$ or LOM, $\text{TOC}_{\text{baseline}}$, optional Core TOC (`CTOC`) * **Output Data:** `DELTA_LOG_R`, `TOC`, `TOC_PASSEY`, `TOC_SHALE_FLAG` diff --git a/mkdocs.yml b/mkdocs.yml index e4870126..2fdc15dd 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -121,13 +121,14 @@ nav: - "Thin-Bed Evaluation": tutorials/03_qpp_ts_single.ipynb - API Reference: - Package Overview: api/overview.md - - QA/QC & Normalization (qaqc): api/qaqc.md + - Environment, Borehole QC & Normalization (qaqc): api/qaqc.md - Raw Log Resolution Enhancement (conditioning): api/conditioning.md - Lithology Inversion (lithology): api/lithology.md - Porosity (porosity): api/porosity.md - Saturation & FWL Optimizer (saturation): api/saturation.md - Permeability (permeability): api/permeability.md - Rock & Fluid Typing (rock_type): api/rock_type.md + - Source Rock & TOC (source_rock): api/source_rock.md - Core Analysis (core_analysis): api/core_analysis.md - SCAL & Relative Permeability (scal): api/scal.md - Uncertainty & Monte Carlo (uncertainty): api/uncertainty.md diff --git a/pyproject.toml b/pyproject.toml index cda39a7d..7b3f5ba4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "quick-pp" -version = "0.3.7" +version = "0.3.8" description = "Comprehensive Python package and web platform for deterministic and probabilistic petrophysical evaluation, SCAL & relative permeability modeling, multi-well FWL optimization, stratigraphic normalization, and geomodel log upscaling." readme = { file = "README.md", content-type = "text/markdown" } license = "MIT" @@ -51,6 +51,7 @@ dependencies = [ "numpy", "pandas", "plotly", + "kaleido>=1.0.0", "python-dotenv", "ruptures", "scikit-learn", @@ -74,6 +75,7 @@ core = [ "numpy", "pandas", "plotly", + "kaleido>=1.0.0", "python-dotenv", "ruptures", "scikit-learn", diff --git a/quick_pp/__init__.py b/quick_pp/__init__.py index 4ebd0eaf..6551844d 100644 --- a/quick_pp/__init__.py +++ b/quick_pp/__init__.py @@ -48,7 +48,7 @@ __author__ = """Imran Fadhil""" __email__ = "imranfadhil@gmail.com" -__version__ = "0.3.7" # Need to be updated manually when releasing a new version/ change in pyproject.toml +__version__ = "0.3.8" # Need to be updated manually when releasing a new version/ change in pyproject.toml # Expose core petrophysical submodules and key public functions at top-level package namespace from quick_pp import ( # noqa: E402 diff --git a/quick_pp/app/backend/main.py b/quick_pp/app/backend/main.py index 8060a30b..32f714c7 100644 --- a/quick_pp/app/backend/main.py +++ b/quick_pp/app/backend/main.py @@ -1,4 +1,6 @@ +import asyncio import logging +import os from contextlib import asynccontextmanager from importlib import resources @@ -70,9 +72,26 @@ async def lifespan(app: "FastAPI"): except Exception as e: logging.getLogger(__name__).exception("Failed to initialize DBConnector: %s", e) + cleanup_task: asyncio.Task | None = None try: + from quick_pp.app.backend.utils.auth import is_demo_mode + + if is_demo_mode(): + from quick_pp.app.backend.services.demo_guard import ( + demo_periodic_cleanup_loop, + run_periodic_demo_cleanup, + ) + + run_periodic_demo_cleanup() + cleanup_task = asyncio.create_task(demo_periodic_cleanup_loop()) yield finally: + if cleanup_task is not None: + cleanup_task.cancel() + try: + await cleanup_task + except asyncio.CancelledError: + pass global _db_connector_instance try: if _db_connector_instance is not None: @@ -85,6 +104,12 @@ async def lifespan(app: "FastAPI"): ) +_initial_demo_mode = os.environ.get("QPP_DEMO_MODE", "false").lower() in ( + "1", + "true", + "yes", +) + app = FastAPI( title="quick_pp API", version=__version__, @@ -96,7 +121,7 @@ async def lifespan(app: "FastAPI"): }, swagger_ui_parameters={"defaultModelsExpandDepth": -1}, openapi_tags=tags_metadata, - debug=True, + debug=not _initial_demo_mode, lifespan=lifespan, ) @@ -125,6 +150,77 @@ async def lifespan(app: "FastAPI"): app.include_router(import_ancillary_router, prefix="/api/v1", include_in_schema=False) +@app.middleware("http") +async def demo_session_and_compute_guard_middleware(request: Request, call_next): + from quick_pp.app.backend.utils.auth import is_demo_mode + + if not is_demo_mode(): + return await call_next(request) + + from quick_pp.app.backend.services.demo_guard import ( + DEMO_SESSION_HEADER, + acquire_compute_slot_sync, + is_heavy_demo_compute_request, + normalize_session_id, + register_or_touch_session, + release_compute_slot_sync, + reset_current_demo_session_id, + set_current_demo_session_id, + ) + + path = request.url.path + sid = normalize_session_id(request.headers.get(DEMO_SESSION_HEADER)) + ctx_token = set_current_demo_session_id(sid) + acquired_compute = False + + try: + # Enforce soft capacity gate when a browser tab presents X-Demo-Session-Id + if sid and not path.startswith( + ("/quick_pp/demo/", "/quick_pp/auth/", "/static/") + ): + client_ip = ( + request.headers.get("cf-connecting-ip") + or request.headers.get("x-real-ip") + or (request.client.host if request.client else "") + ) + snap = register_or_touch_session(sid, client_ip=client_ip) + if not snap.get("admitted", True): + return JSONResponse( + status_code=429, + content={ + "detail": ( + f"Live demo is currently at capacity " + f"({snap['online_users']}/{snap['max_users']} active users). " + "Waiting for an open slot..." + ), + "code": "DEMO_AT_CAPACITY", + "online_users": snap["online_users"], + "max_users": snap["max_users"], + }, + ) + + # Enforce hard concurrency semaphore on CPU/RAM-heavy compute & report routes + if is_heavy_demo_compute_request(request.method, path): + acquired_compute = await asyncio.to_thread(acquire_compute_slot_sync) + if not acquired_compute: + return JSONResponse( + status_code=429, + content={ + "detail": ( + "Demo compute server is busy processing other visitors' " + "calculations. Please retry in a few seconds." + ), + "code": "DEMO_COMPUTE_BUSY", + }, + ) + + return await call_next(request) + finally: + if acquired_compute: + release_compute_slot_sync() + reset_current_demo_session_id(ctx_token) + + @app.get("/favicon.ico", include_in_schema=False) async def favicon(): return FileResponse(str(static_folder / "favicon.ico")) @@ -154,14 +250,22 @@ async def qpp_assistant(request: Request): @app.exception_handler(Exception) -async def internal_server_exception_handler(exc: Exception): +async def internal_server_exception_handler(request: Request, exc: Exception): + from quick_pp.app.backend.utils.auth import is_demo_mode + + msg = return_exception_message(exc) + if is_demo_mode(): + return JSONResponse( + status_code=500, + content={"message": msg, "detail": msg}, + ) return JSONResponse( status_code=500, - content={"message": return_exception_message(exc), "detail": f"{repr(exc)}"}, + content={"message": msg, "detail": f"{repr(exc)}"}, ) -if FastApiMCP is not None: +if FastApiMCP is not None and not _initial_demo_mode: try: mcp = FastApiMCP( app, diff --git a/quick_pp/app/backend/router.py b/quick_pp/app/backend/router.py index e3140658..37c88502 100644 --- a/quick_pp/app/backend/router.py +++ b/quick_pp/app/backend/router.py @@ -5,6 +5,7 @@ from .services.auth import router as auth_router from .services.chat import router as chat_router from .services.database import router as database_router +from .services.demo_guard import router as demo_router from .services.fpt import router as fpt_router from .services.las_handler import import_logs_router from .services.las_handler import router as las_router @@ -27,6 +28,7 @@ api_router = APIRouter(prefix="/quick_pp") api_router.include_router(auth_router) +api_router.include_router(demo_router) api_router.include_router(las_router) api_router.include_router(import_logs_router) api_router.include_router(lithology_router) diff --git a/quick_pp/app/backend/schemas/fluid_density.py b/quick_pp/app/backend/schemas/fluid_density.py index e3d736be..9a1f5e69 100644 --- a/quick_pp/app/backend/schemas/fluid_density.py +++ b/quick_pp/app/backend/schemas/fluid_density.py @@ -23,6 +23,10 @@ class FluidDensityConfig(BaseModel): static_rho_fl: float = Field( default=1.0, ge=0.1, le=1.35, description="Static fluid density (g/cc)." ) + use_hole_sections: bool = Field( + default=True, + description="Use per-interval mud type, salinity, and Rmf from Hole Sections table when available (False = manual override).", + ) mud_type: Literal["WBM", "OBM", "SBM"] = Field( default="WBM", description="Mud system driving the filtrate density." ) diff --git a/quick_pp/app/backend/schemas/report.py b/quick_pp/app/backend/schemas/report.py index 44386af0..f0d2c824 100644 --- a/quick_pp/app/backend/schemas/report.py +++ b/quick_pp/app/backend/schemas/report.py @@ -70,7 +70,13 @@ "include_ai_commentary": True, }, { - "section_id": "10_appendix_cpi", + "section_id": "10_gate_checks", + "title": "10. Petrophysical QA/QC Gate-Check & Peer-Review Audit Log", + "enabled": True, + "include_ai_commentary": False, + }, + { + "section_id": "11_appendix_cpi", "title": "Appendix A: Composite Petrophysical Evaluation Logs (CPI)", "enabled": True, "include_ai_commentary": False, diff --git a/quick_pp/app/backend/schemas/saturation_rw_depth.py b/quick_pp/app/backend/schemas/saturation_rw_depth.py new file mode 100644 index 00000000..34e864f8 --- /dev/null +++ b/quick_pp/app/backend/schemas/saturation_rw_depth.py @@ -0,0 +1,17 @@ +from typing import List + +from pydantic import BaseModel, Field + + +class Data(BaseModel): + """Depth sample for Rw estimation.""" + tvd: float = Field(..., description="True vertical depth (m)") + + +class InputData(BaseModel): + """Rw-at-depth input: salinity, geothermal model and a list of depths.""" + water_salinity: float = Field(35000, description="Water salinity (ppm NaCl)") + surface_temp: float = Field(25.0, description="Surface temperature (degC metric, degF imperial)") + gradient: float = Field(30.0, description="Geothermal gradient (degC/km metric, degF/1000ft imperial)") + meas_system: str = Field('metric', description="Measurement system: 'metric' or 'imperial'") + data: List[Data] = Field([Data(tvd=1500.0), Data(tvd=2000.0)], description="Depths (m)") diff --git a/quick_pp/app/backend/services/ancillary.py b/quick_pp/app/backend/services/ancillary.py index ed29695e..7137504c 100644 --- a/quick_pp/app/backend/services/ancillary.py +++ b/quick_pp/app/backend/services/ancillary.py @@ -155,8 +155,21 @@ "temp_degf", ], "TEST_TYPE": ["test_type", "tool", "type", "rpt", "mdt", "rdt", "sft"], - "TVDSS": ["tvdss", "tvd_ss", "depth_tvdss", "tvdss_m", "tvdss_ft", "subsea_depth"], - "FLUID_TYPE": ["fluid_type", "fluid", "phase", "fluid_phase", "interpreted_fluid"], + "TVDSS": [ + "tvdss", + "tvd_ss", + "depth_tvdss", + "tvdss_m", + "tvdss_ft", + "subsea_depth", + ], + "FLUID_TYPE": [ + "fluid_type", + "fluid", + "phase", + "fluid_phase", + "interpreted_fluid", + ], "TEST_QUALITY": [ "test_quality", "quality", @@ -249,6 +262,98 @@ "type", ], }, + "hole_sections": { + "WELL_NAME": ["well", "well_name", "wellname", "uwi", "wellbore", "well_id"], + "SECTION_NAME": [ + "name", + "section", + "section_name", + "hole_section", + "casing", + "casing_section", + "run", + "interval", + ], + "TOP": [ + "top", + "top_md", + "depth_top", + "top_depth", + "md_top", + "from", + "start_depth", + "start", + "top_m", + "top_ft", + ], + "BOTTOM": [ + "bottom", + "base", + "bot", + "bottom_md", + "base_md", + "depth_bottom", + "depth_base", + "bottom_depth", + "base_depth", + "md_bottom", + "to", + "end_depth", + "end", + "bottom_m", + "bottom_ft", + "td", + "shoe_depth", + ], + "BIT_SIZE": [ + "bit_size", + "bitsize", + "bs", + "bit_size_in", + "hole_size", + "diameter", + "bit_diam", + "bit", + ], + "MUD_TYPE": [ + "mud_type", + "mud", + "mud_system", + "fluid_system", + "drilling_fluid", + "type", + ], + "MUD_WEIGHT": [ + "mud_weight", + "mw", + "mud_density", + "mud_weight_ppg", + "mud_wt", + "density_mud", + "rho_mud", + ], + "MUD_SALINITY": [ + "mud_salinity", + "salinity", + "salinity_ppm", + "mud_filtrate_salinity", + "nacl_ppm", + "chlorides", + ], + "RMF": [ + "rmf", + "r_mf", + "mud_filtrate_resistivity", + "filtrate_resistivity", + ], + "RMF_TEMP": [ + "rmf_temp", + "rmf_temp_c", + "rmf_temperature", + "meas_temp", + "temp_rmf", + ], + }, "rca": { "WELL_NAME": ["well", "well_name", "wellname", "uwi", "wellbore", "well_id"], "SAMPLE_NAME": [ @@ -919,6 +1024,25 @@ def compute_survey_minimum_curvature( return df +def interpolate_tvd_on_md( + md_grid: np.ndarray, + traj_df: pd.DataFrame, +) -> np.ndarray: + """Interpolate TVD onto an MD grid from a ``compute_survey_minimum_curvature`` result. + + Thin wrapper over :func:`quick_pp.utils.interpolate_tvd_on_md`, which holds the + shared surface tie-in / linear / extrapolate-below-last-station rules. + """ + from quick_pp.utils import interpolate_tvd_on_md as _interp + + return _interp( + md_grid, + traj_df["md"].to_numpy(dtype=np.float64), + traj_df["tvd"].to_numpy(dtype=np.float64), + traj_df["inc"].to_numpy(dtype=np.float64), + ) + + def _apply_survey_minimum_curvature_to_well( well: Any, surveys: List[Dict[str, float]], @@ -954,18 +1078,12 @@ def _apply_survey_minimum_curvature_to_well( mds = traj_df["md"].to_numpy(dtype=np.float64) tvds = traj_df["tvd"].to_numpy(dtype=np.float64) - # Prepend 0,0 for interpolation from surface - if mds[0] > 0: - mds_interp = np.insert(mds, 0, 0.0) - tvds_interp = np.insert(tvds, 0, 0.0) - else: - mds_interp, tvds_interp = mds, tvds - if len(well_depth) > 0: - valid_mask = (well_depth >= mds_interp.min()) & (well_depth <= mds_interp.max()) - target_depths = well_depth[valid_mask] + # Keep every finite log depth at or above 0; depths below the last station + # are extrapolated (see interpolate_tvd_on_md). + target_depths = well_depth[np.isfinite(well_depth) & (well_depth >= 0.0)] if len(target_depths) > 0: - interp_tvd = np.interp(target_depths, mds_interp, tvds_interp) + interp_tvd = interpolate_tvd_on_md(target_depths, traj_df) interp_tvdss = interp_tvd - df_elev tvd_dict = dict( zip(target_depths.tolist(), interp_tvd.tolist(), strict=False) @@ -1372,9 +1490,13 @@ def delete_fluid_contacts_project( wells = [proj.get_well(wn) for wn in proj.get_well_names()] for well in wells: - query = session.query(db_objects.ORMFluidContact).filter_by(well_id=well.well_id) + query = session.query(db_objects.ORMFluidContact).filter_by( + well_id=well.well_id + ) if zone: - query = query.filter(db_objects.ORMFluidContact.zone == str(zone).strip()) + query = query.filter( + db_objects.ORMFluidContact.zone == str(zone).strip() + ) if auto_only: auto_conditions = [ @@ -1383,13 +1505,19 @@ def delete_fluid_contacts_project( db_objects.ORMFluidContact.source.ilike("%Optimizer%"), db_objects.ORMFluidContact.source.ilike("%FPT%"), db_objects.ORMFluidContact.source.ilike("%Auto%"), - db_objects.ORMFluidContact.name.in_(["GUT", "GDT", "OUT", "ODT", "WUT"]), + db_objects.ORMFluidContact.name.in_( + ["GUT", "GDT", "OUT", "ODT", "WUT"] + ), db_objects.ORMFluidContact.remarks.ilike("%Proved Gas%"), db_objects.ORMFluidContact.remarks.ilike("%Proved Oil%"), db_objects.ORMFluidContact.remarks.ilike("%Proved Water%"), db_objects.ORMFluidContact.remarks.ilike("%bracketed%"), - db_objects.ORMFluidContact.remarks.ilike("%Optimized Free Water Level%"), - db_objects.ORMFluidContact.remarks.ilike("%Formation Pressure Test%"), + db_objects.ORMFluidContact.remarks.ilike( + "%Optimized Free Water Level%" + ), + db_objects.ORMFluidContact.remarks.ilike( + "%Formation Pressure Test%" + ), ] query = query.filter(or_(*auto_conditions)) @@ -2230,7 +2358,11 @@ def add_perforations_project( status_code=400, detail="Payload must be a dict with key 'perforations' (or 'perfs').", ) - perfs = payload.get("perforations") if "perforations" in payload else payload.get("perfs") + perfs = ( + payload.get("perforations") + if "perforations" in payload + else payload.get("perfs") + ) perfs = perfs or [] replace_mode = bool(payload.get("replace", False)) target_well = well_name or payload.get("well_name") @@ -2297,6 +2429,173 @@ def delete_perforation_project( ) from e +# ============================================================================== +# Hole Sections (Mud Program) Endpoints +# ============================================================================== + + +@router.get( + "/hole_sections", + summary="List wellbore hole sections for a project (optional well_name)", + tags=["Hole Sections"], +) +@router.get( + "/wells/{well_name}/hole_sections", + include_in_schema=False, +) +def list_hole_sections_project(project_id: int, well_name: Optional[str] = None): + from quick_pp.app.backend.services.workspace import _ephemeral_well_configs + from quick_pp.app.backend.utils.auth import is_demo_mode + + def _clean_records(df: pd.DataFrame) -> List[Dict[str, Any]]: + if df is None or df.empty: + return [] + return [ + { + k: (None if isinstance(v, float) and not np.isfinite(v) else v) + for k, v in rec.items() + } + for rec in df.to_dict(orient="records") + ] + + try: + with get_db() as session: + proj = db_objects.Project.load(session, project_id=project_id) + if well_name: + if is_demo_mode(): + eph = _ephemeral_well_configs.get((project_id, well_name)) + if isinstance(eph, dict) and "hole_sections" in eph: + return {"hole_sections": list(eph["hole_sections"])} + well = proj.get_well(well_name) + df = well.get_hole_sections() + return {"hole_sections": _clean_records(df)} + all_rows = [] + for wn in proj.get_well_names(): + try: + if is_demo_mode(): + eph = _ephemeral_well_configs.get((project_id, wn)) + if isinstance(eph, dict) and "hole_sections" in eph: + for r in eph["hole_sections"]: + all_rows.append({**r, "well_name": wn}) + continue + well = proj.get_well(wn) + df = well.get_hole_sections() + for r in _clean_records(df): + r["well_name"] = wn + all_rows.append(r) + except Exception: + continue + return {"hole_sections": all_rows} + except ValueError as e: + raise HTTPException(status_code=404, detail=str(e)) from e + except Exception as e: + raise HTTPException( + status_code=500, detail=f"Failed to list hole sections: {e}" + ) from e + + +@router.post( + "/hole_sections", + summary="Add or update wellbore hole sections for a project (requires well_name)", + tags=["Hole Sections"], +) +@router.post( + "/wells/{well_name}/hole_sections", + include_in_schema=False, +) +def add_hole_sections_project( + project_id: int, + well_name: Optional[str] = None, + payload: Dict[str, Any] = Body(...), +): + from quick_pp.app.backend.services.workspace import _ephemeral_well_configs + from quick_pp.app.backend.utils.auth import is_demo_mode + + if not isinstance(payload, dict) or ( + "hole_sections" not in payload and "sections" not in payload + ): + raise HTTPException( + status_code=400, + detail="Payload must be a dict with key 'hole_sections' (or 'sections').", + ) + sections = ( + payload.get("hole_sections") + if "hole_sections" in payload + else payload.get("sections") + ) or [] + replace_mode = bool(payload.get("replace", False)) + target_well = well_name or payload.get("well_name") + if not target_well: + raise HTTPException( + status_code=400, + detail="well_name must be provided as query parameter or in payload", + ) + try: + if is_demo_mode(): + key = (project_id, str(target_well)) + eph = dict(_ephemeral_well_configs.get(key) or {}) + prev = [] if replace_mode else list(eph.get("hole_sections") or []) + merged = prev + list(sections) + eph["hole_sections"] = merged + _ephemeral_well_configs[key] = eph + return {"created": sections} + with get_db() as session: + proj = db_objects.Project.load(session, project_id=project_id) + well = proj.get_well(target_well) + well.add_hole_sections(sections, replace=replace_mode) + invalidate_well_cache(project_id=project_id, well_name=str(target_well)) + return {"created": sections} + except ValueError as e: + raise HTTPException(status_code=404, detail=str(e)) from e + except Exception as e: + raise HTTPException( + status_code=500, detail=f"Failed to add hole sections: {e}" + ) from e + + +@router.delete( + "/hole_sections/{section_name}", + summary="Delete a hole section by name (requires well_name)", + tags=["Hole Sections"], +) +@router.delete( + "/wells/{well_name}/hole_sections/{section_name}", + include_in_schema=False, +) +def delete_hole_section_project( + project_id: int, section_name: str, well_name: Optional[str] = None +): + target_well = well_name + if not target_well: + raise HTTPException( + status_code=400, + detail="well_name query parameter is required to delete a hole section", + ) + try: + with get_db() as session: + proj = db_objects.Project.load(session, project_id=project_id) + well = proj.get_well(target_well) + orm_secs = list( + session.scalars( + select(db_objects.ORMHoleSection).filter_by( + well_id=well.well_id, name=section_name + ) + ).all() + ) + if not orm_secs: + raise ValueError(f"Hole section '{section_name}' not found") + for s in orm_secs: + session.delete(s) + invalidate_well_cache(project_id=project_id, well_name=str(target_well)) + return {"deleted": section_name} + except ValueError as e: + raise HTTPException(status_code=404, detail=str(e)) from e + except Exception as e: + raise HTTPException( + status_code=500, detail=f"Failed to delete hole section: {e}" + ) from e + + # ============================================================================== # Phase 2 & 3: Unified Interactive Ancillary Preview & Commit Endpoints # ============================================================================== @@ -2382,7 +2681,15 @@ def _convert_ancillary_numeric( u = (source_unit or "").strip().lower() t = target_col.upper() - if t in ("MD", "TVD", "DEPTH", "DEPTH_TOP", "DEPTH_BASE", "TOP", "BOTTOM") and u in ("ft", "feet"): + if t in ( + "MD", + "TVD", + "DEPTH", + "DEPTH_TOP", + "DEPTH_BASE", + "TOP", + "BOTTOM", + ) and u in ("ft", "feet"): return num * 0.3048 if t in ("CPORE", "SW", "CSAT_WATER", "CSAT_OIL"): if u in ("%", "pct", "percent") or (not u and num > 1.0 and num <= 100.0): @@ -2400,11 +2707,20 @@ def _convert_ancillary_numeric( return num * 0.145038 if u in ("mpa",): return num * 145.038 - if t == "TEMPERATURE": + if t in ("TEMPERATURE", "RMF_TEMP"): if u in ("degf", "f", "°f", "deg f", "fahrenheit"): return (num - 32.0) * 5.0 / 9.0 if u in ("k", "kelvin"): return num - 273.15 + if t == "BIT_SIZE" and u in ("mm", "millimeter", "millimetre"): + return num / 25.4 + if t == "MUD_WEIGHT": + if u in ("g/cc", "g/cm3", "g/cm^3", "sg", "s.g.") or (not u and 0 < num <= 3.0): + return num * 8.3454 + if u in ("kg/m3", "kg/m^3") or (not u and num > 500): + return (num / 1000.0) * 8.3454 + if t == "MUD_SALINITY" and u in ("kppm", "g/l", "kg/m3"): + return num * 1000.0 return num @@ -2470,8 +2786,8 @@ def commit_ancillary_data( effective_project_id = project_id if project_id is not None else request.project_id dtype = request.data_type.lower() import_mode = getattr(request, "import_mode", "merge") or "merge" - should_replace = (import_mode == "replace") - should_append = (import_mode != "replace") + should_replace = import_mode == "replace" + should_append = import_mode != "replace" # Build lookup from target_column -> (source_column, source_unit) col_map: Dict[str, Tuple[str, Optional[str]]] = {} @@ -2637,7 +2953,9 @@ def commit_ancillary_data( qual_col, _ = col_map.get("TEST_QUALITY", (None, None)) zone_col, _ = col_map.get("ZONE", (None, None)) - def _opt_str(row: Dict[str, Any], col: Optional[str]) -> Optional[str]: + def _opt_str( + row: Dict[str, Any], col: Optional[str] + ) -> Optional[str]: if not col: return None v = row.get(col) @@ -2706,17 +3024,30 @@ def _opt_str(row: Dict[str, Any], col: Optional[str]) -> Optional[str]: c_type = str(r.get(c_col, "")).strip().upper() d_v = _convert_ancillary_numeric(r.get(d_col), d_unit, "DEPTH") if c_type and d_v is not None: - contacts_payload.append({ - "name": str(r.get("name") or c_type).strip(), - "contact_type": c_type, - "depth": d_v, - "zone": str(r.get(z_col, "")).strip() or None if z_col in r else None, - "fault_block": str(r.get(fb_col, "")).strip() or None if fb_col in r else None, - "source": str(r.get(src_col, "")).strip() or None if src_col in r else None, - "remarks": str(r.get(rem_col, "")).strip() or None if rem_col in r else None, - }) + contacts_payload.append( + { + "name": str(r.get("name") or c_type).strip(), + "contact_type": c_type, + "depth": d_v, + "zone": str(r.get(z_col, "")).strip() or None + if z_col in r + else None, + "fault_block": str(r.get(fb_col, "")).strip() + or None + if fb_col in r + else None, + "source": str(r.get(src_col, "")).strip() or None + if src_col in r + else None, + "remarks": str(r.get(rem_col, "")).strip() or None + if rem_col in r + else None, + } + ) if contacts_payload: - well.add_fluid_contacts(contacts_payload, replace=should_replace) + well.add_fluid_contacts( + contacts_payload, replace=should_replace + ) summary_by_well[wn] = len(contacts_payload) elif dtype in ("perforations", "perfs"): @@ -2726,8 +3057,12 @@ def _opt_str(row: Dict[str, Any], col: Optional[str]) -> Optional[str]: desc_col, _ = col_map.get("DESCRIPTION", ("description", None)) perfs_payload = [] for idx, r in enumerate(w_rows): - top_v = _convert_ancillary_numeric(r.get(top_col), top_unit, "TOP") - bot_v = _convert_ancillary_numeric(r.get(bot_col), bot_unit, "BOTTOM") + top_v = _convert_ancillary_numeric( + r.get(top_col), top_unit, "TOP" + ) + bot_v = _convert_ancillary_numeric( + r.get(bot_col), bot_unit, "BOTTOM" + ) if top_v is None and bot_v is None: continue if top_v is None: @@ -2762,6 +3097,99 @@ def _opt_str(row: Dict[str, Any], col: Optional[str]) -> Optional[str]: well.add_perforations(perfs_payload, replace=should_replace) summary_by_well[wn] = len(perfs_payload) + elif dtype in ("hole_sections", "mud_program"): + name_col, _ = col_map.get("SECTION_NAME", ("name", None)) + top_col, top_unit = col_map.get("TOP", ("top", None)) + bot_col, bot_unit = col_map.get("BOTTOM", ("bottom", None)) + bs_col, bs_unit = col_map.get("BIT_SIZE", ("bit_size", None)) + mt_col, _ = col_map.get("MUD_TYPE", ("mud_type", None)) + mw_col, mw_unit = col_map.get("MUD_WEIGHT", ("mud_weight", None)) + sal_col, sal_unit = col_map.get( + "MUD_SALINITY", ("mud_salinity", None) + ) + rmf_col, rmf_unit = col_map.get("RMF", ("rmf", None)) + rmft_col, rmft_unit = col_map.get("RMF_TEMP", ("rmf_temp", None)) + secs_payload = [] + for idx, r in enumerate(w_rows): + top_v = _convert_ancillary_numeric( + r.get(top_col), top_unit, "TOP" + ) + bot_v = _convert_ancillary_numeric( + r.get(bot_col), bot_unit, "BOTTOM" + ) + if top_v is None and bot_v is None: + continue + if top_v is None: + top_v = bot_v + if bot_v is None: + bot_v = top_v + if bot_v < top_v: + top_v, bot_v = bot_v, top_v + bs_v = ( + _convert_ancillary_numeric( + r.get(bs_col), bs_unit, "BIT_SIZE" + ) + if bs_col + else None + ) + s_name = ( + str(r.get(name_col, "")).strip() + if name_col and r.get(name_col) is not None + else "" + ) + if not s_name or s_name.lower() in ("nan", "none"): + s_name = ( + f'{bs_v:g}" Section' + if bs_v and bs_v > 0 + else f"Section-{idx + 1}" + ) + mt_raw = ( + str(r.get(mt_col, "WBM")).strip().upper() + if mt_col and r.get(mt_col) is not None + else "WBM" + ) + mt_v = ( + "OBM" + if mt_raw in ("OBM", "OIL", "OIL-BASED", "OIL_BASED") + else ( + "SBM" + if mt_raw in ("SBM", "SYNTHETIC", "SOBM") + else "WBM" + ) + ) + secs_payload.append( + { + "name": s_name, + "top": top_v, + "bottom": bot_v, + "bit_size": bs_v, + "mud_type": mt_v, + "mud_weight": _convert_ancillary_numeric( + r.get(mw_col), mw_unit, "MUD_WEIGHT" + ) + if mw_col + else None, + "mud_salinity": _convert_ancillary_numeric( + r.get(sal_col), sal_unit, "MUD_SALINITY" + ) + if sal_col + else None, + "rmf": _convert_ancillary_numeric( + r.get(rmf_col), rmf_unit, "RMF" + ) + if rmf_col + else None, + "rmf_temp": _convert_ancillary_numeric( + r.get(rmft_col), rmft_unit, "RMF_TEMP" + ) + if rmft_col + else None, + } + ) + if secs_payload: + well.add_hole_sections(secs_payload, replace=should_replace) + summary_by_well[wn] = len(secs_payload) + elif dtype == "rca": s_col, _ = col_map.get("SAMPLE_NAME", (None, None)) d_col, d_unit = col_map.get("DEPTH", ("depth", None)) @@ -3016,20 +3444,24 @@ def _opt_str(row: Dict[str, Any], col: Optional[str]) -> Optional[str]: if not s_name or s_name.lower() in ("nan", "none"): s_name = f"SCAL-{idx + 1}" por_v = ( - _convert_ancillary_numeric(r.get(por_col), por_unit, "CPORE") + _convert_ancillary_numeric( + r.get(por_col), por_unit, "CPORE" + ) if por_col else None ) perm_v = ( - _convert_ancillary_numeric(r.get(perm_col), perm_unit, "CPERM") + _convert_ancillary_numeric( + r.get(perm_col), perm_unit, "CPERM" + ) if perm_col else None ) exp_val = ( - str(r.get(exp_col, "micp")).strip() + str(r.get(exp_col, "porous_plate")).strip() if exp_col and r.get(exp_col) is not None - else "micp" - ) or "micp" + else "porous_plate" + ) or "porous_plate" cyc_val = ( str(r.get(cyc_col, "drainage")).strip() if cyc_col and r.get(cyc_col) is not None diff --git a/quick_pp/app/backend/services/chat.py b/quick_pp/app/backend/services/chat.py index 037333f3..56a0251d 100644 --- a/quick_pp/app/backend/services/chat.py +++ b/quick_pp/app/backend/services/chat.py @@ -243,19 +243,46 @@ def _plan_native_tool_calls(req: AgentChatRequest) -> List[Dict[str, Any]]: has_theory_kw = any( kw in q for kw in ( - "equation", "formula", "governing equation", "cite formula", - "how do you calculate", "how is", "mathematical model", - "ssot reference", "technical reference", "workflow reference", - "cutoffs definition", "parameter bounds", "theoretical foundation" + "equation", + "formula", + "governing equation", + "cite formula", + "how do you calculate", + "how is", + "mathematical model", + "ssot reference", + "technical reference", + "workflow reference", + "cutoffs definition", + "parameter bounds", + "theoretical foundation", ) ) has_petro_topic = any( topic in q for topic in ( - "qaqc", "badhole", "washout", "multimineral", "multi-mineral", "lithology", - "porosity", "shf", "leverett", "j-function", "capillary", "conformal", - "uncertainty", "archie", "simandoux", "permeability", "fzi", "vshale", - "clay", "fwl", "fluid contact", "water saturation" + "qaqc", + "badhole", + "washout", + "multimineral", + "multi-mineral", + "lithology", + "porosity", + "shf", + "leverett", + "j-function", + "capillary", + "conformal", + "uncertainty", + "archie", + "simandoux", + "permeability", + "fzi", + "vshale", + "clay", + "fwl", + "fluid contact", + "water saturation", ) ) wants_theory = has_theory_kw and has_petro_topic @@ -615,7 +642,6 @@ def _plan_native_tool_calls(req: AgentChatRequest) -> List[Dict[str, Any]]: return calls - def _handle_unrecognized_native_prompt( req: AgentChatRequest, ) -> tuple[str, List[Dict[str, str]]]: @@ -627,9 +653,24 @@ def _handle_unrecognized_native_prompt( is_regional_or_literature = any( term in q.lower() for term in ( - "sandstone", "formation", "group", "basin", "field", "balmoral", "brent", - "statfjord", "forties", "ekofisk", "clifton", "average porosity", "typical", - "analogue", "analog", "literature", "benchmark", "regional" + "sandstone", + "formation", + "group", + "basin", + "field", + "balmoral", + "brent", + "statfjord", + "forties", + "ekofisk", + "clifton", + "average porosity", + "typical", + "analogue", + "analog", + "literature", + "benchmark", + "regional", ) ) @@ -655,8 +696,7 @@ def _handle_unrecognized_native_prompt( ) actions_md = "\n".join( - f"- ⚡ **{act['label']}**: {act['description']}" - for act in PRESET_QUICK_ACTIONS + f"- ⚡ **{act['label']}**: {act['description']}" for act in PRESET_QUICK_ACTIONS ) reply = ( @@ -689,23 +729,30 @@ def _synthesize_petrophysical_explanation( for rec in tool_records ) no_core = any( - rec.get("name") == "inspect_well" and (rec.get("result") or {}).get("core_sample_count", 0) == 0 + rec.get("name") == "inspect_well" + and (rec.get("result") or {}).get("core_sample_count", 0) == 0 for rec in tool_records ) if has_washout or no_core: reasons: List[str] = [] if has_washout: - reasons.append("washout intervals detected where density/neutron log measurements are degraded by pad standoff") + reasons.append( + "washout intervals detected where density/neutron log measurements are degraded by pad standoff" + ) if no_core: - reasons.append("lack of routine core calibration points (CPORE/CPERM) to anchor porosity and permeability transforms") + reasons.append( + "lack of routine core calibration points (CPORE/CPERM) to anchor porosity and permeability transforms" + ) confidence_badge = ( f"> ⚠️ **Answer Confidence: Medium** — Quantitative results computed from active well logs, but note: " f"{'; '.join(reasons)}.\n" ) sections.append(confidence_badge) else: - sections.append("> ✅ **Answer Confidence: High** — Grounded directly in quantitative MCP tool execution on active well logs.\n") + sections.append( + "> ✅ **Answer Confidence: High** — Grounded directly in quantitative MCP tool execution on active well logs.\n" + ) for rec in tool_records: t_name = rec["name"] @@ -888,8 +935,7 @@ def _synthesize_petrophysical_explanation( ref_md = res.get("reference_content", "") src = res.get("source", "docs/workflows/") sections.append( - f"### 📖 Grounded Petrophysical Foundation (`{src}`)\n\n" - f"{ref_md}\n" + f"### 📖 Grounded Petrophysical Foundation (`{src}`)\n\n{ref_md}\n" ) # Synthesize comprehensive Gaps & Uncertainty Analysis section across all executed tools @@ -907,7 +953,9 @@ def _synthesize_petrophysical_explanation( "Porosity, permeability, and saturation height models rely on uncalibrated empirical log transforms." ) curves = set(res.get("available_curves", [])) - missing_essential = [c for c in ("RHOB", "NPHI", "GR", "RT", "CALI") if c not in curves] + missing_essential = [ + c for c in ("RHOB", "NPHI", "GR", "RT", "CALI") if c not in curves + ] if missing_essential: gaps.append( f"**Missing Essential Curves**: Curves {', '.join(f'`{c}`' for c in missing_essential)} " @@ -932,13 +980,16 @@ def _synthesize_petrophysical_explanation( iw = res.get("interval_width_summary") or {} if iw: uncerts.append( - f"**Conformal P10–P90 Interval Spreads**: Porosity uncertainty is `±{round(iw.get('phit_mean_width_vv', 0)/2, 4)} v/v`, " - f"Sw uncertainty is `±{round(iw.get('sw_mean_width_vv', 0)/2, 4)} v/v`, and Permeability spread is " + f"**Conformal P10–P90 Interval Spreads**: Porosity uncertainty is `±{round(iw.get('phit_mean_width_vv', 0) / 2, 4)} v/v`, " + f"Sw uncertainty is `±{round(iw.get('sw_mean_width_vv', 0) / 2, 4)} v/v`, and Permeability spread is " f"`{iw.get('perm_median_p90_p10_factor')}×` between P10 and P90." ) z_conf = res.get("zonal_conformal_summary") or [] if z_conf: - cert_pay = [f"{z['zone']} ({round(z['certifiable_pay_fraction']*100, 1)}% P10 vs {round(z['upside_pay_fraction']*100, 1)}% P90)" for z in z_conf[:3]] + cert_pay = [ + f"{z['zone']} ({round(z['certifiable_pay_fraction'] * 100, 1)}% P10 vs {round(z['upside_pay_fraction'] * 100, 1)}% P90)" + for z in z_conf[:3] + ] uncerts.append( f"**Pay Confidence Disparity**: Certifiable pay (P10) vs upside pay (P90): {', '.join(cert_pay)}." ) @@ -992,19 +1043,21 @@ def _run_openai_compatible_agent( context_summary: str, ) -> tuple[str, List[Dict[str, Any]]]: """Run petrophysical MCP synthesis and tool-calling against OpenRouter or Local Ollama (`/v1/chat/completions`).""" + from quick_pp.app.backend.services.demo_guard import validate_external_llm_target + provider = req.provider.lower() + base_url, api_key = validate_external_llm_target( + provider=provider, + caller_base_url=req.base_url, + caller_api_key=req.api_key, + env_openrouter_url=_get_env_key( + "OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1" + ), + env_openrouter_key=_get_env_key("OPENROUTER_API_KEY", ""), + ) if provider == "ollama": - base_url = ( - req.base_url or os.getenv("OLLAMA_BASE_URL", "http://localhost:11434/v1") - ).rstrip("/") - api_key = req.api_key or "ollama" model = req.model or "qwen2.5:7b" else: - base_url = ( - req.base_url - or _get_env_key("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1") - ).rstrip("/") - api_key = (req.api_key or "").strip() or _get_env_key("OPENROUTER_API_KEY", "") model = req.model or "deepseek/deepseek-chat" if not api_key: raise ValueError( @@ -1049,7 +1102,9 @@ def _run_openai_compatible_agent( from quick_pp.app.backend.services.ssot_reference import get_step_reference - step_grounding = get_step_reference(req.scope or "single-well", req.step or "overview") + step_grounding = get_step_reference( + req.scope or "single-well", req.step or "overview" + ) messages: List[Dict[str, Any]] = [ { @@ -1151,8 +1206,13 @@ def _run_openai_compatible_agent( ) async def list_assistant_providers(): """Return available agent providers, models, and MCP tool definitions for the Svelte UI drawer.""" + from quick_pp.app.backend.utils.auth import is_demo_mode + + demo = is_demo_mode() providers_out = [] for p in PROVIDERS_CATALOG: + if demo and p.get("id") == "ollama": + continue env_k = p.get("env_key") has_env_key = bool(_get_env_key(env_k)) if env_k else True providers_out.append({**p, "server_key_configured": has_env_key}) @@ -1219,6 +1279,8 @@ async def assistant_chat(req: AgentChatRequest): reply_text = _synthesize_petrophysical_explanation( req.message, executed_tools ) + except HTTPException: + raise except Exception as exc: logger.warning( f"External provider '{provider}' failed ({exc}); falling back to native_mcp agent." diff --git a/quick_pp/app/backend/services/database.py b/quick_pp/app/backend/services/database.py index 4beac85a..c89edc19 100644 --- a/quick_pp/app/backend/services/database.py +++ b/quick_pp/app/backend/services/database.py @@ -35,6 +35,7 @@ from quick_pp.config import Config from quick_pp.database import models as db_models from quick_pp.database import objects as db_objects +from quick_pp.utils import interpolate_tvd_on_md, survey_tvd_stations logger = logging.getLogger(__name__) @@ -50,7 +51,11 @@ def __init__( media_type: Optional[str] = None, background: Any = None, ) -> None: - raw_bytes = content.getvalue() if isinstance(content, io.BytesIO) else bytes(content or b"") + raw_bytes = ( + content.getvalue() + if isinstance(content, io.BytesIO) + else bytes(content or b"") + ) super().__init__( content=raw_bytes, status_code=status_code, @@ -67,7 +72,7 @@ def __init__( # Maps key "{project_id}_{well_name}_{tolerance}" -> (timestamp, pd.DataFrame) _merged_data_cache: Dict[str, tuple[float, pd.DataFrame]] = {} _cache_ttl = 1800 # 30 minutes -_cache_max_entries = 50 +_cache_max_entries = 12 if os.environ.get("QPP_DEMO_MODE", "").lower() in ("1", "true", "yes") else 50 _merge_locks: Dict[str, threading.Lock] = {} _merge_locks_guard = threading.Lock() MAX_DEMO_UPLOAD_BYTES = 5 * 1024 * 1024 # 5 MB cap per file in demo mode @@ -116,6 +121,15 @@ def _safe_cache_token(val: Any) -> str: def write_shared_well_cache(project_id: int, well_name: str, df: pd.DataFrame) -> None: """Persist an updated in-memory merged well DataFrame to shared temp storage so all worker processes see it.""" + if is_demo_mode(): + # Demo container runs a single Uvicorn worker (--workers 1); skip /tmp pickle disk writes + try: + from quick_pp.app.backend.services.demo_guard import mark_demo_state_dirty + + mark_demo_state_dirty() + except Exception: + pass + return try: _SHARED_CACHE_DIR.mkdir(parents=True, exist_ok=True) w_tok = _safe_cache_token(well_name) @@ -189,6 +203,15 @@ async def create_project(payload: dict, request: Request): if not name: raise HTTPException(status_code=400, detail="Project name is required") + if is_demo_mode(): + raise HTTPException( + status_code=403, + detail=( + "Creating new database projects is disabled in the read-only live demo. " + "Select one of the pre-seeded showcase projects to import or evaluate logs." + ), + ) + description = payload.get("description") if isinstance(payload, dict) else "" current_user = get_current_user_optional(request) created_by = ( @@ -224,7 +247,9 @@ async def create_project(payload: dict, request: Request): @router.get("/projects", summary="List projects") -async def list_projects(request: Request): +async def list_projects(request: Request, response: Response = None): + if response is not None: + response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate" try: with get_db() as session: stmt = select(db_models.Project) @@ -294,6 +319,12 @@ async def update_project(project_id: int, payload: dict, request: Request): if not isinstance(payload, dict): raise HTTPException(status_code=400, detail="Invalid payload") + if is_demo_mode(): + raise HTTPException( + status_code=403, + detail="Renaming pre-seeded showcase projects is disabled in the shared live demo.", + ) + new_name = (payload.get("name") or "").strip() new_desc = payload.get("description") if not new_name and new_desc is None: @@ -366,6 +397,11 @@ async def update_project(project_id: int, payload: dict, request: Request): @router.delete("/projects/{project_id}", summary="Delete a project and all its wells") def delete_project(project_id: int, request: Request): """Delete a project and all associated wells, curves, and cache entries.""" + if is_demo_mode(): + raise HTTPException( + status_code=403, + detail="Deleting pre-seeded showcase projects is disabled in the shared live demo.", + ) try: with get_db() as session: orm_proj = session.get(db_models.Project, project_id) @@ -474,6 +510,15 @@ async def rename_well(project_id: int, well_name: str, payload: dict, request: R detail=f"Well '{well_name}' not found in project {project_id}", ) + if is_demo_mode() and target_orm_well is not None: + raise HTTPException( + status_code=403, + detail=( + "Renaming pre-seeded showcase wells is disabled in the shared live demo. " + "Only ephemerally uploaded wells can be renamed." + ), + ) + if any( n.lower() == new_name.lower() and n != well_name for n in active_names ): @@ -570,6 +615,15 @@ def delete_well(project_id: int, well_name: str, request: Request): detail=f"Well '{well_name}' not found in project {project_id}", ) + if is_demo_mode() and target_orm_well is not None: + raise HTTPException( + status_code=403, + detail=( + "Deleting pre-seeded showcase wells is disabled in the shared live demo. " + "Use 'Reset Demo' to restore curve edits." + ), + ) + if in_eph: eph_proj.pop(well_name, None) @@ -580,6 +634,12 @@ def delete_well(project_id: int, well_name: str, request: Request): else: if target_orm_well is not None: wid = target_orm_well.well_id + try: + db_models.HoleSection.__table__.create( + bind=session.get_bind(), checkfirst=True + ) + except Exception: + pass session.expunge_all() for statement in ( "DELETE FROM curve_data WHERE curve_id IN " @@ -594,6 +654,7 @@ def delete_well(project_id: int, well_name: str, request: Request): "DELETE FROM fluid_contacts WHERE well_id = :wid", "DELETE FROM pressure_tests WHERE well_id = :wid", "DELETE FROM perforations WHERE well_id = :wid", + "DELETE FROM hole_sections WHERE well_id = :wid", "DELETE FROM well_surveys WHERE well_id = :wid", "DELETE FROM core_samples WHERE well_id = :wid", "DELETE FROM curves WHERE well_id = :wid", @@ -869,7 +930,9 @@ def get_project_summary(project_id: int) -> Dict[str, Any]: contacts_list_by_well.setdefault(wid, []).append( { "type": str(cname or "OWC").upper(), - "depth": round(float(cdepth), 2) if cdepth is not None else None, + "depth": round(float(cdepth), 2) + if cdepth is not None + else None, } ) @@ -913,7 +976,9 @@ def get_project_summary(project_id: int) -> Dict[str, Any]: { "name": str(pname or "Perf"), "top": round(float(ptop), 2) if ptop is not None else None, - "bottom": round(float(pbot), 2) if pbot is not None else None, + "bottom": round(float(pbot), 2) + if pbot is not None + else None, "description": str(pdesc or ""), } ) @@ -923,6 +988,63 @@ def get_project_summary(project_id: int) -> Dict[str, Any]: except Exception: pass + hole_sec_counts: Dict[int, int] = dict.fromkeys(well_ids, 0) + hole_secs_list_by_well: Dict[int, List[Dict[str, Any]]] = { + wid: [] for wid in well_ids + } + try: + db_models.HoleSection.__table__.create( + bind=session.get_bind(), checkfirst=True + ) + except Exception: + pass + try: + hs_stmt = text( + "SELECT well_id, name, top, bottom, bit_size, mud_type, mud_weight, mud_salinity, rmf, rmf_temp " + "FROM hole_sections WHERE well_id IN :well_ids ORDER BY top, bottom" + ).bindparams(bindparam("well_ids", expanding=True)) + for ( + wid, + sname, + stop, + sbot, + sbs, + smt, + smw, + ssal, + srmf, + srmft, + ) in session.execute(hs_stmt, {"well_ids": well_ids}).fetchall(): + hole_sec_counts[wid] = hole_sec_counts.get(wid, 0) + 1 + hole_secs_list_by_well.setdefault(wid, []).append( + { + "name": str(sname or "Section"), + "top": round(float(stop), 2) if stop is not None else None, + "bottom": round(float(sbot), 2) + if sbot is not None + else None, + "bit_size": round(float(sbs), 3) + if sbs is not None + else None, + "mud_type": str(smt or "WBM").upper(), + "mud_weight": round(float(smw), 3) + if smw is not None + else None, + "mud_salinity": round(float(ssal), 1) + if ssal is not None + else None, + "rmf": round(float(srmf), 4) if srmf is not None else None, + "rmf_temp": round(float(srmft), 2) + if srmft is not None + else None, + } + ) + except Exception: + try: + session.rollback() + except Exception: + pass + from quick_pp.las_handler import ( extract_las_metadata, extract_well_df_elevation, @@ -996,13 +1118,17 @@ def get_project_summary(project_id: int) -> Dict[str, Any]: well_curve_set = set(curves_by_well.get(wid, [])) live_df: Optional[pd.DataFrame] = None cached_entry = _merged_data_cache.get(f"{project_id}_{w.name}_0.16") - if cached_entry is not None and isinstance(cached_entry[1], pd.DataFrame): + if cached_entry is not None and isinstance( + cached_entry[1], pd.DataFrame + ): live_df = cached_entry[1] else: eph_w = _ephemeral_wells.get(project_id, {}).get(w.name) if isinstance(eph_w, pd.DataFrame): live_df = eph_w - elif isinstance(eph_w, dict) and isinstance(eph_w.get("data"), pd.DataFrame): + elif isinstance(eph_w, dict) and isinstance( + eph_w.get("data"), pd.DataFrame + ): live_df = eph_w["data"] if live_df is not None: for col_name in live_df.columns: @@ -1024,7 +1150,9 @@ def get_project_summary(project_id: int) -> Dict[str, Any]: w.config_data if isinstance(w.config_data, dict) else None, target_depth_uom=w.depth_uom or "m", ) - w_meta = dict(extract_las_metadata(w_hdr_src, fallback_well_name=w.name)) + w_meta = dict( + extract_las_metadata(w_hdr_src, fallback_well_name=w.name) + ) w_ovr = ( w_hdr_src.get("header_overrides") if isinstance(w_hdr_src.get("header_overrides"), dict) @@ -1064,14 +1192,12 @@ def get_project_summary(project_id: int) -> Dict[str, Any]: # Compute per-formation depth intervals and curve availability w_tops = tops_list_by_well.get(wid, []) unique_top_depths = sorted( - { - float(t["depth"]) - for t in w_tops - if t.get("depth") is not None - } + {float(t["depth"]) for t in w_tops if t.get("depth") is not None} ) w_cid_map = curve_ids_by_well_mnemonic.get(wid, {}) - zone_intervals: List[Tuple[str, float, float, Optional[Dict[str, Any]]]] = [] + zone_intervals: List[ + Tuple[str, float, float, Optional[Dict[str, Any]]] + ] = [] seen_zone_names = set() for t in w_tops: z_name = str(t.get("name") or "").strip() @@ -1226,6 +1352,8 @@ def get_project_summary(project_id: int) -> Dict[str, Any]: "survey_count": survey_counts.get(wid, 0), "perforation_count": perf_counts.get(wid, 0), "perforations": perfs_list_by_well.get(wid, []), + "hole_section_count": hole_sec_counts.get(wid, 0), + "hole_sections": hole_secs_list_by_well.get(wid, []), } ) @@ -1395,6 +1523,20 @@ def project_read_las( time.time(), merged_ldf.copy(), ) + # Tier 1 cleanup: immediately remove raw uploaded files from disk after loading into RAM + for p in saved_paths: + try: + Path(p).unlink(missing_ok=True) + except OSError: + pass + try: + from quick_pp.app.backend.services.demo_guard import ( + mark_demo_state_dirty, + ) + + mark_demo_state_dirty() + except Exception: + pass else: proj.read_las(saved_paths, depth_uom=depth_uom) @@ -1587,7 +1729,9 @@ def get_well_data( # table can surface them directly (porosity/permeability/grain density). meas_by_prop = {} for m in measurements: - prop = str(m.get("property") or m.get("property_name") or "").upper() + prop = str( + m.get("property") or m.get("property_name") or "" + ).upper() if prop and m.get("value") is not None: meas_by_prop[prop] = m.get("value") sample_entry = { @@ -1621,6 +1765,11 @@ def get_well_data( if not well.get_perforations().empty else [] ), + "hole_sections": ( + well.get_hole_sections().to_dict(orient="records") + if not well.get_hole_sections().empty + else [] + ), "core_samples": core_samples, } @@ -1723,7 +1872,12 @@ def _compute_tvd_from_survey( """Compute TVD along md_values from directional survey minimum curvature (or survey TVD column). Returns None if no valid survey with >= 2 stations is available (never assumes TVD == MD). """ - if len(md_values) == 0 or surveys_df is None or not isinstance(surveys_df, pd.DataFrame) or surveys_df.empty: + if ( + len(md_values) == 0 + or surveys_df is None + or not isinstance(surveys_df, pd.DataFrame) + or surveys_df.empty + ): return None col_map = {str(c).lower(): c for c in surveys_df.columns} @@ -1745,60 +1899,19 @@ def _compute_tvd_from_survey( .drop_duplicates(subset=["md"], keep="last") ) if len(s_sub) >= 2: - mds = s_sub["md"].to_numpy(dtype=float) - tvds = s_sub["tvd"].to_numpy(dtype=float) - if mds[0] > 1.0: - mds = np.insert(mds, 0, 0.0) - tvds = np.insert(tvds, 0, 0.0) - return np.interp(md_values, mds, tvds) + # Shared rules: surface tie-in, linear, extrapolate below last station + return interpolate_tvd_on_md( + md_values, + s_sub["md"].to_numpy(dtype=float), + s_sub["tvd"].to_numpy(dtype=float), + ) if md_c and inc_c and azi_c: - s_sorted = ( - pd.DataFrame( - { - "md": pd.to_numeric(surveys_df[md_c], errors="coerce"), - "inc": pd.to_numeric(surveys_df[inc_c], errors="coerce"), - "azim": pd.to_numeric(surveys_df[azi_c], errors="coerce"), - } - ) - .dropna() - .sort_values("md") - .drop_duplicates(subset=["md"], keep="last") + mds, tvds, incs = survey_tvd_stations( + surveys_df[md_c], surveys_df[inc_c], surveys_df[azi_c] ) - if len(s_sorted) >= 2: - mds = s_sorted["md"].to_numpy(dtype=float) - incs = s_sorted["inc"].to_numpy(dtype=float) - azis = s_sorted["azim"].to_numpy(dtype=float) - if mds[0] > 1.0: - mds = np.insert(mds, 0, 0.0) - incs = np.insert(incs, 0, 0.0) - azis = np.insert(azis, 0, azis[0] if len(azis) > 0 else 0.0) - try: - import wellpathpy as wpp - - dev = wpp.deviation(mds, incs, azis) - pos = dev.minimum_curvature() - return np.interp( - md_values, - np.asarray(pos.md, dtype=float), - np.asarray(pos.depth, dtype=float), - ) - except Exception: - inc_rad = np.deg2rad(incs) - azi_rad = np.deg2rad(azis) - dmd = np.diff(mds) - i1, i2 = inc_rad[:-1], inc_rad[1:] - a1, a2 = azi_rad[:-1], azi_rad[1:] - cos_dl = np.clip( - np.cos(i2 - i1) - np.sin(i1) * np.sin(i2) * (1.0 - np.cos(a2 - a1)), - -1.0, - 1.0, - ) - dl = np.arccos(cos_dl) - rf = np.where(dl > 1e-6, (2.0 / dl) * np.tan(dl / 2.0), 1.0) - dz = 0.5 * dmd * (np.cos(i1) + np.cos(i2)) * rf - tvd_calc = np.concatenate([[0.0], np.cumsum(dz)]) - return np.interp(md_values, mds, tvd_calc) + if len(mds) >= 2: + return interpolate_tvd_on_md(md_values, mds, tvds, incs) return None @@ -1911,9 +2024,7 @@ def _normalize_df_depth(dframe): well = proj.get_well(db_well_name) well_header_data = ( - dict(well.header_data) - if isinstance(well.header_data, dict) - else {} + dict(well.header_data) if isinstance(well.header_data, dict) else {} ) well_config_data = ( dict(well._orm_well.config_data) @@ -1994,9 +2105,7 @@ def _map_discrete_to_single_nearest_row( disc_df: pd.DataFrame, max_tol: float ) -> Dict[str, List[Any]]: cols = [c for c in disc_df.columns if c != "depth"] - out_cols: Dict[str, List[Any]] = { - c: [np.nan] * n_log for c in cols - } + out_cols: Dict[str, List[Any]] = {c: [np.nan] * n_log for c in cols} if n_log == 0 or disc_df.empty or not cols: return out_cols best_dist_at_idx: Dict[int, float] = {} @@ -2090,7 +2199,10 @@ def _top_specificity(name_val: Any) -> tuple: ) if prop_up in ("POR", "CPORE", "POROSITY") and "cpore" not in row_entry: row_entry["cpore"] = val / 100.0 if val > 1.0 else val - elif prop_up in ("PERM", "CPERM", "PERMEABILITY") and "cperm" not in row_entry: + elif ( + prop_up in ("PERM", "CPERM", "PERMEABILITY") + and "cperm" not in row_entry + ): row_entry["cperm"] = val if core_rows_by_depth: @@ -2106,7 +2218,9 @@ def _top_specificity(name_val: Any) -> tuple: merged["core_sample_name"] = mapped_core["core_sample_name"] for c_col in ("cpore", "cperm"): if c_col in mapped_core: - s_mapped = pd.Series(mapped_core[c_col], index=merged.index, dtype=float) + s_mapped = pd.Series( + mapped_core[c_col], index=merged.index, dtype=float + ) if s_mapped.notna().any(): merged[c_col] = s_mapped else: @@ -2116,12 +2230,16 @@ def _top_specificity(name_val: Any) -> tuple: has_ck = "cperm" in merged.columns if (has_cp or has_ck) and n_log > 1: cp_vals = ( - pd.to_numeric(merged["cpore"], errors="coerce").to_numpy(dtype=float) + pd.to_numeric(merged["cpore"], errors="coerce").to_numpy( + dtype=float + ) if has_cp else np.full(n_log, np.nan) ) ck_vals = ( - pd.to_numeric(merged["cperm"], errors="coerce").to_numpy(dtype=float) + pd.to_numeric(merged["cperm"], errors="coerce").to_numpy( + dtype=float + ) if has_ck else np.full(n_log, np.nan) ) @@ -2365,9 +2483,17 @@ def _collect_project_handover_bundles( well_names_filter: Optional[List[str]] = None, ) -> tuple[str, str, List[Dict[str, Any]], Dict[str, Any]]: """Gather project metadata, project-level multi-well config, and per-well handover dictionaries (including ephemeral/cached live edits).""" - from quick_pp.app.backend.services.workspace import _ephemeral_well_configs + from quick_pp.app.backend.services import workspace as ws_service from quick_pp.handover import collect_well_handover_dict + _ephemeral_well_configs = getattr(ws_service, "_ephemeral_well_configs", {}) + _ephemeral_project_module_params = getattr( + ws_service, "_ephemeral_project_module_params", {} + ) + _module_params_key = getattr( + ws_service, "MODULE_PARAMS_CONFIG_KEY", "module_params" + ) + if project_id in _demo_deleted_projects: raise ValueError(f"Project {project_id} not found") @@ -2390,6 +2516,15 @@ def _collect_project_handover_bundles( eph_proj_cfg = _ephemeral_well_configs.get((project_id, "__PROJECT__")) if isinstance(eph_proj_cfg, dict): proj_cfg.update(eph_proj_cfg) + eph_proj_mp = _ephemeral_project_module_params.get(project_id) + if isinstance(eph_proj_mp, dict) and eph_proj_mp: + existing_mp = ( + dict(proj_cfg.get(_module_params_key)) + if isinstance(proj_cfg.get(_module_params_key), dict) + else {} + ) + existing_mp.update(eph_proj_mp) + proj_cfg[_module_params_key] = existing_mp wells_bundle: List[Dict[str, Any]] = [] seen_names = set() @@ -2415,16 +2550,17 @@ def _fetch_well_bundle(w_info: Tuple[int, str, str]) -> Dict[str, Any]: ): live_df = eph_entry["data"] else: - cached = _merged_data_cache.get(f"{project_id}_{curr_n}_0.16") - if cached is not None: - live_df = cached[1] - else: - try: - live_df = _get_merged_dataframe_sync(project_id, curr_n) - except Exception: - live_df = None - - eph_w_cfg = _ephemeral_well_configs.get((project_id, curr_n)) or _ephemeral_well_configs.get((project_id, orig_n)) + try: + live_df = _get_merged_dataframe_sync(project_id, curr_n) + except Exception: + live_df = None + + eph_w_cfg = _ephemeral_well_configs.get( + (project_id, curr_n) + ) or _ephemeral_well_configs.get((project_id, orig_n)) + eph_w_hdr = _ephemeral_well_headers.get( + (project_id, curr_n) + ) or _ephemeral_well_headers.get((project_id, orig_n)) with get_db() as w_session: well_obj = db_objects.Well(w_session, well_id=w_id) b_dict = collect_well_handover_dict( @@ -2432,6 +2568,10 @@ def _fetch_well_bundle(w_info: Tuple[int, str, str]) -> Dict[str, Any]: override_df=live_df, override_config=eph_w_cfg if isinstance(eph_w_cfg, dict) else None, ) + if isinstance(eph_w_hdr, dict) and eph_w_hdr: + merged_h = dict(b_dict.get("header") or {}) + merged_h.update(eph_w_hdr) + b_dict["header"] = merged_h b_dict["name"] = curr_n return b_dict @@ -2478,7 +2618,20 @@ def _fetch_well_bundle(w_info: Tuple[int, str, str]) -> Dict[str, Any]: "formation_tops": pd.DataFrame(columns=["name", "depth"]), "fluid_contacts": pd.DataFrame(columns=["name", "depth"]), "perforations": pd.DataFrame( - columns=["name", "top_depth", "bottom_depth", "description"] + columns=["name", "top", "bottom", "description"] + ), + "hole_sections": pd.DataFrame( + columns=[ + "name", + "top", + "bottom", + "bit_size", + "mud_type", + "mud_weight", + "mud_salinity", + "rmf", + "rmf_temp", + ] ), "well_surveys": pd.DataFrame(columns=["md", "inc", "azim"]), "pressure_tests": pd.DataFrame( @@ -2532,8 +2685,10 @@ def export_project_handover( elif wells: filter_list = [w.strip() for w in wells.split(",") if w.strip()] - proj_name, proj_desc, wells_bundle, proj_cfg = _collect_project_handover_bundles( - project_id=project_id, well_names_filter=filter_list + proj_name, proj_desc, wells_bundle, proj_cfg = ( + _collect_project_handover_bundles( + project_id=project_id, well_names_filter=filter_list + ) ) if not wells_bundle: raise ValueError("No matching wells found to export.") @@ -2623,30 +2778,42 @@ def export_well_las_endpoint(project_id: int, well_name: str): ) from e - @router.post( "/projects/import-handover/inspect", summary="Inspect a Petrophysical Handover Package (.zip) before ingestion", ) def inspect_handover_package_endpoint(file: UploadFile = File(...)): """Inspect an uploaded Petrophysical Handover Package (.zip) and return metadata preview.""" + from sqlalchemy import func + from quick_pp.handover import inspect_handover_archive try: content = file.file.read() preview = inspect_handover_archive(content) + base_name = str(preview.get("project_name") or "Imported_Project").strip() + preview["project_name"] = base_name with get_db() as session: + existing_names_lower = { + str(n).strip().lower() + for (n,) in session.query(db_models.Project.name).all() + if n is not None + } existing = ( session.query(db_models.Project) - .filter_by(name=preview["project_name"]) + .filter(func.lower(db_models.Project.name) == base_name.lower()) .first() ) preview["is_duplicate_name"] = bool(existing) - preview["suggested_name"] = ( - f"{preview['project_name']}_Imported" - if existing - else preview["project_name"] - ) + if existing: + candidate = f"{base_name}_Imported" + suffix = 2 + while candidate.lower() in existing_names_lower: + candidate = f"{base_name}_Imported_{suffix}" + suffix += 1 + preview["suggested_name"] = candidate + else: + preview["suggested_name"] = base_name return preview except Exception as e: logger.exception("Failed to inspect handover package") @@ -2667,21 +2834,33 @@ def commit_handover_package_endpoint( overwrite_existing: bool = Form(True), ): """Import a complete Petrophysical Handover Package (.zip) into database.""" + if is_demo_mode(): + raise HTTPException( + status_code=403, + detail="Importing full database handover archives is disabled in the read-only live demo.", + ) from quick_pp.handover import import_handover_archive try: current_user = get_current_user_optional(request) user_id = int(current_user["user_id"]) if current_user else None + cleaned_name = ( + project_name.strip() + if isinstance(project_name, str) and project_name.strip() + else None + ) content = file.file.read() with get_db() as session: res = import_handover_archive( db_session=session, zip_source=content, - target_project_name=project_name, + target_project_name=cleaned_name, target_project_id=project_id, created_by_user_id=user_id, overwrite_existing_wells=overwrite_existing, ) + if res.get("project_id") is not None: + invalidate_well_cache(project_id=int(res["project_id"])) return res except Exception as e: logger.exception("Failed to import handover package") diff --git a/quick_pp/app/backend/services/demo_guard.py b/quick_pp/app/backend/services/demo_guard.py new file mode 100644 index 00000000..12e2d3d0 --- /dev/null +++ b/quick_pp/app/backend/services/demo_guard.py @@ -0,0 +1,837 @@ +"""Live Demo Session Tracker, Concurrency Limiter, SSRF Guard, and 3-Tier Artifact Cleanup. + +Active when `QPP_DEMO_MODE=true`: +1. Tracks active browser sessions in memory via `X-Demo-Session-Id` heartbeats (`--workers 1`), + exposing online user counts, lag warnings, and soft admission capacity control. +2. Caps simultaneous heavy compute/plotting requests so bursts on a 1-vCPU / 2 GB droplet + queue gracefully instead of triggering OOM kills. +3. Enforces 3-tier ephemeral disk & RAM hygiene: + - Tier 1: Immediate post-commit deletion of staged upload files & disabled pickle disk sync + - Tier 2: Per-session cleanup on tab leave / heartbeat expiry + full state reset after global idle + - Tier 3: Periodic background TTL sweep + hard ring-buffer caps on reports and staged uploads +4. Validates external LLM base URLs to prevent SSRF and server API-key exfiltration. +""" + +from __future__ import annotations + +import asyncio +import ipaddress +import logging +import os +import re +import shutil +import tempfile +import threading +import time +import urllib.parse +from contextvars import ContextVar +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +from fastapi import APIRouter, HTTPException, Request, status +from pydantic import BaseModel, Field + +from quick_pp.app.backend.utils.auth import is_demo_mode + +logger = logging.getLogger(__name__) + +DEMO_SESSION_HEADER = "x-demo-session-id" +_SESSION_ID_RE = re.compile(r"^[A-Za-z0-9_-]{6,64}$") + +_current_demo_session_id: ContextVar[Optional[str]] = ContextVar( + "current_demo_session_id", default=None +) + +_lock = threading.RLock() +_demo_sessions: Dict[str, Dict[str, Any]] = {} +_had_activity_since_reset: bool = False +_last_zero_users_at: Optional[float] = None + +_compute_cond = threading.Condition() +_active_compute_jobs: int = 0 + + +# --------------------------------------------------------------------------- +# Dynamic Configuration Readers (env-driven for runtime & test overrides) +# --------------------------------------------------------------------------- + + +def _env_int(name: str, default: int, minimum: int = 1) -> int: + raw = os.environ.get(name, "").strip() + if not raw: + return default + try: + return max(minimum, int(raw)) + except ValueError: + return default + + +def _env_float(name: str, default: float, minimum: float = 0.1) -> float: + raw = os.environ.get(name, "").strip() + if not raw: + return default + try: + return max(minimum, float(raw)) + except ValueError: + return default + + +def get_demo_max_users() -> int: + return _env_int("QPP_DEMO_MAX_USERS", 6, minimum=1) + + +def get_demo_session_ttl() -> int: + return _env_int("QPP_DEMO_SESSION_TTL_SECONDS", 75, minimum=10) + + +def get_demo_idle_timeout() -> int: + return _env_int("QPP_DEMO_IDLE_TIMEOUT_SECONDS", 600, minimum=30) + + +def get_demo_hidden_idle_timeout() -> int: + return _env_int("QPP_DEMO_HIDDEN_IDLE_TIMEOUT_SECONDS", 300, minimum=20) + + +def get_demo_lag_threshold() -> int: + return _env_int("QPP_DEMO_LAG_WARNING_USERS", 3, minimum=1) + + +def get_demo_max_concurrent_compute() -> int: + return _env_int("QPP_DEMO_MAX_CONCURRENT_COMPUTE", 2, minimum=1) + + +def get_demo_compute_timeout() -> float: + return _env_float("QPP_DEMO_COMPUTE_TIMEOUT_SECONDS", 15.0, minimum=0.05) + + +def get_demo_report_ttl() -> int: + return _env_int("QPP_DEMO_REPORT_TTL_SECONDS", 1800, minimum=60) + + +def get_demo_max_reports() -> int: + return _env_int("QPP_DEMO_MAX_REPORTS", 15, minimum=1) + + +def get_demo_staging_ttl() -> int: + return _env_int("QPP_DEMO_STAGING_TTL_SECONDS", 900, minimum=30) + + +def get_demo_max_staged_files() -> int: + return _env_int("QPP_DEMO_MAX_STAGED_FILES", 20, minimum=1) + + +def get_demo_zero_users_reset_seconds() -> int: + return _env_int("QPP_DEMO_ZERO_USERS_RESET_SECONDS", 600, minimum=10) + + +def get_demo_sweep_interval_seconds() -> int: + return _env_int("QPP_DEMO_SWEEP_INTERVAL_SECONDS", 300, minimum=15) + + +# --------------------------------------------------------------------------- +# Context & Session Helpers +# --------------------------------------------------------------------------- + + +def normalize_session_id(raw: Optional[str]) -> Optional[str]: + if not raw: + return None + cleaned = str(raw).strip() + if _SESSION_ID_RE.match(cleaned): + return cleaned + return None + + +def get_current_demo_session_id() -> Optional[str]: + return _current_demo_session_id.get() + + +def set_current_demo_session_id(session_id: Optional[str]): + return _current_demo_session_id.set(normalize_session_id(session_id)) + + +def reset_current_demo_session_id(token) -> None: + _current_demo_session_id.reset(token) + + +def mark_demo_state_dirty() -> None: + global _had_activity_since_reset + with _lock: + _had_activity_since_reset = True + + +def reset_demo_sessions_for_testing() -> None: + """Clear in-memory demo session tracking (used by tests).""" + global _had_activity_since_reset, _last_zero_users_at + with _lock: + _demo_sessions.clear() + _had_activity_since_reset = False + _last_zero_users_at = None + + +def evict_expired_sessions(now: Optional[float] = None) -> List[str]: + global _last_zero_users_at + ts = time.time() if now is None else now + ttl = get_demo_session_ttl() + evicted: List[str] = [] + + with _lock: + had_any = len(_demo_sessions) > 0 + for sid, meta in list(_demo_sessions.items()): + if ts - float(meta.get("last_seen", 0.0)) > ttl: + _demo_sessions.pop(sid, None) + evicted.append(sid) + if had_any and len(_demo_sessions) == 0: + _last_zero_users_at = ts + + for sid in evicted: + try: + purge_session_artifacts(sid) + except Exception as exc: + logger.debug( + "Failed to purge artifacts for expired session %s: %s", sid, exc + ) + return evicted + + +def _build_snapshot_unlocked( + session_id: Optional[str] = None, + admitted: Optional[bool] = None, +) -> Dict[str, Any]: + online = len(_demo_sessions) + max_users = get_demo_max_users() + lag_thresh = get_demo_lag_threshold() + with _compute_cond: + active_compute = _active_compute_jobs + is_member = bool(session_id and session_id in _demo_sessions) + at_cap = online >= max_users and not is_member + return { + "demo_mode": is_demo_mode(), + "online_users": online, + "max_users": max_users, + "at_capacity": at_cap, + "admitted": is_member if admitted is None else admitted, + "session_active": is_member, + "lag_warning": online >= lag_thresh or active_compute >= 1, + "lag_warning_threshold": lag_thresh, + "active_compute_jobs": active_compute, + "max_compute_jobs": get_demo_max_concurrent_compute(), + "idle_timeout_seconds": get_demo_idle_timeout(), + "hidden_idle_timeout_seconds": get_demo_hidden_idle_timeout(), + "session_ttl_seconds": get_demo_session_ttl(), + } + + +def get_demo_status_snapshot( + session_id: Optional[str] = None, now: Optional[float] = None +) -> Dict[str, Any]: + evict_expired_sessions(now=now) + sid = normalize_session_id(session_id) + with _lock: + return _build_snapshot_unlocked(session_id=sid) + + +def register_or_touch_session( + session_id: Optional[str], + client_ip: str = "", + now: Optional[float] = None, +) -> Dict[str, Any]: + global _had_activity_since_reset, _last_zero_users_at + ts = time.time() if now is None else now + evict_expired_sessions(now=ts) + sid = normalize_session_id(session_id) + if not sid: + with _lock: + return _build_snapshot_unlocked(session_id=None, admitted=True) + + with _lock: + if sid in _demo_sessions: + _demo_sessions[sid]["last_seen"] = ts + if client_ip: + _demo_sessions[sid]["ip"] = client_ip + return _build_snapshot_unlocked(session_id=sid, admitted=True) + + if len(_demo_sessions) >= get_demo_max_users(): + return _build_snapshot_unlocked(session_id=sid, admitted=False) + + _demo_sessions[sid] = { + "created_at": ts, + "last_seen": ts, + "ip": client_ip, + } + _had_activity_since_reset = True + _last_zero_users_at = None + return _build_snapshot_unlocked(session_id=sid, admitted=True) + + +def leave_session( + session_id: Optional[str], now: Optional[float] = None +) -> Dict[str, Any]: + global _last_zero_users_at + ts = time.time() if now is None else now + sid = normalize_session_id(session_id) + removed = False + with _lock: + if sid and sid in _demo_sessions: + _demo_sessions.pop(sid, None) + removed = True + if len(_demo_sessions) == 0: + _last_zero_users_at = ts + + purged = {"reports_deleted": 0, "staged_files_deleted": 0} + if sid: + purged = purge_session_artifacts(sid) + + with _lock: + snap = _build_snapshot_unlocked(session_id=sid, admitted=False) + snap["removed"] = removed + snap["purged"] = purged + return snap + + +# --------------------------------------------------------------------------- +# Heavy Compute Concurrency Guard +# --------------------------------------------------------------------------- + +_LIGHTWEIGHT_WORKSPACE_SUFFIXES = ( + "/demo/reset", + "/config", + "/module_params", +) + + +def is_heavy_demo_compute_request(method: str, path: str) -> bool: + """Return True if this HTTP request runs CPU/RAM-intensive petrophysics, LLM, or PDF work.""" + m = method.upper() + p = path.rstrip("/") + + # Report PDF export is a GET that compiles high-DPI PDF + if m == "GET": + return p.endswith("/pdf") and "/reports/" in p + + if m not in ("POST", "PUT"): + return False + + if "/reports/" in p and (p.endswith("/generate") or p.endswith("/enhance")): + return True + + if p.endswith(("/assistant/chat", "/mcp/call", "/mcp")): + return True + + if "/quick_pp/workspace/projects/" in p: + if any(p.endswith(sfx) for sfx in _LIGHTWEIGHT_WORKSPACE_SUFFIXES): + return False + return True + + heavy_prefixes = ( + "/quick_pp/lithology/", + "/quick_pp/porosity/", + "/quick_pp/saturation/", + "/quick_pp/permeability/", + "/quick_pp/reservoir_summary/", + "/quick_pp/uncertainty/", + "/quick_pp/upscaling/", + "/quick_pp/scal/", + "/quick_pp/rock_typing/", + "/quick_pp/perm_transform/", + "/quick_pp/shf/", + ) + return any(p.startswith(pfx) for pfx in heavy_prefixes) + + +def acquire_compute_slot_sync(timeout: Optional[float] = None) -> bool: + global _active_compute_jobs + wait_s = get_demo_compute_timeout() if timeout is None else max(0.0, float(timeout)) + deadline = time.monotonic() + wait_s + with _compute_cond: + while _active_compute_jobs >= get_demo_max_concurrent_compute(): + remaining = deadline - time.monotonic() + if remaining <= 0: + return False + _compute_cond.wait(timeout=min(remaining, 0.25)) + _active_compute_jobs += 1 + return True + + +def release_compute_slot_sync() -> None: + global _active_compute_jobs + with _compute_cond: + if _active_compute_jobs > 0: + _active_compute_jobs -= 1 + _compute_cond.notify(1) + + +# --------------------------------------------------------------------------- +# 3-Tier Ephemeral Artifact Cleanup (Reports, Staged Uploads, Temp Pickles, RAM) +# --------------------------------------------------------------------------- + + +def _safe_rmtree(path: Path) -> bool: + try: + if path.exists(): + shutil.rmtree(path, ignore_errors=True) + return True + except Exception: + pass + return False + + +def _safe_unlink(path: Path) -> bool: + try: + if path.exists() and path.is_file(): + path.unlink(missing_ok=True) + return True + except Exception: + pass + return False + + +def purge_session_artifacts(session_id: str) -> Dict[str, int]: + """Tier 2: Immediately delete reports and uncommitted staged files owned by `session_id`.""" + sid = normalize_session_id(session_id) + if not sid: + return {"reports_deleted": 0, "staged_files_deleted": 0} + + reports_deleted = 0 + staged_deleted = 0 + + try: + from quick_pp.app.backend.services import report as report_svc + + for rpt_id, rpt_data in list(report_svc._REPORTS_STORE.items()): + if ( + rpt_data.get("_demo_session_id") == sid + or rpt_data.get("demo_session_id") == sid + ): + report_svc._REPORTS_STORE.pop(rpt_id, None) + if _safe_rmtree(report_svc.REPORTS_STATIC_ROOT / rpt_id): + reports_deleted += 1 + + for job_id, job_data in list(report_svc._REPORT_JOBS.items()): + if job_data.get("demo_session_id") == sid: + report_svc._REPORT_JOBS.pop(job_id, None) + _safe_unlink(report_svc._job_path(job_id)) + except Exception as exc: + logger.debug("Session report cleanup skipped for %s: %s", sid, exc) + + try: + from quick_pp.app.backend.services import las_handler as las_svc + + for fid, meta in list(las_svc._STAGED_FILES.items()): + if meta.get("demo_session_id") == sid: + las_svc._STAGED_FILES.pop(fid, None) + fpath = meta.get("path") + if fpath and _safe_unlink(Path(fpath)): + staged_deleted += 1 + except Exception as exc: + logger.debug("Session staging cleanup skipped for %s: %s", sid, exc) + + return { + "reports_deleted": reports_deleted, + "staged_files_deleted": staged_deleted, + } + + +def enforce_report_storage_limits( + now: Optional[float] = None, force_all: bool = False +) -> int: + """Evict expired reports (> TTL) and cap total report folders on disk (ring buffer).""" + ts = time.time() if now is None else now + ttl = get_demo_report_ttl() + max_reports = get_demo_max_reports() + deleted = 0 + + try: + from quick_pp.app.backend.services import report as report_svc + + root = report_svc.REPORTS_STATIC_ROOT + if root.exists(): + rpt_dirs: List[Tuple[float, Path]] = [] + for child in root.iterdir(): + if not child.is_dir(): + continue + if child.name == "_jobs": + for jf in child.glob("*.json"): + try: + age = ts - jf.stat().st_mtime + if force_all or age > ttl: + report_svc._REPORT_JOBS.pop(jf.stem, None) + if _safe_unlink(jf): + deleted += 1 + except OSError: + pass + continue + if not child.name.startswith("rpt_"): + continue + try: + mtime = child.stat().st_mtime + except OSError: + mtime = 0.0 + mem_entry = report_svc._REPORTS_STORE.get(child.name) + if ( + isinstance(mem_entry, dict) + and mem_entry.get("_created_ts") is not None + ): + mtime = float(mem_entry["_created_ts"]) + if force_all or (ts - mtime > ttl): + report_svc._REPORTS_STORE.pop(child.name, None) + if _safe_rmtree(child): + deleted += 1 + else: + rpt_dirs.append((mtime, child)) + + # Ring-buffer cap: keep only newest `max_reports` + if len(rpt_dirs) > max_reports: + rpt_dirs.sort(key=lambda item: (item[0], item[1].name), reverse=True) + for _, old_dir in rpt_dirs[max_reports:]: + report_svc._REPORTS_STORE.pop(old_dir.name, None) + if _safe_rmtree(old_dir): + deleted += 1 + + # Also cap in-memory _REPORTS_STORE if directories were already removed + if force_all: + report_svc._REPORTS_STORE.clear() + report_svc._REPORT_JOBS.clear() + elif len(report_svc._REPORTS_STORE) > max_reports: + ordered = sorted( + report_svc._REPORTS_STORE.items(), + key=lambda kv: float(kv[1].get("_created_ts") or 0.0), + reverse=True, + ) + for old_id, _ in ordered[max_reports:]: + report_svc._REPORTS_STORE.pop(old_id, None) + except Exception as exc: + logger.debug("Report storage cleanup error: %s", exc) + + # Clean orphaned headless browser PDF temp profiles in /tmp + try: + tmp_root = Path(tempfile.gettempdir()) + for pdf_tmp in tmp_root.glob("qpp_pdf_*"): + try: + if force_all or (ts - pdf_tmp.stat().st_mtime > 900): + _safe_rmtree(pdf_tmp) + except OSError: + pass + except Exception: + pass + + return deleted + + +def enforce_upload_storage_limits( + now: Optional[float] = None, force_all: bool = False +) -> int: + """Evict expired staged/uploaded log files (> TTL) and cap staged file count.""" + ts = time.time() if now is None else now + ttl = get_demo_staging_ttl() + max_files = get_demo_max_staged_files() + deleted = 0 + + try: + from quick_pp.app.backend.services import las_handler as las_svc + + for fid, meta in list(las_svc._STAGED_FILES.items()): + created = float(meta.get("created_at") or 0.0) + fpath = Path(meta["path"]) if meta.get("path") else None + if ( + force_all + or (ts - created > ttl) + or (fpath is not None and not fpath.exists()) + ): + las_svc._STAGED_FILES.pop(fid, None) + if fpath and _safe_unlink(fpath): + deleted += 1 + + staged_created_by_path: Dict[str, float] = {} + for meta in las_svc._STAGED_FILES.values(): + if meta.get("path") and meta.get("created_at") is not None: + try: + staged_created_by_path[str(Path(meta["path"]).resolve())] = float( + meta["created_at"] + ) + except OSError: + pass + + upload_dirs = [ + las_svc.STAGING_DIR, + Path("uploads/las_db"), + Path("uploads/las"), + Path("uploads/parquet"), + ] + surviving_staged: List[Tuple[float, Path]] = [] + for udir in upload_dirs: + if not udir.exists(): + continue + for item in udir.iterdir(): + if not item.is_file(): + continue + try: + mtime = staged_created_by_path.get( + str(item.resolve()), item.stat().st_mtime + ) + except OSError: + continue + if force_all or (ts - mtime > ttl): + if _safe_unlink(item): + deleted += 1 + elif udir == las_svc.STAGING_DIR: + surviving_staged.append((mtime, item)) + + if len(surviving_staged) > max_files: + surviving_staged.sort( + key=lambda pair: (pair[0], pair[1].name), reverse=True + ) + keep_paths = {str(p.resolve()) for _, p in surviving_staged[:max_files]} + for _, old_file in surviving_staged[max_files:]: + if _safe_unlink(old_file): + deleted += 1 + for fid, meta in list(las_svc._STAGED_FILES.items()): + mp = meta.get("path") + if mp and str(Path(mp).resolve()) not in keep_paths: + las_svc._STAGED_FILES.pop(fid, None) + except Exception as exc: + logger.debug("Upload storage cleanup error: %s", exc) + + return deleted + + +def reset_all_ephemeral_demo_memory() -> None: + """Reset global in-memory demo DataFrames, caches, and parameter overrides back to seed DB.""" + global _had_activity_since_reset, _last_zero_users_at + try: + from quick_pp.app.backend.services import database as db_svc + from quick_pp.app.backend.services import workspace as ws_svc + + db_svc._ephemeral_wells.clear() + db_svc._merged_data_cache.clear() + db_svc.reset_demo_project_state(None) + ws_svc._ephemeral_well_configs.clear() + if hasattr(ws_svc, "_ephemeral_project_module_params"): + ws_svc._ephemeral_project_module_params.clear() + _safe_rmtree(db_svc._SHARED_CACHE_DIR) + except Exception as exc: + logger.debug("Ephemeral memory reset error: %s", exc) + + with _lock: + _had_activity_since_reset = False + _last_zero_users_at = None + + +def run_periodic_demo_cleanup( + now: Optional[float] = None, force_all: bool = False +) -> Dict[str, Any]: + """Run Tier 2 + Tier 3 cleanup across sessions, reports, uploads, temp pickles, and idle memory.""" + ts = time.time() if now is None else now + evicted_sessions = evict_expired_sessions(now=ts) + reports_cleaned = enforce_report_storage_limits(now=ts, force_all=force_all) + uploads_cleaned = enforce_upload_storage_limits(now=ts, force_all=force_all) + + # Remove any stray /tmp/qpp_well_cache_sync pickles in single-worker demo mode + if is_demo_mode(): + try: + from quick_pp.app.backend.services import database as db_svc + + _safe_rmtree(db_svc._SHARED_CACHE_DIR) + except Exception: + pass + + memory_reset = False + with _lock: + should_reset_mem = force_all or ( + len(_demo_sessions) == 0 + and _had_activity_since_reset + and _last_zero_users_at is not None + and (ts - _last_zero_users_at) >= get_demo_zero_users_reset_seconds() + ) + if should_reset_mem: + reset_all_ephemeral_demo_memory() + memory_reset = True + + return { + "evicted_sessions": len(evicted_sessions), + "reports_cleaned": reports_cleaned, + "uploads_cleaned": uploads_cleaned, + "memory_reset": memory_reset, + } + + +async def demo_periodic_cleanup_loop() -> None: + """Background asyncio task started in FastAPI lifespan when `QPP_DEMO_MODE=true`.""" + while True: + interval = get_demo_sweep_interval_seconds() + await asyncio.sleep(interval) + if is_demo_mode(): + try: + await asyncio.to_thread(run_periodic_demo_cleanup) + except Exception as exc: + logger.warning("Periodic demo cleanup failed: %s", exc) + + +# --------------------------------------------------------------------------- +# External LLM SSRF & Server API-Key Exfiltration Protection +# --------------------------------------------------------------------------- + +_CANONICAL_OPENROUTER_URL = "https://openrouter.ai/api/v1" + + +def _is_private_or_internal_host(hostname: str) -> bool: + host = (hostname or "").strip().lower().strip("[]") + if not host: + return True + if host in ("localhost", "0.0.0.0") or host.endswith((".local", ".internal")): + return True + try: + ip = ipaddress.ip_address(host) + return ( + ip.is_private + or ip.is_loopback + or ip.is_link_local + or ip.is_multicast + or ip.is_reserved + or ip.is_unspecified + ) + except ValueError: + return False + + +def validate_external_llm_target( + provider: str, + caller_base_url: Optional[str], + caller_api_key: Optional[str], + env_openrouter_url: str = _CANONICAL_OPENROUTER_URL, + env_openrouter_key: str = "", +) -> Tuple[str, str]: + """Validate `(base_url, api_key)` for external LLM requests, blocking SSRF and env-key leaks. + + - In `QPP_DEMO_MODE=true`: + - Blocks `ollama` and any custom `base_url` (including private/metadata IPs like `169.254.169.254`). + - Allows only `https://openrouter.ai/api/v1` with a caller-supplied `api_key` (or explicit demo env key). + - In all modes: + - Never attaches `env_openrouter_key` when the caller overrides `base_url` to a different host. + """ + prov = (provider or "native_mcp").strip().lower() + raw_caller_url = (caller_base_url or "").strip().rstrip("/") + clean_caller_key = (caller_api_key or "").strip() + default_or_url = ( + (env_openrouter_url or _CANONICAL_OPENROUTER_URL).strip().rstrip("/") + ) + + if is_demo_mode(): + if prov == "ollama": + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Local Ollama connections are disabled in the public live demo.", + ) + if raw_caller_url and raw_caller_url.lower() != _CANONICAL_OPENROUTER_URL: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Custom LLM base URLs are disabled in the public live demo.", + ) + effective_url = _CANONICAL_OPENROUTER_URL + effective_key = clean_caller_key or env_openrouter_key + return effective_url, effective_key + + # Non-demo mode + if prov == "ollama": + effective_url = raw_caller_url or os.environ.get( + "OLLAMA_BASE_URL", "http://localhost:11434/v1" + ).strip().rstrip("/") + parsed = urllib.parse.urlsplit(effective_url) + if parsed.scheme not in ("http", "https") or not parsed.hostname: + raise ValueError("Invalid Ollama base_url; must be an http(s) URL.") + return effective_url, clean_caller_key or "ollama" + + effective_url = raw_caller_url or default_or_url + parsed = urllib.parse.urlsplit(effective_url) + if parsed.scheme not in ("http", "https") or not parsed.hostname: + raise ValueError("Invalid LLM base_url; must be an http(s) URL.") + + # Block cloud link-local metadata endpoints (169.254.169.254) unconditionally + try: + ip = ipaddress.ip_address(parsed.hostname.strip("[]")) + if ip.is_link_local: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Link-local metadata addresses are not permitted as LLM base_url.", + ) + except ValueError: + pass + + # Never send server's OPENROUTER_API_KEY to a caller-overridden host! + default_parsed = urllib.parse.urlsplit(default_or_url) + same_trusted_origin = ( + parsed.scheme.lower() == default_parsed.scheme.lower() + and (parsed.hostname or "").lower() == (default_parsed.hostname or "").lower() + and parsed.port == default_parsed.port + ) + if raw_caller_url and not same_trusted_origin: + effective_key = clean_caller_key + else: + effective_key = clean_caller_key or env_openrouter_key + + return effective_url, effective_key + + +# --------------------------------------------------------------------------- +# FastAPI Router (`/quick_pp/demo/*`) +# --------------------------------------------------------------------------- + +router = APIRouter(prefix="/demo", tags=["Live Demo Telemetry & Session"]) + + +class DemoHeartbeatRequest(BaseModel): + session_id: Optional[str] = Field( + None, + description="Client tab session identifier (falls back to X-Demo-Session-Id header)", + ) + + +def _extract_client_ip(request: Request) -> str: + return ( + request.headers.get("cf-connecting-ip") + or request.headers.get("x-real-ip") + or (request.client.host if request.client else "") + or "" + ).strip() + + +@router.get("/status", summary="Get live demo online user count and capacity status") +def api_demo_status(request: Request): + sid = request.headers.get(DEMO_SESSION_HEADER) + return get_demo_status_snapshot(session_id=sid) + + +@router.post("/heartbeat", summary="Register or refresh active demo browser session") +def api_demo_heartbeat( + request: Request, + payload: Optional[DemoHeartbeatRequest] = None, +): + sid = ( + payload.session_id if payload and payload.session_id else None + ) or request.headers.get(DEMO_SESSION_HEADER) + if not is_demo_mode(): + return get_demo_status_snapshot(session_id=sid) + return register_or_touch_session( + session_id=sid, + client_ip=_extract_client_ip(request), + ) + + +@router.post( + "/leave", + summary="Release active demo browser session and clean up session artifacts", +) +async def api_demo_leave(request: Request): + sid = request.headers.get(DEMO_SESSION_HEADER) + if not sid: + try: + raw = await request.body() + if raw: + import json + + body = json.loads(raw.decode("utf-8")) + if isinstance(body, dict): + sid = body.get("session_id") + except Exception: + pass + return leave_session(session_id=sid) diff --git a/quick_pp/app/backend/services/fpt.py b/quick_pp/app/backend/services/fpt.py index 2217d462..eb9ded0c 100644 --- a/quick_pp/app/backend/services/fpt.py +++ b/quick_pp/app/backend/services/fpt.py @@ -10,7 +10,7 @@ requested display units (psi | bar | kPa, m | ft). """ -from typing import Any, Dict, List, Literal, Optional +from typing import Any, Dict, List, Literal, Optional, Tuple import numpy as np import pandas as pd @@ -57,10 +57,12 @@ class ManualGradientOverride(BaseModel): None, description="Alternative to `gradient`: fixed in-situ density (g/cc)" ) anchor_tvdss: Optional[float] = Field( - None, description="Anchor TVDSS (display depth unit) for a manual / regional line" + None, + description="Anchor TVDSS (display depth unit) for a manual / regional line", ) anchor_pressure: Optional[float] = Field( - None, description="Anchor pressure (display pressure unit) for a manual / regional line" + None, + description="Anchor pressure (display pressure unit) for a manual / regional line", ) std_err_gradient: Optional[float] = Field(0.0, ge=0.0) @@ -75,7 +77,9 @@ class PointOverride(BaseModel): class AutoClassifyOptions(BaseModel): """Configuration options for automatic mobility/supercharge quality flagging and phase clustering.""" - min_mobility: Optional[float] = Field(None, description="Flag TIGHT below this mobility (mD/cP)") + min_mobility: Optional[float] = Field( + None, description="Flag TIGHT below this mobility (mD/cP)" + ) ransac_residual_threshold: Optional[float] = Field( None, description="Supercharge threshold (display pressure unit); 0 = automatic (2.5 x MAD)", @@ -149,6 +153,85 @@ def _zone_for_md(md: float, tops: List[Dict[str, Any]]) -> str: return zone +def _resolve_fpt_point_zone( + md: float, + stored_zone: Optional[str], + well_df: Optional[pd.DataFrame], + tops: List[Dict[str, Any]], +) -> Tuple[str, str]: + """Resolve geological zone for a formation pressure test point with fallback and unit alignment. + + Priority: + 1. Explicit stored zone on the pressure test record (if non-empty). + 2. Continuous ZONES curve in well_df at the nearest depth sample (with unit scale check). + 3. Formation tops intervals (with unit scale check). + """ + if stored_zone and str(stored_zone).strip(): + z_str = str(stored_zone).strip() + if z_str.lower() not in ("nan", "none", "unknown", "unzoned"): + return z_str, "stored" + + # 1. Try well_df continuous ZONES curve + if ( + well_df is not None + and not well_df.empty + and "DEPTH" in well_df.columns + and "ZONES" in well_df.columns + ): + try: + w_depths = pd.to_numeric(well_df["DEPTH"], errors="coerce") + valid_d = w_depths.dropna() + if not valid_d.empty: + med_w = float(valid_d.median()) + target_md = float(md) + if med_w > 0: + ratio = target_md / med_w + if 2.8 < ratio < 3.6: # md in ft, well_df in m + target_md *= 0.3048 + elif 0.27 < ratio < 0.35: # md in m, well_df in ft + target_md /= 0.3048 + + diff = (w_depths - target_md).abs() + idx_near = diff.idxmin() + if pd.notna(idx_near): + span = abs(float(valid_d.iloc[-1] - valid_d.iloc[0])) + tol = max(5.0, span * 0.05) if span > 0 else 5.0 + if float(diff.loc[idx_near]) <= tol: + z_val = well_df.loc[idx_near, "ZONES"] + if pd.notna(z_val): + z_str = str(z_val).strip() + if z_str and z_str.lower() not in ( + "nan", + "none", + "unknown", + "unzoned", + ): + return z_str, "well_logs" + except Exception: + pass + + # 2. Fallback to tops with unit scale alignment + if tops: + try: + top_depths = [float(t["depth"]) for t in tops if t.get("depth") is not None] + target_md = float(md) + if top_depths: + med_t = float(np.median(top_depths)) + if med_t > 0: + ratio = target_md / med_t + if 2.8 < ratio < 3.6: # md in ft, tops in m + target_md *= 0.3048 + elif 0.27 < ratio < 0.35: # md in m, tops in ft + target_md /= 0.3048 + resolved = _zone_for_md(target_md, tops) + if resolved: + return resolved, "tops" + except Exception: + pass + + return "", "missing" + + def _collect_fpt_points( project_id: int, well_names: Optional[List[str]] = None ) -> List[Dict[str, Any]]: @@ -196,6 +279,16 @@ def _collect_fpt_points( except Exception: tvd_arr = np.full(len(md_arr), np.nan) + w_uom = ( + getattr(well, "depth_uom", None) + or getattr(getattr(well, "_orm_well", None), "depth_uom", None) + or "m" + ) + is_well_ft = isinstance(w_uom, str) and w_uom.strip().lower() in ( + "ft", + "feet", + ) + for i, row in enumerate(ptdf.to_dict(orient="records")): override = row.get("tvdss") if override is not None and np.isfinite(float(override)): @@ -205,6 +298,26 @@ def _collect_fpt_points( else: tvdss, src = None, "missing" md = float(row["depth"]) + + # Storage contract: psi & metres. Normalize MD and TVDSS to metres. + # 1. If well is explicitly imperial (depth_uom = ft): + if is_well_ft and md > 1000: + md *= 0.3048 + if tvdss is not None: + tvdss *= 0.3048 + + # 2. Physics & unit mismatch check: TVDSS <= MD. + # If TVDSS is ~3.28x MD (or MD is ~3.28x TVDSS), one is in feet and one in metres. + if tvdss is not None and md > 0: + ratio = tvdss / md + if 2.5 < ratio < 3.8: # TVDSS in ft, MD in m + tvdss *= 0.3048 + elif 0.27 < ratio < 0.37 and md > 3500: # MD in ft, TVDSS in m + md *= 0.3048 + + z_name, z_src = _resolve_fpt_point_zone( + md, row.get("zone"), well_df, tops + ) points.append( { "id": int(row["test_id"]), @@ -218,8 +331,8 @@ def _collect_fpt_points( "temperature": row.get("temperature"), "fluid_type": row.get("fluid_type") or "UNASSIGNED", "test_quality": row.get("test_quality") or "VALID", - "zone": (row.get("zone") or "").strip() or _zone_for_md(md, tops), - "zone_source": "stored" if (row.get("zone") or "").strip() else "tops", + "zone": z_name, + "zone_source": z_src, "remarks": row.get("remarks") or "", } ) @@ -229,14 +342,21 @@ def _collect_fpt_points( # --------------------------------------------------------------------------- # Endpoints # --------------------------------------------------------------------------- -@router.get("/points", summary="List formation pressure points across wells with resolved TVDSS") +@router.get( + "/points", summary="List formation pressure points across wells with resolved TVDSS" +) def fpt_list_points( project_id: int, well_names: Optional[str] = Query(None, description="Comma-separated well names"), ) -> Dict[str, Any]: """List formation pressure points across wells in a project with resolved TVDSS and zone.""" try: - wn_list = [w.strip() for w in well_names.split(",")] if well_names else None + if isinstance(well_names, str): + wn_list = [w.strip() for w in well_names.split(",") if w.strip()] + elif isinstance(well_names, (list, tuple, set)): + wn_list = [str(w).strip() for w in well_names if str(w).strip()] + else: + wn_list = None pts = _collect_fpt_points(project_id, wn_list) return _sanitize_for_json( { @@ -251,7 +371,29 @@ def fpt_list_points( except ValueError as e: raise HTTPException(status_code=404, detail=str(e)) from e except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to list FPT points: {e}") from e + raise HTTPException( + status_code=500, detail=f"Failed to list FPT points: {e}" + ) from e + + +def _find_zone_override( + overrides_by_zone: Optional[Dict[str, Any]], z_name: str +) -> Optional[Any]: + """Resolve zone manual overrides case-insensitively with alias support.""" + if not overrides_by_zone or not z_name: + return None + if z_name in overrides_by_zone: + return overrides_by_zone[z_name] + z_clean = z_name.strip().upper() + for k, v in overrides_by_zone.items(): + if k and k.strip().upper() == z_clean: + return v + for k, v in overrides_by_zone.items(): + if k: + k_clean = k.strip().upper() + if k_clean in z_clean or z_clean in k_clean: + return v + return None def _analyze_subset( @@ -265,7 +407,9 @@ def _analyze_subset( { "ID": [p["id"] for p in pts_sub], "WELL_NAME": [p["well_name"] for p in pts_sub], - "TVDSS": [p["tvdss"] * df_ if p["tvdss"] is not None else np.nan for p in pts_sub], + "TVDSS": [ + p["tvdss"] * df_ if p["tvdss"] is not None else np.nan for p in pts_sub + ], "PRESSURE": [p["pressure"] * pf for p in pts_sub], "FLUID_TYPE": [p["fluid_type"] for p in pts_sub], "TEST_QUALITY": [p["test_quality"] for p in pts_sub], @@ -296,7 +440,9 @@ def _analyze_subset( continue grad = ov.gradient if grad is None and ov.density_gcc is not None: - grad = density_to_gradient(ov.density_gcc, req.pressure_unit, req.depth_unit) + grad = density_to_gradient( + ov.density_gcc, req.pressure_unit, req.depth_unit + ) if grad is None: continue ov_dict[fl.upper()] = { @@ -305,8 +451,12 @@ def _analyze_subset( "anchor_pressure": ov.anchor_pressure, "std_err_gradient": ov.std_err_gradient or 0.0, } - fpa.fit_all(method=req.regression_method, overrides=ov_dict, allowed_fluids=allowed_fluids) - contacts = fpa.estimate_contacts(n_simulations=req.n_simulations, allowed_fluids=allowed_fluids) + fpa.fit_all( + method=req.regression_method, overrides=ov_dict, allowed_fluids=allowed_fluids + ) + contacts = fpa.estimate_contacts( + n_simulations=req.n_simulations, allowed_fluids=allowed_fluids + ) excess = fpa.calculate_excess_pressure( req.ref_water_gradient, req.datum_tvdss, req.datum_pressure ) @@ -347,7 +497,9 @@ def _analyze_subset( "plot_lines": plot_lines, "reference": { "gradient": m_ref, - "density_gcc": gradient_to_density(m_ref, req.pressure_unit, req.depth_unit), + "density_gcc": gradient_to_density( + m_ref, req.pressure_unit, req.depth_unit + ), "datum_tvdss": z0, "datum_pressure": p0, }, @@ -357,16 +509,38 @@ def _analyze_subset( } -@router.post("/analyze", summary="Fit fluid gradients and estimate contacts with P10/P50/P90 uncertainty") +@router.post( + "/analyze", + summary="Fit fluid gradients and estimate contacts with P10/P50/P90 uncertainty", +) def fpt_analyze(project_id: int, req: FPTAnalysisRequest) -> Dict[str, Any]: """Run fluid gradient regression, fluid contact intersection, and excess pressure analysis.""" try: pts = _collect_fpt_points(project_id, req.well_names) if req.zones: - allowed_z = {z.strip() for z in req.zones if z and z.strip()} - pts = [p for p in pts if p["zone"] in allowed_z] + allowed_z_raw = {str(z).strip() for z in req.zones if z and str(z).strip()} + allowed_z_upper = {z.upper() for z in allowed_z_raw} + + def _matches_zone(z_name: str) -> bool: + if not z_name: + return False + z_clean = z_name.strip() + if z_clean in allowed_z_raw: + return True + z_up = z_clean.upper() + if z_up in allowed_z_upper: + return True + # Check sub-formation / alias matches (e.g. 'FULMAR SAND' matching 'FULMAR') + for az in allowed_z_upper: + if az in z_up or z_up in az: + return True + return False + + pts = [p for p in pts if _matches_zone(p.get("zone") or "")] if not pts: - raise ValueError("No formation pressure points found for the selected wells / zones.") + raise ValueError( + "No formation pressure points found for the selected wells / zones." + ) overrides = req.point_overrides or {} for p in pts: @@ -384,11 +558,18 @@ def fpt_analyze(project_id: int, req: FPTAnalysisRequest) -> Dict[str, Any]: # Group points by zone (or 'Unzoned' if empty) zone_pts_map: Dict[str, List[Dict[str, Any]]] = {} for p in pts: - z_name = p["zone"].strip() if (p.get("zone") and str(p["zone"]).strip()) else "Unzoned" + z_name = ( + p["zone"].strip() + if (p.get("zone") and str(p["zone"]).strip()) + else "Unzoned" + ) zone_pts_map.setdefault(z_name, []).append(p) for z_name, z_pts in zone_pts_map.items(): - z_ov = (req.overrides_by_zone or {}).get(z_name) or req.manual_overrides + z_ov = ( + _find_zone_override(req.overrides_by_zone, z_name) + or req.manual_overrides + ) sub_res = _analyze_subset(z_pts, req, overrides=z_ov) by_zone_res[z_name] = { "gradients": sub_res["gradients"], @@ -404,15 +585,36 @@ def fpt_analyze(project_id: int, req: FPTAnalysisRequest) -> Dict[str, Any]: excess = sub_res["excess"] for i, p in enumerate(z_pts): row = fpa_df.iloc[i] - p["tvdss_display"] = None if pd.isna(row["TVDSS"]) else float(row["TVDSS"]) + p["tvdss_display"] = ( + None if pd.isna(row["TVDSS"]) else float(row["TVDSS"]) + ) p["pressure_display"] = float(row["PRESSURE"]) p["fluid_type"] = row["FLUID_TYPE"] p["test_quality"] = row["TEST_QUALITY"] - p["excess_pressure"] = None if pd.isna(excess.iloc[i]) else float(excess.iloc[i]) - p["used_in_fit"] = any(p["id"] in g.point_ids for g in fpa_grads.values()) + p["excess_pressure"] = ( + None if pd.isna(excess.iloc[i]) else float(excess.iloc[i]) + ) + p["used_in_fit"] = any( + p["id"] in g.point_ids for g in fpa_grads.values() + ) available_zones = sorted(by_zone_res.keys()) - active = req.active_zone if (req.active_zone and req.active_zone in by_zone_res) else ("ALL" if len(available_zones) > 1 else available_zones[0]) + active = "ALL" + if req.active_zone and req.active_zone != "ALL": + matched_key = next( + ( + k + for k in by_zone_res + if k.strip().upper() == req.active_zone.strip().upper() + ), + None, + ) + if matched_key: + active = matched_key + elif len(available_zones) == 1: + active = available_zones[0] + elif len(available_zones) == 1: + active = available_zones[0] if active in by_zone_res: top_gradients = by_zone_res[active]["gradients"] @@ -427,13 +629,26 @@ def fpt_analyze(project_id: int, req: FPTAnalysisRequest) -> Dict[str, Any]: for w in zr["warnings"]: top_warnings.append(f"[{z_name}] {w}") # For top-level fallback, use the zone with the most points - largest_z = max(by_zone_res.keys(), key=lambda k: by_zone_res[k]["n_points"]) if by_zone_res else None + largest_z = ( + max(by_zone_res.keys(), key=lambda k: by_zone_res[k]["n_points"]) + if by_zone_res + else None + ) top_gradients = by_zone_res[largest_z]["gradients"] if largest_z else {} top_contacts = by_zone_res[largest_z]["contacts"] if largest_z else {} - top_plot_lines = by_zone_res[largest_z]["plot_lines"] if largest_z else {} - top_reference = by_zone_res[largest_z]["reference"] if largest_z else { - "gradient": 0.0, "density_gcc": 1.0, "datum_tvdss": 0.0, "datum_pressure": 0.0 - } + top_plot_lines = ( + by_zone_res[largest_z]["plot_lines"] if largest_z else {} + ) + top_reference = ( + by_zone_res[largest_z]["reference"] + if largest_z + else { + "gradient": 0.0, + "density_gcc": 1.0, + "datum_tvdss": 0.0, + "datum_pressure": 0.0, + } + ) else: # Fit globally across all points sub_res = _analyze_subset(pts, req, overrides=req.manual_overrides) @@ -442,12 +657,18 @@ def fpt_analyze(project_id: int, req: FPTAnalysisRequest) -> Dict[str, Any]: excess = sub_res["excess"] for i, p in enumerate(pts): row = fpa_df.iloc[i] - p["tvdss_display"] = None if pd.isna(row["TVDSS"]) else float(row["TVDSS"]) + p["tvdss_display"] = ( + None if pd.isna(row["TVDSS"]) else float(row["TVDSS"]) + ) p["pressure_display"] = float(row["PRESSURE"]) p["fluid_type"] = row["FLUID_TYPE"] p["test_quality"] = row["TEST_QUALITY"] - p["excess_pressure"] = None if pd.isna(excess.iloc[i]) else float(excess.iloc[i]) - p["used_in_fit"] = any(p["id"] in g.point_ids for g in fpa_grads.values()) + p["excess_pressure"] = ( + None if pd.isna(excess.iloc[i]) else float(excess.iloc[i]) + ) + p["used_in_fit"] = any( + p["id"] in g.point_ids for g in fpa_grads.values() + ) top_gradients = sub_res["gradients"] top_contacts = sub_res["contacts"] @@ -492,7 +713,10 @@ def fpt_analyze(project_id: int, req: FPTAnalysisRequest) -> Dict[str, Any]: raise HTTPException(status_code=500, detail=f"FPT analysis failed: {e}") from e -@router.patch("/points", summary="Persist fluid phase / test quality / zone assignments for pressure points") +@router.patch( + "/points", + summary="Persist fluid phase / test quality / zone assignments for pressure points", +) def fpt_patch_points(project_id: int, req: FPTPointsPatchRequest) -> Dict[str, Any]: """Persist fluid phase, test quality, zone, or TVDSS overrides for pressure points.""" if not req.updates: @@ -501,7 +725,9 @@ def fpt_patch_points(project_id: int, req: FPTPointsPatchRequest) -> Dict[str, A by_well: Dict[str, List[Dict[str, Any]]] = {} for u in req.updates: fields = u.fields or [ - f for f in ("fluid_type", "test_quality", "zone", "tvdss") if getattr(u, f) is not None + f + for f in ("fluid_type", "test_quality", "zone", "tvdss") + if getattr(u, f) is not None ] payload: Dict[str, Any] = {"test_id": u.test_id} for f in fields: @@ -521,7 +747,9 @@ def fpt_patch_points(project_id: int, req: FPTPointsPatchRequest) -> Dict[str, A except ValueError as e: raise HTTPException(status_code=404, detail=str(e)) from e except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to update FPT points: {e}") from e + raise HTTPException( + status_code=500, detail=f"Failed to update FPT points: {e}" + ) from e @router.post( @@ -551,17 +779,30 @@ def fpt_apply_contacts(project_id: int, req: FPTApplyContactsRequest) -> Dict[st surveys_df = None wdf = _get_merged_dataframe_sync(project_id, wn) if wdf is None or wdf.empty or "DEPTH" not in wdf.columns: - results.append({"well_name": wn, "written": {}, "skipped": "no depth data"}) + results.append( + {"well_name": wn, "written": {}, "skipped": "no depth data"} + ) continue - md = np.sort(pd.to_numeric(wdf["DEPTH"], errors="coerce").dropna().unique()) + md = np.sort( + pd.to_numeric(wdf["DEPTH"], errors="coerce").dropna().unique() + ) tvd = _resolve_well_tvd_array(md, wdf, surveys_df) ok = np.isfinite(tvd) if ok.sum() < 2: - results.append({"well_name": wn, "written": {}, "skipped": "no TVD/TVDSS"}) + results.append( + {"well_name": wn, "written": {}, "skipped": "no TVD/TVDSS"} + ) continue md_ok, tvd_ok = md[ok], tvd[ok] + if len(tvd_ok) > 0 and len(md_ok) > 0: + med_tvd = float(np.median(tvd_ok)) + med_md = float(np.median(md_ok)) + if med_md > 0 and med_tvd > 0 and 2.5 < (med_tvd / med_md) < 3.8: + tvd_ok = tvd_ok * 0.3048 # Keep monotonic TVDSS branch for inversion (ignore horizontal / up-dip sections) - mono = np.concatenate([[True], np.diff(np.maximum.accumulate(tvd_ok)) > 1e-6]) + mono = np.concatenate( + [[True], np.diff(np.maximum.accumulate(tvd_ok)) > 1e-6] + ) md_ok, tvd_ok = md_ok[mono], tvd_ok[mono] written: Dict[str, float] = {} outside: List[str] = [] @@ -569,13 +810,15 @@ def fpt_apply_contacts(project_id: int, req: FPTApplyContactsRequest) -> Dict[st for name, z in contacts.items(): if tvd_ok[0] <= z <= tvd_ok[-1]: md_c = float(np.interp(z, tvd_ok, md_ok)) - payload.append({ - "name": name, - "depth": round(md_c, 3), - "contact_type": name, - "source": "FPT Analysis", - "remarks": "Formation Pressure Test gradient intersection", - }) + payload.append( + { + "name": name, + "depth": round(md_c, 3), + "contact_type": name, + "source": "FPT Analysis", + "remarks": "Formation Pressure Test gradient intersection", + } + ) written[name] = round(md_c, 3) else: outside.append(name) @@ -602,4 +845,6 @@ def fpt_apply_contacts(project_id: int, req: FPTApplyContactsRequest) -> Dict[st except ValueError as e: raise HTTPException(status_code=404, detail=str(e)) from e except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to apply contacts: {e}") from e + raise HTTPException( + status_code=500, detail=f"Failed to apply contacts: {e}" + ) from e diff --git a/quick_pp/app/backend/services/las_handler.py b/quick_pp/app/backend/services/las_handler.py index 5276000c..2ebd4372 100644 --- a/quick_pp/app/backend/services/las_handler.py +++ b/quick_pp/app/backend/services/las_handler.py @@ -133,7 +133,9 @@ def _inspect_single_log_file_worker( if ext == ".parquet": df_pq = pd.read_parquet(p) - raw_cols = [str(c) for c in df_pq.columns if str(c).upper() not in ("WELL_NAME", "UWI")] + raw_cols = [ + str(c) for c in df_pq.columns if str(c).upper() not in ("WELL_NAME", "UWI") + ] col_map = mnemonic_mapper(raw_cols) w_name = ( str(df_pq["WELL_NAME"].dropna().iloc[0]) @@ -146,7 +148,9 @@ def _inspect_single_log_file_worker( raw_mnemonic=c, target_mnemonic=col_map.get(c, c.upper()), raw_unit="", - target_unit=Config.VARS.get(col_map.get(c, c.upper()), {}).get("unit", ""), + target_unit=Config.VARS.get(col_map.get(c, c.upper()), {}).get( + "unit", "" + ), include=True, ) for c in raw_cols @@ -188,10 +192,21 @@ def _inspect_single_log_file_worker( target_u = raw_u auto_conv = None u_up = raw_u.upper() - if target_m in ("DEPTH", "TVD", "TVDSS") and u_up in ("FT", "F", "FEET", "0.1 IN", "0.1IN"): + if target_m in ("DEPTH", "TVD", "TVDSS") and u_up in ( + "FT", + "F", + "FEET", + "0.1 IN", + "0.1IN", + ): target_u = "m" auto_conv = f"{raw_u} -> m" - elif target_m in ("NPHI", "PHIT", "PHIE", "CPORE", "CPOR") and u_up in ("%", "PU", "P.U.", "PCT"): + elif target_m in ("NPHI", "PHIT", "PHIE", "CPORE", "CPOR") and u_up in ( + "%", + "PU", + "P.U.", + "PCT", + ): target_u = "v/v" auto_conv = f"{raw_u} -> v/v" elif target_m == "RHOB" and u_up in ("KG/M3", "KGM3"): @@ -216,7 +231,9 @@ def _inspect_single_log_file_worker( ) if meta.step is not None and meta.step <= 0: - qaqc_warnings.append("Non-uniform or zero STEP detected in LAS header; regularization recommended.") + qaqc_warnings.append( + "Non-uniform or zero STEP detected in LAS header; regularization recommended." + ) elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 2) return LogInspectFileResult( @@ -279,13 +296,21 @@ def _parse_single_log_file_worker(task_spec: Dict[str, Any]) -> Dict[str, Any]: std_units.update(s_units) df = ( - splice_and_regularize_runs(frame_dfs, step=0.1524, conflict_mode="keep_last") + splice_and_regularize_runs( + frame_dfs, step=0.1524, conflict_mode="keep_last" + ) if len(frame_dfs) > 1 else (frame_dfs[0] if frame_dfs else pd.DataFrame()) ) header_df = pd.DataFrame( [ - {"section": "Well", "mnemonic": k.upper(), "unit": "", "value": v, "descr": k} + { + "section": "Well", + "mnemonic": k.upper(), + "unit": "", + "value": v, + "descr": k, + } for k, v in meta_dict.items() if not isinstance(v, (dict, list)) and v is not None ] @@ -312,17 +337,27 @@ def _parse_single_log_file_worker(task_spec: Dict[str, Any]) -> Dict[str, Any]: filename=original_filename, ) frame_dfs.append(frame_df) - meta_dict.update({key: value for key, value in frame_meta.items() if value is not None}) + meta_dict.update( + {key: value for key, value in frame_meta.items() if value is not None} + ) std_units.update(frame_units) df = ( - splice_and_regularize_runs(frame_dfs, step=0.1524, conflict_mode="keep_last") + splice_and_regularize_runs( + frame_dfs, step=0.1524, conflict_mode="keep_last" + ) if len(frame_dfs) > 1 else (frame_dfs[0] if frame_dfs else pd.DataFrame()) ) header_df = pd.DataFrame( [ - {"section": "Well", "mnemonic": key.upper(), "unit": "", "value": value, "descr": key} + { + "section": "Well", + "mnemonic": key.upper(), + "unit": "", + "value": value, + "descr": key, + } for key, value in meta_dict.items() if not isinstance(value, (dict, list)) and value is not None ] @@ -342,7 +377,15 @@ def _parse_single_log_file_worker(task_spec: Dict[str, Any]) -> Dict[str, Any]: ) meta_dict = WellHeaderMetadata(well_name=w_name, uwi=w_name).model_dump() header_df = pd.DataFrame( - [{"section": "Well", "mnemonic": "WELL", "unit": "", "value": w_name, "descr": "WELL"}] + [ + { + "section": "Well", + "mnemonic": "WELL", + "unit": "", + "value": w_name, + "descr": "WELL", + } + ] ) else: # LAS 2.0 / 3.0 fast hybrid parser @@ -364,12 +407,24 @@ def _parse_single_log_file_worker(task_spec: Dict[str, Any]) -> Dict[str, Any]: first_col = str(raw_df.columns[0]).strip().upper() if first_col != index_mnemonic: raw_units[first_col] = raw_units.get(index_mnemonic, "") - custom_upper = {str(k).strip().upper(): v for k, v in custom_mnemonic_map.items()} + custom_upper = { + str(k).strip().upper(): v for k, v in custom_mnemonic_map.items() + } if index_mnemonic in custom_upper: - custom_mnemonic_map = {**custom_mnemonic_map, first_col: custom_upper[index_mnemonic]} + custom_mnemonic_map = { + **custom_mnemonic_map, + first_col: custom_upper[index_mnemonic], + } # Ensure first curve is mapped to DEPTH if it's the index curve - if first_col not in custom_mnemonic_map and Config.resolve_mnemonic_alias(first_col) == "DEPTH": - custom_mnemonic_map = {"DEPTH": "DEPTH", first_col: "DEPTH", **custom_mnemonic_map} + if ( + first_col not in custom_mnemonic_map + and Config.resolve_mnemonic_alias(first_col) == "DEPTH" + ): + custom_mnemonic_map = { + "DEPTH": "DEPTH", + first_col: "DEPTH", + **custom_mnemonic_map, + } df, std_units, _ = standardize_curve_units( raw_df, @@ -381,7 +436,9 @@ def _parse_single_log_file_worker(task_spec: Dict[str, Any]) -> Dict[str, Any]: if first_col != index_mnemonic: for entry in curve_lineage: if entry["source_mnemonic"].upper() == first_col: - entry["source_mnemonic"] = str(las_header.curves[0].mnemonic).strip() + entry["source_mnemonic"] = str( + las_header.curves[0].mnemonic + ).strip() break header_df = _las_header_to_dataframe(las_header) @@ -394,27 +451,54 @@ def _parse_single_log_file_worker(task_spec: Dict[str, Any]) -> Dict[str, Any]: for idx_r, r in core_df.iterrows(): d_v = pd.to_numeric(r.get(d_col), errors="coerce") if pd.notna(d_v): - por_c = c_cols.get("CPOR") or c_cols.get("CPORE") or c_cols.get("POR") - perm_c = c_cols.get("CKHG") or c_cols.get("CPERM") or c_cols.get("PERM") - por_v = pd.to_numeric(r.get(por_c), errors="coerce") if por_c else np.nan + por_c = ( + c_cols.get("CPOR") + or c_cols.get("CPORE") + or c_cols.get("POR") + ) + perm_c = ( + c_cols.get("CKHG") + or c_cols.get("CPERM") + or c_cols.get("PERM") + ) + por_v = ( + pd.to_numeric(r.get(por_c), errors="coerce") + if por_c + else np.nan + ) if pd.notna(por_v) and por_v > 1.5: por_v = por_v / 100.0 - perm_v = pd.to_numeric(r.get(perm_c), errors="coerce") if perm_c else np.nan - sname_c = c_cols.get("SAMPLE") or c_cols.get("SAMPLE_ID") or c_cols.get("SAMPLE_NAME") + perm_v = ( + pd.to_numeric(r.get(perm_c), errors="coerce") + if perm_c + else np.nan + ) + sname_c = ( + c_cols.get("SAMPLE") + or c_cols.get("SAMPLE_ID") + or c_cols.get("SAMPLE_NAME") + ) sname = str(r.get(sname_c) if sname_c else f"LAS3-{idx_r + 1}") embedded_core_rows.append( { "sample_name": sname, "depth": float(d_v), "porosity": float(por_v) if pd.notna(por_v) else None, - "permeability": float(perm_v) if pd.notna(perm_v) else None, + "permeability": float(perm_v) + if pd.notna(perm_v) + else None, } ) tops_df = getattr(las_header, "_las3_tops_df", pd.DataFrame()) if isinstance(tops_df, pd.DataFrame) and not tops_df.empty: t_cols = {str(c).upper(): c for c in tops_df.columns} - n_col = t_cols.get("TOP") or t_cols.get("TOP_NAME") or t_cols.get("NAME") or t_cols.get("ZONE") + n_col = ( + t_cols.get("TOP") + or t_cols.get("TOP_NAME") + or t_cols.get("NAME") + or t_cols.get("ZONE") + ) d_col = t_cols.get("DEPTH") or t_cols.get("MD") or t_cols.get("DEPT") if n_col and d_col: for _, r in tops_df.iterrows(): @@ -433,23 +517,21 @@ def _parse_single_log_file_worker(task_spec: Dict[str, Any]) -> Dict[str, Any]: .replace("/", "-") .replace(" ", "-") ) - uwi = ( - str(meta_dict.get("uwi") or well_name) - .replace("/", "-") - .replace(" ", "-") - ) + uwi = str(meta_dict.get("uwi") or well_name).replace("/", "-").replace(" ", "-") meta_dict["well_name"] = well_name meta_dict["uwi"] = uwi # Drop excluded curves (never drop DEPTH) if excluded_curves: excluded_targets = { - entry["stored_curve"] for entry in curve_lineage + entry["stored_curve"] + for entry in curve_lineage if entry["source_mnemonic"].upper() in excluded_curves or entry["stored_curve"].upper() in excluded_curves } retained_targets = { - entry["stored_curve"] for entry in curve_lineage + entry["stored_curve"] + for entry in curve_lineage if entry["source_mnemonic"].upper() not in excluded_curves and entry["stored_curve"].upper() not in excluded_curves } @@ -461,11 +543,14 @@ def _parse_single_log_file_worker(task_spec: Dict[str, Any]) -> Dict[str, Any]: if entry["raw_curve"]: df = df.drop(columns=[entry["raw_curve"]], errors="ignore") df = df.drop( - columns=[c for c in excluded_targets - retained_targets if c.upper() != "DEPTH"], + columns=[ + c for c in excluded_targets - retained_targets if c.upper() != "DEPTH" + ], errors="ignore", ) curve_lineage = [ - entry for entry in curve_lineage + entry + for entry in curve_lineage if entry["stored_curve"].upper() == "DEPTH" or ( entry["source_mnemonic"].upper() not in excluded_curves @@ -522,9 +607,7 @@ async def _run_tasks_in_pool(worker_fn, task_args_list: List[Any]) -> List[Any]: max_workers = min(os.cpu_count() or 4, 8, len(task_args_list)) loop = asyncio.get_running_loop() with ThreadPoolExecutor(max_workers=max_workers) as pool: - tasks = [ - loop.run_in_executor(pool, worker_fn, arg) for arg in task_args_list - ] + tasks = [loop.run_in_executor(pool, worker_fn, arg) for arg in task_args_list] return list(await asyncio.gather(*tasks)) @@ -558,6 +641,11 @@ async def inspect_log_files(files: List[UploadFile] = File(...)) -> LogInspectRe detail=f"File '{safe_name}' exceeds 5.0 MB demo upload limit.", ) + from quick_pp.app.backend.services.demo_guard import ( + enforce_upload_storage_limits, + get_current_demo_session_id, + ) + fid = uuid4().hex[:12] staged_path = STAGING_DIR / f"{fid}_{safe_name}" save_upload_file(f, staged_path) @@ -566,7 +654,10 @@ async def inspect_log_files(files: List[UploadFile] = File(...)) -> LogInspectRe "path": str(staged_path), "filename": orig_name, "created_at": time.time(), + "demo_session_id": get_current_demo_session_id(), } + if is_demo_mode(): + enforce_upload_storage_limits() try: inspected_dict = _inspect_single_log_file_worker( @@ -612,22 +703,44 @@ async def commit_log_files(request: Request) -> Dict[str, Any]: form = await request.form() raw_json = form.get("commit_request_json") if not raw_json: - raise HTTPException(status_code=400, detail="Missing commit_request_json in form data") + raise HTTPException( + status_code=400, detail="Missing commit_request_json in form data" + ) payload = LogCommitRequest(**json.loads(str(raw_json))) STAGING_DIR.mkdir(parents=True, exist_ok=True) + from quick_pp.app.backend.services.demo_guard import ( + enforce_upload_storage_limits, + get_current_demo_session_id, + ) + for item in form.getlist("files"): if hasattr(item, "filename") and hasattr(item, "file"): orig_name = str(item.filename or "upload.las") + validate_file_extension(orig_name) + safe_item_name = sanitize_filename(orig_name) + if is_demo_mode(): + item.file.seek(0, 2) + fsize = item.file.tell() + item.file.seek(0) + if fsize > MAX_DEMO_UPLOAD_BYTES: + item.file.close() + raise HTTPException( + status_code=413, + detail=f"File '{safe_item_name}' exceeds 5.0 MB demo upload limit.", + ) fid = uuid4().hex[:12] - staged_path = STAGING_DIR / f"{fid}_{sanitize_filename(orig_name)}" + staged_path = STAGING_DIR / f"{fid}_{safe_item_name}" save_upload_file(item, staged_path) _STAGED_FILES[fid] = { "file_id": fid, "path": str(staged_path), "filename": orig_name, "created_at": time.time(), + "demo_session_id": get_current_demo_session_id(), } uploaded_by_name[orig_name] = fid + if is_demo_mode(): + enforce_upload_storage_limits() else: body_dict = await request.json() payload = LogCommitRequest(**body_dict) @@ -638,7 +751,9 @@ async def commit_log_files(request: Request) -> Dict[str, Any]: splicing_mode = payload.splice_overlap_mode or payload.splicing_mode or "keep_last" task_specs: List[Dict[str, Any]] = [] for f_cfg in payload.files: - fid_lookup = f_cfg.file_id or (uploaded_by_name.get(f_cfg.filename or "") if f_cfg.filename else None) + fid_lookup = f_cfg.file_id or ( + uploaded_by_name.get(f_cfg.filename or "") if f_cfg.filename else None + ) staged = _STAGED_FILES.get(fid_lookup) if fid_lookup else None file_path_str: Optional[str] = None orig_filename = f_cfg.filename or f_cfg.file_id or "upload.las" @@ -687,7 +802,9 @@ async def commit_log_files(request: Request) -> Dict[str, Any]: t0 = time.perf_counter() try: - parsed_results = await _run_tasks_in_pool(_parse_single_log_file_worker, task_specs) + parsed_results = await _run_tasks_in_pool( + _parse_single_log_file_worker, task_specs + ) except Exception as e: raise HTTPException( status_code=500, detail=f"Parallel log ingestion failed: {e}" @@ -782,12 +899,18 @@ def _commit_wells_to_db_sync() -> List[Dict[str, Any]]: ) resolved = step_summary.get("resolved_curves", {}) for entry in r.get("curve_lineage", []): - lineage.append({ - **entry, - "filename": r["filename"], - "stored_curve": resolved.get(entry["stored_curve"], entry["stored_curve"]), - "raw_curve": resolved.get(entry["raw_curve"], entry["raw_curve"]), - }) + lineage.append( + { + **entry, + "filename": r["filename"], + "stored_curve": resolved.get( + entry["stored_curve"], entry["stored_curve"] + ), + "raw_curve": resolved.get( + entry["raw_curve"], entry["raw_curve"] + ), + } + ) batch_appended.extend(step_summary.get("appended_curves", [])) if idx > 0: batch_skipped.extend(step_summary.get("skipped_curves", [])) @@ -831,8 +954,12 @@ def _commit_wells_to_db_sync() -> List[Dict[str, Any]]: final_renamed.update(demo_summary.get("renamed_curves", {})) resolved = demo_summary.get("resolved_curves", {}) for entry in lineage: - entry["stored_curve"] = resolved.get(entry["stored_curve"], entry["stored_curve"]) - entry["raw_curve"] = resolved.get(entry["raw_curve"], entry["raw_curve"]) + entry["stored_curve"] = resolved.get( + entry["stored_curve"], entry["stored_curve"] + ) + entry["raw_curve"] = resolved.get( + entry["raw_curve"], entry["raw_curve"] + ) final_curves = [ c for c in spliced_df.columns @@ -848,7 +975,9 @@ def _commit_wells_to_db_sync() -> List[Dict[str, Any]]: for mk, mv in primary_meta.items(): if mv is not None or mk not in merged_demo_hdr: merged_demo_hdr[mk] = mv - merged_demo_hdr["curve_lineage"] = list(merged_demo_hdr.get("curve_lineage") or []) + lineage + merged_demo_hdr["curve_lineage"] = ( + list(merged_demo_hdr.get("curve_lineage") or []) + lineage + ) _ephemeral_well_headers[(project_id, well_name)] = merged_demo_hdr _merged_data_cache[f"{project_id}_{well_name}_0.16"] = ( time.time(), @@ -882,8 +1011,12 @@ def _commit_wells_to_db_sync() -> List[Dict[str, Any]]: ) resolved = db_merge_summary.get("resolved_curves", {}) for entry in lineage: - entry["stored_curve"] = resolved.get(entry["stored_curve"], entry["stored_curve"]) - entry["raw_curve"] = resolved.get(entry["raw_curve"], entry["raw_curve"]) + entry["stored_curve"] = resolved.get( + entry["stored_curve"], entry["stored_curve"] + ) + entry["raw_curve"] = resolved.get( + entry["raw_curve"], entry["raw_curve"] + ) appended = set(db_merge_summary.get("appended_curves", [])) for curve in well_obj._orm_well.curves: if curve.mnemonic not in appended: @@ -896,7 +1029,9 @@ def _commit_wells_to_db_sync() -> List[Dict[str, Any]]: curve.unit = entry["stored_unit"] break header = dict(well_obj.header_data or {}) - header["curve_lineage"] = list(header.get("curve_lineage") or []) + lineage + header["curve_lineage"] = ( + list(header.get("curve_lineage") or []) + lineage + ) well_obj.header_data = header if is_existing_well and isinstance(db_merge_summary, dict): final_appended = list( @@ -923,7 +1058,11 @@ def _commit_wells_to_db_sync() -> List[Dict[str, Any]]: _ephemeral_well_headers.pop((project_id, well_name), None) invalidate_well_cache(project_id=project_id, well_name=well_name) - if len(well_runs) == 1 and not payload.regularize_grid and well_runs[0].get("qaqc"): + if ( + len(well_runs) == 1 + and not payload.regularize_grid + and well_runs[0].get("qaqc") + ): merged_qaqc = well_runs[0]["qaqc"] else: merged_qaqc = compute_curve_qaqc(spliced_df, curve_units=merged_units) @@ -952,30 +1091,36 @@ def _commit_wells_to_db_sync() -> List[Dict[str, Any]]: try: committed_wells = await asyncio.to_thread(_commit_wells_to_db_sync) + if is_demo_mode(): + from quick_pp.app.backend.services.demo_guard import mark_demo_state_dirty + + mark_demo_state_dirty() except db_objects.WellIdentityConflictError as e: raise HTTPException(status_code=409, detail=str(e)) from e - - # Clean up staged files after commit - for spec in task_specs: - fp = spec.get("file_path") - fid = spec.get("file_id") - if fid and fid in _STAGED_FILES: - _STAGED_FILES.pop(fid, None) - if fp and os.path.exists(fp) and "import_staging" in str(fp): - try: - os.remove(fp) - except Exception: - pass + finally: + # Clean up staged files immediately after commit (even on conflict in demo mode) + for spec in task_specs: + fp = spec.get("file_path") + fid = spec.get("file_id") + if fid and fid in _STAGED_FILES: + _STAGED_FILES.pop(fid, None) + if fp and os.path.exists(fp) and "import_staging" in str(fp): + try: + os.remove(fp) + except Exception: + pass elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 2) - return sanitize_json_primitives({ - "status": "success", - "project_id": project_id, - "wells_committed": len(committed_wells), - "wells": committed_wells, - "wells_imported": committed_wells, - "elapsed_ms": elapsed_ms, - }) + return sanitize_json_primitives( + { + "status": "success", + "project_id": project_id, + "wells_committed": len(committed_wells), + "wells": committed_wells, + "wells_imported": committed_wells, + "elapsed_ms": elapsed_ms, + } + ) @router.post( @@ -985,6 +1130,11 @@ def _commit_wells_to_db_sync() -> List[Dict[str, Any]]: ) async def process_las_file(files: List[UploadFile] = File(...)): """Asynchronously processes a list of uploaded LAS files by saving the raw files and converting them to Parquet.""" + if is_demo_mode(): + raise HTTPException( + status_code=403, + detail="Disk-persisted LAS-to-Parquet batch conversion is disabled in the live demo. Use the interactive log importer.", + ) processed_file_paths = [] for file in files: try: diff --git a/quick_pp/app/backend/services/qaqc.py b/quick_pp/app/backend/services/qaqc.py index cf8ebbd2..3203625a 100644 --- a/quick_pp/app/backend/services/qaqc.py +++ b/quick_pp/app/backend/services/qaqc.py @@ -9,7 +9,7 @@ - `HCCorrectionInput` — Hydrocarbon correction for NPHI/RHOB data """ -from typing import List, Optional, Tuple +from typing import List, Literal, Optional, Tuple import numpy as np import pandas as pd @@ -81,8 +81,16 @@ class EnvironmentalCorrectionInput(BaseModel): mud_weight: float = Field(9.0, description="Drilling mud weight (ppg)") surface_temp: float = Field(75.0, description="Surface temperature (deg F)") temp_grad: float = Field(1.5, description="Geothermal gradient (deg F / 100 ft)") - salinity_ppm: float = Field(0.0, description="Salinity (ppm NaCl)") + salinity_ppm: float = Field(0.0, description="Borehole mud salinity (ppm NaCl)") rho_mudcake: float = Field(1.5, description="Mudcake bulk density (g/cm^3)") + tool_type: Literal["WL", "LWD"] = Field("WL", description="Generic tool profile") + mud_type: Literal["WBM", "OBM", "SBM"] = Field("WBM") + res_tool: Optional[Literal["induction", "laterolog", "propagation"]] = Field(None) + depth_unit: Literal["m", "ft", "auto"] = Field( + "auto", description="Depth unit of DEPTH/TVD; 'auto' guesses from magnitude" + ) + formation_salinity_ppm: Optional[float] = Field(None) + washout_thold: float = Field(2.0, gt=0) data: List[dict] = Field(..., description="Well log records") @@ -183,6 +191,15 @@ async def run_environmental_corrections(inputs: EnvironmentalCorrectionInput): temp_grad=inputs.temp_grad, salinity_ppm=inputs.salinity_ppm, rho_mudcake=inputs.rho_mudcake, + tool_type=inputs.tool_type, + mud_type=inputs.mud_type, + res_tool=inputs.res_tool, + depth_unit=inputs.depth_unit, + formation_salinity_ppm=inputs.formation_salinity_ppm, + washout_thold=inputs.washout_thold, ) - return {"data": corr_df.replace({np.nan: None}).to_dict(orient="records")} + return { + "data": corr_df.replace({np.nan: None}).to_dict(orient="records"), + "assumptions": list(corr_df.attrs.get("env_assumptions") or []), + } diff --git a/quick_pp/app/backend/services/report.py b/quick_pp/app/backend/services/report.py index 1da42847..0991fe07 100644 --- a/quick_pp/app/backend/services/report.py +++ b/quick_pp/app/backend/services/report.py @@ -19,7 +19,7 @@ import threading from datetime import datetime from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple, Union +from typing import Any, Dict, List, Optional, Sequence, Tuple, Union from uuid import uuid4 import jinja2 @@ -50,10 +50,17 @@ from quick_pp.app.backend.services.workspace import ( _ephemeral_well_configs, _select_nphi_rhob, + _synthesize_bitsize_series, ) from quick_pp.app.backend.utils.db import get_db +from quick_pp.borehole_corrections import ( + ENV_QC_REASON_BITS, + confidence_weighted_curve, +) from quick_pp.config import Config from quick_pp.database import objects as db_objects +from quick_pp.environment import environment_from_config +from quick_pp.las_handler import extract_las_metadata from quick_pp.permeability import choo_permeability from quick_pp.plotter import report_plots from quick_pp.ressum import calc_reservoir_summary @@ -69,12 +76,23 @@ REPORTS_STATIC_ROOT = BACKEND_DIR / "static" / "reports" REPORTS_STATIC_ROOT.mkdir(parents=True, exist_ok=True) + +def _pluralize(count: Any, singular: str, plural: Optional[str] = None) -> str: + """Lightweight Jinja2 pluralization helper (Task 4.3).""" + try: + c = int(count) + except Exception: + c = 1 + return singular if c == 1 else (plural or f"{singular}s") + + _jinja_env = jinja2.Environment( loader=jinja2.FileSystemLoader(str(REPORTS_TEMPLATE_DIR)), autoescape=False, trim_blocks=True, lstrip_blocks=True, ) +_jinja_env.filters["pluralize"] = _pluralize SECTION_TEMPLATE_MAP: Dict[str, str] = { "01_executive_summary": "sections/01_executive_summary.md.j2", @@ -86,6 +104,8 @@ "07_shf_scal": "sections/07_shf_scal.md.j2", "08_ressum_uncertainty": "sections/08_ressum_uncertainty.md.j2", "09_upscaling": "sections/09_upscaling.md.j2", + "10_gate_checks": "sections/10_gate_checks.md.j2", + "11_appendix_cpi": "sections/10_appendix_cpi.md.j2", "10_appendix_cpi": "sections/10_appendix_cpi.md.j2", } @@ -105,7 +125,10 @@ "ressum_uncert": "08_ressum_uncertainty", "ressum_uncertainty": "08_ressum_uncertainty", "upscaling": "09_upscaling", - "appendix_cpi": "10_appendix_cpi", + "gate_checks": "10_gate_checks", + "gate_check": "10_gate_checks", + "appendix_cpi": "11_appendix_cpi", + "10_appendix_cpi": "11_appendix_cpi", } @@ -121,14 +144,27 @@ def _col_series(df: pd.DataFrame, col: str, default: float = np.nan) -> pd.Serie REPORT_TYPE_PRESETS: Dict[str, List[str]] = { - "FDP_FULL": list(SECTION_TEMPLATE_MAP.keys()), + "FDP_FULL": [ + "01_executive_summary", + "02_data_inventory", + "03_qaqc", + "04_lithology_porosity", + "05_rock_typing_perm", + "06_saturation_contacts", + "07_shf_scal", + "08_ressum_uncertainty", + "09_upscaling", + "10_gate_checks", + "11_appendix_cpi", + ], "SINGLE_WELL_CPI": [ "01_executive_summary", "03_qaqc", "04_lithology_porosity", "06_saturation_contacts", "08_ressum_uncertainty", - "10_appendix_cpi", + "10_gate_checks", + "11_appendix_cpi", ], "QAQC_SUMMARY": [ "01_executive_summary", @@ -161,17 +197,150 @@ def _safe_float(val: Any, default: float = 0.0) -> float: } +_STRATIGRAPHIC_CORRECTIONS = { + re.compile(r"\bWest\s*Phalian\b", re.IGNORECASE): "Westphalian", + re.compile(r"\bSteph\s*Anian\b", re.IGNORECASE): "Stephanian", + re.compile(r"\bNamur\s*Ian\b", re.IGNORECASE): "Namurian", + re.compile(r"\bVise\s*An\b", re.IGNORECASE): "Visean", + re.compile(r"\bKimme\s*Ridg\s*Ian\b", re.IGNORECASE): "Kimmeridgian", + re.compile(r"\bRot\s*Liegend\b", re.IGNORECASE): "Rotliegend", + re.compile(r"\bZech\s*Stein\b", re.IGNORECASE): "Zechstein", + re.compile(r"\bStat\s*Fjord\b", re.IGNORECASE): "Statfjord", +} + + def _normalize_zone_name( raw_zone: Any, well_zones_upper: Optional[set[str]] = None, ) -> str: - """Clean and normalize a formation/zone name without field-specific hardcoded aliases.""" + """Clean and normalize a formation/zone name preserving stratigraphic stage capitalization (Task 4.2).""" s = str(raw_zone or "").strip() - if not s or s.lower() in ("nan", "none"): + if not s or s.lower() in ("nan", "none", "unknown"): return "Unknown" + + # If ALL_CAPS, all-lowercase, or snake_case, format to clean Title Case preserving alphanumeric / Roman numeral suffixes + if s.isupper() or s.islower() or "_" in s: + words = s.replace("_", " ").split() + norm_words = [] + for w in words: + if len(w) <= 2 or w.upper() in ( + "II", + "III", + "IV", + "VI", + "VII", + "VIII", + "IX", + "X", + ): + norm_words.append(w.upper()) + else: + norm_words.append(w.capitalize()) + s = " ".join(norm_words) + + # Post-normalization stratigraphic stage replacement dictionary + for pattern, replacement in _STRATIGRAPHIC_CORRECTIONS.items(): + s = pattern.sub(replacement, s) + return s +_ENV_REASON_LABELS: List[Tuple[int, str]] = [ + (ENV_QC_REASON_BITS["WASHOUT"], "Washout"), + (ENV_QC_REASON_BITS["DRHO_HIGH"], "High DRHO"), + (ENV_QC_REASON_BITS["BADHOLE"], "Badhole"), + (ENV_QC_REASON_BITS["INVASION"], "Invasion"), + (ENV_QC_REASON_BITS["NO_CALIPER"], "No Caliper"), + (ENV_QC_REASON_BITS["SPIKE"], "Spike"), + (ENV_QC_REASON_BITS["FLATLINE"], "Flatline"), + (ENV_QC_REASON_BITS["CYCLE_SKIP"], "Cycle Skip"), + (ENV_QC_REASON_BITS["BS_ASSUMED"], "Assumed BS"), + (ENV_QC_REASON_BITS["RES_MUD_MISMATCH"], "Res/Mud Mismatch"), +] +_ENV_CURVE_UNITS: Dict[str, str] = { + "GR": "gAPI", + "NPHI": "v/v", + "RHOB": "g/cc", + "RT": "dec", + "DT": "us/ft", +} + + +def _dominant_env_reason(reason_s: pd.Series, mask: Optional[pd.Series] = None) -> str: + """Return the top 1-2 decoded ENV_QC_REASON flags across `mask` (or `'Clean'`).""" + if reason_s is None or reason_s.empty: + return "Clean" + vals = pd.to_numeric(reason_s, errors="coerce").fillna(0).astype(int) + if mask is not None: + vals = vals[mask.reindex(vals.index, fill_value=False)] + if vals.empty: + return "Clean" + arr = vals.to_numpy(dtype=int) + counts: List[Tuple[int, str]] = [] + for bit, label in _ENV_REASON_LABELS: + cnt = int(np.sum((arr & bit) != 0)) + if cnt > 0: + counts.append((cnt, label)) + if not counts: + return "Clean" + counts.sort(key=lambda item: item[0], reverse=True) + return ", ".join(lbl for _, lbl in counts[:2]) + + +def _select_conditioned_curve( + df: pd.DataFrame, + base_col: str, + prefer_hc: bool = False, + weight_by_conf: bool = True, +) -> pd.Series: + """Select the best conditioned curve (`_HC` -> `_ENV_CORR` -> ``) with optional QC confidence weighting.""" + idx = df.index + hc_col = f"{base_col}_HC" + if prefer_hc and hc_col in df.columns: + hc_s = pd.to_numeric(df[hc_col], errors="coerce") + if hc_s.notna().any(): + return hc_s + + qc_prefix = "DT" if base_col in ("DTC", "DT") else base_col + corr_col = f"{qc_prefix}_ENV_CORR" + conf_col = f"{qc_prefix}_QC_CONF" + raw_s = ( + pd.to_numeric(df[base_col], errors="coerce") + if base_col in df.columns + else pd.Series(np.nan, index=idx, dtype=float) + ) + base_s = raw_s + if corr_col in df.columns: + corr_s = pd.to_numeric(df[corr_col], errors="coerce") + if corr_s.notna().any(): + base_s = corr_s.combine_first(raw_s) + + if weight_by_conf and conf_col in df.columns and base_s.notna().any(): + conf_s = pd.to_numeric(df[conf_col], errors="coerce") + if conf_s.notna().any(): + depth_arr = ( + pd.to_numeric(df["DEPTH"], errors="coerce").to_numpy(dtype=float) + if "DEPTH" in df.columns + else None + ) + try: + if qc_prefix == "RT": + lb = np.log10(base_s.clip(lower=1e-3)) + blended = confidence_weighted_curve( + lb, conf_s.fillna(1.0), depth=depth_arr + ) + out = pd.Series(10.0 ** blended.to_numpy(), index=idx) + return out.where(base_s.notna()) + blended = confidence_weighted_curve( + base_s, conf_s.fillna(1.0), depth=depth_arr + ) + blended.index = idx + return blended.where(base_s.notna()) + except Exception: + return base_s + return base_s + + def _ensure_evaluated_curves(df: pd.DataFrame, well_name: str) -> pd.DataFrame: """Ensure baseline VCLAY, PHIT, PHIE, PERM, and SWT exist without synthetic scalar padding (Spec 1.1 & CHK-01).""" if df is None or df.empty: @@ -193,8 +362,8 @@ def _ensure_evaluated_curves(df: pd.DataFrame, well_name: str) -> pd.DataFrame: # Vectorized log derivations strictly where input logs exist (np.nan outside evaluated intervals) if not has_vclay: - if "GR" in work.columns and work["GR"].notna().any(): - gr_s = pd.to_numeric(work["GR"], errors="coerce") + gr_s = _select_conditioned_curve(work, "GR") + if gr_s.notna().any(): p10 = float(np.nanpercentile(gr_s, 10)) if gr_s.notna().sum() > 5 else 15.0 p90 = float(np.nanpercentile(gr_s, 90)) if gr_s.notna().sum() > 5 else 115.0 denom = max(p90 - p10, 20.0) @@ -203,11 +372,13 @@ def _ensure_evaluated_curves(df: pd.DataFrame, well_name: str) -> pd.DataFrame: work["VCLAY"] = np.nan if not has_phit: - try: - nphi, rhob = _select_nphi_rhob(work, use_hc_corrected=True) - except Exception: - nphi = _col_series(work, "NPHI", np.nan) - rhob = _col_series(work, "RHOB", np.nan) + nphi = _select_conditioned_curve(work, "NPHI", prefer_hc=True) + rhob = _select_conditioned_curve(work, "RHOB", prefer_hc=True) + if not (nphi.notna().any() or rhob.notna().any()): + try: + nphi, rhob = _select_nphi_rhob(work, use_hc_corrected=True) + except Exception: + pass if rhob.notna().any(): phid = ((2.65 - rhob) / (2.65 - 1.0)).clip(0.005, 0.45) if nphi.notna().any(): @@ -225,7 +396,9 @@ def _ensure_evaluated_curves(df: pd.DataFrame, well_name: str) -> pd.DataFrame: phie_s = pd.to_numeric(work["PHIE"], errors="coerce") work["PHIT"] = np.where( phie_s.notna(), - (phie_s / np.maximum(1.0 - 0.35 * vsh_s.fillna(0.20), 0.3)).clip(0.005, 0.45), + (phie_s / np.maximum(1.0 - 0.35 * vsh_s.fillna(0.20), 0.3)).clip( + 0.005, 0.45 + ), np.nan, ) else: @@ -241,8 +414,9 @@ def _ensure_evaluated_curves(df: pd.DataFrame, well_name: str) -> pd.DataFrame: ) # CHK-01 enforcement: if PHIT/PHIE were not explicitly saved in DB, mask outside RT-logged interval - if not (orig_phit_present or orig_phie_present) and "RT" in work.columns and work["RT"].notna().any(): - rt_valid = pd.to_numeric(work["RT"], errors="coerce").notna() + rt_gate_s = _select_conditioned_curve(work, "RT", weight_by_conf=False) + if not (orig_phit_present or orig_phie_present) and rt_gate_s.notna().any(): + rt_valid = rt_gate_s.notna() work.loc[~rt_valid, "PHIT"] = np.nan work.loc[~rt_valid, "PHIE"] = np.nan @@ -250,11 +424,21 @@ def _ensure_evaluated_curves(df: pd.DataFrame, well_name: str) -> pd.DataFrame: try: phit_s = pd.to_numeric(work["PHIT"], errors="coerce") if phit_s.notna().any(): - vcl_arr = _col_series(work, "VCLAY", np.nan).fillna(0.20).to_numpy(dtype=float) - vsi_arr = _col_series(work, "VSILT", np.nan).fillna(0.10).to_numpy(dtype=float) + vcl_arr = ( + _col_series(work, "VCLAY", np.nan) + .fillna(0.20) + .to_numpy(dtype=float) + ) + vsi_arr = ( + _col_series(work, "VSILT", np.nan) + .fillna(0.10) + .to_numpy(dtype=float) + ) phi_arr = phit_s.fillna(0.15).to_numpy(dtype=float) perm_est = np.clip( - np.asarray(choo_permeability(vcl_arr, vsi_arr, phi_arr), dtype=float), + np.asarray( + choo_permeability(vcl_arr, vsi_arr, phi_arr), dtype=float + ), 1e-3, 1e5, ) @@ -266,7 +450,7 @@ def _ensure_evaluated_curves(df: pd.DataFrame, well_name: str) -> pd.DataFrame: if not has_swt: try: - rt_s = pd.to_numeric(work["RT"], errors="coerce") if "RT" in work.columns else pd.Series(np.nan, index=work.index) + rt_s = _select_conditioned_curve(work, "RT") phit_s = pd.to_numeric(work["PHIT"], errors="coerce") if rt_s.notna().any() and phit_s.notna().any(): rt_arr = rt_s.clip(lower=0.1).to_numpy(dtype=float) @@ -313,6 +497,11 @@ def _load_project_wells_fast( "formation_top_count": int( w.get("formation_top_count") or len(w.get("tops") or []) ), + "hole_section_count": int( + w.get("hole_section_count") or len(w.get("hole_sections") or []) + ), + "hole_sections": list(w.get("hole_sections") or []), + "depth_uom": w.get("depth_uom"), "well_config": w.get("well_config") or {}, } for idx, w in enumerate(raw_wells) @@ -328,7 +517,9 @@ def _load_project_wells_fast( .all() ) if not orm_wells: - raise ValueError(f"No wells found in project {project_id} ({project_name}).") + raise ValueError( + f"No wells found in project {project_id} ({project_name})." + ) requested_all = ( not well_names @@ -383,6 +574,36 @@ def _load_project_wells_fast( .group_by(db_objects.ORMFormationTop.well_id) ).all() ) + hole_sections_by_well: Dict[int, List[Dict[str, Any]]] = {} + try: + hs_rows = ( + session.execute( + select(db_objects.ORMHoleSection) + .where(db_objects.ORMHoleSection.well_id.in_(well_ids)) + .order_by( + db_objects.ORMHoleSection.top, + db_objects.ORMHoleSection.bottom, + ) + ) + .scalars() + .all() + ) + for hs in hs_rows: + hole_sections_by_well.setdefault(hs.well_id, []).append( + { + "name": str(hs.name or "Section"), + "top": hs.top, + "bottom": hs.bottom, + "bit_size": hs.bit_size, + "mud_type": hs.mud_type or "WBM", + "mud_weight": hs.mud_weight, + "mud_salinity": hs.mud_salinity, + "rmf": hs.rmf, + "rmf_temp": hs.rmf_temp, + } + ) + except Exception as exc: + logger.debug(f"Hole sections query skipped in report loader: {exc}") selected_wells_meta: List[Dict[str, Any]] = [] for w in orm_wells: @@ -392,20 +613,660 @@ def _load_project_wells_fast( eph_cfg = _ephemeral_well_configs.get((project_id, w.name)) if eph_cfg: w_cfg = {**w_cfg, **eph_cfg} + w_hs = ( + list(eph_cfg["hole_sections"]) + if isinstance(eph_cfg, dict) + and isinstance(eph_cfg.get("hole_sections"), list) + else hole_sections_by_well.get(w.well_id, []) + ) selected_wells_meta.append( { "id": w.well_id, "name": str(w.name), "uwi": str(w.uwi or w.name), + "depth_uom": getattr(w, "depth_uom", None), "core_sample_count": int(core_counts.get(w.well_id, 0)), "pressure_test_count": int(press_counts.get(w.well_id, 0)), "formation_top_count": int(top_counts.get(w.well_id, 0)), + "hole_section_count": len(w_hs), + "hole_sections": w_hs, "well_config": w_cfg, } ) return project_name, selected_wells_meta +def _load_saved_project_module_entry( + project_id: int, module: str, target_zones: Optional[List[str]] = None +) -> Dict[str, Any]: + """Return the saved multi-well module entry (`params`, `label`, `_key`) for the active zone selection. + + Mirrors the workbench lookup order: exact zone bundle, each single zone, `all`, then any saved entry. + Returns an empty dict when nothing is saved or the store is unreachable. + """ + try: + from quick_pp.app.backend.services.workspace import ( + _load_project_module_params, + ) + + mp, _ = _load_project_module_params(int(project_id)) + except Exception as exc: + logger.debug(f"Saved module params unavailable for '{module}': {exc}") + return {} + mod_map = mp.get(module) if isinstance(mp, dict) else None + if not isinstance(mod_map, dict) or not mod_map: + return {} + zones = [str(z).strip() for z in (target_zones or []) if str(z).strip()] + candidates: List[str] = [] + if zones: + candidates.append("zone:" + "+".join(zones)) + for z in zones: + candidates.extend([z, f"zone:{z}"]) + candidates.extend(["all", "ALL", "default"]) + for cand in candidates: + entry = mod_map.get(cand) + if isinstance(entry, dict): + return {**entry, "_key": cand} + first_key = next(iter(mod_map)) + entry = mod_map[first_key] + return {**entry, "_key": first_key} if isinstance(entry, dict) else {} + + +_EDITED_CURVE_SUFFIXES = ( + "_ORI", + "_RECONSTRUCTED", + "_DEN_CORR", + "_ENV_CORR", + "_ENH", + "_UNSHIFTED", + "_AMB", + "_AIR", + "_SYN", + "_FILLED", + "_NORM", +) +_EDITED_CURVE_NAMES = { + "RHOB_DEN_CORR", + "DEN_CORR_FLAG", + "BADHOLE_BASE", + "PHID_RAW_100", + "PROJ_NPHI", + "PROJ_RHOB", +} +_COMPUTED_CURVE_SUFFIXES = ( + "_CORR_DELTA", + "_SIGMA", + "_QC_CONF", + "_QC_STATUS", + "_RECON", + "_P10", + "_P50", + "_P90", +) +_COMPUTED_CURVE_PREFIXES = ( + "SWT_", + "SXO_", + "PRESSURE_", + "CORE_", + "HI_", + "RHO_", + "TEMP_", + "TOC_", + "VCL_", + "ENV_", + "INVASION_", +) +_COMPUTED_CURVE_NAMES = { + "VCLAY", + "VSHALE", + "_REPORT_VSHALE", + "PHIT", + "PHIE", + "PHID", + "PHIN", + "PHIS", + "PHIT_SH", + "PHIT_CONSTRUCTED", + "PERM", + "PERM_TRANS", + "SWT", + "SWE", + "SHF", + "BVW", + "BVHC", + "ROCK_FLAG", + "ROCK_FLAG_CUTOFF", + "ROCK_FLAG_ML", + "FZI", + "R35", + "RFN", + "BADHOLE", + "BAD_HOLE", + "BAD_HOLE_FLAG", + "BS", + "DCALI", + "CALI_FLAG", + "DRHO_FLAG", + "RUGOSITY_FLAG", + "HOLE_SEVERITY", + "RXO_EST", + "DI_EST", + "SHC_INV", + "DECONV_WEIGHT", + "HC_FLAG", + "TIGHT_FLAG", + "COAL_FLAG", + "GAS_FLAG", + "OIL_FLAG", + "UNC_FLAG", + "FLUID_TYPE", + "TOP_NAME", + "TVD", + "TVDSS", + "CPORE", + "CPERM", + "QVN", + "QV", + "RW", + "RS", + "RHOM", + "RHOB_HC", + "NPHI_HC", + "TEMP_GRAD", + "M_CALC", + "M_STAR", + "B", + "CWA", + "AVG_ERROR", + "CHI2_ERROR", + "OPTIMIZER_SUCCESS", + "DELTA_LOG_R", + "PP_EST", + "SV_EST", + "NCS_EST", + "Z_FACTOR", + "NU_DYN", + "VDL", + "CGR_SYN", + "TOC", + "PRES_FL", + "SWIRR", + "RT_ORI", +} + + +def _classify_curve_provenance(curve_names: Sequence[str]) -> Dict[str, List[str]]: + """Split curve mnemonics into raw (as loaded), edited (conditioned versions of raw) and computed. + + Rules are name-based because curves carry no provenance tag. Mineral/volume curves (`V*` such as + VSAND, VCALC) are computed. A curve is edited when it has a conditioning suffix (`_ORI`, + `_RECONSTRUCTED`, `_DEN_CORR`, `_ENV_CORR`, `_ENH`...); `*_ORI` columns hold the unedited copy + and are reported with the edited group so the original is not mistaken for a new measurement. + """ + raw: List[str] = [] + edited: List[str] = [] + computed: List[str] = [] + volume_like = { + "VSAND", + "VSILT", + "VCALC", + "VDOLO", + "VANHY", + "VCHLO", + "VILLI", + "VKAOL", + "VSMEC", + "VGLAUC", + "VGYPS", + "VHALI", + "VKERO", + "VKFELD", + "VMUSC", + "VPYRI", + "VSIDE", + "VBIOT", + "VFELD", + "VCOAL", + "VGAS", + "VOIL", + "VWATER", + "VUNC", + "VANKE", + "VSH_GR", + "VSH_DN", + } + for c in curve_names: + u = str(c).upper() + if u in _EDITED_CURVE_NAMES or u.endswith(_EDITED_CURVE_SUFFIXES): + edited.append(str(c)) + elif ( + u in _COMPUTED_CURVE_NAMES + or u in volume_like + or u.startswith(_COMPUTED_CURVE_PREFIXES) + or u.endswith(_COMPUTED_CURVE_SUFFIXES) + ): + computed.append(str(c)) + else: + raw.append(str(c)) + return {"raw": raw, "edited": edited, "computed": computed} + + +def _compute_field_summary(zonal_summary: Sequence[Dict[str, Any]]) -> Dict[str, Any]: + """Single source for field-level pay metrics used by the executive summary and Section 8.4. + + Definitions (each zone row already holds the per-well mean for that zone): + - `column_hcpt` / `column_net_pay`: sum of zone means, i.e. what a typical well penetrating every + evaluated zone would encounter. + - `mean_zone_hcpt` / `mean_zone_net_pay`: the same totals divided by the number of evaluated zones. + - `phie` / `sw`: net-pay-thickness weighted porosity and pore-volume weighted water saturation over the + zones that carry pay. + - `ntg_pay`: total net pay over total gross across zones. + """ + zones = list(zonal_summary or []) + n_zones = len(zones) + column_hcpt = sum(float(z.get("hcpt", 0.0)) for z in zones) + column_net_pay = sum(float(z.get("net_pay", 0.0)) for z in zones) + column_gross = sum(float(z.get("gross", 0.0)) for z in zones) + pay_zones = [z for z in zones if float(z.get("net_pay", 0.0)) > 0] + phie = sw = None + if pay_zones: + h = np.array([max(float(z.get("net_pay", 0.0)), 1e-6) for z in pay_zones]) + phi_z = np.array( + [float(z.get("phie_pay", z.get("phie", 0.0))) for z in pay_zones] + ) + sw_z = np.array([float(z.get("sw_pay", z.get("sw", 0.0))) for z in pay_zones]) + phie = float(np.sum(h * phi_z) / np.sum(h)) + pv = np.maximum(h * phi_z, 1e-6) + sw = float(np.sum(pv * sw_z) / np.sum(pv)) + return { + "n_zones": n_zones, + "n_pay_zones": len(pay_zones), + "column_hcpt": round(column_hcpt, 2), + "column_net_pay": round(column_net_pay, 1), + "mean_zone_hcpt": round(column_hcpt / max(n_zones, 1), 2), + "mean_zone_net_pay": round(column_net_pay / max(n_zones, 1), 1), + "ntg_pay": round(column_net_pay / column_gross, 3) if column_gross > 0 else 0.0, + "phie": round(phie, 3) if phie is not None else None, + "sw": round(sw, 3) if sw is not None else None, + } + + +def _build_shf_reconciliation_sentence(shf_p: Dict[str, Any]) -> str: + """Describe the SHF vs log Sw agreement truthfully, including failure and missing-data cases.""" + sc = shf_p.get("ift_cos_theta", 26.0) + src = shf_p.get("fit_source", "unspecified") + rmse = shf_p.get("reconciliation_rmse") + if rmse is None: + return ( + f"The Leverett $J$-Function saturation-height model ($\\sigma\\cos\\theta = {sc}\\text{{ dynes/cm}}$, " + f"fit source: {src}) could not be reconciled with log $S_w$ because too few overlapping " + f"target-zone samples above the FWL were available. " + ) + bias = shf_p.get("reconciliation_bias") or 0.0 + text = ( + f"The Leverett $J$-Function saturation-height model ($\\sigma\\cos\\theta = {sc}\\text{{ dynes/cm}}$, " + f"fit source: {src}) gives $\\text{{RMSE}} = {rmse:.3f}\\text{{ v/v}}$ and mean bias " + f"${bias:+.3f}\\text{{ v/v}}$ against wireline log $S_w$ (n={shf_p.get('reconciliation_n', 0)}). " + ) + if rmse > 0.12: + text += ( + "This exceeds the 0.12 v/v acceptance limit, so the saturation-height function does not yet reproduce " + "the log saturation and should not be used to initialise the static model until the rock-type fits, " + "FWL and fluid densities are revisited. " + ) + if not shf_p.get("uses_saved_fit"): + text += "No saved per-rock-type SHF fit was applied, so the curve uses a generic fallback J-function. " + return text + + +def _build_rock_typing_narrative( + rock_types: List[Dict[str, Any]], + rt_sum: Dict[str, Any], + cutoffs: List[float], +) -> str: + """Narrative derived strictly from the fitted classes, cutoffs and their provenance.""" + n_rt = len(rock_types) + cut_txt = ", ".join(f"{c:g}" for c in cutoffs) if cutoffs else "n/a" + src = rt_sum.get("cutoff_source", "unspecified source") + parts = [ + f"Hydraulic Flow Unit partitioning on **{rt_sum.get('basis', 'Target-Zone Dataset')}** classified the " + f"reservoir into **{n_rt}** Discrete Rock Types using Flow Zone Indicator cut-offs of " + f"${cut_txt}\\text{{ }}\\mu\\text{{m}}$ (source: {src}). " + ] + dom = rt_sum.get("dominant_codes") or [] + if dom and rt_sum.get("dominant_kh_pct") is not None: + parts.append( + f"Flow capacity is concentrated in **{', '.join(dom)}**, which together hold " + f"**{rt_sum['dominant_share_pct']:.1f}%** of samples and **{rt_sum['dominant_kh_pct']:.1f}%** of " + f"cumulative permeability-thickness ($\\sum K\\cdot h$). " + ) + weak = [ + r["name"].split("—")[0].strip() + for r in rock_types + if r.get("fit_status") != "fitted" + ] + if weak: + parts.append( + f"No porosity-permeability regression is reported for {', '.join(weak)} because fewer than " + f"3 samples (or no porosity spread) fall in the class. " + ) + if rt_sum.get("method_note"): + parts.append(str(rt_sum["method_note"]) + " ") + return "".join(parts).strip() + + +def _gather_and_analyze_fpt_data( + project_id: int, + wells_inventory: List[Dict[str, Any]], + merged_configs: Dict[str, Any], + fluid_contacts_rows: List[Dict[str, Any]], + target_zones: List[str], + fwl_val: Optional[float] = None, + fwl_is_committed: bool = False, +) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: + """Gather and analyze Formation Pressure Test (FPT) data for Section 6.3 (GAP-13). + + Points are restricted to the target zones, valid quality and plausible pressure. Gradient fits are + accepted only inside physical density ranges. Contact reconciliation is flagged INDICATIVE unless the + reference FWL comes from a committed contact or an explicit user override (`fwl_is_committed`). + """ + raw_points: List[Dict[str, Any]] = [] + + # Priority 1: Direct injection in configs (e.g. tests or pre-calculated) + if "fpt_points" in merged_configs and isinstance( + merged_configs["fpt_points"], list + ): + raw_points = list(merged_configs["fpt_points"]) + elif any(int(w.get("pressure_test_count", 0)) > 0 for w in wells_inventory): + try: + from quick_pp.app.backend.services.fpt import _collect_fpt_points + + w_names = [w["name"] for w in wells_inventory] + raw_points = _collect_fpt_points(int(project_id), w_names) + except Exception as exc: + logger.debug(f"Failed collecting FPT points via service: {exc}") + + if not raw_points: + return { + "has_data": False, + "total_stations": 0, + "valid_stations": 0, + "well_fpt_rows": [], + "fpt_gradient_rows": [], + "fpt_contacts": [], + "fitted_densities": {}, + "fwl": fwl_val, + }, [] + + # Filter valid stations: quality, finite depth, plausible pressure, and active target zone. + tz_upper = {str(z).strip().upper() for z in (target_zones or []) if str(z).strip()} + any_zone_info = any( + str(p.get("zone") or "").strip() not in ("", "None", "nan") for p in raw_points + ) + exclusions = {"quality": 0, "bad_pressure": 0, "no_depth": 0, "outside_target": 0} + valid_points = [] + for p in raw_points: + if str(p.get("test_quality", "VALID")).strip().upper() != "VALID": + exclusions["quality"] += 1 + continue + try: + pr = float(p.get("pressure")) + tv = p.get("tvdss") + tv = float(tv) if tv is not None else float("nan") + except (TypeError, ValueError): + exclusions["bad_pressure"] += 1 + continue + if not np.isfinite(tv): + exclusions["no_depth"] += 1 + continue + # Reject physically implausible points (< 0.2 or > 1.2 psi/ft equivalent over TVDSS). + grad_eq = pr / max(tv * 3.28084, 1.0) + if not np.isfinite(pr) or pr <= 0 or tv <= 0 or not (0.2 <= grad_eq <= 1.2): + exclusions["bad_pressure"] += 1 + continue + if tz_upper and any_zone_info: + if str(p.get("zone") or "").strip().upper() not in tz_upper: + exclusions["outside_target"] += 1 + continue + valid_points.append(p) + fpt_filter_note = ( + f"{len(valid_points)} of {len(raw_points)} stations retained for gradient analysis " + f"(excluded: {exclusions['outside_target']} outside target zones, " + f"{exclusions['quality']} non-valid quality, " + f"{exclusions['bad_pressure']} implausible pressure, " + f"{exclusions['no_depth']} without TVDSS)." + ) + + well_fpt_rows = [] + wells_with_pts = sorted({p["well_name"] for p in raw_points}) + for wn in wells_with_pts: + w_all = [p for p in raw_points if p["well_name"] == wn] + w_val = [p for p in valid_points if p["well_name"] == wn] + tvdss_l = [ + float(p["tvdss"]) + for p in w_val + if p.get("tvdss") is not None and np.isfinite(float(p["tvdss"])) + ] + p_l = [ + float(p["pressure"]) + for p in w_val + if p.get("pressure") is not None and np.isfinite(float(p["pressure"])) + ] + mob_l = [ + float(p["mobility"]) + for p in w_val + if p.get("mobility") is not None + and np.isfinite(float(p["mobility"])) + and float(p["mobility"]) > 0 + ] + + d_str = f"{min(tvdss_l):.1f} – {max(tvdss_l):.1f} m TVDss" if tvdss_l else "—" + p_str = f"{min(p_l):.1f} – {max(p_l):.1f} psia" if p_l else "—" + m_str = f"{min(mob_l):.1f} – {max(mob_l):.1f} mD/cP" if mob_l else "—" + + # Determine overpressure regime relative to normal hydrostatic (0.433 - 0.465 psi/ft) + if tvdss_l and p_l: + mean_p = float(np.mean(p_l)) + mean_z_ft = float(np.mean(tvdss_l)) * 3.28084 + grad_est = mean_p / max(mean_z_ft, 1.0) + if grad_est < 0.42: + regime = "Depleted / Sub-Hydrostatic" + elif grad_est <= 0.47: + regime = "Normal Hydrostatic" + else: + regime = "Moderately Overpressured" + else: + regime = "Normal Hydrostatic" + + well_fpt_rows.append( + { + "well_name": wn, + "total_count": len(w_all), + "valid_count": len(w_val), + "depth_range": d_str, + "pressure_range": p_str, + "mobility_range": m_str, + "overpressure_regime": regime, + } + ) + + # Fit fluid gradients via FormationPressureAnalyzer + fpt_gradient_rows = [] + fpt_contacts = [] + fitted_densities: Dict[str, Dict[str, Any]] = {} + + if len(valid_points) >= 2: + try: + from quick_pp.fluid_type import FormationPressureAnalyzer + + fpa_df = pd.DataFrame( + { + "ID": [p.get("id", i + 1) for i, p in enumerate(valid_points)], + "WELL_NAME": [p["well_name"] for p in valid_points], + "TVDSS": [ + float(p["tvdss"]) if p.get("tvdss") is not None else np.nan + for p in valid_points + ], + "PRESSURE": [float(p["pressure"]) for p in valid_points], + "FLUID_TYPE": [ + str(p.get("fluid_type", "UNASSIGNED")).upper() + for p in valid_points + ], + "TEST_QUALITY": [ + str(p.get("test_quality", "VALID")).upper() + for p in valid_points + ], + "MOBILITY": [p.get("mobility") for p in valid_points], + } + ).dropna(subset=["TVDSS", "PRESSURE"]) + + fpa = FormationPressureAnalyzer( + fpa_df, + pressure_unit="psi", + depth_unit="m", + id_col="ID", + ) + if all(f == "UNASSIGNED" for f in fpa_df["FLUID_TYPE"]): + fpa.auto_classify_points() + + fpa.fit_all() + contacts_res = fpa.estimate_contacts() + + ref_fwl = fwl_val if fwl_val is not None else 2500.0 + for fl, g in fpa.gradients.items(): + g_dict = g.to_dict() + g_psi_m = _safe_float(g_dict.get("gradient"), 0.0) + g_psi_ft = round(g_psi_m * 0.3048, 4) + rho_gcc = round(_safe_float(g_dict.get("density_gcc"), 0.0), 3) + r2 = round(_safe_float(g_dict.get("r_squared"), 0.0), 3) + t_range = g_dict.get("tvdss_range", [0, 0]) + t_str = ( + f"{t_range[0]:.1f} – {t_range[1]:.1f} m TVDss" + if t_range and t_range[0] is not None + else "—" + ) + datum_p = round( + g_psi_m * ref_fwl + _safe_float(g_dict.get("intercept"), 0.0), 1 + ) + + # Physical plausibility bounds on in-situ density (g/cc) by phase. + dens_bounds = { + "GAS": (0.02, 0.45), + "OIL": (0.40, 1.00), + "WATER": (0.95, 1.25), + }.get(str(fl).upper()) + n_fit = int(g_dict.get("n_points", 0)) + reject_reason = "" + if dens_bounds and not (dens_bounds[0] <= rho_gcc <= dens_bounds[1]): + reject_reason = ( + f"density {rho_gcc:.3f} g/cc outside physical range " + f"{dens_bounds[0]:.2f}–{dens_bounds[1]:.2f}" + ) + elif n_fit < 3: + reject_reason = f"only {n_fit} station(s)" + elif r2 < 0.80: + reject_reason = f"poor fit (R²={r2:.2f})" + + # Zone label from the stations that actually fall in this phase's depth range. + t_lo = t_range[0] if t_range and t_range[0] is not None else None + t_hi = t_range[1] if t_range and len(t_range) > 1 else None + if t_lo is not None and t_hi is not None: + fit_zones = sorted( + { + str(p.get("zone")).strip() + for p in valid_points + if p.get("tvdss") is not None + and t_lo - 0.5 <= float(p["tvdss"]) <= t_hi + 0.5 + and str(p.get("zone") or "").strip() + not in ("", "None", "nan") + } + ) + else: + fit_zones = [] + zone_label = ( + ", ".join(fit_zones) + if fit_zones + else ( + ", ".join(target_zones) if target_zones else "Target Reservoir" + ) + ) + + fpt_gradient_rows.append( + { + "zone": zone_label, + "fluid_type": fl.title(), + "gradient_psi_ft": g_psi_ft, + "density_gcc": rho_gcc, + "datum_pressure": datum_p, + "r_squared": r2, + "n_points": n_fit, + "tvdss_range": t_str, + "accepted": not reject_reason, + "reject_reason": reject_reason, + } + ) + if not reject_reason: + fitted_densities[fl.upper()] = { + "density_gcc": rho_gcc, + "r_squared": r2, + "n_points": n_fit, + "gradient_psi_ft": g_psi_ft, + "fluid_type": fl, + } + + # Contacts from intersecting gradients are only meaningful when the intersecting + # fits are physical; otherwise suppress them rather than present an arbitrary depth. + accepted_phases = set(fitted_densities.keys()) + if len(accepted_phases) < 2: + contacts_res = {} + for c_key, c_val in contacts_res.items(): + c_dict = c_val.to_dict() + p50_tvdss = _safe_float(c_dict.get("tvdss_p50")) + p10_tvdss = _safe_float(c_dict.get("tvdss_p10"), p50_tvdss) + p90_tvdss = _safe_float(c_dict.get("tvdss_p90"), p50_tvdss) + p_contact = _safe_float(c_dict.get("pressure_at_contact"), 0.0) + delta_log = round(p50_tvdss - ref_fwl, 1) + if not fwl_is_committed: + status_str = ( + "INDICATIVE (no committed contact to reconcile against)" + ) + elif abs(delta_log) <= 2.0: + status_str = "✓ RECONCILED (< 2.0 m)" + else: + status_str = f"Δ = {delta_log:+.1f} m" + + fpt_contacts.append( + { + "contact_type": c_dict.get( + "label", c_dict.get("contact_type", c_key) + ), + "tvdss_p50": p50_tvdss, + "tvdss_p10": p10_tvdss, + "tvdss_p90": p90_tvdss, + "pressure_at_contact": p_contact, + "delta_log_tvdss": delta_log, + "status": status_str, + } + ) + except Exception as exc: + logger.debug(f"Formation pressure gradient regression fallback: {exc}") + + fpt_summary = { + "has_data": len(raw_points) > 0, + "total_stations": len(raw_points), + "valid_stations": len(valid_points), + "well_fpt_rows": well_fpt_rows, + "fpt_gradient_rows": fpt_gradient_rows, + "fpt_contacts": fpt_contacts, + "fitted_densities": fitted_densities, + "fwl": fwl_val, + "filter_note": fpt_filter_note, + "fwl_is_committed": fwl_is_committed, + "rejected_fits": [r for r in fpt_gradient_rows if not r.get("accepted", True)], + } + return fpt_summary, valid_points + + # --------------------------------------------------------------------------- # Step 1: Context Collector (`build_report_context`) & Gate-Check Validator # --------------------------------------------------------------------------- @@ -434,13 +1295,20 @@ def build_report_context( phie_cut = _safe_float(cut.get("phie", cut.get("PHIT", 0.08)), 0.08) sw_cut = _safe_float(cut.get("sw", cut.get("SWT", 0.65)), 0.65) ressum_cutoffs = {"VSHALE": vsh_cut, "PHIT": phie_cut, "SWT": sw_cut} - need_upscaling = enabled_section_ids is None or "09_upscaling" in enabled_section_ids + need_upscaling = ( + enabled_section_ids is None or "09_upscaling" in enabled_section_ids + ) wells_inventory: List[Dict[str, Any]] = [] qaqc_table: List[Dict[str, Any]] = [] upscaling_table: List[Dict[str, Any]] = [] well_zonal_rows: List[Dict[str, Any]] = [] anomaly_flags: List[Dict[str, str]] = [] + hole_sections_rows: List[Dict[str, Any]] = [] + env_well_rows: List[Dict[str, Any]] = [] + invasion_well_rows: List[Dict[str, Any]] = [] + env_assumptions_seen: List[str] = [] + resolved_envs: List[Any] = [] combined_dfs: List[pd.DataFrame] = [] unfiltered_dfs: List[pd.DataFrame] = [] @@ -469,13 +1337,17 @@ def build_report_context( if w_cfg: merged_configs.update(w_cfg) requested_model = model_params or {} - well_litho_model = str( - requested_model.get("litho_model_key") - or requested_model.get("litho_model") - or w_cfg.get("litho_model_key") - or w_cfg.get("litho_model") - or "" - ).strip().lower() + well_litho_model = ( + str( + requested_model.get("litho_model_key") + or requested_model.get("litho_model") + or w_cfg.get("litho_model_key") + or w_cfg.get("litho_model") + or "" + ) + .strip() + .lower() + ) is_bulk_shale = well_litho_model == "vsh_bulk" w_df = raw_df.copy() @@ -528,12 +1400,21 @@ def build_report_context( # Enforce strict TVD / TVDss check (Spec 2.1: Never substitute MD into TVD/TVDss) has_tvd = False - if "TVD" in w_df.columns and pd.to_numeric(w_df["TVD"], errors="coerce").notna().any(): + if ( + "TVD" in w_df.columns + and pd.to_numeric(w_df["TVD"], errors="coerce").notna().any() + ): has_tvd = True tvd_s = pd.to_numeric(w_df["TVD"], errors="coerce") - if "TVDSS" not in w_df.columns or not pd.to_numeric(w_df["TVDSS"], errors="coerce").notna().any(): + if ( + "TVDSS" not in w_df.columns + or not pd.to_numeric(w_df["TVDSS"], errors="coerce").notna().any() + ): w_df["TVDSS"] = tvd_s - df_val - elif "TVDSS" in w_df.columns and pd.to_numeric(w_df["TVDSS"], errors="coerce").notna().any(): + elif ( + "TVDSS" in w_df.columns + and pd.to_numeric(w_df["TVDSS"], errors="coerce").notna().any() + ): has_tvd = True tvdss_s = pd.to_numeric(w_df["TVDSS"], errors="coerce") w_df["TVD"] = tvdss_s + df_val @@ -607,12 +1488,14 @@ def build_report_context( if is_bulk_shale: w_df["_REPORT_VSHALE"] = _col_series(w_df, "VSHALE", np.nan) if w_df["_REPORT_VSHALE"].isna().any(): - anomaly_flags.append({ - "category": "Missing bulk shale", - "target": w_name, - "message": "Bulk VSHALE is missing at one or more samples; those samples are excluded from shale-cutoff calculations.", - "mitigation": "Save a calibrated bulk-shale evaluation before generating the report.", - }) + anomaly_flags.append( + { + "category": "Missing bulk shale", + "target": w_name, + "message": "Bulk VSHALE is missing at one or more samples; those samples are excluded from shale-cutoff calculations.", + "mitigation": "Save a calibrated bulk-shale evaluation before generating the report.", + } + ) else: w_df["_REPORT_VSHALE"] = _col_series(w_df, "VCLAY", np.nan).fillna(0.20) @@ -623,13 +1506,134 @@ def build_report_context( total_logged_thickness += td # Inventory row + eval_curve_names = { + "VCLAY", + "VSHALE", + "_REPORT_VSHALE", + "PHIT", + "PHIE", + "PERM", + "SWT", + "SWE", + "ROCK_FLAG", + "PERM_TRANS", + "SHF", + "BADHOLE", + "HC_FLAG", + "TIGHT_FLAG", + "COAL_FLAG", + "CPORE", + "CPERM", + "CPORE_UNSHIFTED", + "CPERM_UNSHIFTED", + "CPORE_AMB", + "CPERM_AIR", + "CPORE_ORI", + "CPERM_ORI", + } + provenance = _classify_curve_provenance(raw_curves) + raw_curves_only = [ + c for c in provenance["raw"] if c.upper() not in eval_curve_names + ] + edited_curves_found = provenance["edited"] + computed_curves_found = [ + c for c in provenance["computed"] if c.upper() not in eval_curve_names + ] + + # Coverage of each raw curve (% of the logged interval with a valid value), so the table can show + # only the primary measurements with their completeness instead of every column. + raw_coverage: Dict[str, float] = {} + n_rows_w = max(len(w_df), 1) + for c in raw_curves_only: + try: + raw_coverage[c] = round( + 100.0 + * float(pd.to_numeric(w_df[c], errors="coerce").notna().sum()) + / n_rows_w, + 0, + ) + except Exception: + continue + + eval_curves_only = [ + c + for c in [ + "VCLAY", + "PHIT", + "PHIE", + "PERM", + "SWT", + "ROCK_FLAG", + "SHF", + "CPORE", + "CPERM", + "BADHOLE", + ] + if c in w_df.columns and w_df[c].notna().any() + ] + cpore_cnt = ( int(pd.to_numeric(w_df["CPORE"], errors="coerce").notna().sum()) if "CPORE" in w_df.columns else 0 ) core_cnt = max(int(w_meta.get("core_sample_count") or 0), cpore_cnt) + scal_curves_found = [ + c + for c in ("PC", "KRW", "KRO", "SCAL_PC") + if c in w_df.columns and w_df[c].notna().any() + ] + n_scal = int(w_meta.get("scal_sample_count") or len(scal_curves_found)) + if core_cnt > 0 or n_scal > 0: + core_status_str = f"RCA: {core_cnt} pts | SCAL: {n_scal} pts" + else: + core_status_str = "No Core Plugs" + press_cnt = int(w_meta.get("pressure_test_count") or 0) + w_hole_sections = list(w_meta.get("hole_sections") or []) + w_hs_cnt = int(w_meta.get("hole_section_count") or len(w_hole_sections)) + for hs_item in w_hole_sections: + if not isinstance(hs_item, dict): + continue + hole_sections_rows.append( + { + "well_name": w_name, + "name": str(hs_item.get("name") or "Section"), + "top": _safe_float(hs_item.get("top"), 0.0), + "bottom": _safe_float(hs_item.get("bottom"), 0.0), + "bit_size": ( + round(float(hs_item["bit_size"]), 3) + if hs_item.get("bit_size") is not None + else None + ), + "mud_type": str(hs_item.get("mud_type") or "WBM").upper(), + "mud_weight": ( + round(float(hs_item["mud_weight"]), 2) + if hs_item.get("mud_weight") is not None + else None + ), + "mud_salinity": ( + int(round(float(hs_item["mud_salinity"]))) + if hs_item.get("mud_salinity") is not None + else None + ), + "rmf": ( + round(float(hs_item["rmf"]), 4) + if hs_item.get("rmf") is not None + else None + ), + "rmf_temp": ( + round(float(hs_item["rmf_temp"]), 1) + if hs_item.get("rmf_temp") is not None + else None + ), + } + ) + has_env_corr_well = any( + f"{lg}_ENV_CORR" in w_df.columns + and pd.to_numeric(w_df[f"{lg}_ENV_CORR"], errors="coerce").notna().any() + for lg in ("GR", "NPHI", "RHOB", "RT", "DT") + ) wells_inventory.append( { "name": w_name, @@ -640,11 +1644,22 @@ def build_report_context( "max_depth": round(d_max, 1), "td": round(td, 1), "curves": display_curves[:13], + "raw_curves": raw_curves_only, + "raw_coverage": raw_coverage, + "edited_curves": edited_curves_found, + "computed_curves": computed_curves_found, + "eval_curves": eval_curves_only, "available_curves": raw_curves, "core_sample_count": core_cnt, + "core_status": core_status_str, "has_core": f"Yes ({core_cnt} pts)" if core_cnt > 0 else "No", "pressure_test_count": press_cnt, "has_pressure": f"Yes ({press_cnt} pts)" if press_cnt > 0 else "No", + "hole_section_count": w_hs_cnt, + "has_hole_sections": ( + f"Yes ({w_hs_cnt} sec)" if w_hs_cnt > 0 else "No" + ), + "has_env_corr": has_env_corr_well, "formation_top_count": int( w_meta.get("formation_top_count") or len( @@ -673,14 +1688,244 @@ def build_report_context( combined_dfs.append(w_df) + # Resolve per-well logging environment (LAS header + saved module_params['qaqc-env'] + request env_corr_params + hole sections) + req_env_p = ( + requested_model.get("env_corr_params") + if isinstance(requested_model.get("env_corr_params"), dict) + else {} + ) + saved_w_mp = ( + w_cfg.get("module_params", {}).get("qaqc-env") + if isinstance(w_cfg.get("module_params"), dict) + else None + ) + saved_env_p: Dict[str, Any] = {} + if isinstance(saved_w_mp, dict) and saved_w_mp: + first_env_entry = next(iter(saved_w_mp.values())) + if isinstance(first_env_entry, dict) and isinstance( + first_env_entry.get("params"), dict + ): + saved_env_p = dict(first_env_entry["params"]) + env_src_cfg: Dict[str, Any] = {} + if isinstance(header_info, dict) and header_info: + try: + las_meta = extract_las_metadata(header_info, fallback_well_name=w_name) + env_src_cfg.update( + {k: v for k, v in dict(las_meta).items() if v is not None} + ) + except Exception: + pass + if isinstance(header_info.get("header_overrides"), dict): + env_src_cfg.update( + { + k: v + for k, v in header_info["header_overrides"].items() + if v is not None + } + ) + for k, v in w_cfg.items(): + if not str(k).startswith("_") and v is not None: + env_src_cfg[k] = v + + env_overrides: Dict[str, Any] = {} + for p_src in (saved_env_p, req_env_p): + if not p_src: + continue + if p_src.get("mudType") or p_src.get("mud_type"): + mt_cand = str(p_src.get("mudType") or p_src.get("mud_type")).upper() + if mt_cand in ("WBM", "OBM", "SBM"): + env_overrides["mud_type"] = mt_cand + if ( + p_src.get("mudWeight") is not None + or p_src.get("mud_weight") is not None + ): + env_overrides["mud_weight_ppg"] = p_src.get( + "mudWeight", p_src.get("mud_weight") + ) + if ( + p_src.get("bitsizeDefault") is not None + or p_src.get("bitsize_default") is not None + ): + env_overrides["bit_size"] = p_src.get( + "bitsizeDefault", p_src.get("bitsize_default") + ) + if ( + p_src.get("salinityPpm") is not None + or p_src.get("salinity_ppm") is not None + ): + env_overrides["mud_salinity_ppm"] = p_src.get( + "salinityPpm", p_src.get("salinity_ppm") + ) + if ( + p_src.get("formationSalinityPpm") is not None + or p_src.get("formation_salinity_ppm") is not None + ): + env_overrides["formation_salinity_ppm"] = p_src.get( + "formationSalinityPpm", p_src.get("formation_salinity_ppm") + ) + if p_src.get("rmf") is not None and _safe_float(p_src.get("rmf"), 0.0) > 0: + env_overrides["rmf"] = float(p_src["rmf"]) + if ( + p_src.get("rmfTempC") is not None + or p_src.get("rmf_temp_c") is not None + ): + env_overrides["rmf_temp"] = float( + p_src.get("rmfTempC", p_src.get("rmf_temp_c")) + ) + env_overrides["rmf_temp_unit"] = "degC" + if ( + p_src.get("offshore") + and _safe_float(p_src.get("waterDepth", p_src.get("water_depth")), 0.0) + > 0 + ): + env_overrides["water_depth"] = float( + p_src.get("waterDepth", p_src.get("water_depth")) + ) + if ( + p_src.get("seabedTempC") is not None + or p_src.get("seabed_temp_c") is not None + ): + env_overrides["seabed_temp_c"] = float( + p_src.get("seabedTempC", p_src.get("seabed_temp_c")) + ) + if ( + p_src.get("surfaceTemp") is not None + or p_src.get("surface_temp") is not None + ): + env_overrides["surface_temp"] = float( + p_src.get("surfaceTemp", p_src.get("surface_temp")) + ) + env_overrides["surface_temp_unit"] = "degF" + tg_f = p_src.get( + "tempGrad", p_src.get("tempGradient", p_src.get("temp_grad")) + ) + if tg_f is not None: + env_overrides["temp_gradient_c_per_km"] = ( + float(tg_f) * (5.0 / 9.0) * (1000.0 / 30.48) + ) + + use_hs_well = bool( + req_env_p.get( + "useHoleSections", + req_env_p.get( + "use_hole_sections", + requested_model.get("use_hole_sections", True), + ), + ) + ) + if use_hs_well and w_hole_sections: + mp_list = [] + for s_hs in w_hole_sections: + if ( + isinstance(s_hs, dict) + and s_hs.get("top") is not None + and s_hs.get("bottom") is not None + ): + mp_list.append( + { + "top": float(s_hs["top"]), + "bottom": float(s_hs["bottom"]), + "bit_size_in": s_hs.get("bit_size"), + "mud_type": str(s_hs.get("mud_type") or "WBM").upper(), + "mud_weight_ppg": s_hs.get("mud_weight"), + "salinity_ppm": s_hs.get("mud_salinity"), + "rmf": s_hs.get("rmf"), + "rmf_temp_c": s_hs.get("rmf_temp"), + } + ) + if mp_list: + env_overrides["mud_program"] = mp_list + + if env_src_cfg.get("mud_type") is not None and str( + env_src_cfg["mud_type"] + ).upper() not in ("WBM", "OBM", "SBM"): + env_src_cfg.pop("mud_type", None) + + raw_duom = str( + req_env_p.get("depthUnit") + or req_env_p.get("depth_unit") + or w_meta.get("depth_uom") + or env_src_cfg.get("datum_unit") + or "m" + ).lower() + eff_duom = "ft" if raw_duom in ("ft", "f", "feet", "foot") else "m" + try: + well_env = environment_from_config( + env_src_cfg, env_overrides, depth_unit=eff_duom + ) + except Exception: + well_env = environment_from_config({}, {}, depth_unit="m") + resolved_envs.append(well_env) + for a_msg in well_env.assumptions: + if a_msg not in env_assumptions_seen: + env_assumptions_seen.append(a_msg) + + w_tool_type = str( + req_env_p.get("toolType") + or req_env_p.get("tool_type") + or saved_env_p.get("toolType") + or w_cfg.get("tool_type") + or "WL" + ).upper() + if w_tool_type not in ("WL", "LWD"): + w_tool_type = "WL" + w_mud_types = sorted( + {iv.mud_type for iv in well_env.mud_program if iv.mud_type} + or {well_env.default_mud_type} + ) + w_mud_str = "/".join(w_mud_types) + # QA/QC row n_samples = len(w_df) - if "BADHOLE" in w_df.columns: + cali_s = _col_series(w_df, "CALI", np.nan) + bs_default_val = _safe_float( + merged_configs.get("bitsize_default", well_env.default_bit_size_in), 8.5 + ) + if ( + "ENV_BS" in w_df.columns + and pd.to_numeric(w_df["ENV_BS"], errors="coerce").notna().any() + ): + bs_s = _col_series(w_df, "ENV_BS", bs_default_val) + elif ( + "BS" in w_df.columns + and pd.to_numeric(w_df["BS"], errors="coerce").notna().any() + ): + bs_s = _col_series(w_df, "BS", bs_default_val) + elif use_hs_well and w_hole_sections and "DEPTH" in w_df.columns: + bs_hs = _synthesize_bitsize_series(w_df["DEPTH"], w_hole_sections) + bs_s = bs_hs.fillna(bs_default_val) + bs_s.index = w_df.index + else: + bs_s = pd.Series(bs_default_val, index=w_df.index, dtype=float) + drho_s = _col_series(w_df, "DRHO", np.nan) + rhob_s = _col_series(w_df, "RHOB", np.nan) + nphi_s = _col_series(w_df, "NPHI", np.nan) + + if "BADHOLE" in w_df.columns and w_df["BADHOLE"].notna().any(): bh_mask = _col_series(w_df, "BADHOLE", 0.0) >= 1.0 else: - rhob_s = _col_series(w_df, "RHOB", np.nan) - nphi_s = _col_series(w_df, "NPHI", np.nan) - bh_mask = ((rhob_s < 2.0) | (nphi_s > 0.42)).fillna(False) + bh_conds = [] + if cali_s.notna().any(): + bh_conds.append( + (cali_s - bs_s) + > _safe_float(merged_configs.get("cali_threshold"), 2.0) + ) + if drho_s.notna().any(): + bh_conds.append( + drho_s.abs() + > _safe_float(merged_configs.get("drho_threshold"), 0.15) + ) + if rhob_s.notna().any(): + bh_conds.append( + rhob_s < _safe_float(merged_configs.get("rhob_min"), 1.95) + ) + if bh_conds: + bh_mask = bh_conds[0] + for c in bh_conds[1:]: + bh_mask = bh_mask | c + bh_mask = bh_mask.fillna(False) + else: + bh_mask = ((rhob_s < 2.0) | (nphi_s > 0.42)).fillna(False) bh_cnt = int(bh_mask.sum()) bh_pct = 100.0 * bh_cnt / max(n_samples, 1) @@ -689,21 +1934,270 @@ def build_report_context( tight_cnt = int((_col_series(w_df, "TIGHT_FLAG", 0.0) >= 1.0).sum()) coal_cnt = int((_col_series(w_df, "COAL_FLAG", 0.0) >= 1.0).sum()) - gr_clean = _col_series(w_df, "GR", np.nan).dropna() - rhob_clean = _col_series(w_df, "RHOB", np.nan).dropna() + gr_clean = _select_conditioned_curve(w_df, "GR", weight_by_conf=False).dropna() + rhob_clean = _select_conditioned_curve( + w_df, "RHOB", weight_by_conf=False + ).dropna() gr_p50 = float(np.percentile(gr_clean, 50)) if not gr_clean.empty else 55.0 rhob_p50 = ( float(np.percentile(rhob_clean, 50)) if not rhob_clean.empty else 2.42 ) - qc_status = "FLAGGED (>15% Washout)" if bh_pct > 15.0 else "PASS" - if bh_pct > 15.0: - anomaly_flags.append( - { - "category": "Borehole Rugosity / Washout", - "target": w_name, - "message": f"Bad-hole flag exceeds 15% threshold ({bh_pct:.1f}%, {bh_cnt} depth samples).", - "mitigation": "Applied GR-derived shale fallback and excluded rugose intervals from density porosity calibration.", + # Per-well Borehole Environmental Correction & Sensor Confidence Audit + env_curves_w: List[str] = [] + conf_vals_w: List[float] = [] + unrel_pcts_w: List[float] = [] + env_deltas_w: Dict[str, str] = { + "GR": "—", + "NPHI": "—", + "RHOB": "—", + "RT": "—", + } + for lg_k in ("GR", "NPHI", "RHOB", "RT", "DT"): + c_col = f"{lg_k}_ENV_CORR" + st_col = f"{lg_k}_QC_STATUS" + cf_col = f"{lg_k}_QC_CONF" + dl_col = f"{lg_k}_CORR_DELTA" + if ( + c_col in w_df.columns + and pd.to_numeric(w_df[c_col], errors="coerce").notna().any() + ): + env_curves_w.append(lg_k) + if st_col in w_df.columns: + st_s = pd.to_numeric(w_df[st_col], errors="coerce") + valid_st = st_s >= 0 + n_st = int(valid_st.sum()) + if n_st > 0: + unrel_pcts_w.append(100.0 * float((st_s == 2).sum()) / n_st) + if cf_col in w_df.columns: + cf_s = pd.to_numeric(w_df[cf_col], errors="coerce").dropna() + if not cf_s.empty: + conf_vals_w.append(float(cf_s.mean())) + if lg_k in env_deltas_w: + if dl_col in w_df.columns: + dl_s = pd.to_numeric(w_df[dl_col], errors="coerce").dropna() + elif c_col in w_df.columns and lg_k in w_df.columns: + if lg_k == "RT": + dl_s = ( + np.log10( + pd.to_numeric(w_df[c_col], errors="coerce").clip( + lower=1e-3 + ) + ) + - np.log10( + pd.to_numeric(w_df[lg_k], errors="coerce").clip( + lower=1e-3 + ) + ) + ).dropna() + else: + dl_s = ( + pd.to_numeric(w_df[c_col], errors="coerce") + - pd.to_numeric(w_df[lg_k], errors="coerce") + ).dropna() + else: + dl_s = pd.Series(dtype=float) + if not dl_s.empty: + fmt_spec = "+.1f" if lg_k == "GR" else "+.3f" + env_deltas_w[lg_k] = format(float(dl_s.median()), fmt_spec) + + w_has_env = len(env_curves_w) > 0 + w_mean_conf = round(float(np.mean(conf_vals_w)), 3) if conf_vals_w else None + w_max_unrel = round(max(unrel_pcts_w), 1) if unrel_pcts_w else 0.0 + sev_s = ( + pd.to_numeric(w_df["HOLE_SEVERITY"], errors="coerce") + if "HOLE_SEVERITY" in w_df.columns + else pd.Series(dtype=float) + ) + w_severe_pct = ( + round(100.0 * float((sev_s >= 2).mean()), 1) + if not sev_s.dropna().empty + else round(bh_pct, 1) + ) + reason_w_s = ( + pd.to_numeric(w_df["ENV_QC_REASON"], errors="coerce").fillna(0).astype(int) + if "ENV_QC_REASON" in w_df.columns + else pd.Series(dtype=int) + ) + w_cycle_skips = ( + int( + ( + (reason_w_s.to_numpy(dtype=int) & ENV_QC_REASON_BITS["CYCLE_SKIP"]) + != 0 + ).sum() + ) + if not reason_w_s.empty + else 0 + ) + w_res_mismatch = ( + int( + ( + ( + reason_w_s.to_numpy(dtype=int) + & ENV_QC_REASON_BITS["RES_MUD_MISMATCH"] + ) + != 0 + ).sum() + ) + if not reason_w_s.empty + else 0 + ) + w_dom_reason = _dominant_env_reason(reason_w_s) + + if w_has_env: + env_well_rows.append( + { + "well_name": w_name, + "tool_type": w_tool_type, + "mud_type": w_mud_str, + "hole_sections": w_hs_cnt, + "curves": ", ".join(env_curves_w), + "mean_conf": w_mean_conf, + "unreliable_pct": w_max_unrel, + "severe_hole_pct": w_severe_pct, + "cycle_skips": w_cycle_skips, + "delta_gr": env_deltas_w["GR"], + "delta_nphi": env_deltas_w["NPHI"], + "delta_rhob": env_deltas_w["RHOB"], + "delta_rt": env_deltas_w["RT"], + "dominant_reason": w_dom_reason, + } + ) + + # Radial Resistivity Invasion Profile summary per well + if "INVASION_PROFILE" in w_df.columns or "INVASION_FLAG" in w_df.columns: + inv_fl = ( + pd.to_numeric(w_df["INVASION_FLAG"], errors="coerce").fillna(0) + if "INVASION_FLAG" in w_df.columns + else pd.Series(0, index=w_df.index) + ) + inv_pr = ( + pd.to_numeric(w_df["INVASION_PROFILE"], errors="coerce").fillna(0) + if "INVASION_PROFILE" in w_df.columns + else pd.Series(0, index=w_df.index) + ) + di_s = ( + pd.to_numeric(w_df["DI_EST"], errors="coerce").dropna() + if "DI_EST" in w_df.columns + else pd.Series(dtype=float) + ) + rt_ref_s = _select_conditioned_curve(w_df, "RT", weight_by_conf=False) + n_rt_valid = max(int(rt_ref_s.notna().sum()), 1) + inv_cnt = int((inv_fl > 0).sum()) + inv_pct_w = round(100.0 * inv_cnt / n_rt_valid, 1) + water_like_pct = round(100.0 * float((inv_pr == 1).sum()) / n_rt_valid, 1) + hc_like_pct = round(100.0 * float((inv_pr == 2).sum()) / n_rt_valid, 1) + anom_pct = round(100.0 * float((inv_pr == 3).sum()) / n_rt_valid, 1) + tight_inv_pct = round(100.0 * float((inv_pr == 4).sum()) / n_rt_valid, 1) + med_di = round(float(di_s.median()), 1) if not di_s.empty else None + p90_di = ( + round(float(np.nanpercentile(di_s, 90)), 1) + if len(di_s) >= 3 + else med_di + ) + invasion_well_rows.append( + { + "well_name": w_name, + "mud_type": w_mud_str, + "samples": n_rt_valid, + "invaded_pct": inv_pct_w, + "water_like_pct": water_like_pct, + "hc_like_pct": hc_like_pct, + "anomalous_pct": anom_pct, + "tight_pct": tight_inv_pct, + "median_di_in": med_di, + "p90_di_in": p90_di, + } + ) + if anom_pct > 15.0: + anomaly_flags.append( + { + "category": "Anomalous Resistivity Invasion Contrast", + "target": w_name, + "message": ( + f"{anom_pct:.1f}% of resistivity samples exhibit anomalous Rxo/Rt contrast " + "(INVASION_PROFILE = 3, exceeding expected Rmf/Rw bounds)." + ), + "mitigation": "Verify depth alignment between shallow/medium/deep resistivity curves, Rmf @ Tmeas input, and thin-bed shoulder effects.", + } + ) + + if w_res_mismatch > 0: + anomaly_flags.append( + { + "category": "Resistivity Tool / Mud-Type Mismatch", + "target": w_name, + "message": ( + f"Laterolog resistivity flagged in non-conductive {w_mud_str} mud across {w_res_mismatch} samples (ENV_QC_REASON bit 512)." + ), + "mitigation": "Confirm induction/propagation resistivity tool type or switch mud system metadata before water saturation evaluation.", + } + ) + if w_has_env and w_max_unrel > 20.0: + anomaly_flags.append( + { + "category": "Low Borehole Sensor Confidence", + "target": w_name, + "message": ( + f"Up to {w_max_unrel:.1f}% of environmentally corrected samples are rated UNRELIABLE " + f"(mean confidence = {w_mean_conf if w_mean_conf is not None else 0.0:.2f}; dominant cause: {w_dom_reason})." + ), + "mitigation": "Enable QC confidence weighting (`confidence_weighting=True`) or bad-hole fallback across low-confidence washouts.", + } + ) + if n_samples > 0 and (100.0 * w_cycle_skips / n_samples) > 5.0: + anomaly_flags.append( + { + "category": "Sonic Cycle-Skip Excursions", + "target": w_name, + "message": ( + f"Detected {w_cycle_skips} sonic cycle-skip samples ({100.0 * w_cycle_skips / n_samples:.1f}% of interval) removed in DT_ENV_CORR." + ), + "mitigation": "Use DT_ENV_CORR or density-neutron porosity across cycle-skipped intervals.", + } + ) + + if w_res_mismatch > 0: + qc_status = "FLAGGED (Res/Mud Mismatch)" + elif bh_pct > 15.0: + qc_status = "FLAGGED (>15% Washout)" + elif w_has_env and w_max_unrel > 20.0: + qc_status = "REVIEW (Low Conf)" + else: + qc_status = "PASS" + + delta_gr = "—" + delta_rhob = "—" + delta_nphi = "—" + if "GR_NORM" in w_df.columns and "GR" in w_df.columns: + d_gr = ( + pd.to_numeric(w_df["GR_NORM"], errors="coerce") + - pd.to_numeric(w_df["GR"], errors="coerce") + ).dropna() + if not d_gr.empty: + delta_gr = f"{float(d_gr.median()):+.1f}" + if "RHOB_NORM" in w_df.columns and "RHOB" in w_df.columns: + d_rhob = ( + pd.to_numeric(w_df["RHOB_NORM"], errors="coerce") + - pd.to_numeric(w_df["RHOB"], errors="coerce") + ).dropna() + if not d_rhob.empty: + delta_rhob = f"{float(d_rhob.median()):+.3f}" + if "NPHI_NORM" in w_df.columns and "NPHI" in w_df.columns: + d_nphi = ( + pd.to_numeric(w_df["NPHI_NORM"], errors="coerce") + - pd.to_numeric(w_df["NPHI"], errors="coerce") + ).dropna() + if not d_nphi.empty: + delta_nphi = f"{float(d_nphi.median()):+.3f}" + + if bh_pct > 15.0: + anomaly_flags.append( + { + "category": "Borehole Rugosity / Washout", + "target": w_name, + "message": f"Bad-hole flag exceeds 15% threshold ({bh_pct:.1f}%, {bh_cnt} depth samples).", + "mitigation": "Applied GR-derived shale fallback and excluded rugose intervals from density porosity calibration.", } ) @@ -718,6 +2212,15 @@ def build_report_context( "coal_count": coal_cnt, "gr_p50": round(gr_p50, 2), "rhob_p50": round(rhob_p50, 3), + "delta_gr": delta_gr, + "delta_rhob": delta_rhob, + "delta_nphi": delta_nphi, + "has_env_corr": w_has_env, + "env_curves": ", ".join(env_curves_w) if env_curves_w else "—", + "mean_qc_conf": w_mean_conf, + "unreliable_pct": w_max_unrel, + "hole_section_count": w_hs_cnt, + "mud_type": w_mud_str, "status": qc_status, } ) @@ -741,7 +2244,9 @@ def build_report_context( ) has_real_zones = bool(real_zone_mask.any()) - eval_mask = phi_eval.notna() & sw_eval.notna() & w_df["_REPORT_VSHALE"].notna() + eval_mask = ( + phi_eval.notna() & sw_eval.notna() & w_df["_REPORT_VSHALE"].notna() + ) if has_real_zones: eval_mask &= real_zone_mask @@ -754,7 +2259,9 @@ def build_report_context( depth=pd.to_numeric(eval_df["DEPTH"], errors="coerce").to_numpy( dtype=float ), - vshale=pd.to_numeric(eval_df["_REPORT_VSHALE"], errors="coerce").to_numpy(dtype=float), + vshale=pd.to_numeric( + eval_df["_REPORT_VSHALE"], errors="coerce" + ).to_numpy(dtype=float), phit=pd.to_numeric(eval_df[phi_col_name], errors="coerce").to_numpy( dtype=float ), @@ -776,7 +2283,9 @@ def build_report_context( str(r.get("zones")): r for _, r in rs_df[rs_df["flag"] == "pay"].iterrows() } - zone_keys = list(dict.fromkeys(list(res_rows.keys()) + list(pay_rows.keys()))) + zone_keys = list( + dict.fromkeys(list(res_rows.keys()) + list(pay_rows.keys())) + ) for z_key in zone_keys: r_res = res_rows.get(z_key, {}) @@ -921,13 +2430,27 @@ def build_report_context( { "DEPTH": pd.to_numeric(up_src["DEPTH"], errors="coerce"), "VCLAY": pd.to_numeric( - up_src["VCLAY"], errors="coerce" + up_src["VCLAY"] + if "VCLAY" in up_src.columns + else up_src.get("_REPORT_VSHALE", 0.20), + errors="coerce", + ).fillna(0.20), + "_REPORT_VSHALE": pd.to_numeric( + up_src["_REPORT_VSHALE"] + if "_REPORT_VSHALE" in up_src.columns + else up_src.get("VCLAY", 0.20), + errors="coerce", ).fillna(0.20), "PHIT": _col_series( up_src, "PHIE" if "PHIE" in up_src.columns else "PHIT", np.nan, ), + "PHIE": _col_series( + up_src, + "PHIE" if "PHIE" in up_src.columns else "PHIT", + np.nan, + ), "SWT": pd.to_numeric(up_src["SWT"], errors="coerce"), "PERM": pd.to_numeric(up_src["PERM"], errors="coerce") .fillna(1.0) @@ -936,9 +2459,15 @@ def build_report_context( } ).dropna(subset=["DEPTH", "PHIT", "SWT"]) if not up_in.empty: + up_cell_sz = _safe_float( + merged_configs.get( + "upscaling_cell_size", w_cfg.get("upscaling_cell_size") + ), + 2.0, + ) blocked = upscale_logs( up_in, - cell_size=2.0, + cell_size=up_cell_sz, by_zone=True, depth_col="DEPTH", zone_col="ZONES", @@ -960,9 +2489,7 @@ def build_report_context( if "PERM_HARM" in blocked.columns else "PERM_HARM_UP" ) - phi_up_col = ( - "PHIT" if "PHIT" in blocked.columns else "PHIT_UP" - ) + phi_up_col = "PHIT" if "PHIT" in blocked.columns else "PHIT_UP" sw_up_col = "SWT" if "SWT" in blocked.columns else "SWT_UP" k_am = ( @@ -980,11 +2507,109 @@ def build_report_context( if k_hm_col in blocked.columns else 0.0 ) + gross_m = ( + round(float(up_in["DEPTH"].max() - up_in["DEPTH"].min()), 1) + if "DEPTH" in up_in.columns and len(up_in) > 1 + else round(float(len(blocked) * up_cell_sz), 1) + ) + + # Net-reservoir calculation at fine scale + v_cut_val = _safe_float(ressum_cutoffs.get("vsh"), 0.40) + p_cut_val = _safe_float(ressum_cutoffs.get("phie"), 0.08) + vsh_fine = pd.to_numeric( + up_in["_REPORT_VSHALE"] + if "_REPORT_VSHALE" in up_in.columns + else up_in["VCLAY"], + errors="coerce", + ).fillna(0.0) + phie_fine = pd.to_numeric( + up_in["PHIE"] if "PHIE" in up_in.columns else up_in["PHIT"], + errors="coerce", + ).fillna(0.0) + sw_fine = pd.to_numeric(up_in["SWT"], errors="coerce").fillna( + 1.0 + ) + + fine_res_mask = (vsh_fine <= v_cut_val) & ( + phie_fine >= p_cut_val + ) + if fine_res_mask.any(): + phie_res_fine = round( + _safe_float(phie_fine[fine_res_mask].mean(), 0.0), 3 + ) + swt_res_fine = round( + _safe_float(sw_fine[fine_res_mask].mean(), 1.0), 3 + ) + else: + phie_res_fine = round(_safe_float(phie_fine.mean(), 0.0), 3) + swt_res_fine = round(_safe_float(sw_fine.mean(), 1.0), 3) + + # Net-reservoir calculation at blocked cellular scale + vsh_up_col = ( + "VCLAY" + if "VCLAY" in blocked.columns + else ( + "_REPORT_VSHALE" + if "_REPORT_VSHALE" in blocked.columns + else None + ) + ) + vsh_blocked = ( + pd.to_numeric(blocked[vsh_up_col], errors="coerce").fillna( + 0.0 + ) + if vsh_up_col + else pd.Series(0.0, index=blocked.index) + ) + phie_blocked = ( + pd.to_numeric(blocked[phi_up_col], errors="coerce").fillna( + 0.0 + ) + if phi_up_col in blocked.columns + else pd.Series(0.0, index=blocked.index) + ) + sw_blocked = ( + pd.to_numeric(blocked[sw_up_col], errors="coerce").fillna( + 1.0 + ) + if sw_up_col in blocked.columns + else pd.Series(1.0, index=blocked.index) + ) + + blocked_res_mask = (vsh_blocked <= v_cut_val) & ( + phie_blocked >= p_cut_val + ) + if blocked_res_mask.any(): + n_res_cells = int(blocked_res_mask.sum()) + ntg_res_up = round( + float(n_res_cells / max(len(blocked), 1)), 3 + ) + phie_res_up = round( + _safe_float(phie_blocked[blocked_res_mask].mean(), 0.0), + 3, + ) + swt_res_up = round( + _safe_float(sw_blocked[blocked_res_mask].mean(), 1.0), 3 + ) + else: + n_res_cells = int(len(blocked)) + ntg_res_up = 1.0 + phie_res_up = round( + _safe_float(phie_blocked.mean(), 0.0), 3 + ) + swt_res_up = round(_safe_float(sw_blocked.mean(), 1.0), 3) + + delta_phi_res = round(abs(phie_res_up - phie_res_fine), 3) + conservation_status = ( + "✓ CONSERVED" if delta_phi_res <= 0.015 else "⚠ DIVERGENT" + ) + upscaling_table.append( { "well_name": w_name, "fine_samples": int(len(up_in)), "n_cells": int(len(blocked)), + "gross_m": gross_m, "phit_up": round( _safe_float(blocked[phi_up_col].mean(), 0.0), 3 ) @@ -1001,6 +2626,14 @@ def build_report_context( "kv_kh": round(k_hm / max(k_am, 1e-6), 3) if k_am > 0 else 0.0, + "n_res_cells": n_res_cells, + "ntg_res_up": ntg_res_up, + "phie_res_up": phie_res_up, + "phie_res_fine": phie_res_fine, + "swt_res_up": swt_res_up, + "swt_res_fine": swt_res_fine, + "delta_phi_res": delta_phi_res, + "conservation_status": conservation_status, } ) except Exception as exc: @@ -1027,7 +2660,9 @@ def build_report_context( ) # Stratigraphic Target Filtering (`zones` / `target_zones` from Top Bar Zone Filter) - cfg_target_zones = requested_zones or target_zones or merged_configs.get("target_zones") + cfg_target_zones = ( + requested_zones or target_zones or merged_configs.get("target_zones") + ) if cfg_target_zones and isinstance(cfg_target_zones, list): resolved_target_zones = [ _normalize_zone_name(z) @@ -1049,9 +2684,7 @@ def build_report_context( target_zones_upper = {z.upper() for z in resolved_target_zones} if well_zonal_rows and target_zones_upper: filtered_wz = [ - r - for r in well_zonal_rows - if r["zone"].upper() in target_zones_upper + r for r in well_zonal_rows if r["zone"].upper() in target_zones_upper ] if filtered_wz: well_zonal_rows = filtered_wz @@ -1069,8 +2702,7 @@ def build_report_context( w_res = res_grp["net_res"].to_numpy(dtype=float) w_res_sum = max(float(np.sum(w_res)), 1e-6) vsh_res_mean = float( - np.sum(w_res * res_grp["vsh_res"].to_numpy(dtype=float)) - / w_res_sum + np.sum(w_res * res_grp["vsh_res"].to_numpy(dtype=float)) / w_res_sum ) phie_res_mean = float( np.sum(w_res * res_grp["phie_res"].to_numpy(dtype=float)) @@ -1097,9 +2729,7 @@ def build_report_context( phie_pay_mean = float( np.sum(w_pay * pay_grp["phie"].to_numpy(dtype=float)) / w_pay_sum ) - pore_w = np.maximum( - w_pay * pay_grp["phie"].to_numpy(dtype=float), 1e-6 - ) + pore_w = np.maximum(w_pay * pay_grp["phie"].to_numpy(dtype=float), 1e-6) sw_pay_mean = float( np.sum(pore_w * pay_grp["sw"].to_numpy(dtype=float)) / float(np.sum(pore_w)) @@ -1202,7 +2832,11 @@ def build_report_context( ck_s = _col_series(full_df, "CPERM", np.nan) pm_s = _col_series(full_df, "PERM", np.nan) tz_mask_perm = ( - full_df["ZONES"].astype(str).str.strip().str.upper().isin(target_zones_upper) + full_df["ZONES"] + .astype(str) + .str.strip() + .str.upper() + .isin(target_zones_upper) if "ZONES" in full_df.columns else pd.Series(True, index=full_df.index) ) @@ -1216,7 +2850,7 @@ def build_report_context( ky = np.log10(pm_s[active_kmask].to_numpy(dtype=float)) valid_cal_perm_count = int(len(kx)) core_perm_log_rmse = round(float(np.sqrt(np.mean((ky - kx) ** 2))), 3) - core_perm_factor_err = round(float(10.0 ** core_perm_log_rmse), 2) + core_perm_factor_err = round(float(10.0**core_perm_log_rmse), 2) ss_res_k = float(np.sum((ky - kx) ** 2)) ss_tot_k = float(np.sum((kx - np.mean(kx)) ** 2)) core_perm_r2 = round( @@ -1227,20 +2861,18 @@ def build_report_context( ph_s = _col_series( full_df, "PHIT" if "PHIT" in full_df.columns else "PHIE", np.nan ) - cp_s = pd.Series( - np.where(cp_s > 1.0, cp_s / 100.0, cp_s), index=full_df.index - ) + cp_s = pd.Series(np.where(cp_s > 1.0, cp_s / 100.0, cp_s), index=full_df.index) tz_mask_core = ( - full_df["ZONES"].astype(str).str.strip().str.upper().isin(target_zones_upper) + full_df["ZONES"] + .astype(str) + .str.strip() + .str.upper() + .isin(target_zones_upper) if "ZONES" in full_df.columns else pd.Series(True, index=full_df.index) ) cmask_target = ( - cp_s.notna() - & ph_s.notna() - & (cp_s > 0.005) - & (cp_s < 0.48) - & tz_mask_core + cp_s.notna() & ph_s.notna() & (cp_s > 0.005) & (cp_s < 0.48) & tz_mask_core ) cmask_all = cp_s.notna() & ph_s.notna() & (cp_s > 0.005) & (cp_s < 0.48) active_cmask = cmask_target if cmask_target.sum() >= 3 else cmask_all @@ -1284,51 +2916,248 @@ def build_report_context( rhoma_count = int(len(gs_valid)) break + # Spec 2.2: Well-by-Well Core Parity Breakdown + well_core_parity: List[Dict[str, Any]] = [] + unique_wells_for_parity = [w["name"] for w in wells_inventory] + for wn in unique_wells_for_parity: + w_df_sub = ( + full_df[ + full_df["WELL_NAME"].astype(str).str.strip().str.upper() + == wn.strip().upper() + ] + if ("WELL_NAME" in full_df.columns and not full_df.empty) + else full_df + ) + if w_df_sub.empty: + continue + + cp_w = _col_series(w_df_sub, "CPORE", np.nan) + cp_w = pd.Series(np.where(cp_w > 1.0, cp_w / 100.0, cp_w), index=w_df_sub.index) + phit_w = _col_series(w_df_sub, "PHIT", np.nan) + phie_w = _col_series(w_df_sub, "PHIE", np.nan) + + tz_sub = ( + w_df_sub["ZONES"] + .astype(str) + .str.strip() + .str.upper() + .isin(target_zones_upper) + if "ZONES" in w_df_sub.columns and target_zones_upper + else pd.Series(True, index=w_df_sub.index) + ) + valid_p_mask = cp_w.notna() & (cp_w > 0.005) & (cp_w < 0.48) & tz_sub + if valid_p_mask.sum() < 3: + valid_p_mask = cp_w.notna() & (cp_w > 0.005) & (cp_w < 0.48) + + n_plugs_w = int(valid_p_mask.sum()) + shift_s = _col_series(w_df_sub, "SHIFT_M", 0.0) + mean_shift_m = ( + float(shift_s[valid_p_mask].mean()) + if (n_plugs_w > 0 and shift_s.notna().any()) + else 0.0 + ) + + r2_phit_w = 0.0 + r2_phie_w = 0.0 + rmse_phi_w = 0.0 + bias_phi_w = 0.0 + + if n_plugs_w >= 3: + cx_w = cp_w[valid_p_mask].to_numpy(dtype=float) + if phit_w.notna().any(): + ly_t = phit_w[valid_p_mask].to_numpy(dtype=float) + valid_t = ~np.isnan(ly_t) + if valid_t.sum() >= 3: + cx_t = cx_w[valid_t] + ly_t = ly_t[valid_t] + rmse_phi_w = round(float(np.sqrt(np.mean((ly_t - cx_t) ** 2))), 4) + bias_phi_w = round(float(np.mean(ly_t - cx_t)), 4) + if np.std(cx_t) > 1e-6 and np.std(ly_t) > 1e-6: + corr_t = float(np.corrcoef(cx_t, ly_t)[0, 1]) + r2_phit_w = round(max(0.0, corr_t**2), 3) + if phie_w.notna().any(): + ly_e = phie_w[valid_p_mask].to_numpy(dtype=float) + valid_e = ~np.isnan(ly_e) + if valid_e.sum() >= 3: + cx_e = cx_w[valid_e] + ly_e = ly_e[valid_e] + if np.std(cx_e) > 1e-6 and np.std(ly_e) > 1e-6: + corr_e = float(np.corrcoef(cx_e, ly_e)[0, 1]) + r2_phie_w = round(max(0.0, corr_e**2), 3) + + ck_w = _col_series(w_df_sub, "CPERM", np.nan) + pm_w = _col_series(w_df_sub, "PERM", np.nan) + valid_k_mask = ( + ck_w.notna() & pm_w.notna() & (ck_w > 1e-3) & (pm_w > 1e-3) & tz_sub + ) + if valid_k_mask.sum() < 3: + valid_k_mask = ck_w.notna() & pm_w.notna() & (ck_w > 1e-3) & (pm_w > 1e-3) + n_perm_w = int(valid_k_mask.sum()) + r2_perm_w = 0.0 + rmse_log_k_w = 0.0 + factor_err_k_w = 1.0 + if n_perm_w >= 3: + kx_w = np.log10(ck_w[valid_k_mask].to_numpy(dtype=float)) + ky_w = np.log10(pm_w[valid_k_mask].to_numpy(dtype=float)) + rmse_log_k_w = round(float(np.sqrt(np.mean((ky_w - kx_w) ** 2))), 3) + factor_err_k_w = round(float(10.0**rmse_log_k_w), 2) + if np.std(kx_w) > 1e-6 and np.std(ky_w) > 1e-6: + corr_k = float(np.corrcoef(kx_w, ky_w)[0, 1]) + r2_perm_w = round(max(0.0, corr_k**2), 3) + + if n_plugs_w == 0 and n_perm_w == 0: + status_w = "NO PLUGS" + rec_w = "No overlapping core plugs in evaluated intervals." + elif r2_phit_w >= 0.60 or (abs(bias_phi_w) <= 0.02 and rmse_phi_w <= 0.03): + status_w = "ALIGNED" + rec_w = "Core-to-log porosity calibration is consistent." + elif r2_phit_w >= 0.40: + status_w = "REVIEW" + rec_w = ( + "Moderate correlation; verify depth matching and mineral grain density." + ) + else: + status_w = "MISALIGNED" + rec_w = "Low correlation / high residual; depth shifting or facies-specific grain density required." + + perm_status_w = ( + "ALIGNED" + if r2_perm_w >= 0.50 + else ("REVIEW" if r2_perm_w >= 0.30 else "MISALIGNED") + ) + perm_rec_w = ( + "Permeability transform consistent with core." + if r2_perm_w >= 0.50 + else "Inspect rock-typing flow zone indicators (FZI) and hydraulic flow units." + ) + + well_core_parity.append( + { + "well_name": wn, + "n_plugs": n_plugs_w, + "mean_shift_m": round(mean_shift_m, 2), + "r2_phit": r2_phit_w, + "r2_phie": r2_phie_w, + "rmse_phi": rmse_phi_w, + "bias_phi": bias_phi_w, + "status": status_w, + "recommendation": rec_w, + "n_perm_plugs": n_perm_w, + "r2_perm": r2_perm_w, + "rmse_log_perm": rmse_log_k_w, + "factor_err_perm": factor_err_k_w, + "perm_status": perm_status_w, + "perm_recommendation": perm_rec_w, + } + ) + # Spec 2.2: Dynamic Rock Typing & Permeability Regression via `scipy.stats.linregress` - cfg_fzi_cutoffs = ( - (model_params.get("fzi_cutoffs") or model_params.get("fziCutoffs")) - if isinstance(model_params, dict) - else None - ) or merged_configs.get("fzi_cutoffs") or merged_configs.get("fziCutoffs") - if cfg_fzi_cutoffs and isinstance(cfg_fzi_cutoffs, (list, tuple)): - resolved_fzi_cutoffs = sorted([float(c) for c in cfg_fzi_cutoffs if float(c) > 0]) + # Cutoff resolution order: explicit request > workbench-saved rock typing > well config > documented default. + saved_rt_entry = _load_saved_project_module_entry( + pid, "rock-typing", resolved_target_zones + ) + saved_rt_params = ( + saved_rt_entry.get("params") if isinstance(saved_rt_entry, dict) else None + ) or {} + saved_rt_method = str(saved_rt_params.get("drtMethod") or "fzi").strip().lower() + saved_fzi_cutoffs = saved_rt_params.get("fziCutoffs") + + cfg_fzi_cutoffs = None + cutoff_source = "" + for src_label, cand in ( + ( + "request override", + (model_params or {}).get("fzi_cutoffs") + or (model_params or {}).get("fziCutoffs") + if isinstance(model_params, dict) + else None, + ), + ( + f"saved workbench rock typing ({saved_rt_entry.get('label', 'project')})" + if saved_rt_entry + else "", + saved_fzi_cutoffs if saved_rt_method == "fzi" else None, + ), + ( + "well configuration", + merged_configs.get("fzi_cutoffs") or merged_configs.get("fziCutoffs"), + ), + ): + if cand and isinstance(cand, (list, tuple)): + try: + vals = sorted(float(c) for c in cand if float(c) > 0) + except (TypeError, ValueError): + vals = [] + if vals: + cfg_fzi_cutoffs, cutoff_source = vals, src_label + break + if cfg_fzi_cutoffs: + resolved_fzi_cutoffs = cfg_fzi_cutoffs else: resolved_fzi_cutoffs = [0.5, 1.5, 3.0] + cutoff_source = "generic default (no saved rock typing found; not calibrated to this project)" + anomaly_flags.append( + { + "category": "Rock Typing Cutoffs Not Calibrated", + "target": "Field Rock Typing (Section 5)", + "message": "No saved rock-typing cutoffs were found; generic FZI cutoffs [0.5, 1.5, 3.0] were applied.", + "mitigation": "Run and save Rock Typing in the multi-well workbench for the target zones, then regenerate the report.", + } + ) + if saved_rt_method in ("winland", "lucia"): + anomaly_flags.append( + { + "category": "Rock Typing Method Mismatch", + "target": "Field Rock Typing (Section 5)", + "message": ( + f"Workbench rock typing used the '{saved_rt_method}' method, but Section 5 re-bins " + "core plugs by FZI for the permeability regression table." + ), + "mitigation": "Compare Section 5 classes against the saved ROCK_FLAG curve before using them downstream.", + } + ) + # Class labels are neutral and positional. Facies names (e.g. "shoreface") cannot be inferred from FZI + # alone, so none are invented; quality is described only by the FZI range. rt_Specs = [] n_cuts = len(resolved_fzi_cutoffs) for i in range(n_cuts + 1): idx = i + 1 if i == 0: c_high = resolved_fzi_cutoffs[0] - name = "RT1 — Nano/Micro-Porous Argillaceous" + quality = "Lowest flow quality" code = f"DRT 1 (FZI < {c_high:.2f})" fzi_str = f"< {c_high:.2f}" - def_m, def_c, def_r2 = 12.4, -1.85, 0.79 elif i == n_cuts: c_low = resolved_fzi_cutoffs[-1] - name = f"RT{idx} — Mega-Porous Clean Channel Sand" + quality = "Highest flow quality" code = f"DRT {idx} (FZI ≥ {c_low:.2f})" fzi_str = f"≥ {c_low:.2f}" - def_m, def_c, def_r2 = 16.8, -0.45, 0.92 else: c_low = resolved_fzi_cutoffs[i - 1] c_high = resolved_fzi_cutoffs[i] - name = f"RT{idx} — Meso/Macro-Porous Shoreface" + quality = "Intermediate flow quality" code = f"DRT {idx} ({c_low:.2f}–{c_high:.2f})" fzi_str = f"{c_low:.2f} – {c_high:.2f}" - def_m, def_c, def_r2 = 14.2 + (i - 1) * 1.4, -1.35 + (i - 1) * 0.43, 0.85 - rt_Specs.append((idx, name, code, fzi_str, def_m, def_c, def_r2)) + rt_Specs.append((idx, f"RT{idx} — {quality}", code, fzi_str)) rock_types: List[Dict[str, Any]] = [] - rt34_share_pct = 43.5 - rt34_kh_pct = 82.0 + saved_flag_rows: List[Dict[str, Any]] = [] + rt34_share_pct: Optional[float] = None + rt34_kh_pct: Optional[float] = None + dominant_codes: List[str] = [] + dominant_share_pct: Optional[float] = None + dominant_kh_pct: Optional[float] = None rt_basis_source = "Core Plugs (CPORE & CPERM)" if not full_df.empty: tz_sub_rt = ( full_df[ - full_df["ZONES"].astype(str).str.strip().str.upper().isin(target_zones_upper) + full_df["ZONES"] + .astype(str) + .str.strip() + .str.upper() + .isin(target_zones_upper) ] if "ZONES" in full_df.columns else full_df @@ -1342,9 +3171,14 @@ def build_report_context( ) ck_rt = _col_series(tz_sub_rt, "CPERM", np.nan) core_rt_mask = ( - cp_rt.notna() & ck_rt.notna() & (cp_rt > 0.01) & (cp_rt < 0.48) & (ck_rt > 1e-3) + cp_rt.notna() + & ck_rt.notna() + & (cp_rt > 0.01) + & (cp_rt < 0.48) + & (ck_rt > 1e-3) ) + rt_sel_mask = core_rt_mask if core_rt_mask.sum() >= 12: p_arr = cp_rt[core_rt_mask].to_numpy(dtype=float) k_arr = ck_rt[core_rt_mask].to_numpy(dtype=float) @@ -1364,6 +3198,84 @@ def build_report_context( p_arr = ph_rt[log_rt_mask].to_numpy(dtype=float) k_arr = pm_rt[log_rt_mask].to_numpy(dtype=float) rt_basis_source = f"Target-Zone Evaluated Logs (n={len(p_arr)})" + rt_sel_mask = log_rt_mask + + # Saved workbench ROCK_FLAG classes on the same samples, fitted as K = a * phi^b (the workbench form). + if "ROCK_FLAG" in tz_sub_rt.columns and len(p_arr) >= 8: + rf_sel = pd.to_numeric( + tz_sub_rt.loc[rt_sel_mask, "ROCK_FLAG"], errors="coerce" + ).to_numpy(dtype=float) + ok_rf = np.isfinite(rf_sel) & (rf_sel >= 1) + if ok_rf.sum() >= 8: + n_rf_tot = int(ok_rf.sum()) + saved_perm_entry = _load_saved_project_module_entry( + pid, "perm-transform", resolved_target_zones + ) + saved_perm_p = ( + saved_perm_entry.get("params") + if isinstance(saved_perm_entry, dict) + else None + ) or {} + manual_fits = ( + saved_perm_p.get("fits") + if saved_perm_p.get("manualEdits") + and isinstance(saved_perm_p.get("fits"), dict) + else {} + ) + kh_total = float(np.sum(k_arr[ok_rf])) or 1e-9 + for rf_v in sorted({int(v) for v in rf_sel[ok_rf]}): + m_f = ok_rf & (rf_sel == rf_v) + n_f = int(m_f.sum()) + row_f: Dict[str, Any] = { + "rock_flag": rf_v, + "n_samples": n_f, + "share_pct": round(100.0 * n_f / n_rf_tot, 1), + "kh_pct": round( + 100.0 * float(np.sum(k_arr[m_f])) / kh_total, 1 + ), + "a": None, + "b": None, + "r2": None, + "source": "insufficient data", + } + pf, kf = p_arr[m_f], k_arr[m_f] + if str(rf_v) in manual_fits: + try: + row_f["a"] = float(manual_fits[str(rf_v)]["a"]) + row_f["b"] = float(manual_fits[str(rf_v)]["b"]) + row_f["source"] = "saved workbench fit (manual)" + except (TypeError, ValueError, KeyError): + pass + if ( + row_f["a"] is None + and n_f >= 3 + and float(np.std(np.log10(pf))) > 1e-3 + ): + b_fit, log_a = np.polyfit( + np.log10(np.clip(pf, 1e-6, None)), + np.log10(np.clip(kf, 1e-6, None)), + 1, + ) + row_f["a"], row_f["b"] = float(10.0**log_a), float(b_fit) + row_f["source"] = "fitted on report samples" + if row_f["a"] is not None: + pred = np.log10( + np.clip( + row_f["a"] * np.clip(pf, 1e-6, None) ** row_f["b"], + 1e-6, + None, + ) + ) + obs = np.log10(np.clip(kf, 1e-6, None)) + ss_t = float(np.sum((obs - obs.mean()) ** 2)) + row_f["r2"] = ( + round(1.0 - float(np.sum((obs - pred) ** 2)) / ss_t, 2) + if ss_t > 1e-12 + else None + ) + row_f["a"] = round(row_f["a"], 3) + row_f["b"] = round(row_f["b"], 3) + saved_flag_rows.append(row_f) if len(p_arr) >= 8: rqi = 0.0314 * np.sqrt(k_arr / np.clip(p_arr, 1e-4, 0.99)) @@ -1373,17 +3285,24 @@ def build_report_context( total_n = max(len(p_arr), 1) total_kh = max(float(np.sum(k_arr)), 1e-9) - for rt_idx, r_name, r_code, r_fzi, def_m, def_c, def_r2 in rt_Specs: + class_kh: Dict[int, float] = {} + for rt_idx, r_name, r_code, r_fzi in rt_Specs: m_rt = rt_bins == rt_idx cnt_rt = int(np.sum(m_rt)) share_v = round(100.0 * cnt_rt / total_n, 1) + class_kh[rt_idx] = float(np.sum(k_arr[m_rt])) if cnt_rt else 0.0 + fit_status = "fitted" if cnt_rt >= 3 and float(np.std(p_arr[m_rt])) > 1e-4: - reg = linregress(p_arr[m_rt], np.log10(np.clip(k_arr[m_rt], 1e-4, 1e6))) + reg = linregress( + p_arr[m_rt], np.log10(np.clip(k_arr[m_rt], 1e-4, 1e6)) + ) slope_v = round(float(reg.slope), 2) inter_v = round(float(reg.intercept), 2) - r2_v = round(max(0.0, min(0.99, float(reg.rvalue**2))), 2) + r2_v = round(max(0.0, min(1.0, float(reg.rvalue**2))), 2) else: - slope_v, inter_v, r2_v = def_m, def_c, (def_r2 if cnt_rt > 0 else 0.0) + # No invented transform: report the absence of a fit instead of defaults. + slope_v = inter_v = r2_v = None + fit_status = "insufficient_data" rock_types.append( { "name": r_name, @@ -1394,26 +3313,133 @@ def build_report_context( "slope": slope_v, "intercept": inter_v, "r2": r2_v, + "fit_status": fit_status, "basis": rt_basis_source, } ) - m_34 = (rt_bins == 3) | (rt_bins == 4) - rt34_share_pct = round(100.0 * float(np.sum(m_34)) / total_n, 1) - rt34_kh_pct = round(100.0 * float(np.sum(k_arr[m_34])) / total_kh, 1) + + # Flow-capacity concentration: the fewest top-FZI classes holding >= 70% of sum(K). + ranked = sorted(class_kh.items(), key=lambda kv: kv[1], reverse=True) + run_kh, picked = 0.0, [] + for idx_c, kh_c in ranked: + if kh_c <= 0: + break + picked.append(idx_c) + run_kh += kh_c + if run_kh / total_kh >= 0.70: + break + if picked: + picked.sort() + dominant_codes = [f"RT{i}" for i in picked] + dominant_kh_pct = round(100.0 * run_kh / total_kh, 1) + dominant_share_pct = round( + 100.0 * float(np.sum(np.isin(rt_bins, picked))) / total_n, 1 + ) + rt34_share_pct, rt34_kh_pct = dominant_share_pct, dominant_kh_pct if not rock_types: - for _, r_name, r_code, r_fzi, def_m, def_c, def_r2 in rt_Specs: + # Insufficient data: list the configured classes without any fabricated statistics. + for _, r_name, r_code, r_fzi in rt_Specs: rock_types.append( { "name": r_name, "code": r_code, "fzi_range": r_fzi, "n_samples": 0, - "share_pct": 25.0, - "slope": def_m, - "intercept": def_c, - "r2": def_r2, - "basis": rt_basis_source, + "share_pct": None, + "slope": None, + "intercept": None, + "r2": None, + "fit_status": "insufficient_data", + "basis": "Insufficient core/log data for rock typing (< 8 valid samples)", + } + ) + rt_basis_source = ( + "Insufficient core/log data for rock typing (< 8 valid samples)" + ) + + if model_params and isinstance(model_params, dict): + merged_configs.update({k: v for k, v in model_params.items() if v is not None}) + + # Pre-query committed fluid contacts for selected project wells to support Tier 2 FWL & fluid type resolution + well_name_by_id = {w["id"]: w["name"] for w in selected_wells_meta} + fluid_contacts_rows: List[Dict[str, Any]] = [] + + def _map_spatial_zone( + w_name_target: str, contact_depth: Optional[float], current_zone: Optional[str] + ) -> Tuple[str, bool]: + if contact_depth is None: + return str(current_zone or "All Zones"), False + cz = str(current_zone or "").strip() + if cz and cz.upper() not in { + "ALL ZONES", + "GENERAL", + "UNKNOWN", + "NAN", + "NONE", + "", + }: + return cz, False + cands = [zr for zr in well_zonal_rows if zr.get("well_name") == w_name_target] + if not cands: + cands = well_zonal_rows + for zr in cands: + top_v = ( + zr.get("top_tvdss") + if zr.get("top_tvdss") is not None + else zr.get("top") + ) + bot_v = ( + zr.get("bottom_tvdss") + if zr.get("bottom_tvdss") is not None + else zr.get("bottom") + ) + if top_v is not None and bot_v is not None: + min_d = min(top_v, bot_v) + max_d = max(top_v, bot_v) + 15.0 + if min_d <= contact_depth <= max_d: + return str(zr["zone"]), True + return cz or "All Zones", False + + with get_db() as session: + fc_res = session.execute( + select( + db_objects.ORMFluidContact.well_id, + db_objects.ORMFluidContact.name, + db_objects.ORMFluidContact.depth, + db_objects.ORMFluidContact.zone, + db_objects.ORMFluidContact.contact_type, + db_objects.ORMFluidContact.fault_block, + db_objects.ORMFluidContact.source, + db_objects.ORMFluidContact.remarks, + ) + .where(db_objects.ORMFluidContact.well_id.in_(list(well_name_by_id.keys()))) + .order_by(db_objects.ORMFluidContact.depth) + ).all() + for r in fc_res: + c_type = str(r.contact_type or r.name or "CONTACT").upper() + if c_type == "WDT": # Excluded per user instruction + continue + wn = well_name_by_id.get(r.well_id, f"Well-{r.well_id}") + cdepth = round(float(r.depth), 1) if r.depth is not None else None + mapped_z, was_mapped = _map_spatial_zone(wn, cdepth, r.zone) + remarks = str(r.remarks) if r.remarks else "" + if was_mapped: + remarks = ( + remarks + " (Mapped from 'All Zones' by TVDss intersection)" + ).strip() + fluid_contacts_rows.append( + { + "well_name": wn, + "name": str(r.name), + "depth": cdepth, + "zone": mapped_z, + "contact_type": c_type, + "fault_block": str(r.fault_block) if r.fault_block else None, + "source": str(r.source) + if r.source + else "Petrophysical Log Evaluation", + "remarks": remarks, } ) @@ -1424,7 +3450,11 @@ def build_report_context( if not full_df.empty: tz_df_fwl = ( full_df[ - full_df["ZONES"].astype(str).str.strip().str.upper().isin(target_zones_upper) + full_df["ZONES"] + .astype(str) + .str.strip() + .str.upper() + .isin(target_zones_upper) ] if "ZONES" in full_df.columns else full_df @@ -1432,9 +3462,15 @@ def build_report_context( if tz_df_fwl.empty: tz_df_fwl = full_df - if "TVDSS" in tz_df_fwl.columns and pd.to_numeric(tz_df_fwl["TVDSS"], errors="coerce").notna().any(): + if ( + "TVDSS" in tz_df_fwl.columns + and pd.to_numeric(tz_df_fwl["TVDSS"], errors="coerce").notna().any() + ): depth_ref_s = pd.to_numeric(tz_df_fwl["TVDSS"], errors="coerce") - elif "TVD" in tz_df_fwl.columns and pd.to_numeric(tz_df_fwl["TVD"], errors="coerce").notna().any(): + elif ( + "TVD" in tz_df_fwl.columns + and pd.to_numeric(tz_df_fwl["TVD"], errors="coerce").notna().any() + ): depth_ref_s = pd.to_numeric(tz_df_fwl["TVD"], errors="coerce") - 25.0 else: depth_ref_s = pd.to_numeric(tz_df_fwl["DEPTH"], errors="coerce") - 25.0 @@ -1452,7 +3488,9 @@ def build_report_context( & (vsh_fwl <= vsh_cut) ) if res_mask_fwl.any(): - median_target_tvdss = round(float(np.nanmedian(depth_ref_s[res_mask_fwl])), 1) + median_target_tvdss = round( + float(np.nanmedian(depth_ref_s[res_mask_fwl])), 1 + ) elif depth_ref_s.notna().any(): median_target_tvdss = round(float(np.nanmedian(depth_ref_s.dropna())), 1) @@ -1471,35 +3509,165 @@ def build_report_context( else: inferred_fwl_tvdss = round(median_target_tvdss + 15.0, 1) - explicit_fwl = fwl_tvdss if fwl_tvdss is not None else merged_configs.get("fwl") - fwl_basis_str = "Target-Zone Hydrocarbon-Water Transition Zone (TVDss)" - if explicit_fwl is not None: - cand_fwl = _safe_float(explicit_fwl, inferred_fwl_tvdss) - if abs(cand_fwl - median_target_tvdss) > 300.0: - anomaly_flags.append( - { - "category": "Suspicious Free Water Level Depth (CHK-02)", - "target": f"FWL = {cand_fwl:.1f} m vs Target Median = {median_target_tvdss:.1f} m TVDss", - "message": f"Configured FWL ({cand_fwl:.1f} m) deviates by >300 m from the target reservoir depth ({median_target_tvdss:.1f} m TVDss).", - "mitigation": f"Overrode uncalibrated TD/depth fallback with target-zone transition FWL ({inferred_fwl_tvdss:.1f} m TVDss).", - } + # 4-tier FWL resolution hierarchy (GAP-02) + fwl_val: Optional[float] = None + fwl_basis_str: str = "" + + # Tier 1: Explicit Request Override + if fwl_tvdss is not None and np.isfinite(fwl_tvdss): + fwl_val = round(float(fwl_tvdss), 1) + fwl_basis_str = "User Request Override" + + # Tier 2: Committed Database Contacts (ORMFluidContact) + if fwl_val is None and fluid_contacts_rows: + + def _match_zone(z_name: str) -> bool: + if not z_name or str(z_name).strip().upper() in ( + "ALL ZONES", + "GENERAL", + "ALL", + "-", + "NONE", + ): + return True + return str(z_name).strip().upper() in target_zones_upper + + fwl_matches = [ + r["depth"] + for r in fluid_contacts_rows + if r["depth"] is not None + and r["contact_type"] == "FWL" + and _match_zone(r["zone"]) + ] + if not fwl_matches: + fwl_matches = [ + r["depth"] + for r in fluid_contacts_rows + if r["depth"] is not None and r["contact_type"] == "FWL" + ] + if not fwl_matches: + fwl_matches = [ + r["depth"] + for r in fluid_contacts_rows + if r["depth"] is not None + and r["contact_type"] == "GWC" + and _match_zone(r["zone"]) + ] + if not fwl_matches: + fwl_matches = [ + r["depth"] + for r in fluid_contacts_rows + if r["depth"] is not None + and r["contact_type"] == "OWC" + and _match_zone(r["zone"]) + ] + if fwl_matches: + fwl_val = round(float(np.median(fwl_matches)), 1) + fwl_basis_str = "Committed Fluid Contact / FWL Optimizer (Pc = 0 datum)" + + # Saved workbench SHF snapshot (FWL, fluid system, per-rock-type J fits) for the active zone selection. + saved_shf_entry = _load_saved_project_module_entry( + pid, "shf", resolved_target_zones + ) + saved_shf_params = ( + saved_shf_entry.get("params") if isinstance(saved_shf_entry, dict) else None + ) or {} + saved_shf_inner = ( + saved_shf_params.get("shfParams") + if isinstance(saved_shf_params.get("shfParams"), dict) + else {} + ) + + # Tier 3: Project Configuration (workbench-saved SHF FWL takes precedence over well config) + if fwl_val is None: + cfg_fwl = ( + saved_shf_inner.get("fwl") + or merged_configs.get("fwl") + or ( + merged_configs.get("shf_params", {}).get("fwl") + if isinstance(merged_configs.get("shf_params"), dict) + else None ) - fwl_val = inferred_fwl_tvdss - fwl_basis_str = "Overridden to Target-Zone Transition Zone (TVDss)" - else: - fwl_val = round(cand_fwl, 1) - fwl_basis_str = "Configured / Project Parameters (TVDss)" - else: + ) + if cfg_fwl is not None: + cand_fwl = _safe_float(cfg_fwl, None) + if cand_fwl is not None and np.isfinite(cand_fwl): + if abs(cand_fwl - median_target_tvdss) <= 300.0: + fwl_val = round(cand_fwl, 1) + fwl_basis_str = "Project Saturation/SHF Configuration" + else: + anomaly_flags.append( + { + "category": "Suspicious Free Water Level Depth (CHK-02)", + "target": f"FWL = {cand_fwl:.1f} m vs Target Median = {median_target_tvdss:.1f} m TVDss", + "message": f"Configured FWL ({cand_fwl:.1f} m) deviates by >300 m from the target reservoir depth ({median_target_tvdss:.1f} m TVDss).", + "mitigation": f"Overrode uncalibrated TD/depth fallback with target-zone transition FWL ({inferred_fwl_tvdss:.1f} m TVDss).", + } + ) + + # Tier 4: Transition-Zone Heuristic Fallback + if fwl_val is None: fwl_val = inferred_fwl_tvdss fwl_basis_str = "Inferred from Hydrocarbon-Water Transition Zone (TVDss)" # Spec 3.2, CHK-04, CHK-05: True Probabilistic Monte Carlo / Latin Hypercube Uncertainty Engine (N=1000) + # Incorporate borehole environmental correction 1-sigma (`NPHI_SIGMA`, `RHOB_SIGMA`, `RT_SIGMA`) when available. uncertainty_summary: List[Dict[str, Any]] = [] rng_mc = np.random.default_rng(42) n_mc = 1000 - d_phi_mc = rng_mc.normal(0.0, 0.018, size=(n_mc, 1)) + phi_sigma_mc = 0.018 + sw_sigma_mc = 0.11 + env_sigma_used = False + if not full_df.empty: + tz_unc_df = ( + full_df[ + full_df["ZONES"] + .astype(str) + .str.strip() + .str.upper() + .isin(target_zones_upper) + ] + if "ZONES" in full_df.columns and target_zones_upper + else full_df + ) + if tz_unc_df.empty: + tz_unc_df = full_df + nphi_sig_s = ( + pd.to_numeric(tz_unc_df["NPHI_SIGMA"], errors="coerce").dropna() + if "NPHI_SIGMA" in tz_unc_df.columns + else pd.Series(dtype=float) + ) + rhob_sig_s = ( + pd.to_numeric(tz_unc_df["RHOB_SIGMA"], errors="coerce").dropna() + if "RHOB_SIGMA" in tz_unc_df.columns + else pd.Series(dtype=float) + ) + rt_sig_s = ( + pd.to_numeric(tz_unc_df["RT_SIGMA"], errors="coerce").dropna() + if "RT_SIGMA" in tz_unc_df.columns + else pd.Series(dtype=float) + ) + if not nphi_sig_s.empty or not rhob_sig_s.empty: + sig_n = float(nphi_sig_s.median()) if not nphi_sig_s.empty else 0.015 + sig_d = float(rhob_sig_s.median()) / 1.65 if not rhob_sig_s.empty else 0.015 + phi_sigma_mc = float( + np.clip(math.sqrt(0.5 * (sig_n**2 + sig_d**2)), 0.012, 0.045) + ) + env_sigma_used = True + if not rt_sig_s.empty: + sig_rt_dec = float(rt_sig_s.median()) + # Propagate log10(Rt) sigma through Sw ~ Rt^(-1/n) combined with Archie/WS parameter uncertainty + sw_sigma_mc = float( + np.clip( + math.sqrt(0.095**2 + (0.5 * math.log(10.0) * sig_rt_dec) ** 2), + 0.09, + 0.28, + ) + ) + env_sigma_used = True + d_phi_mc = rng_mc.normal(0.0, phi_sigma_mc, size=(n_mc, 1)) d_vsh_mc = rng_mc.normal(0.0, 0.035, size=(n_mc, 1)) - sw_mult_mc = rng_mc.lognormal(0.0, 0.11, size=(n_mc, 1)) + sw_mult_mc = rng_mc.lognormal(0.0, sw_sigma_mc, size=(n_mc, 1)) for z in zonal_summary: z_name = z["zone"] @@ -1529,7 +3697,9 @@ def build_report_context( if not z_df.empty else np.array([]) ) - valid_z = np.isfinite(phi_z) & np.isfinite(sw_z) & np.isfinite(vsh_z) & (phi_z > 0.0) + valid_z = ( + np.isfinite(phi_z) & np.isfinite(sw_z) & np.isfinite(vsh_z) & (phi_z > 0.0) + ) phi_z = phi_z[valid_z] vsh_z = vsh_z[valid_z] sw_z = sw_z[valid_z] @@ -1575,12 +3745,15 @@ def build_report_context( ) / np.maximum(net_h_reals, 1e-6) pv_reals = np.maximum(net_h_reals * phi_reals, 1e-6) sw_reals = ( - np.sum( - np.where(pay_real, phi_real * sw_real * step_scale, 0.0), axis=1 - ) + np.sum(np.where(pay_real, phi_real * sw_real * step_scale, 0.0), axis=1) / pv_reals ) + net_p90 = round(float(np.nanpercentile(net_h_reals, 10)), 1) + net_p50 = round(float(np.nanpercentile(net_h_reals, 50)), 1) + net_p10 = round(float(np.nanpercentile(net_h_reals, 90)), 1) + net_p90, net_p50, net_p10 = sorted([net_p90, net_p50, net_p10]) + hcpt_p90 = round(float(np.nanpercentile(hcpt_reals, 10)), 2) hcpt_p50 = round(float(np.nanpercentile(hcpt_reals, 50)), 2) hcpt_p10 = round(float(np.nanpercentile(hcpt_reals, 90)), 2) @@ -1602,74 +3775,465 @@ def build_report_context( if phi_p50 <= 0.0: hcpt_p50 = 0.0 - spread_ratio = ( - round(hcpt_p10 / hcpt_p90, 2) if hcpt_p90 > 0.005 else 1.0 - ) - uncertainty_summary.append( - { - "zone": z_name, - "metric": "HCPT (m) / Φe (v/v) / Sw (v/v)", - "p90_hcpt": hcpt_p90, - "p50_hcpt": hcpt_p50, - "p10_hcpt": hcpt_p10, - "p90_phie": phi_p90, - "p50_phie": phi_p50, - "p10_phie": phi_p10, - "p90_sw": sw_p90, - "p50_sw": sw_p50, - "p10_sw": sw_p10, - "spread_ratio": spread_ratio, - "p90": f"{hcpt_p90:.2f} m (Φ={phi_p90:.3f}, Sw={sw_p90:.3f})", - "p50": f"{hcpt_p50:.2f} m (Φ={phi_p50:.3f}, Sw={sw_p50:.3f})", - "p10": f"{hcpt_p10:.2f} m (Φ={phi_p10:.3f}, Sw={sw_p10:.3f})", - "spread": f"{spread_ratio:.2f}×" if hcpt_p90 > 0.005 else "—", - } + spread_ratio = round(hcpt_p10 / hcpt_p90, 2) if hcpt_p90 > 0.005 else 1.0 + uncertainty_summary.extend( + [ + { + "zone": z_name, + "metric": "Net Pay (m)", + "p90_hcpt": hcpt_p90, + "p50_hcpt": hcpt_p50, + "p10_hcpt": hcpt_p10, + "p50_phie": phi_p50, + "p90": f"{net_p90:.1f} m", + "p50": f"{net_p50:.1f} m", + "p10": f"{net_p10:.1f} m", + "spread": f"{round(net_p10 / max(net_p90, 0.01), 2):.2f}×" + if net_p90 > 0.05 + else "—", + }, + { + "zone": z_name, + "metric": "Mean Effective Porosity Φe (v/v)", + "p90_hcpt": hcpt_p90, + "p50_hcpt": hcpt_p50, + "p10_hcpt": hcpt_p10, + "p50_phie": phi_p50, + "p90": f"{phi_p90:.3f}", + "p50": f"{phi_p50:.3f}", + "p10": f"{phi_p10:.3f}", + "spread": f"{round(phi_p10 / max(phi_p90, 0.001), 2):.2f}×" + if phi_p90 > 0.001 + else "—", + }, + { + "zone": z_name, + "metric": "Mean Water Saturation Sw (v/v)", + "p90_hcpt": hcpt_p90, + "p50_hcpt": hcpt_p50, + "p10_hcpt": hcpt_p10, + "p50_phie": phi_p50, + "p90": f"{sw_p90:.3f}", + "p50": f"{sw_p50:.3f}", + "p10": f"{sw_p10:.3f}", + "spread": f"{round(sw_p90 / max(sw_p10, 0.001), 2):.2f}×" + if sw_p10 > 0.001 + else "—", + }, + { + "zone": z_name, + "metric": "Hydrocarbon Pore Thickness HCPT (m)", + "p90_hcpt": hcpt_p90, + "p50_hcpt": hcpt_p50, + "p10_hcpt": hcpt_p10, + "p50_phie": phi_p50, + "p90": f"{hcpt_p90:.2f} m", + "p50": f"{hcpt_p50:.2f} m", + "p10": f"{hcpt_p10:.2f} m", + "spread": f"{spread_ratio:.2f}×" if hcpt_p90 > 0.005 else "—", + # Numeric twin of `spread` so narratives quote the table value, not a default. + "spread_ratio": spread_ratio if hcpt_p90 > 0.005 else None, + }, + ] ) else: # Spec 3.2 & CHK-05: Zero deterministic Net Pay -> report 0.00 m (no dummy 0.11 / 0.15 / 0.19) - uncertainty_summary.append( - { - "zone": z_name, - "metric": "HCPT (m) / Φe (v/v) / Sw (v/v)", - "p90_hcpt": 0.0, - "p50_hcpt": 0.0, - "p10_hcpt": 0.0, - "p90_phie": 0.0, - "p50_phie": 0.0, - "p10_phie": 0.0, - "p90_sw": 1.0, - "p50_sw": 1.0, - "p10_sw": 1.0, - "spread_ratio": 1.0, - "p90": "0.00 m (Water-bearing / No Pay)", - "p50": "0.00 m (Water-bearing / No Pay)", - "p10": "0.00 m (Water-bearing / No Pay)", - "spread": "—", - } + uncertainty_summary.extend( + [ + { + "zone": z_name, + "metric": "Net Pay (m)", + "p90_hcpt": 0.0, + "p50_hcpt": 0.0, + "p10_hcpt": 0.0, + "p50_phie": 0.0, + "p90": "0.0 m", + "p50": "0.0 m", + "p10": "0.0 m", + "spread": "—", + }, + { + "zone": z_name, + "metric": "Mean Effective Porosity Φe (v/v)", + "p90_hcpt": 0.0, + "p50_hcpt": 0.0, + "p10_hcpt": 0.0, + "p50_phie": 0.0, + "p90": "0.000", + "p50": "0.000", + "p10": "0.000", + "spread": "—", + }, + { + "zone": z_name, + "metric": "Mean Water Saturation Sw (v/v)", + "p90_hcpt": 0.0, + "p50_hcpt": 0.0, + "p10_hcpt": 0.0, + "p50_phie": 0.0, + "p90": "1.000", + "p50": "1.000", + "p10": "1.000", + "spread": "—", + }, + { + "zone": z_name, + "metric": "Hydrocarbon Pore Thickness HCPT (m)", + "p90_hcpt": 0.0, + "p50_hcpt": 0.0, + "p10_hcpt": 0.0, + "p50_phie": 0.0, + "p90": "0.00 m (Water-bearing / No Pay)", + "p50": "0.00 m (Water-bearing / No Pay)", + "p10": "0.00 m (Water-bearing / No Pay)", + "spread": "—", + }, + ] ) - shf_rmse = 0.042 - shf_bias = -0.008 - if not full_df.empty and "SHF" in full_df.columns and "SWT" in full_df.columns: - diff = ( - pd.to_numeric(full_df["SWT"], errors="coerce") - - pd.to_numeric(full_df["SHF"], errors="coerce") - ).dropna() - if not diff.empty: - shf_rmse = round(float(np.sqrt(np.mean(diff**2))), 4) - shf_bias = round(float(diff.mean()), 4) + uncertainty_drivers_text = ( + "Hydrocarbon pore thickness (HCPT) variance is primarily governed by: " + "(1) Formation water resistivity ($R_w$) & saturation exponent ($n$)" + + ( + f" coupled with borehole resistivity 1-sigma ($\\sigma_{{Sw}} = {sw_sigma_mc:.3f}$), " + if env_sigma_used + else ", " + ) + + "(2) Matrix density ($\\rho_{ma}$) & porosity calibration" + + ( + f" propagating environmental sensor uncertainty ($\\sigma_\\phi = {phi_sigma_mc:.3f}\\text{{ v/v}}$), and " + if env_sigma_used + else ", and " + ) + + f"(3) Net pay cutoff thresholds ($\\Phi_e \\ge {phie_cut:.2f}$, $V_{{sh}} \\le {vsh_cut:.2f}$, $S_w \\le {sw_cut:.2f}$)." + ) - if model_params and isinstance(model_params, dict): - merged_configs.update( - {k: v for k, v in model_params.items() if v is not None} + # Task 1.2: Phase-aware fluid type and fluid densities detection (GAP-07) + shf_cfg = ( + merged_configs.get("shf_params") + if isinstance(merged_configs.get("shf_params"), dict) + else {} + ) + litho_cfg = ( + merged_configs.get("litho_params") + if isinstance(merged_configs.get("litho_params"), dict) + else {} + ) + raw_fluid_type = ( + str( + merged_configs.get("fluid_type") + or shf_cfg.get("fluid_type") + or litho_cfg.get("hc_fluid_type") + or merged_configs.get("hc_fluid_type") + or "" + ) + .strip() + .lower() + ) + + # Gather & analyze Formation Pressure Test (FPT) data for Section 6.3 & SHF density reconciliation (GAP-13) + fpt_summary, raw_fpt_points = _gather_and_analyze_fpt_data( + project_id=pid, + wells_inventory=wells_inventory, + merged_configs=merged_configs, + fluid_contacts_rows=fluid_contacts_rows, + target_zones=resolved_target_zones, + fwl_val=fwl_val, + fwl_is_committed=not str(fwl_basis_str).startswith("Inferred"), + ) + fitted_dens = fpt_summary.get("fitted_densities", {}) + water_fit = fitted_dens.get("WATER") + gas_fit = fitted_dens.get("GAS") + oil_fit = fitted_dens.get("OIL") + + contact_types_seen = {r["contact_type"] for r in fluid_contacts_rows} + has_gas_contacts = bool({"GUT", "GDT", "GWC"} & contact_types_seen) or ( + bool( + gas_fit + and gas_fit.get("r_squared", 0.0) >= 0.85 + and gas_fit.get("n_points", 0) >= 2 + ) + ) + has_oil_contacts = bool({"OUT", "ODT", "OWC"} & contact_types_seen) or ( + bool( + oil_fit + and oil_fit.get("r_squared", 0.0) >= 0.85 + and oil_fit.get("n_points", 0) >= 2 + ) + ) + + raw_rho_hc = ( + merged_configs.get("rho_hc") or shf_cfg.get("ghc") or litho_cfg.get("rho_hc") + ) + rho_hc_cand = _safe_float(raw_rho_hc, None) + + if raw_fluid_type in ("gas", "dry_gas", "wet_gas", "condensate"): + res_fluid = "gas" + elif raw_fluid_type in ("oil", "black_oil", "heavy_oil", "volatile_oil"): + res_fluid = "oil" + elif has_gas_contacts and not has_oil_contacts: + res_fluid = "gas" + elif rho_hc_cand is not None and rho_hc_cand < 0.45: + res_fluid = "gas" + else: + res_fluid = ( + "oil" if has_oil_contacts else ("gas" if has_gas_contacts else "oil") + ) + + # Measured FPT Formation Water Gradient reconciliation + if ( + water_fit + and water_fit.get("r_squared", 0.0) >= 0.90 + and water_fit.get("n_points", 0) >= 3 + ): + gw_val = water_fit["density_gcc"] + gw_basis = f"Measured FPT Formation Water Gradient ({water_fit['density_gcc']:.3f} g/cc, R²={water_fit['r_squared']:.2f})" + else: + gw_val = _safe_float( + shf_cfg.get("gw") + or merged_configs.get("rho_w") + or merged_configs.get("gw"), + 1.05, + ) + gw_basis = "Configured / Regional Formation Water Density" + + # Measured FPT Hydrocarbon Gradient reconciliation + if res_fluid == "gas": + if ( + gas_fit + and gas_fit.get("r_squared", 0.0) >= 0.90 + and gas_fit.get("n_points", 0) >= 3 + ): + ghc_val = gas_fit["density_gcc"] + ghc_basis = f"Measured FPT Gas Gradient ({gas_fit['density_gcc']:.3f} g/cc, R²={gas_fit['r_squared']:.2f})" + elif rho_hc_cand is not None and rho_hc_cand < 0.45: + ghc_val = round(rho_hc_cand, 3) + ghc_basis = "Configured Gas Density" + else: + ghc_val = 0.22 + ghc_basis = "Default Dry/Wet Gas Reservoir Density (No PVT/FPT Override)" + else: + if ( + oil_fit + and oil_fit.get("r_squared", 0.0) >= 0.90 + and oil_fit.get("n_points", 0) >= 3 + ): + ghc_val = oil_fit["density_gcc"] + ghc_basis = f"Measured FPT Oil Gradient ({oil_fit['density_gcc']:.3f} g/cc, R²={oil_fit['r_squared']:.2f})" + else: + ghc_val = round(rho_hc_cand if rho_hc_cand is not None else 0.80, 3) + ghc_basis = "Configured Oil Density" + delta_rho = round(gw_val - ghc_val, 3) + + # Re-evaluate SHF curve using resolved FWL, phase-aware delta_rho (GAP-07) and the workbench-saved + # per-rock-type Leverett-J fits. No reconciliation statistic is reported unless it is actually computed. + shf_rmse: Optional[float] = None + shf_bias: Optional[float] = None + shf_fit_rows: List[Dict[str, Any]] = [] + shf_fit_source = "" + shf_n_compared = 0 + saved_fits_blob = saved_shf_params.get("fits") + saved_fits: Dict[str, Dict[str, Any]] = {} + saved_fit_model = "leverett_j" + if isinstance(saved_fits_blob, dict): + saved_fit_model = str(saved_fits_blob.get("model") or "leverett_j") + inner = saved_fits_blob.get("fits") + if isinstance(inner, dict): + for k, v in inner.items(): + if ( + isinstance(v, dict) + and v.get("a") is not None + and v.get("b") is not None + ): + saved_fits[str(k)] = v + use_saved_fits = bool(saved_fits) and saved_fit_model == "leverett_j" + if use_saved_fits: + shf_fit_source = ( + f"saved workbench SHF fit ({saved_shf_entry.get('label', 'project')})" + ) + elif saved_fits: + shf_fit_source = ( + f"generic fallback J-function (saved fit uses '{saved_fit_model}', " + "which the report does not evaluate)" + ) + else: + shf_fit_source = "generic fallback J-function (no saved SHF fit found)" + if not full_df.empty: + d_col = ( + "TVDSS" + if "TVDSS" in full_df.columns + else ("TVD" if "TVD" in full_df.columns else "DEPTH") + ) + phi_col = ( + "PHIE" + if "PHIE" in full_df.columns + else ("PHIT" if "PHIT" in full_df.columns else None) ) + k_col = ( + "CPERM" + if "CPERM" in full_df.columns + else ("PERM" if "PERM" in full_df.columns else None) + ) + if phi_col and k_col and d_col in full_df.columns: + try: + from quick_pp.core_analysis import sw_shf_leverett_j + + d_arr = pd.to_numeric(full_df[d_col], errors="coerce").to_numpy( + dtype=float + ) + phi_arr = pd.to_numeric(full_df[phi_col], errors="coerce").to_numpy( + dtype=float + ) + phi_arr = np.where(phi_arr > 1.0, phi_arr / 100.0, phi_arr) + k_arr = pd.to_numeric(full_df[k_col], errors="coerce").to_numpy( + dtype=float + ) + ift_val = _safe_float( + merged_configs.get("ift_res", shf_cfg.get("ift", 30.0)), 30.0 + ) + theta_val = _safe_float( + merged_configs.get("theta_res", shf_cfg.get("theta", 30.0)), 30.0 + ) + # Per-row a/b: saved fit for the row's ROCK_FLAG, else the generic fallback pair. + a_arr = np.full(len(full_df), 0.22, dtype=float) + b_arr = np.full(len(full_df), -0.50, dtype=float) + if use_saved_fits and "ROCK_FLAG" in full_df.columns: + rf_arr = pd.to_numeric( + full_df["ROCK_FLAG"], errors="coerce" + ).to_numpy(dtype=float) + for rf_key, fit in saved_fits.items(): + try: + rf_int = int(rf_key) + a_fit, b_fit = float(fit["a"]), float(fit["b"]) + except (TypeError, ValueError, KeyError): + continue + m_rf = np.isfinite(rf_arr) & (rf_arr == rf_int) + a_arr[m_rf] = a_fit + b_arr[m_rf] = b_fit + elif use_saved_fits: + # No ROCK_FLAG on the data: use the first saved fit as a single global pair. + first_fit = next(iter(saved_fits.values())) + a_arr[:] = float(first_fit["a"]) + b_arr[:] = float(first_fit["b"]) + shf_fit_source += ( + " (single global pair; no ROCK_FLAG curve on data)" + ) + + shf_calc = sw_shf_leverett_j( + perm=k_arr, + phit=phi_arr, + depth=d_arr, + fwl=fwl_val, + ift=ift_val, + theta=theta_val, + gw=gw_val, + ghc=ghc_val, + a=a_arr, + b=b_arr, + unit="metric" if d_col in ("TVDSS", "TVD", "DEPTH") else "imperial", + clip=True, + ) + full_df["SHF"] = shf_calc + except Exception as exc: + logger.debug(f"SHF recomputation skipped: {exc}") + + # Reconcile only inside the active target zones and above the FWL, on rows where both curves exist. + if "SHF" in full_df.columns and "SWT" in full_df.columns: + rec_df = full_df + if "ZONES" in full_df.columns and target_zones_upper: + rec_mask_z = ( + full_df["ZONES"] + .astype(str) + .str.strip() + .str.upper() + .isin(target_zones_upper) + ) + if rec_mask_z.any(): + rec_df = full_df[rec_mask_z] + rec_depth = pd.to_numeric( + rec_df[d_col] if d_col in rec_df.columns else rec_df["DEPTH"], + errors="coerce", + ) + sw_log = pd.to_numeric(rec_df["SWT"], errors="coerce") + sw_cap = pd.to_numeric(rec_df["SHF"], errors="coerce") + rec_ok = ( + sw_log.notna() + & sw_cap.notna() + & rec_depth.notna() + & (rec_depth < fwl_val) + ) + diff = (sw_log[rec_ok] - sw_cap[rec_ok]).dropna() + shf_n_compared = int(len(diff)) + if shf_n_compared >= 20: + shf_rmse = round(float(np.sqrt(np.mean(diff**2))), 4) + shf_bias = round(float(diff.mean()), 4) + + # Per-rock-type fit table: saved parameters plus the log-vs-capillary agreement in each class. + if use_saved_fits: + rf_series = ( + pd.to_numeric(full_df["ROCK_FLAG"], errors="coerce") + if "ROCK_FLAG" in full_df.columns + else None + ) + for rf_key in sorted( + saved_fits, key=lambda k: (not str(k).isdigit(), str(k)) + ): + fit = saved_fits[rf_key] + row = { + "rock_flag": rf_key, + "a": round(float(fit["a"]), 4), + "b": round(float(fit["b"]), 4), + "r2": fit.get("r2"), + "rmse": fit.get("rmse"), + "n_scal": int(fit.get("count", 0) or 0), + "n_log": None, + "log_rmse": None, + } + if ( + rf_series is not None + and "SHF" in full_df.columns + and "SWT" in full_df.columns + and str(rf_key).isdigit() + ): + m_c = ( + (rf_series == int(rf_key)) + & pd.to_numeric(full_df["SWT"], errors="coerce").notna() + & pd.to_numeric(full_df["SHF"], errors="coerce").notna() + ) + if "ZONES" in full_df.columns and target_zones_upper: + m_c &= ( + full_df["ZONES"] + .astype(str) + .str.strip() + .str.upper() + .isin(target_zones_upper) + ) + d_c = ( + pd.to_numeric(full_df[d_col], errors="coerce") + if d_col in full_df.columns + else None + ) + if d_c is not None: + m_c &= d_c < fwl_val + if int(m_c.sum()) >= 10: + dd = ( + pd.to_numeric(full_df.loc[m_c, "SWT"], errors="coerce") + - pd.to_numeric(full_df.loc[m_c, "SHF"], errors="coerce") + ).dropna() + row["n_log"] = int(len(dd)) + row["log_rmse"] = round(float(np.sqrt(np.mean(dd**2))), 3) + shf_fit_rows.append(row) # Resolve active Lithology, Porosity, and Saturation models from config or evaluated curves - raw_litho_key = str( - merged_configs.get("litho_model_key") - or merged_configs.get("litho_model") - or "" - ).strip().lower() + raw_litho_key = ( + str( + merged_configs.get("litho_model_key") + or merged_configs.get("litho_model") + or "" + ) + .strip() + .lower() + ) def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: if full_df.empty or col_name not in full_df.columns: @@ -1678,8 +4242,7 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: return bool((s_num > threshold).any()) has_carb_evap = any( - _has_positive_col(c) - for c in ("VCALC", "VDOLO", "VANHY", "VHALI", "VGYPS") + _has_positive_col(c) for c in ("VCALC", "VDOLO", "VANHY", "VHALI", "VGYPS") ) has_ssc_cols = _has_positive_col("VSAND") and _has_positive_col("VSILT") @@ -1731,7 +4294,9 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: if log_str: litho_model_display += f" — input logs: {log_str}" elif resolved_litho_key == "sand_shale": - litho_model_display = "Binary Sand-Shale Neutron-Density Crossplot Model (Vsh from N-D)" + litho_model_display = ( + "Binary Sand-Shale Neutron-Density Crossplot Model (Vsh from N-D)" + ) elif resolved_litho_key == "vsh_gr": litho_model_display = "Gamma Ray Shale Volume Index (Vsh,GR) Model" elif resolved_litho_key == "vsh_bulk": @@ -1739,18 +4304,28 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: else: litho_model_display = "Modified Kuttan Sand-Silt-Clay (SSC) Ternary Model" - raw_poro_key = str( - merged_configs.get("porosity_method_key") - or merged_configs.get("porosity_method") - or "den" - ).strip().lower() + raw_poro_key = ( + str( + merged_configs.get("porosity_method_key") + or merged_configs.get("porosity_method") + or "den" + ) + .strip() + .lower() + ) if resolved_litho_key == "vsh_bulk": poro_method_display = "Bulk Shale Density-Balance Porosity" elif raw_poro_key in ("neu_den", "neutron_density", "xplot"): poro_method_display = ( "Neutron-Density Crossplot Total & Clay-Corrected Effective Porosity" ) - elif raw_poro_key in ("sonic_wyllie", "sonic_hunt_raymer", "avg_weighted", "avg_arithmetic", "avg_gaymard"): + elif raw_poro_key in ( + "sonic_wyllie", + "sonic_hunt_raymer", + "avg_weighted", + "avg_arithmetic", + "avg_gaymard", + ): poro_method_display = { "sonic_wyllie": "Wyllie Sonic Porosity", "sonic_hunt_raymer": "Hunt-Raymer Sonic Porosity", @@ -1759,15 +4334,17 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: "avg_gaymard": "RMS (Gaymard/Gas) Neutron-Density Porosity", }[raw_poro_key] else: - poro_method_display = ( - "Clay-Corrected Matrix Density Total & Effective Porosity" - ) + poro_method_display = "Clay-Corrected Matrix Density Total & Effective Porosity" - raw_sw_key = str( - merged_configs.get("sw_model_key") - or merged_configs.get("sw_model") - or "archie" - ).strip().lower() + raw_sw_key = ( + str( + merged_configs.get("sw_model_key") + or merged_configs.get("sw_model") + or "archie" + ) + .strip() + .lower() + ) sw_model_display = { "archie": "Archie Clean-Sand Water Saturation Model", "waxman_smits": "Waxman-Smits Shaly-Sand Cation Exchange ($Q_v$) Model", @@ -1810,36 +4387,385 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: else bh_treat_raw ) + # Aggregate Field/Well Borehole Environmental Correction, P&T & Invasion Summary + primary_env = resolved_envs[0] if resolved_envs else environment_from_config({}, {}) + req_env_cfg = ( + merged_configs.get("env_corr_params") + if isinstance(merged_configs.get("env_corr_params"), dict) + else {} + ) + eff_tool_type = str( + req_env_cfg.get("toolType") + or req_env_cfg.get("tool_type") + or merged_configs.get("tool_type") + or "WL" + ).upper() + if eff_tool_type not in ("WL", "LWD"): + eff_tool_type = "WL" + eff_res_tool = str( + req_env_cfg.get("resTool") + or req_env_cfg.get("res_tool") + or ("propagation" if eff_tool_type == "LWD" else "induction") + ).lower() + if eff_res_tool == "auto": + eff_res_tool = "propagation" if eff_tool_type == "LWD" else "induction" + + tz_env_df = ( + full_df[ + full_df["ZONES"] + .astype(str) + .str.strip() + .str.upper() + .isin(target_zones_upper) + ] + if not full_df.empty and "ZONES" in full_df.columns and target_zones_upper + else full_df + ) + if tz_env_df.empty: + tz_env_df = full_df + + env_corr_curve_table: List[Dict[str, Any]] = [] + if not tz_env_df.empty: + reason_tz = ( + pd.to_numeric(tz_env_df["ENV_QC_REASON"], errors="coerce") + .fillna(0) + .astype(int) + if "ENV_QC_REASON" in tz_env_df.columns + else pd.Series(dtype=int) + ) + for lg_k in ("GR", "NPHI", "RHOB", "RT", "DT"): + c_col = f"{lg_k}_ENV_CORR" + st_col = f"{lg_k}_QC_STATUS" + cf_col = f"{lg_k}_QC_CONF" + sg_col = f"{lg_k}_SIGMA" + dl_col = f"{lg_k}_CORR_DELTA" + has_c = ( + c_col in tz_env_df.columns + and pd.to_numeric(tz_env_df[c_col], errors="coerce").notna().any() + ) + has_st = ( + st_col in tz_env_df.columns + and pd.to_numeric(tz_env_df[st_col], errors="coerce").ge(0).any() + ) + if not (has_c or has_st): + continue + if has_st: + st_s = pd.to_numeric(tz_env_df[st_col], errors="coerce") + valid_m = st_s >= 0 + nv = int(valid_m.sum()) + good_p = round(100.0 * float((st_s == 0).sum()) / max(nv, 1), 1) + corr_p = round(100.0 * float((st_s == 1).sum()) / max(nv, 1), 1) + unrel_p = round(100.0 * float((st_s == 2).sum()) / max(nv, 1), 1) + else: + corr_s = pd.to_numeric(tz_env_df[c_col], errors="coerce") + valid_m = corr_s.notna() + nv = int(valid_m.sum()) + good_p, corr_p, unrel_p = 0.0, 100.0, 0.0 + cf_mean = ( + round( + float( + pd.to_numeric(tz_env_df[cf_col], errors="coerce")[ + valid_m + ].mean() + ), + 3, + ) + if cf_col in tz_env_df.columns and nv > 0 + else None + ) + sg_mean = ( + round( + float( + pd.to_numeric(tz_env_df[sg_col], errors="coerce")[ + valid_m + ].mean() + ), + 4, + ) + if sg_col in tz_env_df.columns and nv > 0 + else None + ) + if dl_col in tz_env_df.columns: + dl_s = pd.to_numeric(tz_env_df[dl_col], errors="coerce")[ + valid_m + ].dropna() + elif has_c and lg_k in tz_env_df.columns: + if lg_k == "RT": + dl_s = ( + np.log10( + pd.to_numeric(tz_env_df[c_col], errors="coerce").clip( + lower=1e-3 + ) + ) + - np.log10( + pd.to_numeric(tz_env_df[lg_k], errors="coerce").clip( + lower=1e-3 + ) + ) + )[valid_m].dropna() + else: + dl_s = ( + pd.to_numeric(tz_env_df[c_col], errors="coerce") + - pd.to_numeric(tz_env_df[lg_k], errors="coerce") + )[valid_m].dropna() + else: + dl_s = pd.Series(dtype=float) + dom_r = ( + _dominant_env_reason(reason_tz, valid_m) + if not reason_tz.empty + else "Clean" + ) + env_corr_curve_table.append( + { + "curve": lg_k, + "corr_curve": c_col, + "unit": _ENV_CURVE_UNITS.get(lg_k, ""), + "samples": nv, + "good_pct": good_p, + "corrected_pct": corr_p, + "unreliable_pct": unrel_p, + "mean_conf": cf_mean, + "mean_sigma": sg_mean, + "mean_delta": ( + round(float(dl_s.mean()), 4) if not dl_s.empty else None + ), + "mean_abs_delta": ( + round(float(dl_s.abs().mean()), 4) if not dl_s.empty else None + ), + "p95_abs_delta": ( + round(float(dl_s.abs().quantile(0.95)), 4) + if not dl_s.empty + else None + ), + "dominant_reason": dom_r, + } + ) + + env_temp_s = ( + pd.to_numeric(tz_env_df["ENV_TEMP_C"], errors="coerce").dropna() + if not tz_env_df.empty and "ENV_TEMP_C" in tz_env_df.columns + else pd.Series(dtype=float) + ) + env_rm_s = ( + pd.to_numeric(tz_env_df["ENV_RM"], errors="coerce").dropna() + if not tz_env_df.empty and "ENV_RM" in tz_env_df.columns + else pd.Series(dtype=float) + ) + env_rmf_s = ( + pd.to_numeric(tz_env_df["ENV_RMF"], errors="coerce").dropna() + if not tz_env_df.empty and "ENV_RMF" in tz_env_df.columns + else pd.Series(dtype=float) + ) + env_rw_s = ( + pd.to_numeric(tz_env_df["ENV_RW"], errors="coerce").dropna() + if not tz_env_df.empty and "ENV_RW" in tz_env_df.columns + else pd.Series(dtype=float) + ) + reason_all = ( + pd.to_numeric(tz_env_df["ENV_QC_REASON"], errors="coerce").fillna(0).astype(int) + if not tz_env_df.empty and "ENV_QC_REASON" in tz_env_df.columns + else pd.Series(dtype=int) + ) + total_cycle_skips = ( + int( + ( + (reason_all.to_numpy(dtype=int) & ENV_QC_REASON_BITS["CYCLE_SKIP"]) != 0 + ).sum() + ) + if not reason_all.empty + else sum(int(r.get("cycle_skips", 0)) for r in env_well_rows) + ) + total_res_mismatch = ( + int( + ( + ( + reason_all.to_numpy(dtype=int) + & ENV_QC_REASON_BITS["RES_MUD_MISMATCH"] + ) + != 0 + ).sum() + ) + if not reason_all.empty + else 0 + ) + + invasion_rollup: Dict[str, Any] = {} + if invasion_well_rows: + tot_inv_s = max(sum(r["samples"] for r in invasion_well_rows), 1) + di_vals = [ + r["median_di_in"] + for r in invasion_well_rows + if r.get("median_di_in") is not None + ] + p90_di_vals = [ + r["p90_di_in"] for r in invasion_well_rows if r.get("p90_di_in") is not None + ] + invasion_rollup = { + "invaded_pct": round( + sum(r["invaded_pct"] * r["samples"] for r in invasion_well_rows) + / tot_inv_s, + 1, + ), + "water_like_pct": round( + sum(r["water_like_pct"] * r["samples"] for r in invasion_well_rows) + / tot_inv_s, + 1, + ), + "hc_like_pct": round( + sum(r["hc_like_pct"] * r["samples"] for r in invasion_well_rows) + / tot_inv_s, + 1, + ), + "anomalous_pct": round( + sum(r["anomalous_pct"] * r["samples"] for r in invasion_well_rows) + / tot_inv_s, + 1, + ), + "tight_pct": round( + sum(r["tight_pct"] * r["samples"] for r in invasion_well_rows) + / tot_inv_s, + 1, + ), + "median_di_in": round(float(np.median(di_vals)), 1) if di_vals else None, + "p90_di_in": round(float(max(p90_di_vals)), 1) if p90_di_vals else None, + } + + all_mud_types = sorted( + {r["mud_type"] for r in hole_sections_rows if r.get("mud_type")} + | {e.default_mud_type for e in resolved_envs} + ) + any_env_applied = len(env_corr_curve_table) > 0 or any( + r.get("has_env_corr") for r in qaqc_table + ) + curve_confs = [ + float(r["mean_conf"]) + for r in env_corr_curve_table + if r.get("mean_conf") is not None + ] + curve_unrels = [float(r["unreliable_pct"]) for r in env_corr_curve_table] + bht_calibrated = any(bool(e.bht_records) for e in resolved_envs) + + env_corr_summary: Dict[str, Any] = { + "any_applied": any_env_applied, + "wells_applied": sum(1 for r in qaqc_table if r.get("has_env_corr")), + "total_wells": len(qaqc_table), + "tool_type": eff_tool_type, + "res_tool": eff_res_tool, + "mud_type": "/".join(all_mud_types) + if all_mud_types + else primary_env.default_mud_type, + "mud_weight_ppg": round(float(primary_env.default_mud_weight_ppg), 2), + "mud_salinity_ppm": int(round(float(primary_env.default_mud_salinity_ppm))), + "formation_salinity_ppm": int(round(float(primary_env.formation_salinity_ppm))), + "offshore": any(e.offshore for e in resolved_envs), + "water_depth_m": round( + max((e.water_depth_m for e in resolved_envs), default=0.0), 1 + ), + "top_temp_c": round(float(primary_env.top_temp_c), 1), + "gradient_c_per_km": round(float(primary_env.gradient_c_per_km), 1), + "bht_calibrated": bht_calibrated, + "hole_section_count": len(hole_sections_rows), + "hole_sections_table": hole_sections_rows, + "temp_min_c": ( + round(float(env_temp_s.min()), 1) if not env_temp_s.empty else None + ), + "temp_max_c": ( + round(float(env_temp_s.max()), 1) if not env_temp_s.empty else None + ), + "temp_median_c": ( + round(float(env_temp_s.median()), 1) if not env_temp_s.empty else None + ), + "median_rm": round(float(env_rm_s.median()), 4) if not env_rm_s.empty else None, + "median_rmf": ( + round(float(env_rmf_s.median()), 4) if not env_rmf_s.empty else None + ), + "median_rw": round(float(env_rw_s.median()), 4) if not env_rw_s.empty else None, + "mean_conf": round(float(np.mean(curve_confs)), 3) if curve_confs else None, + "min_mean_conf": round(float(min(curve_confs)), 3) if curve_confs else None, + "max_unreliable_pct": round(max(curve_unrels), 1) if curve_unrels else 0.0, + "cycle_skip_count": total_cycle_skips, + "res_mud_mismatch_count": total_res_mismatch, + "corrected_curves": [r["corr_curve"] for r in env_corr_curve_table], + "curve_table": env_corr_curve_table, + "well_table": env_well_rows, + "has_invasion": len(invasion_well_rows) > 0, + "invasion_table": invasion_well_rows, + "invasion_rollup": invasion_rollup, + "sigma_propagated": env_sigma_used, + "assumptions": env_assumptions_seen[:8], + } + + cali_lim = _safe_float( + req_env_cfg.get( + "washoutThold", + req_env_cfg.get("washout_thold", merged_configs.get("cali_threshold")), + ), + 2.0, + ) + drho_lim = _safe_float(merged_configs.get("drho_threshold"), 0.15) + rhob_m = _safe_float(merged_configs.get("rhob_min"), 1.95) qaqc_params = { - "caliper_limit": _safe_float(merged_configs.get("cali_threshold"), 2.0), - "bitsize_in": _safe_float(merged_configs.get("bitsize_default"), 8.5), - "drho_limit": _safe_float(merged_configs.get("drho_threshold"), 0.15), - "rhob_min": _safe_float(merged_configs.get("rhob_min"), 1.95), + "caliper_limit": cali_lim, + "bitsize_in": _safe_float( + merged_configs.get("bitsize_default", primary_env.default_bit_size_in), 8.5 + ), + "drho_limit": drho_lim, + "rhob_min": rhob_m, "badhole_treatment": bh_treat_display, + "badhole_criteria_used": f"CALI - BS > {cali_lim:.1f} in, |DRHO| > {drho_lim:.2f} g/cc, RHOB < {rhob_m:.2f} g/cc", "rho_hc": _safe_float(merged_configs.get("rho_hc"), 0.80), "hi_hc": _safe_float(merged_configs.get("hi_hc"), 0.90), "norm_method": "Stratigraphic Zonal P10–P90 Quantile Alignment", + "env_corr_applied": any_env_applied, + "tool_type": eff_tool_type, + "mud_type": env_corr_summary["mud_type"], + "mud_weight_ppg": env_corr_summary["mud_weight_ppg"], + "hole_section_count": len(hole_sections_rows), + "offshore": env_corr_summary["offshore"], + "water_depth_m": env_corr_summary["water_depth_m"], + "top_temp_c": env_corr_summary["top_temp_c"], + "gradient_c_per_km": env_corr_summary["gradient_c_per_km"], } dry_sand_pt = merged_configs.get("dry_sand_point") or (-0.02, 2.65) - dry_clay_pt = merged_configs.get("dry_clay_point") or (round(nphi_clay_cfg, 2), round(rho_clay_cfg, 2)) + dry_clay_pt = merged_configs.get("dry_clay_point") or ( + round(nphi_clay_cfg, 2), + round(rho_clay_cfg, 2), + ) dry_silt_pt = merged_configs.get("dry_silt_point") silt_angle_cfg = _safe_float(merged_configs.get("silt_line_angle"), 119.0) fluid_pt = merged_configs.get("fluid_point") or (1.0, 1.0) + gamma_cfg = merged_configs.get("gamma") or {} + gamma_src = ( + str(gamma_cfg.get("source") or gamma_cfg.get("gamma_source") or "") + .strip() + .lower() + ) + if gamma_src in ("cgr", "derived_cgr") and gamma_cfg.get("gamma_clean") is not None: + gr_clean_active = round( + _safe_float(gamma_cfg.get("gamma_clean"), gr_clean_cfg), 1 + ) + gr_shale_active = round( + _safe_float(gamma_cfg.get("gamma_shale"), gr_clay_cfg), 1 + ) + else: + gr_clean_active = round(gr_clean_cfg, 1) + gr_shale_active = round(gr_clay_cfg, 1) + litho_params = { "model_key": resolved_litho_key, "model_name": litho_model_display, "rho_clay": round(rho_clay_cfg, 2), "nphi_clay": round(nphi_clay_cfg, 2), - "gr_clean": round(gr_clean_cfg, 1), - "gr_shale": round(gr_clay_cfg, 1), + "gr_clean": gr_clean_active, + "gr_shale": gr_shale_active, "dry_sand_point": dry_sand_pt, "dry_clay_point": dry_clay_pt, "dry_silt_point": dry_silt_pt, "silt_line_angle": silt_angle_cfg, "fluid_point": fluid_pt, "bulk_shale": merged_configs.get("bulk_shale") or {}, - "gamma": merged_configs.get("gamma") or {}, + "gamma": gamma_cfg, } scal_cfg = ( merged_configs.get("scal_params") @@ -1855,18 +4781,24 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: or ("CPERM_ORI" in full_df.columns) ) ncs_val = _safe_float( - merged_configs.get("net_confining_stress", scal_cfg.get("net_confining_stress")), + merged_configs.get( + "net_confining_stress", scal_cfg.get("net_confining_stress") + ), 3500.0, ) pm_val = _safe_float( merged_configs.get("mean_pore_pressure", scal_cfg.get("mean_pore_pressure")), 45.0, ) - core_litho_val = str( - merged_configs.get("core_lithology") - or scal_cfg.get("core_lithology") - or "sandstone" - ).strip().lower() + core_litho_val = ( + str( + merged_configs.get("core_lithology") + or scal_cfg.get("core_lithology") + or "sandstone" + ) + .strip() + .lower() + ) if core_litho_val == "carbonate": default_c_phi = 2.5e-6 core_litho_label = "Carbonate (Stiff / Well-Cemented)" @@ -1886,15 +4818,19 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: ), c_phi_val * 5.0, ) - klink_method_val = str( - merged_configs.get("klinkenberg_method") - or scal_cfg.get("klinkenberg_method") - or "jones" - ).strip().title() - - core_shift_mode_raw = str( - merged_configs.get("core_shift_mode") or "affine" - ).strip().lower() + klink_method_val = ( + str( + merged_configs.get("klinkenberg_method") + or scal_cfg.get("klinkenberg_method") + or "jones" + ) + .strip() + .title() + ) + + core_shift_mode_raw = ( + str(merged_configs.get("core_shift_mode") or "affine").strip().lower() + ) core_shift_delta_val = _safe_float(merged_configs.get("core_shift_delta"), 0.0) core_stretch_val = _safe_float(merged_configs.get("core_stretch_factor"), 1.0) core_tie_pts = ( @@ -1980,6 +4916,69 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: "core_perm_liq_mean", scal_cfg.get("core_perm_liq_mean") ), } + sw_cfg = ( + merged_configs.get("sw_params") + if isinstance(merged_configs.get("sw_params"), dict) + else {} + ) + raw_temp = ( + sw_cfg.get("temp") + or merged_configs.get("formation_temp") + or merged_configs.get("temp") + ) + if raw_temp is not None: + res_temp = round(float(raw_temp), 1) + temp_basis = "Configured Formation Temperature" + elif env_corr_summary.get("temp_median_c") is not None: + res_temp = float(env_corr_summary["temp_median_c"]) + temp_basis = ( + f"Borehole Environment Profile (`ENV_TEMP_C`, {env_corr_summary['gradient_c_per_km']:.1f} °C/km" + + ( + f", offshore WD={env_corr_summary['water_depth_m']:.0f} m" + if env_corr_summary["offshore"] + else "" + ) + + (", BHT-calibrated)" if env_corr_summary["bht_calibrated"] else ")") + ) + elif primary_env.offshore or primary_env.explicit.get("temperature"): + res_temp = round(float(primary_env.temperature_c(median_target_tvdss)), 1) + temp_basis = ( + f"{'Offshore Seabed-Anchored' if primary_env.offshore else 'BHT-Calibrated'} " + f"Geothermal Profile ({primary_env.gradient_c_per_km:.1f} °C/km @ {median_target_tvdss:.0f} m TVDss)" + ) + else: + surf_temp = _safe_float(merged_configs.get("surface_temp"), 15.0) + temp_grad = _safe_float( + merged_configs.get("temp_grad") + or merged_configs.get("saturation_temp_grad"), + 3.0, + ) + res_temp = round(surf_temp + temp_grad * (median_target_tvdss / 100.0), 1) + temp_basis = f"Computed from Geothermal Gradient ({temp_grad:.1f} °C/100m @ {median_target_tvdss:.0f} m TVDss)" + + rw_val = round(_safe_float(merged_configs.get("rw_val"), 0.080), 3) + from quick_pp.saturation import estimate_b_waxman_smits + + b_conductance = round(float(estimate_b_waxman_smits(res_temp, rw_val)), 2) + + qv_val = _safe_float( + sw_cfg.get("qv") + or merged_configs.get("qv") + or ( + full_df["QV"].median() + if ("QV" in full_df.columns and full_df["QV"].notna().any()) + else 0.55 + ), + 0.55, + ) + cec_val = _safe_float(sw_cfg.get("cec") or merged_configs.get("cec"), 12.0) + phish_val = _safe_float(sw_cfg.get("phish") or merged_configs.get("phish"), 0.25) + qv_method = str( + sw_cfg.get("qv_method") + or merged_configs.get("qv_method") + or "Juhasz Qvn Empirical Correlation" + ) + sw_params = { "model_key": raw_sw_key, "model_name": sw_model_display, @@ -1987,17 +4986,25 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: "fwl_basis": fwl_basis_str, "median_target_tvdss": median_target_tvdss, "salinity": int(_safe_float(merged_configs.get("water_salinity"), 35000.0)), - "rw": round(_safe_float(merged_configs.get("rw_val"), 0.080), 3), - "temp": 75.0, + "rw": rw_val, + "temp": res_temp, + "temp_basis": temp_basis, "a": round(_safe_float(merged_configs.get("sw_a"), 1.0), 2), "m": round(_safe_float(merged_configs.get("sw_m"), 2.0), 2), "n": round(_safe_float(merged_configs.get("sw_n"), 2.0), 2), + "b_conductance": b_conductance, + "qv": round(qv_val, 3), + "cec": round(cec_val, 1), + "phish": round(phish_val, 3), + "qv_method": qv_method, "rsh": round(_safe_float(merged_configs.get("sw_rsh"), 2.0), 3), "swb": round(_safe_float(merged_configs.get("sw_swb"), 0.2), 3), "rwb": round(_safe_float(merged_configs.get("sw_rwb"), 0.1), 3), } ift_res_cfg = _safe_float( - merged_configs.get("ift_res", scal_cfg.get("ift_res", merged_configs.get("ift"))), + merged_configs.get( + "ift_res", scal_cfg.get("ift_res", merged_configs.get("ift")) + ), 30.0, ) theta_res_cfg = _safe_float( @@ -2012,7 +5019,7 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: theta_lab_cfg = _safe_float( merged_configs.get("theta_lab", scal_cfg.get("theta_lab")), 140.0 ) - lab_denom = max( abs(ift_lab_cfg * math.cos(math.radians(theta_lab_cfg))), 1e-6 ) + lab_denom = max(abs(ift_lab_cfg * math.cos(math.radians(theta_lab_cfg))), 1e-6) res_num = abs(ift_res_cfg * math.cos(math.radians(theta_res_cfg))) pc_scale_cfg = _safe_float( merged_configs.get("pc_scale_factor", scal_cfg.get("pc_scale_factor")), @@ -2022,6 +5029,8 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: merged_configs.get("pc_scaling_applied") or scal_cfg.get("pc_scaling_applied") ) shf_params = { + "fwl": fwl_val, + "fwl_basis": fwl_basis_str, "ift": round(ift_res_cfg, 1), "theta": round(theta_res_cfg, 1), "ift_cos_theta": round(res_num, 1), @@ -2037,21 +5046,36 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: merged_configs.get("pc_res_output", scal_cfg.get("pc_res_output")), round(25.0 * pc_scale_cfg, 3), ), - "gw": 1.05, - "ghc": 0.80, + "gw": gw_val, + "gw_basis": gw_basis, + "ghc": ghc_val, + "delta_rho": delta_rho, + "ghc_basis": ghc_basis, + "reservoir_fluid": res_fluid, "reconciliation_rmse": shf_rmse, "reconciliation_bias": shf_bias, + "reconciliation_n": shf_n_compared, + "fit_source": shf_fit_source, + "uses_saved_fit": use_saved_fits, + "fit_rows": shf_fit_rows, } - scal_model_key = str( - scal_cfg.get("model") or merged_configs.get("scal_model") or "corey" - ).strip().lower() + scal_model_key = ( + str(scal_cfg.get("model") or merged_configs.get("scal_model") or "let") + .strip() + .lower() + ) + is_scal_calibrated = bool( + any_scal_data + or scal_cfg.get("user_calibrated") + or scal_cfg.get("is_calibrated") + ) scal_params = { - "is_analogue": not (any_scal_data or bool(scal_cfg)), + "is_analogue": not is_scal_calibrated, "model": scal_model_key, "source_label": ( f"Calibrated {scal_model_key.upper()} SCAL & Core Parameterization" - if (any_scal_data or bool(scal_cfg)) - else "Analogue / Default Corey SCAL Parameterization" + if is_scal_calibrated + else f"Regional Analogue / Screening {scal_model_key.upper()} Parameterization" ), "swirr": _safe_float( scal_cfg.get("swirr", merged_configs.get("scal_swirr")), 0.15 @@ -2078,49 +5102,41 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: scal_cfg.get("pc_max", merged_configs.get("scal_pc_max")), 50.0 ), } + has_custom_up = ( + "upscaling_cell_size" in merged_configs or "upscaling_omega" in merged_configs + ) upscaling_params = { - "cell_size": 2.0, - "omega": 0.33, + "cell_size": _safe_float(merged_configs.get("upscaling_cell_size"), 2.0), + "omega": _safe_float(merged_configs.get("upscaling_omega"), 0.33), + "basis": "Project Upscaling Config" + if has_custom_up + else "Default Simulation Grid Standard", + } + mean_kv_kh = ( + round(float(np.mean([r["kv_kh"] for r in upscaling_table])), 3) + if upscaling_table + else 0.0 + ) + kv_kh_vals = [ + r["kv_kh"] + for r in upscaling_table + if r.get("kv_kh") is not None and r["kv_kh"] > 0 + ] + min_kv_kh = round(float(np.min(kv_kh_vals)), 3) if kv_kh_vals else mean_kv_kh + max_kv_kh = round(float(np.max(kv_kh_vals)), 3) if kv_kh_vals else mean_kv_kh + upscaling_summary = { + "mean_kv_kh": mean_kv_kh, + "min_kv_kh": min_kv_kh, + "max_kv_kh": max_kv_kh, + "cell_size": upscaling_params["cell_size"], + "omega": upscaling_params["omega"], } - - # Query all committed fluid contacts for selected project wells - well_name_by_id = {w["id"]: w["name"] for w in selected_wells_meta} - fluid_contacts_rows: List[Dict[str, Any]] = [] - with get_db() as session: - fc_res = session.execute( - select( - db_objects.ORMFluidContact.well_id, - db_objects.ORMFluidContact.name, - db_objects.ORMFluidContact.depth, - db_objects.ORMFluidContact.zone, - db_objects.ORMFluidContact.contact_type, - db_objects.ORMFluidContact.fault_block, - db_objects.ORMFluidContact.source, - db_objects.ORMFluidContact.remarks, - ) - .where(db_objects.ORMFluidContact.well_id.in_(list(well_name_by_id.keys()))) - .order_by(db_objects.ORMFluidContact.depth) - ).all() - for r in fc_res: - c_type = str(r.contact_type or r.name or "CONTACT").upper() - if c_type == "WDT": # Excluded per user instruction - continue - wn = well_name_by_id.get(r.well_id, f"Well-{r.well_id}") - fluid_contacts_rows.append({ - "well_name": wn, - "name": str(r.name), - "depth": round(float(r.depth), 1) if r.depth is not None else None, - "zone": str(r.zone) if r.zone else "All Zones", - "contact_type": c_type, - "fault_block": str(r.fault_block) if r.fault_block else None, - "source": str(r.source) if r.source else "Petrophysical Log Evaluation", - "remarks": str(r.remarks) if r.remarks else "", - }) # If no stored contacts in DB, dynamically extract them from full_df if not fluid_contacts_rows and not full_df.empty: try: from quick_pp.saturation import extract_fluid_contacts_and_limits + extracted_df = extract_fluid_contacts_and_limits( df=full_df, fwl_dict={"default": fwl_val}, @@ -2133,16 +5149,26 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: c_type = str(r.get("contact_type") or "").upper() if c_type == "WDT": continue - fluid_contacts_rows.append({ - "well_name": str(r.get("well_name") or "Field"), - "name": str(r.get("name") or c_type), - "depth": round(float(r["depth"]), 1) if r.get("depth") is not None else None, - "zone": str(r.get("zone")) if r.get("zone") else "All Zones", - "contact_type": c_type, - "fault_block": str(r.get("fault_block")) if r.get("fault_block") else None, - "source": str(r.get("source") or "Petrophysical Log Interpretation"), - "remarks": str(r.get("remarks") or ""), - }) + fluid_contacts_rows.append( + { + "well_name": str(r.get("well_name") or "Field"), + "name": str(r.get("name") or c_type), + "depth": round(float(r["depth"]), 1) + if r.get("depth") is not None + else None, + "zone": str(r.get("zone")) + if r.get("zone") + else "All Zones", + "contact_type": c_type, + "fault_block": str(r.get("fault_block")) + if r.get("fault_block") + else None, + "source": str( + r.get("source") or "Petrophysical Log Interpretation" + ), + "remarks": str(r.get("remarks") or ""), + } + ) except Exception: pass @@ -2163,6 +5189,7 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: "gwc": None, "owc": None, "fwl": None, + "_fwl_list": [], } g = zonal_contact_groups[key] ctype = r["contact_type"] @@ -2186,10 +5213,160 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: elif ctype == "OWC": g["owc"] = d elif ctype == "FWL": - g["fwl"] = d + g["_fwl_list"].append(d) + + for g in zonal_contact_groups.values(): + fwl_l = g.pop("_fwl_list", []) + if fwl_l: + min_f = min(fwl_l) + max_f = max(fwl_l) + if abs(max_f - min_f) < 0.1: + g["fwl"] = round(min_f, 1) + else: + g["fwl"] = f"{min_f:.1f}–{max_f:.1f}" fluid_contacts_summary = list(zonal_contact_groups.values()) + # Volumetric Summary Calculation & Handover Readiness Fallback (GAP-12) + area_acres = _safe_float( + merged_configs.get("area_acres") + or merged_configs.get("area") + or (model_params.get("area_acres") if model_params else None), + None, + ) + vol_sum_existing = merged_configs.get("volumetric_summary") + if isinstance(vol_sum_existing, dict) and "field_totals" in vol_sum_existing: + volumetric_summary = vol_sum_existing + volumetric_readiness = None + elif area_acres is not None and area_acres > 0.0: + res_fl = ( + str( + merged_configs.get("reservoir_fluid") + or (model_params.get("reservoir_fluid") if model_params else "") + or "oil" + ) + .strip() + .lower() + ) + bg_eff = _safe_float( + merged_configs.get("bg") + or (model_params.get("bg") if model_params else None), + 0.0045 if res_fl == "gas" else 0.005, + ) + bo_eff = _safe_float( + merged_configs.get("bo") + or merged_configs.get("boi") + or (model_params.get("bo") if model_params else None), + 1.25 if res_fl != "gas" else 1.20, + ) + bg_eff = max(bg_eff, 1e-5) + bo_eff = max(bo_eff, 0.1) + + zonal_vol_summaries = [] + stoiip_p90_tot = 0.0 + stoiip_p50_tot = 0.0 + stoiip_p10_tot = 0.0 + rec_oil_p50_tot = 0.0 + giip_p90_tot = 0.0 + giip_p50_tot = 0.0 + giip_p10_tot = 0.0 + rec_gas_p50_tot = 0.0 + + for z in zonal_summary: + z_name = z["zone"] + z_unc_rows = [ + u + for u in uncertainty_summary + if u["zone"] == z_name + and u["metric"] == "Hydrocarbon Pore Thickness HCPT (m)" + ] + if z_unc_rows: + h_p90 = _safe_float(z_unc_rows[0].get("p90_hcpt"), 0.0) + h_p50 = _safe_float(z_unc_rows[0].get("p50_hcpt"), 0.0) + h_p10 = _safe_float(z_unc_rows[0].get("p10_hcpt"), 0.0) + else: + h_p50 = float(z.get("hcpt", 0.0)) + h_p90 = round(h_p50 * 0.8, 2) + h_p10 = round(h_p50 * 1.2, 2) + + # 1 m = 3.28084 ft + # HCPV (acre-ft) = Area (acres) * (HCPT (m) * 3.28084) + hcpv_p90 = area_acres * (h_p90 * 3.28084) + hcpv_p50 = area_acres * (h_p50 * 3.28084) + hcpv_p10 = area_acres * (h_p10 * 3.28084) + + # Gas GIIP (Bcf) = 43560 * HCPV / (Bg * 1e9) + giip_p90 = round((43560.0 * hcpv_p90) / (bg_eff * 1e9), 2) + giip_p50 = round((43560.0 * hcpv_p50) / (bg_eff * 1e9), 2) + giip_p10 = round((43560.0 * hcpv_p10) / (bg_eff * 1e9), 2) + rec_gas_p50 = round(giip_p50 * 0.70, 2) + + # Oil STOIIP (MMbbl) = 7758 * HCPV / (Bo * 1e6) + stoiip_p90 = round((7758.0 * hcpv_p90) / (bo_eff * 1e6), 2) + stoiip_p50 = round((7758.0 * hcpv_p50) / (bo_eff * 1e6), 2) + stoiip_p10 = round((7758.0 * hcpv_p10) / (bo_eff * 1e6), 2) + rec_oil_p50 = round(stoiip_p50 * 0.35, 2) + + zonal_vol_summaries.append( + { + "zone": z_name, + "stoiip": { + "p90": stoiip_p90, + "p50": stoiip_p50, + "p10": stoiip_p10, + }, + "rec_oil": {"p50": rec_oil_p50}, + "giip": {"p90": giip_p90, "p50": giip_p50, "p10": giip_p10}, + "rec_gas": {"p50": rec_gas_p50}, + } + ) + stoiip_p90_tot += stoiip_p90 + stoiip_p50_tot += stoiip_p50 + stoiip_p10_tot += stoiip_p10 + rec_oil_p50_tot += rec_oil_p50 + giip_p90_tot += giip_p90 + giip_p50_tot += giip_p50 + giip_p10_tot += giip_p10 + rec_gas_p50_tot += rec_gas_p50 + + volumetric_summary = { + "mode": "Drainage Area", + "n_samples": 1000, + "zonal_summaries": zonal_vol_summaries, + "field_totals": { + "stoiip": { + "p90": round(stoiip_p90_tot, 2), + "p50": round(stoiip_p50_tot, 2), + "p10": round(stoiip_p10_tot, 2), + }, + "rec_oil": {"p50": round(rec_oil_p50_tot, 2)}, + "giip": { + "p90": round(giip_p90_tot, 2), + "p50": round(giip_p50_tot, 2), + "p10": round(giip_p10_tot, 2), + }, + "rec_gas": {"p50": round(rec_gas_p50_tot, 2)}, + }, + } + volumetric_readiness = None + else: + volumetric_summary = None + fs = _compute_field_summary(zonal_summary) + volumetric_readiness = { + "status": "AWAITING_RESERVOIR_AREA", + # `mean_*` keys are per-zone means; `column_*` are sums across zones (a well through every zone). + "mean_hcpt": fs["mean_zone_hcpt"], + "mean_net_pay": fs["mean_zone_net_pay"], + "mean_ntg": fs["ntg_pay"], + "mean_phie": fs["phie"] if fs["phie"] is not None else 0.0, + "mean_sw": fs["sw"] if fs["sw"] is not None else 0.0, + "total_hcpt": fs["column_hcpt"], + "column_hcpt": fs["column_hcpt"], + "column_net_pay": fs["column_net_pay"], + "evaluated_zones": fs["n_zones"], + "pay_zones": fs["n_pay_zones"], + } + ctx_payload: Dict[str, Any] = { "project_id": pid, "project_name": project_name, @@ -2201,12 +5378,19 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: "cutoffs": {"vsh": vsh_cut, "phie": phie_cut, "sw": sw_cut}, "qaqc_params": qaqc_params, "qaqc_table": qaqc_table, + "env_corr_summary": env_corr_summary, "litho_params": litho_params, "poro_params": poro_params, "rock_types": rock_types, + "saved_flag_rows": saved_flag_rows, "fzi_cutoffs": resolved_fzi_cutoffs, "rt_summary": { "basis": rt_basis_source, + "cutoff_source": cutoff_source, + "method": saved_rt_method, + "dominant_codes": dominant_codes, + "dominant_share_pct": dominant_share_pct, + "dominant_kh_pct": dominant_kh_pct, "rt34_share_pct": rt34_share_pct, "rt34_kh_pct": rt34_kh_pct, }, @@ -2219,32 +5403,45 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: "fluid_contacts_rows": fluid_contacts_rows, "fluid_contacts_summary": fluid_contacts_summary, "uncertainty_summary": uncertainty_summary, - "volumetric_summary": merged_configs.get("volumetric_summary"), + "uncertainty_drivers_text": uncertainty_drivers_text, + "volumetric_summary": volumetric_summary, + "volumetric_readiness": volumetric_readiness, "volumetric_params": merged_configs.get("volumetric_params"), "upscaling_params": upscaling_params, "upscaling_table": upscaling_table, + "upscaling_summary": upscaling_summary, + "fpt_summary": fpt_summary, + "_fpt_points": raw_fpt_points, "anomaly_flags": anomaly_flags, + "well_core_parity": well_core_parity, "_full_df": full_df, } ctx_payload["gate_checks"] = validate_fdp_report_payload(ctx_payload) + ctx_payload["gate_summary"] = summarize_gate_checks(ctx_payload["gate_checks"]) return ctx_payload def validate_fdp_report_payload(context: Dict[str, Any]) -> List[Dict[str, str]]: - """Execute Spec 5 Pre-Render Automated Gate-Check Assertions (CHK-01 through CHK-06).""" + """Execute Spec 5 Pre-Render Automated Gate-Check Assertions (CHK-01 through CHK-08).""" checks: List[Dict[str, str]] = [] full_df: pd.DataFrame = context.get("_full_df", pd.DataFrame()) target_zones_upper = {str(z).upper() for z in context.get("target_zones", [])} sw_p = context.get("sw_params", {}) poro_p = context.get("poro_params", {}) unc_list = context.get("uncertainty_summary", []) + shf_p = context.get("shf_params", {}) + contacts_rows = context.get("fluid_contacts_rows", []) # CHK-01: No synthetic constant padding outside evaluated intervals chk01_status = "PASS" chk01_detail = "All non-evaluated overburden/underburden intervals preserve null data (0 synthetic padded rows)." if not full_df.empty and "PHIE" in full_df.columns and "RT" in full_df.columns: outside_mask = ( - ~full_df["ZONES"].astype(str).str.strip().str.upper().isin(target_zones_upper) + ~full_df["ZONES"] + .astype(str) + .str.strip() + .str.upper() + .isin(target_zones_upper) if "ZONES" in full_df.columns and target_zones_upper else pd.Series(False, index=full_df.index) ) @@ -2255,7 +5452,20 @@ def validate_fdp_report_payload(context: Dict[str, Any]) -> List[Dict[str, str]] full_df.loc[padded_outside, ["PHIE", "PHIT", "SWT", "PERM"]] = np.nan chk01_status = "REMEDIATED" chk01_detail = f"Stripped {int(padded_outside.sum())} constant-padded sample(s) outside evaluated target zones." - checks.append({"id": "CHK-01", "rule": "Null-Padding Integrity Outside Target Zones", "status": chk01_status, "detail": chk01_detail}) + checks.append( + { + "id": "CHK-01", + "rule": "Null-Padding Integrity Outside Target Zones", + "category": "Data Conditioning", + "criterion": "Zero synthetic constant padding in overburden/underburden intervals", + "measured": chk01_detail, + "status": chk01_status, + "action_note": "Handover approved: interval boundaries verified." + if chk01_status in ("PASS", "REMEDIATED") + else "Remediation required.", + "detail": chk01_detail, + } + ) # CHK-02: abs(fwl_tvdss - median_target_tvdss) < 300.0 fwl_v = _safe_float(sw_p.get("fwl"), 2943.0) @@ -2266,7 +5476,13 @@ def validate_fdp_report_payload(context: Dict[str, Any]) -> List[Dict[str, str]] { "id": "CHK-02", "rule": "Free Water Level vs. Target Reservoir TVDss (<300 m)", + "category": "Fluid Contacts", + "criterion": "|FWL - Median Target TVDss| < 300 m", + "measured": f"FWL = {fwl_v:.1f} m TVDss vs. Target Median = {med_tvdss:.1f} m TVDss (Δ = {diff_fwl:.1f} m)", "status": chk02_status, + "action_note": "Hydrostatic datum consistent with target interval." + if chk02_status == "PASS" + else "Inspect regional aquifer / fault compartmentalization.", "detail": f"FWL = {fwl_v:.1f} m TVDss vs. Target Median = {med_tvdss:.1f} m TVDss (Δ = {diff_fwl:.1f} m).", } ) @@ -2279,13 +5495,27 @@ def validate_fdp_report_payload(context: Dict[str, Any]) -> List[Dict[str, str]] if c_cnt >= 3 and c_r2 >= 0.40 and c_rmse <= 0.040: chk03_status = "PASS" chk03_detail = f"Valid Target-Zone Plugs = {c_cnt}/{c_tot} (R² = {c_r2:.2f}, RMSE = {c_rmse:.3f} v/v)." + chk03_note = "Porosity calibration verified against target-zone RCA plugs." elif c_tot == 0: chk03_status = "N/A (Log-Only)" chk03_detail = "No RCA core plugs loaded in project; conditional narrative set to log-only." + chk03_note = "Log-only workflow active; core calibration bypassed." else: chk03_status = "QA ALERT" chk03_detail = f"Overlapping Target Plugs = {c_cnt}/{c_tot} (R² = {c_r2:.2f}, RMSE = {c_rmse:.3f} v/v); 'strong parity' claim suppressed." - checks.append({"id": "CHK-03", "rule": "Core-to-Log Depth Alignment & Parity Threshold", "status": chk03_status, "detail": chk03_detail}) + chk03_note = "Review per-well core parity diagnostics in Section 4.1." + checks.append( + { + "id": "CHK-03", + "rule": "Core-to-Log Depth Alignment & Parity Threshold", + "category": "Core Calibration", + "criterion": "Target RCA R² ≥ 0.40 and RMSE ≤ 0.040 v/v", + "measured": chk03_detail, + "status": chk03_status, + "action_note": chk03_note, + "detail": chk03_detail, + } + ) # CHK-04: P90_HCPT <= P50_HCPT <= P10_HCPT chk04_ok = all( @@ -2298,8 +5528,14 @@ def validate_fdp_report_payload(context: Dict[str, Any]) -> List[Dict[str, str]] { "id": "CHK-04", "rule": "Monotonic Uncertainty Percentiles (P90 ≤ P50 ≤ P10)", + "category": "Uncertainty Quantification", + "criterion": "P90 ≤ P50 ≤ P10 monotonically across all zones", + "measured": f"Verified across {len(unc_list)} target {_pluralize(len(unc_list), 'zone')}", "status": "PASS" if chk04_ok else "FAIL", - "detail": f"Verified across {len(unc_list)} target zone(s).", + "action_note": "Volumetric percentiles mathematically verified." + if chk04_ok + else "Distribution error: P90 exceeds P10.", + "detail": f"Verified across {len(unc_list)} target {_pluralize(len(unc_list), 'zone')}.", } ) @@ -2313,7 +5549,13 @@ def validate_fdp_report_payload(context: Dict[str, Any]) -> List[Dict[str, str]] { "id": "CHK-05", "rule": "Zero-Pay / Zero-Porosity HCPT Consistency", + "category": "Volumetrics Integrity", + "criterion": "P50_PHIE == 0 implies P50_HCPT == 0", + "measured": f"Sum of P50_HCPT where PHIE=0: {zero_phi_hcpt:.2f} m", "status": "PASS" if zero_phi_hcpt == 0.0 else "FAIL", + "action_note": "Zero-porosity non-reservoir integrity verified." + if zero_phi_hcpt == 0.0 + else "Phantom hydrocarbon volume detected in non-reservoir.", "detail": f"Sum of P50_HCPT where P50_PHIE == 0 is {zero_phi_hcpt:.2f} m.", } ) @@ -2327,13 +5569,290 @@ def validate_fdp_report_payload(context: Dict[str, Any]) -> List[Dict[str, str]] { "id": "CHK-06", "rule": "Target-Zoomed CPI & Blocking Vertical Span (≤ 500 m)", + "category": "Visualization QC", + "criterion": "Target depth window span ≤ 500 m MD", + "measured": f"Span = {span_w:.1f} m MD ({ymin_w:.1f}–{ymax_w:.1f} m)", "status": "PASS" if span_w <= 500.0 else "FAIL", + "action_note": "High-resolution target zoom active." + if span_w <= 500.0 + else "Span exceeds 500 m limit; compress interval.", "detail": f"Target plot depth window = {ymin_w:.1f}–{ymax_w:.1f} m MD (span = {span_w:.1f} m).", } ) + + # CHK-07: Fluid Contact Consistency + fwl_comm = None + for r in contacts_rows: + if r.get("contact_type") in ("FWL", "OWC") and r.get("depth") is not None: + fwl_comm = float(r["depth"]) + break + if fwl_comm is not None: + delta_fc = abs(fwl_v - fwl_comm) + chk07_ok = delta_fc <= 10.0 + chk07_status = "PASS" if chk07_ok else "QA ALERT" + chk07_measured = ( + f"|FWL ({fwl_v:.1f} m) - Committed ({fwl_comm:.1f} m)| = {delta_fc:.1f} m" + ) + chk07_note = ( + "Hydrostatic equilibrium verified within ±10 m tolerance." + if chk07_ok + else "Committed contact deviates from log transition; verify hydrodynamic tilt." + ) + else: + chk07_status = "PASS" + chk07_measured = f"Model FWL = {fwl_v:.1f} m TVDss (Single Source of Truth, no conflicting discrete contacts)" + chk07_note = "Single Source of Truth FWL verified across all reservoir zones." + + checks.append( + { + "id": "CHK-07", + "rule": "Fluid Contact Consistency (|FWL - Committed| ≤ 10 m)", + "category": "Fluid Contacts", + "criterion": "|Inferred FWL - Committed Contact| ≤ 10.0 m TVDss", + "measured": chk07_measured, + "status": chk07_status, + "action_note": chk07_note, + "detail": chk07_measured, + } + ) + + # CHK-08: Saturation-Height Reconciliation (SHF RMSE <= 0.12) + shf_rmse_val = shf_p.get("reconciliation_rmse") + shf_rmse = _safe_float(shf_rmse_val, None) if shf_rmse_val is not None else None + if shf_rmse is not None: + chk08_ok = shf_rmse <= 0.12 + chk08_status = "PASS" if chk08_ok else "QA ALERT" + chk08_measured = ( + f"SHF vs Log SWT RMSE = {shf_rmse:.3f} v/v " + f"(n={shf_p.get('reconciliation_n', 0)}; {shf_p.get('fit_source', 'unspecified fit')})" + ) + chk08_note = ( + "Saturation-height model consistent with active log saturation." + if chk08_ok + else "Capillary equilibrium deviation exceeds 0.12 v/v; inspect transition zone, FWL and rock-type fits." + ) + else: + chk08_status = "QA ALERT" + chk08_measured = "SHF vs log Sw reconciliation could not be computed (insufficient overlapping samples)" + chk08_note = "No SHF reconciliation statistic is reported; run the SHF module for the target zones." + + checks.append( + { + "id": "CHK-08", + "rule": "Saturation-Height Reconciliation (RMSE ≤ 0.12 v/v)", + "category": "Saturation-Height Modeling", + "criterion": "SHF Model vs. Active Log Sw RMSE ≤ 0.12 v/v", + "measured": chk08_measured, + "status": chk08_status, + "action_note": chk08_note, + "detail": chk08_measured, + } + ) + + # CHK-09: Core-to-log permeability parity + k_cnt = int(poro_p.get("core_perm_count", 0) or 0) + k_r2 = _safe_float(poro_p.get("core_perm_r2"), 0.0) + k_factor = _safe_float(poro_p.get("core_perm_factor_err"), 1.0) + if k_cnt >= 3 and k_r2 >= 0.40 and k_factor <= 5.0: + chk09_status = "PASS" + chk09_measured = f"Valid perm plugs = {k_cnt} (R² = {k_r2:.2f}, factor error = {k_factor:.1f}×)." + chk09_note = "Log permeability transform reproduces core permeability." + elif k_cnt == 0: + chk09_status = "N/A (Log-Only)" + chk09_measured = "No overlapping core permeability plugs in the target zones." + chk09_note = "Permeability is uncalibrated against core." + else: + chk09_status = "QA ALERT" + chk09_measured = ( + f"Valid perm plugs = {k_cnt} (R² = {k_r2:.2f}, factor error = {k_factor:.1f}×); " + "log permeability does not reproduce core." + ) + chk09_note = "Rock-type permeability transforms are not validated; do not use PERM for static-model handover." + checks.append( + { + "id": "CHK-09", + "rule": "Core-to-Log Permeability Parity (R² ≥ 0.40, factor error ≤ 5×)", + "category": "Permeability", + "criterion": "Target RCA permeability R² ≥ 0.40 and multiplicative error ≤ 5×", + "measured": chk09_measured, + "status": chk09_status, + "action_note": chk09_note, + "detail": chk09_measured, + } + ) + + # CHK-10: Rock typing calibrated to project (saved cutoffs, fitted classes) + rt_sum = context.get("rt_summary", {}) or {} + rts = context.get("rock_types", []) or [] + n_unfit = sum(1 for r in rts if r.get("fit_status") != "fitted") + generic_cut = str(rt_sum.get("cutoff_source", "")).startswith("generic default") + if generic_cut or (rts and n_unfit == len(rts)): + chk10_status = "QA ALERT" + chk10_measured = ( + "Generic FZI cutoffs applied; no saved rock typing for the target zones." + if generic_cut + else "No rock-type class has enough samples for a porosity-permeability fit." + ) + chk10_note = "Run and save Rock Typing in the workbench, then regenerate." + elif n_unfit > 0: + chk10_status = "REVIEW" + chk10_measured = f"{len(rts) - n_unfit} of {len(rts)} classes fitted; cutoffs: {rt_sum.get('cutoff_source', 'n/a')}." + chk10_note = "Classes without a fit carry no permeability transform." + else: + chk10_status = "PASS" + chk10_measured = f"All {len(rts)} classes fitted; cutoffs: {rt_sum.get('cutoff_source', 'n/a')}." + chk10_note = "Rock typing cutoffs and class regressions are project-calibrated." + checks.append( + { + "id": "CHK-10", + "rule": "Rock Typing Calibrated to Project Data", + "category": "Rock Typing", + "criterion": "Saved project cutoffs and a regression for every class", + "measured": chk10_measured, + "status": chk10_status, + "action_note": chk10_note, + "detail": chk10_measured, + } + ) + + # CHK-11: Formation pressure gradients physical and contacts committed + fpt_s = context.get("fpt_summary", {}) or {} + if fpt_s.get("has_data"): + rejected = fpt_s.get("rejected_fits", []) or [] + committed = bool(fpt_s.get("fwl_is_committed")) + if rejected: + chk11_status = "QA ALERT" + chk11_measured = ( + f"{len(rejected)} fitted gradient(s) rejected as unphysical or poorly constrained " + f"({', '.join(str(r.get('fluid_type')) for r in rejected)})." + ) + chk11_note = "Review pressure picks, fluid assignment and depth reference before using gradients." + elif not committed: + chk11_status = "REVIEW" + chk11_measured = "Gradients are physical, but no committed fluid contact exists to reconcile against." + chk11_note = "Contacts derived from pressure are indicative only." + else: + chk11_status = "PASS" + chk11_measured = ( + "Gradients physical and reconciled against committed contact." + ) + chk11_note = "Pressure regime consistent with the fluid model." + checks.append( + { + "id": "CHK-11", + "rule": "Formation Pressure Gradients Physical and Contacts Committed", + "category": "Formation Pressure", + "criterion": "Gradient densities within phase bounds; reference contact committed", + "measured": chk11_measured, + "status": chk11_status, + "action_note": chk11_note, + "detail": chk11_measured, + } + ) + + # CHK-12: Borehole Environmental Correction & Sensor Confidence Audit + env_s = context.get("env_corr_summary", {}) or {} + if env_s.get("any_applied"): + max_unrel = _safe_float(env_s.get("max_unreliable_pct"), 0.0) + mean_cf = env_s.get("mean_conf") + min_cf = env_s.get("min_mean_conf") + n_mismatch = int(env_s.get("res_mud_mismatch_count") or 0) + cf_txt = f"{mean_cf:.2f}" if isinstance(mean_cf, (int, float)) else "n/a" + if n_mismatch > 0 or max_unrel > 25.0: + chk12_status = "QA ALERT" + chk12_measured = ( + f"Env corrections applied ({', '.join(env_s.get('corrected_curves', []))}); " + f"max unreliable = {max_unrel:.1f}%, mean conf = {cf_txt}" + + ( + f", res/mud mismatch = {n_mismatch} samples." + if n_mismatch > 0 + else "." + ) + ) + chk12_note = "Inspect washout severity, resistivity/mud-type compatibility and enable confidence weighting." + elif max_unrel > 10.0 or (isinstance(min_cf, (int, float)) and min_cf < 0.65): + chk12_status = "REVIEW" + chk12_measured = ( + f"Applied across {env_s.get('wells_applied', 0)}/{env_s.get('total_wells', 0)} well(s) " + f"({env_s.get('tool_type', 'WL')}/{env_s.get('mud_type', 'WBM')}); " + f"mean conf = {cf_txt}, max unreliable = {max_unrel:.1f}%." + ) + chk12_note = "Propagate *_QC_CONF confidence weights and *_SIGMA uncertainties into downstream solvers." + else: + chk12_status = "PASS" + chk12_measured = ( + f"Applied across {env_s.get('wells_applied', 0)}/{env_s.get('total_wells', 0)} well(s) " + f"({env_s.get('tool_type', 'WL')}/{env_s.get('mud_type', 'WBM')}); " + f"mean conf = {cf_txt}, max unreliable = {max_unrel:.1f}%." + ) + chk12_note = ( + "Borehole environmental corrections and sensor confidence verified." + ) + else: + hs_n = int(env_s.get("hole_section_count") or 0) + chk12_status = "N/A (Raw Logs)" + chk12_measured = f"No *_ENV_CORR curves saved on project logs (hole sections loaded: {hs_n})." + chk12_note = "Run Borehole Environmental Corrections in Data & QA/QC to generate *_ENV_CORR and *_SIGMA." + checks.append( + { + "id": "CHK-12", + "rule": "Borehole Environmental Correction & Sensor Confidence", + "category": "Borehole Environment", + "criterion": "Max UNRELIABLE ≤ 10%, mean QC confidence ≥ 0.65, zero res/mud mismatch", + "measured": chk12_measured, + "status": chk12_status, + "action_note": chk12_note, + "detail": chk12_measured, + } + ) + return checks +_GATE_BLOCKING_STATUSES = {"QA ALERT", "FLAGGED", "FAIL", "FAILED"} +_GATE_REVIEW_STATUSES = {"REVIEW"} + + +def summarize_gate_checks(checks: Sequence[Dict[str, Any]]) -> Dict[str, Any]: + """Collapse the gate list into counts and the items that must be visible in the executive summary.""" + blocking = [ + c for c in checks if str(c.get("status", "")).upper() in _GATE_BLOCKING_STATUSES + ] + review = [ + c for c in checks if str(c.get("status", "")).upper() in _GATE_REVIEW_STATUSES + ] + if blocking: + overall = "NOT READY" + elif review: + overall = "CONDITIONAL" + else: + overall = "READY" + return { + "overall": overall, + "n_total": len(checks), + "n_blocking": len(blocking), + "n_review": len(review), + "blocking": [ + { + "id": c.get("id"), + "rule": c.get("rule"), + "measured": c.get("measured"), + "action": c.get("action_note"), + } + for c in blocking + ], + "review": [ + { + "id": c.get("id"), + "rule": c.get("rule"), + "measured": c.get("measured"), + "action": c.get("action_note"), + } + for c in review + ], + } + + def get_compact_report_context( project_id: Union[int, str], well_names: Optional[List[str]] = None, @@ -2372,6 +5891,7 @@ def synthesize_domain_ai_commentary( well_names = context.get("well_names", []) zonal = context.get("zonal_summary", []) qaqc_tbl = context.get("qaqc_table", []) + env_s = context.get("env_corr_summary", {}) or {} poro_p = context.get("poro_params", {}) sw_p = context.get("sw_params", {}) shf_p = context.get("shf_params", {}) @@ -2391,18 +5911,70 @@ def synthesize_domain_ai_commentary( ref_zones = pay_zones if pay_zones else zonal top_zone = max(ref_zones, key=lambda z: z.get("hcpt", 0.0)) if ref_zones else {} - # Thickness/Pore-volume weighted field summary numbers - if pay_zones: - w_h = np.array([max(float(z.get("net_pay", 0.0)), 1e-6) for z in pay_zones]) - mean_phie = float(np.sum(w_h * np.array([float(z.get("phie", 0.16)) for z in pay_zones])) / np.sum(w_h)) - w_pv = np.maximum(w_h * np.array([float(z.get("phie", 0.16)) for z in pay_zones]), 1e-6) - mean_sw = float(np.sum(w_pv * np.array([float(z.get("sw", 0.38)) for z in pay_zones])) / np.sum(w_pv)) + # Field summary numbers come from the same helper as Section 8.4 so both always agree. + field_sum = _compute_field_summary(zonal) + if field_sum["phie"] is not None: + mean_phie = field_sum["phie"] + mean_sw = field_sum["sw"] else: - mean_phie = float(np.mean([z.get("phie_res", 0.0) for z in ref_zones])) if ref_zones else 0.0 + mean_phie = ( + float(np.mean([z.get("phie_res", 0.0) for z in ref_zones])) + if ref_zones + else 0.0 + ) mean_sw = 1.0 - total_hcpt = sum(float(z.get("hcpt", 0.0)) for z in zonal) + total_hcpt = field_sum["column_hcpt"] + mean_zone_hcpt = field_sum["mean_zone_hcpt"] + n_eval_zones = field_sum["n_zones"] max_bh = max((q.get("badhole_pct", 0.0) for q in qaqc_tbl), default=0.0) + if env_s.get("any_applied"): + env_curves_txt = ", ".join(f"`{c}`" for c in env_s.get("corrected_curves", [])) + env_cf_val = env_s.get("mean_conf") + env_cf_txt = ( + f"{env_cf_val:.2f}" if isinstance(env_cf_val, (int, float)) else "n/a" + ) + env_regime_txt = ( + f"offshore ($WD = {env_s.get('water_depth_m', 0.0):.0f}\\text{{ m}}$)" + if env_s.get("offshore") + else "onshore" + ) + inv_roll = env_s.get("invasion_rollup") or {} + inv_clause = "" + if env_s.get("has_invasion") and inv_roll: + di_txt = ( + f", median $d_i = {inv_roll['median_di_in']:.1f}\\text{{ in}}$" + if inv_roll.get("median_di_in") is not None + else "" + ) + inv_clause = ( + f" Step-profile radial resistivity inversion classifies **{inv_roll.get('hc_like_pct', 0.0):.1f}%** " + f"of samples as movable-hydrocarbon invasion ($R_{{xo}}/R_t < R_{{mf}}/R_w$) and " + f"**{inv_roll.get('water_like_pct', 0.0):.1f}%** as water-zone invasion{di_txt}." + ) + env_narrative_suffix = ( + f" Generic **{env_s.get('tool_type', 'WL')}** borehole environmental corrections ({env_curves_txt}) were applied " + f"for a **{env_s.get('mud_type', 'WBM')}** ({env_s.get('mud_weight_ppg', 9.0):.1f} ppg, {env_regime_txt}, " + f"${env_s.get('gradient_c_per_km', 30.0):.1f}^\\circ\\text{{C/km}}$ geothermal gradient" + + ( + f", {env_s.get('hole_section_count', 0)} mud-program hole {_pluralize(env_s.get('hole_section_count', 0), 'section')}" + if env_s.get("hole_section_count") + else "" + ) + + f") logging environment, yielding a mean sensor confidence of **{env_cf_txt}** and " + f"a maximum unreliable-sample rate of **{env_s.get('max_unreliable_pct', 0.0):.1f}%**." + + inv_clause + ) + else: + hs_n = int(env_s.get("hole_section_count") or 0) + env_narrative_suffix = ( + " Explicit `*_ENV_CORR` environmental corrections have not yet been saved on the project curves" + + ( + f" ({hs_n} borehole mud-program {_pluralize(hs_n, 'section')} loaded in ancillary metadata)." + if hs_n > 0 + else "." + ) + ) # Spec 4.1: Threshold-driven calibration parity prose (never claim "strong parity" when R² is low) c_r2 = _safe_float(poro_p.get("core_r2"), 0.0) @@ -2412,7 +5984,9 @@ def synthesize_domain_ai_commentary( if c_r2 >= 0.75 and c_rmse <= 0.030: parity_desc = "strong parity and acceptable calibration accuracy" elif c_r2 >= 0.50 and c_rmse <= 0.045: - parity_desc = "moderate agreement, though local facies/depth-shift scatter is present" + parity_desc = ( + "moderate agreement, though local facies/depth-shift scatter is present" + ) else: parity_desc = ( "poor statistical correlation, indicating unresolved core depth-shifts, " @@ -2422,12 +5996,15 @@ def synthesize_domain_ai_commentary( # Empirical P10/P90 ratio from Monte Carlo uncertainty table valid_spreads = [ - float(u.get("spread_ratio", 1.0)) + float(u["spread_ratio"]) for u in unc_list - if float(u.get("p90_hcpt", 0.0)) > 0.005 + if u.get("spread_ratio") is not None + and str(u.get("metric", "")).startswith("Hydrocarbon Pore Thickness") ] median_spread_str = ( - f"{float(np.median(valid_spreads)):.2f}×" if valid_spreads else "N/A (Water-bearing)" + f"{float(np.median(valid_spreads)):.2f}×" + if valid_spreads + else "N/A (Water-bearing)" ) if is_single_well: @@ -2442,18 +6019,16 @@ def synthesize_domain_ai_commentary( f"(out of **{c_tot_cnt} total core plugs loaded**), exhibiting {parity_desc}." ) elif c_tot_cnt > 0: - core_clause = ( - f"evaluated from environmentally conditioned wireline logs ({c_tot_cnt} core plugs loaded in deeper/non-overlapping intervals)" - ) + core_clause = f"evaluated from environmentally conditioned wireline logs ({c_tot_cnt} core plugs loaded in deeper/non-overlapping intervals)" litho_core_sentence = ( f"Although **{c_tot_cnt} core plugs** are loaded in **`{focal_well}`**, **{c_cal_cnt} plugs** overlap the log-evaluated target reservoir window; " f"effective porosity ($\\phi_e$) was therefore derived from neutron-density crossplot total porosity ($\\phi_t$) after subtracting clay-bound water ($CBW$)." ) else: - core_clause = "evaluated from environmentally conditioned triple-combo wireline logs" - litho_core_sentence = ( - "Effective porosity ($\\phi_e$) was derived from neutron-density total porosity ($\\phi_t$) after subtracting clay-bound water ($CBW$)." + core_clause = ( + "evaluated from environmentally conditioned triple-combo wireline logs" ) + litho_core_sentence = "Effective porosity ($\\phi_e$) was derived from neutron-density total porosity ($\\phi_t$) after subtracting clay-bound water ($CBW$)." base_commentary = { "executive_summary": ( @@ -2465,8 +6040,8 @@ def synthesize_domain_ai_commentary( f"light-hydrocarbon corrected effective porosity ($\\phi_e$), and shaly-sand water saturation ($S_w$), " f"{core_clause}. Across the evaluated target reservoir succession in **`{focal_well}`**, net-thickness-weighted mean " f"effective porosity ($\\phi_e$) is **${mean_phie:.3f}\\text{{ v/v}}$** with a pore-volume weighted water " - f"saturation ($S_w$) of **${mean_sw:.3f}\\text{{ v/v}}$** and cumulative zonal Hydrocarbon Pore Thickness " - f"($HCPT$) of **${total_hcpt:.2f}\\text{{ m}}$**. " + f"saturation ($S_w$) of **${mean_sw:.3f}\\text{{ v/v}}$** and cumulative Hydrocarbon Pore Thickness " + f"($HCPT$) across the **{n_eval_zones}** evaluated zones of **${total_hcpt:.2f}\\text{{ m}}$**. " + ( f"The primary pay interval is **{top_zone.get('zone')}**, delivering " f"**${top_zone.get('net_pay', 0.0):.1f}\\text{{ m}}$** of Net Pay ($NTG_{{pay}} = {top_zone.get('ntg', 0.0):.2f}\\text{{ v/v}}$, " @@ -2485,7 +6060,7 @@ def synthesize_domain_ai_commentary( ), "inventory_narrative": ( f"Well **`{focal_well}`** penetrates **{context.get('total_logged_thickness', 0.0):.1f} m** of logged " - f"section across **{len(context.get('target_zones', []))} target reservoir zone(s)** (`{', '.join(context.get('target_zones', []))}`)." + f"section across **{len(context.get('target_zones', []))} target reservoir {_pluralize(len(context.get('target_zones', [])), 'zone')}** (`{', '.join(context.get('target_zones', []))}`)." ), "qaqc_narrative": ( f"Borehole environmental quality control was performed on well **`{focal_well}`** prior to quantitative CPI " @@ -2498,6 +6073,7 @@ def synthesize_domain_ai_commentary( if max_bh > 15.0 else f"Well **`{focal_well}`** exhibits good overall borehole stability (<15% washout flagging), providing reliable density-neutron porosity response across the target zones." ) + + env_narrative_suffix ), "litho_poro_narrative": ( f"In well **`{focal_well}`**, shale volume ($V_{{sh}}$) and mineral fractions were solved using the " @@ -2539,21 +6115,20 @@ def synthesize_domain_ai_commentary( f"are flagged in the QA/QC audit prior to static model handover." ) else: - fdp_core_sentence = ( - "No Routine Core Analysis (RCA) plugs were available in the target zones; porosity was derived from hydrocarbon-corrected neutron-density crossplot logs." - ) + fdp_core_sentence = "No Routine Core Analysis (RCA) plugs were available in the target zones; porosity was derived from hydrocarbon-corrected neutron-density crossplot logs." base_commentary = { "executive_summary": ( f"This Field Development Plan (FDP) Petrophysical Evaluation integrates wireline log conditioning, " f"{context['litho_params']['model_name']} lithology evaluation, Routine Core Analysis (RCA), " f"Hydraulic Flow Unit ($FZI$) rock typing, and Leverett-$J$ Saturation Height Modeling ($SHF$) across " - f"**{len(well_names)} evaluated well(s)** (`{', '.join(well_names)}`) in **{proj_name}**, focusing on the " + f"**{len(well_names)} evaluated {_pluralize(len(well_names), 'well')}** (`{', '.join(well_names)}`) in **{proj_name}**, focusing on the " f"target reservoir succession (`{', '.join(context.get('target_zones', []))}`). " f"Across the evaluated target zones, net-thickness-weighted mean effective porosity ($\\phi_e$) is " f"**${mean_phie:.3f}\\text{{ v/v}}$** with a pore-volume weighted water saturation ($S_w$) of " - f"**${mean_sw:.3f}\\text{{ v/v}}$** and cumulative zonal mean Hydrocarbon Pore Thickness ($HCPT$) of " - f"**${total_hcpt:.2f}\\text{{ m}}$**. " + f"**${mean_sw:.3f}\\text{{ v/v}}$**. A well penetrating all **{n_eval_zones}** evaluated zones accumulates a " + f"Hydrocarbon Pore Thickness ($HCPT$) of **${total_hcpt:.2f}\\text{{ m}}$** " + f"(sum of per-zone means; average ${mean_zone_hcpt:.2f}\\text{{ m}}$ per zone). " + ( f"The primary pay container is **{top_zone.get('zone')}**, delivering a field-mean Net Pay of " f"**${top_zone.get('net_pay', 0.0):.1f}\\text{{ m}}$** ($NTG_{{pay}} = {top_zone.get('ntg', 0.0):.2f}\\text{{ v/v}}$, " @@ -2565,16 +6140,16 @@ def synthesize_domain_ai_commentary( ) ), "inventory_narrative": ( - f"The petrophysical database for **{proj_name}** comprises **{len(wells)} wells** totaling " + f"The petrophysical database for **{proj_name}** comprises **{len(wells)} {_pluralize(len(wells), 'well')}** totaling " f"**{context.get('total_logged_thickness', 0.0):.1f} m** of logged borehole section across " f"**{len(context.get('all_zones', []))} mapped geological formations**, with volumetric and CPI reporting " - f"filtered to the **{len(context.get('target_zones', []))} target reservoir zone(s)** (`{', '.join(context.get('target_zones', []))}`). " + f"filtered to the **{len(context.get('target_zones', []))} target reservoir {_pluralize(len(context.get('target_zones', [])), 'zone')}** (`{', '.join(context.get('target_zones', []))}`). " f"A total of **{c_tot_cnt} Routine Core Analysis (RCA) plug measurements** are loaded in the project inventory (Table 2.1), " f"of which **{c_cal_cnt} valid plugs** overlap log-evaluated target reservoir intervals for active porosity calibration." ), "qaqc_narrative": ( f"Rigorous borehole environmental conditioning and multi-well normalization were executed prior to quantitative " - f"interpretation. Across the {len(qaqc_tbl)} evaluated well(s), maximum washout/bad-hole flagging is " + f"interpretation. Across the {len(qaqc_tbl)} evaluated {_pluralize(len(qaqc_tbl), 'well')}, maximum washout/bad-hole flagging is " f"**{max_bh:.1f}%** (using caliper washout $> {context['qaqc_params']['caliper_limit']}$ in (inches) and " f"$\\Delta\\rho > {context['qaqc_params']['drho_limit']}$ g/cc criteria). " + ( @@ -2583,6 +6158,7 @@ def synthesize_domain_ai_commentary( if max_bh > 15.0 else "All evaluated reservoir intervals exhibit good borehole stability (<15% washout flagging), requiring minimal synthetic curve reconstruction." ) + + env_narrative_suffix ), "litho_poro_narrative": ( f"Shale volume ($V_{{sh}}$) and mineral fractions were resolved using the **{context['litho_params']['model_name']}** " @@ -2591,13 +6167,10 @@ def synthesize_domain_ai_commentary( f"($GR_{{shale}} = {context['litho_params']['gr_shale']}\\text{{ gAPI}}$, $\\rho_{{clay}} = {context['litho_params']['rho_clay']}\\text{{ g/cc}}$). " + fdp_core_sentence ), - "rock_typing_narrative": ( - f"Hydraulic Flow Unit partitioning on **{rt_sum.get('basis', 'Target-Zone Dataset')}** classified the reservoir into " - f"four Discrete Rock Types (`RT1` through `RT4`) using Flow Zone Indicator cut-offs of $0.5, 1.5,\\text{{ and }}3.0\\text{{ }}\\mu\\text{{m}}$. " - f"Dominant flow capacity is controlled by **RT3 (Macro-Porous Upper Shoreface)** and **RT4 (Mega-Porous Channel Sand)**, " - f"which represent **{rt_sum.get('rt34_share_pct', 43.5):.1f}%** of reservoir samples while contributing " - f"**{rt_sum.get('rt34_kh_pct', 82.0):.1f}%** of cumulative permeability-thickness ($\\sum K\\cdot h$) " - f"on the Stratigraphic Modified Lorenz Plot ($SMLP$)." + "rock_typing_narrative": _build_rock_typing_narrative( + context.get("rock_types", []), + rt_sum, + context.get("fzi_cutoffs", []), ), "saturation_narrative": ( f"Water saturation ($S_w$) was evaluated using the **{sw_p.get('model_name')}** to account for clay-bound " @@ -2609,14 +6182,16 @@ def synthesize_domain_ai_commentary( f"$FWL = {sw_p.get('fwl', 2943.0):.1f}\\text{{ m TVDss}}$." ), "shf_scal_narrative": ( - f"3D static model water saturation initialization via the Leverett $J$-Function ($\\sigma\\cos\\theta = " - f"{shf_p.get('ift_cos_theta', 26.0)}\\text{{ dynes/cm}}$) reconciles with wireline log $S_w$ " - f"($\\text{{RMSE}} = {shf_p.get('reconciliation_rmse', 0.042):.3f}\\text{{ v/v}}$, mean bias " - f"${shf_p.get('reconciliation_bias', -0.008):+.3f}\\text{{ v/v}}$). Dynamic simulation relative permeability " - f"tables (`SWOF`, **{scal_p.get('source_label', 'Analogue / Default Corey SCAL Parameterization')}**) " - f"were parameterized using Corey exponents $N_w = {scal_p.get('nw', 2.5)}, " - f"N_o = {scal_p.get('no', 2.5)}$ with $S_{{wc}} = {scal_p.get('swirr', 0.15):.2f}\\text{{ v/v}}$ " - f"and $S_{{or}} = {scal_p.get('sor', 0.20):.2f}\\text{{ v/v}}$." + _build_shf_reconciliation_sentence(shf_p) + + f"Dynamic simulation relative permeability " + f"tables (`SWOF`, **{scal_p.get('source_label', 'Regional Analogue / Screening Parameterization')}**) " + + ( + f"were parameterized using LET exponents $L_w = {scal_p.get('lw', 2.0)}, E_w = {scal_p.get('ew', 1.5)}, T_w = {scal_p.get('tw', 2.0)}$ and " + f"$L_o = {scal_p.get('lo', 2.0)}, E_o = {scal_p.get('eo', 1.5)}, T_o = {scal_p.get('to', 2.0)}$ with " + if str(scal_p.get("model", "corey")).lower() == "let" + else f"were parameterized using Corey exponents $N_w = {scal_p.get('nw', 2.5)}, N_o = {scal_p.get('no', 2.5)}$ with " + ) + + f"$S_{{wc}} = {scal_p.get('swirr', 0.15):.2f}\\text{{ v/v}}$ and $S_{{or}} = {scal_p.get('sor', 0.20):.2f}\\text{{ v/v}}$." ), "uncertainty_narrative": ( f"Zonal summation decouples **Net Reservoir** ($V_{{sh}} \\le {cut['vsh']:.2f}\\text{{ v/v}}$, " @@ -2629,8 +6204,10 @@ def synthesize_domain_ai_commentary( "upscaling_narrative": ( f"Fine-scale evaluated CPI logs within the target reservoir succession were blocked to " f"${context['upscaling_params']['cell_size']:.1f}\\text{{ m}}$ cellular resolution honoring geological zone boundaries. " - f"Cardwell-Parsons directional permeability bounds yield a field-mean vertical-to-horizontal anisotropy ratio " - f"($K_v / K_h = K_{{harm}} / K_{{arith}}$) across the evaluated wells, preserving thin-bed vertical baffles for Eclipse/Intersect dynamic simulation." + f"Cardwell-Parsons directional permeability bounds yield a field-mean vertical-to-horizontal anisotropy ratio of " + f"**$K_v / K_h = {context.get('upscaling_summary', {}).get('mean_kv_kh', 0.0):.3f}$** " + f"(range `{context.get('upscaling_summary', {}).get('min_kv_kh', 0.0):.3f}–{context.get('upscaling_summary', {}).get('max_kv_kh', 0.0):.3f}`) " + f"across the evaluated {len(well_names)} {_pluralize(len(well_names), 'well')}, preserving thin-bed vertical baffles for Eclipse/Intersect dynamic simulation." ), } @@ -2652,6 +6229,9 @@ def synthesize_domain_ai_commentary( "cutoffs": cut, "zonal_summary": zonal, "qaqc_table": qaqc_tbl, + "env_corr_summary": { + k: v for k, v in env_s.items() if k not in ("hole_sections_table",) + }, "poro_params": poro_p, "sw_params": sw_p, "shf_params": shf_p, @@ -2680,18 +6260,22 @@ def synthesize_domain_ai_commentary( ) if prov in ("openrouter", "ollama", "openai"): - b_url = ( - base_url - or ( - os.getenv("OLLAMA_BASE_URL", "http://localhost:11434/v1") - if prov == "ollama" - else os.getenv("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1") - ) - ).rstrip("/") - key = api_key or ( - "ollama" if prov == "ollama" else os.getenv("OPENROUTER_API_KEY", "") + from quick_pp.app.backend.services.demo_guard import ( + validate_external_llm_target, + ) + + b_url, key = validate_external_llm_target( + provider=prov, + caller_base_url=base_url, + caller_api_key=api_key, + env_openrouter_url=os.getenv( + "OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1" + ), + env_openrouter_key=os.getenv("OPENROUTER_API_KEY", ""), + ) + mdl = model or ( + "qwen2.5:7b" if prov == "ollama" else "deepseek/deepseek-chat" ) - mdl = model or ("qwen2.5:7b" if prov == "ollama" else "deepseek/deepseek-chat") if key: resp = requests.post( f"{b_url}/chat/completions", @@ -2758,10 +6342,15 @@ def synthesize_domain_ai_commentary( "include_ai_commentary": True, }, { - "section_id": "10_appendix_cpi", + "section_id": "11_appendix_cpi", "title": "6. Composite CPI Log Plot", "include_ai_commentary": False, }, + { + "section_id": "10_gate_checks", + "title": "7. QA/QC Gate-Check & Peer-Review Audit Log", + "include_ai_commentary": False, + }, ] @@ -2821,12 +6410,29 @@ def _generate_all_report_plots( report_id: str, context: Dict[str, Any], enabled_section_ids: set[str], + report_type: str = "FDP_FULL", ) -> Dict[str, Any]: """Generate high-DPI PNG assets for enabled sections and return URL dictionary.""" out_dir = REPORTS_STATIC_ROOT / report_id out_dir.mkdir(parents=True, exist_ok=True) url_prefix = f"/static/reports/{report_id}" + with report_plots.report_type_scope(report_type): + return _generate_all_report_plots_scoped( + out_dir=out_dir, + url_prefix=url_prefix, + context=context, + enabled_section_ids=enabled_section_ids, + ) + + +def _generate_all_report_plots_scoped( + out_dir: Path, + url_prefix: str, + context: Dict[str, Any], + enabled_section_ids: set[str], +) -> Dict[str, Any]: + full_df: pd.DataFrame = context.get("_full_df", pd.DataFrame()) well_names: List[str] = context.get("well_names", []) wells_meta: List[Dict[str, Any]] = context.get("wells", []) @@ -2836,6 +6442,7 @@ def _generate_all_report_plots( assets: Dict[str, Any] = { "inventory_heatmap": None, "norm_plot": None, + "env_corr_plot": None, "litho_poro_crossplot": None, "core_calibration_plot": None, "perm_crossplot": None, @@ -2848,6 +6455,8 @@ def _generate_all_report_plots( target_zones: Optional[List[str]] = context.get("target_zones") scal_p = context.get("scal_params", {}) + poro_p = context.get("poro_params", {}) + env_s = context.get("env_corr_summary", {}) or {} is_analogue_scal = bool(scal_p.get("is_analogue", True)) if "02_data_inventory" in enabled_section_ids: @@ -2858,6 +6467,22 @@ def _generate_all_report_plots( assets["norm_plot"] = report_plots.generate_qaqc_norm_plot( full_df, well_names, output_dir=out_dir, url_prefix=url_prefix ) + has_env_cols = bool(env_s.get("any_applied")) or any( + c in full_df.columns + for c in ("ENV_TEMP_C", "HOLE_SEVERITY", "INVASION_PROFILE") + ) + if has_env_cols and not full_df.empty: + try: + assets["env_corr_plot"] = report_plots.generate_env_corr_qc_plot( + full_df, + well_names=well_names, + env_corr_summary=env_s, + target_zones=target_zones, + output_dir=out_dir, + url_prefix=url_prefix, + ) + except Exception as exc: + logger.debug(f"Failed generating borehole env QC plot: {exc}") litho_p = context.get("litho_params", {}) if "04_lithology_porosity" in enabled_section_ids: assets["litho_poro_crossplot"] = report_plots.generate_nd_crossplot( @@ -2871,6 +6496,7 @@ def _generate_all_report_plots( dry_clay_point=litho_p.get("dry_clay_point", (0.33, 2.70)), fluid_point=litho_p.get("fluid_point", (1.0, 1.0)), silt_line_angle=_safe_float(litho_p.get("silt_line_angle"), 119.0), + use_hc_corrected=bool(poro_p.get("use_hc_corrected", False)), output_dir=out_dir, url_prefix=url_prefix, ) @@ -2898,6 +6524,18 @@ def _generate_all_report_plots( output_dir=out_dir, url_prefix=url_prefix, ) + if context.get("fpt_summary", {}).get("has_data") and context.get( + "_fpt_points" + ): + try: + assets["fpt_pressure_plot"] = report_plots.generate_fpt_pressure_plot( + fpt_points=context.get("_fpt_points", []), + fpt_summary=context.get("fpt_summary", {}), + output_dir=out_dir, + url_prefix=url_prefix, + ) + except Exception as exc: + logger.debug(f"Failed generating FPT pressure plot: {exc}") if "07_shf_scal" in enabled_section_ids: assets["shf_scal_plot"] = report_plots.generate_shf_j_function_plot( full_df, @@ -2929,8 +6567,12 @@ def _generate_all_report_plots( output_dir=out_dir, url_prefix=url_prefix, ) - if "10_appendix_cpi" in enabled_section_ids: + if ( + "11_appendix_cpi" in enabled_section_ids + or "10_appendix_cpi" in enabled_section_ids + ): cpi_list = [] + cpi_skipped = [] cpi_candidate_wells = [] candidate_scores = [] if not full_df.empty and "WELL_NAME" in full_df.columns: @@ -2988,7 +6630,16 @@ def _generate_all_report_plots( # Strict requirement: well must have evaluated porosity and at least one other key curve (RT, SWT, or PERM) if phi_cnt < 10 or (swt_cnt < 5 and perm_cnt < 5 and rt_cnt < 5): - # Empty or uninterpreted in target window -> skip! + # Uninterpreted in target window: record it so the report can state why it is absent. + cpi_skipped.append( + { + "well_name": wn, + "reason": ( + f"insufficient evaluated data in target window " + f"(PHI={phi_cnt}, SWT={swt_cnt}, PERM={perm_cnt}, RT={rt_cnt} samples)" + ), + } + ) continue has_core = ( @@ -3012,7 +6663,7 @@ def _generate_all_report_plots( candidate_scores.sort(key=lambda x: x[0], reverse=True) cpi_candidate_wells = [wn for _, wn in candidate_scores] - for wn in cpi_candidate_wells[:4]: + for wn in cpi_candidate_wells: cpi_url = report_plots.generate_well_cpi_plot( full_df, wn, @@ -3023,7 +6674,12 @@ def _generate_all_report_plots( ) if cpi_url: cpi_list.append({"well_name": wn, "plot_url": cpi_url, "url": cpi_url}) + else: + cpi_skipped.append( + {"well_name": wn, "reason": "CPI plot rendering returned no output"} + ) assets["cpi_plots"] = cpi_list + assets["cpi_skipped"] = cpi_skipped return assets @@ -3309,7 +6965,20 @@ def _stash_inline(match: re.Match) -> str: def _persist_report_state(report_data: Dict[str, Any]) -> None: + import time + + from quick_pp.app.backend.services.demo_guard import ( + enforce_report_storage_limits, + get_current_demo_session_id, + mark_demo_state_dirty, + ) + from quick_pp.app.backend.utils.auth import is_demo_mode + report_id = report_data["report_id"] + report_data.setdefault("_created_ts", time.time()) + sid = get_current_demo_session_id() + if sid and not report_data.get("_demo_session_id"): + report_data["_demo_session_id"] = sid report_data["html_content"] = _render_markdown_body_to_html( report_data.get("markdown_content", "") ) @@ -3323,6 +6992,9 @@ def _persist_report_state(report_data: Dict[str, Any]) -> None: (out_dir / "report.md").write_text( report_data.get("markdown_content", ""), encoding="utf-8" ) + if is_demo_mode(): + mark_demo_state_dirty() + enforce_report_storage_limits() def get_latest_project_report(project_id: Union[int, str]) -> Optional[Dict[str, Any]]: @@ -3395,7 +7067,9 @@ def generate_petrophysical_report_service( focal_w = context["well_names"][0] if context["well_names"] else "Active Well" effective_title = f"Well {focal_w} — Petrophysical CPI & Evaluation Dossier" - assets = _generate_all_report_plots(report_id, context, enabled_ids) + assets = _generate_all_report_plots( + report_id, context, enabled_ids, report_type=req.report_type + ) ai_commentary = ( synthesize_domain_ai_commentary( context, @@ -3642,7 +7316,7 @@ def render_report_print_html(report_id: str, auto_print: bool = False) -> str: Download Direct PDF -
+
Prepared with quick_pp — Quantitative Petrophysics & Reservoir Evaluation Suite

{html.escape(state.get("title", default_doc_title))}

@@ -3734,6 +7408,94 @@ def _strip_latex_for_pdf_text(text: str) -> str: return out +def _localize_static_urls(html_str: str) -> str: + """Point `/static/...` asset URLs at local files so offline renderers can load them.""" + static_uri = (BACKEND_DIR / "static").as_uri() + return html_str.replace('src="/static/', f'src="{static_uri}/') + + +def _find_browser_executable() -> Optional[str]: + """Locate a Chromium-family browser (env override, PATH, then common install paths).""" + import shutil + + candidates: List[str] = [] + for env_key in ("BROWSER_PATH", "CHROME_PATH"): + if os.environ.get(env_key): + candidates.append(os.environ[env_key]) + for name in ( + "chromium", + "chromium-browser", + "google-chrome", + "google-chrome-stable", + "chrome", + "msedge", + ): + found = shutil.which(name) + if found: + candidates.append(found) + for base in ( + os.environ.get("PROGRAMFILES"), + os.environ.get("PROGRAMFILES(X86)"), + os.environ.get("LOCALAPPDATA"), + ): + if base: + candidates.append(str(Path(base) / "Google/Chrome/Application/chrome.exe")) + candidates.append(str(Path(base) / "Microsoft/Edge/Application/msedge.exe")) + candidates += [ + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "/usr/bin/chromium", + "/usr/bin/google-chrome", + ] + for cand in candidates: + if cand and Path(cand).is_file(): + return cand + return None + + +def _render_pdf_with_browser(html_str: str, out_dir: Path, pdf_path: Path) -> bool: + """Print the report HTML to PDF with headless Chromium/Edge. Returns True on success.""" + import shutil + import subprocess + import tempfile + + browser = _find_browser_executable() + if not browser: + return False + + src_html = out_dir / "_pdf_source.html" + profile_dir = Path(tempfile.mkdtemp(prefix="qpp_pdf_")) + tmp_pdf = out_dir / "_pdf_tmp.pdf" + try: + src_html.write_text(_localize_static_urls(html_str), encoding="utf-8") + tmp_pdf.unlink(missing_ok=True) + cmd = [ + browser, + "--headless=new", + "--disable-gpu", + "--no-sandbox", + "--allow-file-access-from-files", + "--hide-scrollbars", + "--no-pdf-header-footer", + "--print-to-pdf-no-header", + f"--user-data-dir={profile_dir}", + "--virtual-time-budget=15000", + f"--print-to-pdf={tmp_pdf}", + src_html.as_uri(), + ] + subprocess.run(cmd, capture_output=True, timeout=180, check=False) + if tmp_pdf.exists() and tmp_pdf.stat().st_size > 1024: + tmp_pdf.replace(pdf_path) + return True + logger.warning(f"Headless browser produced no PDF using {browser}") + except Exception as exc: + logger.warning(f"Headless browser PDF export failed ({browser}): {exc}") + finally: + shutil.rmtree(profile_dir, ignore_errors=True) + src_html.unlink(missing_ok=True) + tmp_pdf.unlink(missing_ok=True) + return False + + def compile_report_to_pdf(report_id: str) -> Path: """Compile the report Markdown and high-DPI plot assets into a downloadable multi-page PDF file.""" state = _load_report_state(report_id) @@ -3745,17 +7507,28 @@ def compile_report_to_pdf(report_id: str) -> Path: html_str = render_report_print_html(report_id, auto_print=False) (out_dir / "report_print.html").write_text(html_str, encoding="utf-8") - # Option 1: Try WeasyPrint if installed + # Option 1: headless Chromium/Edge renders the same HTML as the print view, + # so tables, equations and figures paginate like the browser print preview. + if _render_pdf_with_browser(html_str, out_dir, pdf_path): + return pdf_path + + # Option 2: WeasyPrint if installed try: import weasyprint # type: ignore - weasyprint.HTML(string=html_str, base_url=str(BACKEND_DIR)).write_pdf( - str(pdf_path) - ) + weasyprint.HTML( + string=_localize_static_urls(html_str), base_url=str(BACKEND_DIR) + ).write_pdf(str(pdf_path)) if pdf_path.exists() and pdf_path.stat().st_size > 0: return pdf_path - except Exception: - pass + except Exception as exc: + logger.debug(f"WeasyPrint PDF export unavailable: {exc}") + + logger.warning( + "PDF export fell back to the basic matplotlib renderer (no Chromium/Edge or " + "WeasyPrint found). Tables and equations are simplified. Install Chromium or " + "set BROWSER_PATH for full-fidelity PDFs." + ) # Option 2: Built-in Multi-Page Publication PDF Compiler via matplotlib PdfPages md_content = state.get("markdown_content", "") @@ -3918,7 +7691,9 @@ def compile_report_to_pdf(report_id: str) -> Path: 0.01, y_cursor, row_str[:135], - fontsize=6.6 if n_cols > 8 else (7.3 if is_hdr else 7.0), + fontsize=6.6 + if n_cols > 8 + else (7.3 if is_hdr else 7.0), fontweight="bold" if is_hdr else "normal", color="#0f172a" if is_hdr else "#334155", family="monospace", @@ -4014,24 +7789,66 @@ def api_get_project_report_context( _REPORT_JOBS: Dict[str, Dict[str, Any]] = {} +# Job state is also written to disk. The backend runs several gunicorn workers on Linux, and a status poll +# can reach a different worker than the one that started the job, so an in-memory dict alone returns 404. +_REPORT_JOBS_DIR = REPORTS_STATIC_ROOT / "_jobs" + + +def _job_path(job_id: str) -> Path: + safe = "".join(c for c in str(job_id) if c.isalnum() or c in ("_", "-")) + return _REPORT_JOBS_DIR / f"{safe}.json" + + +def _save_job(job_id: str, state: Dict[str, Any]) -> None: + from quick_pp.app.backend.services.demo_guard import get_current_demo_session_id + + sid = get_current_demo_session_id() + if sid and not state.get("demo_session_id"): + state["demo_session_id"] = sid + _REPORT_JOBS[job_id] = state + try: + _REPORT_JOBS_DIR.mkdir(parents=True, exist_ok=True) + path = _job_path(job_id) + tmp = path.with_suffix(f".{uuid4().hex[:6]}.tmp") + tmp.write_text(json.dumps(state, default=str), encoding="utf-8") + tmp.replace(path) + except Exception as exc: + logger.warning(f"Could not persist report job {job_id} to disk: {exc}") + + +def _load_job(job_id: str) -> Optional[Dict[str, Any]]: + path = _job_path(job_id) + if path.exists(): + try: + return json.loads(path.read_text(encoding="utf-8")) + except Exception as exc: + logger.warning(f"Could not read report job {job_id} from disk: {exc}") + return _REPORT_JOBS.get(job_id) + def _run_report_job(job_id: str, req: ReportGenerationRequest) -> None: try: res = generate_petrophysical_report_service(req) - _REPORT_JOBS[job_id] = { - "job_id": job_id, - "status": "completed", - "report": res.model_dump(), - "error": None, - } + _save_job( + job_id, + { + "job_id": job_id, + "status": "completed", + "report": res.model_dump(), + "error": None, + }, + ) except Exception as e: logger.exception(f"Background report job {job_id} failed: {e}") - _REPORT_JOBS[job_id] = { - "job_id": job_id, - "status": "failed", - "report": None, - "error": str(e), - } + _save_job( + job_id, + { + "job_id": job_id, + "status": "failed", + "report": None, + "error": str(e), + }, + ) @router.post( @@ -4050,15 +7867,16 @@ def api_generate_project_report( req.project_id = project_id if async_job: job_id = f"job_{uuid4().hex[:10]}" - _REPORT_JOBS[job_id] = { - "job_id": job_id, - "status": "running", - "report": None, - "error": None, - } - t = threading.Thread( - target=_run_report_job, args=(job_id, req), daemon=True + _save_job( + job_id, + { + "job_id": job_id, + "status": "running", + "report": None, + "error": None, + }, ) + t = threading.Thread(target=_run_report_job, args=(job_id, req), daemon=True) t.start() return {"job_id": job_id, "status": "running"} @@ -4079,7 +7897,7 @@ def api_generate_project_report( ) def api_get_report_job_status(project_id: int, job_id: str): """Return status and completed payload for an asynchronous report generation job.""" - job = _REPORT_JOBS.get(job_id) + job = _load_job(job_id) if not job: raise HTTPException(status_code=404, detail=f"Report job '{job_id}' not found.") return job diff --git a/quick_pp/app/backend/services/saturation.py b/quick_pp/app/backend/services/saturation.py index 201b8fd8..f5e14c08 100644 --- a/quick_pp/app/backend/services/saturation.py +++ b/quick_pp/app/backend/services/saturation.py @@ -10,6 +10,7 @@ from quick_pp.app.backend.schemas.saturation_qv import InputData as QvInput from quick_pp.app.backend.schemas.saturation_qvn import InputData as QvnInput from quick_pp.app.backend.schemas.saturation_rw import InputData as RwInput +from quick_pp.app.backend.schemas.saturation_rw_depth import InputData as RwDepthInput from quick_pp.app.backend.schemas.saturation_temp_grad import InputData as TempGradInput from quick_pp.app.backend.schemas.saturation_waxman_smits import ( InputData as WaxmanSmitsInput, @@ -210,6 +211,38 @@ async def estimate_rw(inputs: RwInput) -> List[Dict[str, float]]: ) from e +@router.post( + "/rw_at_depth", + summary="Estimate Rw and formation temperature at depth", + description=( + "Single source of truth for Rw(T, salinity) along a linear geothermal gradient " + "(Bateman-Konen). Temperature is clamped to 5-250 degC and salinity floored at 100 ppm. " + "Returns TEMP_C and RW per input depth." + ), + operation_id="estimate_rw_at_depth", +) +async def estimate_rw_at_depth_(inputs: RwDepthInput) -> List[Dict[str, float]]: + """Return formation temperature (degC) and Rw (ohm.m) for each TVD sample.""" + from quick_pp.saturation import estimate_rw_at_depth, formation_temperature_c + + p = inputs.model_dump() + try: + tvd = np.asarray([row["tvd"] for row in p["data"]], dtype=float) + args = (p["surface_temp"], p["gradient"], p["meas_system"]) + temp = np.atleast_1d(formation_temperature_c(tvd, *args)) + rw = np.atleast_1d( + estimate_rw_at_depth(tvd, p["water_salinity"], *args) + ) + return [ + {"TEMP_C": _safe_float(t), "RW": _safe_float(r)} + for t, r in zip(temp, rw, strict=False) + ] + except Exception as e: + raise HTTPException( + status_code=400, detail=f"Error processing request: {e}" + ) from e + + @router.post( "/b_waxman_smits", summary="Estimate B Parameter using Waxman-Smits Model", diff --git a/quick_pp/app/backend/services/ssot_reference.py b/quick_pp/app/backend/services/ssot_reference.py index e6e366c3..19d883e3 100644 --- a/quick_pp/app/backend/services/ssot_reference.py +++ b/quick_pp/app/backend/services/ssot_reference.py @@ -21,27 +21,41 @@ "single-well": { "overview": "sw-level-1-2-diagrams", "diagrams": "sw-level-1-2-diagrams", - "qaqc": "sw-step-1-qaqc", - "conditioning": "sw-step-1-qaqc", - "deconv": "sw-step-1-qaqc", - "resolution": "sw-step-1-qaqc", - "enhancement": "sw-step-1-qaqc", - "enhancer": "sw-step-1-qaqc", - "1": "sw-step-1-qaqc", - "ancillary": "sw-step-2-ancillary", - "trajectory": "sw-step-2-ancillary", - "tops": "sw-step-2-ancillary", - "2": "sw-step-2-ancillary", + "ancillary": "sw-step-1-ancillary", + "header": "sw-step-1-ancillary", + "hole-sections": "sw-step-1-ancillary", + "hole_sections": "sw-step-1-ancillary", + "trajectory": "sw-step-1-ancillary", + "survey": "sw-step-1-ancillary", + "tops": "sw-step-1-ancillary", + "1": "sw-step-1-ancillary", + "qaqc": "sw-step-2-qaqc", + "conditioning": "sw-step-2-qaqc", + "env-corr": "sw-step-2-qaqc", + "env_corr": "sw-step-2-qaqc", + "invasion": "sw-step-2-qaqc", + "imputation": "sw-step-2-qaqc", + "splice": "sw-step-2-qaqc", + "deconv": "sw-step-2-qaqc", + "resolution": "sw-step-2-qaqc", + "enhancement": "sw-step-2-qaqc", + "enhancer": "sw-step-2-qaqc", + "2": "sw-step-2-qaqc", "litho-poro": "sw-step-3-litho-poro", "litho_poro": "sw-step-3-litho-poro", "lithology": "sw-step-3-litho-poro", "porosity": "sw-step-3-litho-poro", "vsh": "sw-step-3-litho-poro", "vshale": "sw-step-3-litho-poro", + "thomas-stieber": "sw-step-3-litho-poro", "3": "sw-step-3-litho-poro", "perm": "sw-step-4-perm", "permeability": "sw-step-4-perm", + "choo": "sw-step-4-perm", + "kozeny-carman": "sw-step-4-perm", + "kozeny_carman": "sw-step-4-perm", "timur": "sw-step-4-perm", + "tixier": "sw-step-4-perm", "coates": "sw-step-4-perm", "4": "sw-step-4-perm", "saturation": "sw-step-5-saturation", @@ -49,15 +63,21 @@ "archie": "sw-step-5-saturation", "waxman-smits": "sw-step-5-saturation", "dual-water": "sw-step-5-saturation", + "simandoux": "sw-step-5-saturation", + "indonesian": "sw-step-5-saturation", + "fluid-typing": "sw-step-5-saturation", + "fluid_typing": "sw-step-5-saturation", "5": "sw-step-5-saturation", "ressum": "sw-step-6-ressum", "summary": "sw-step-6-ressum", + "cutoffs": "sw-step-6-ressum", "blocking": "sw-step-6-ressum", "upscaling": "sw-step-6-ressum", "netpay": "sw-step-6-ressum", "6": "sw-step-6-ressum", "report": "sw-step-7-report", "cpi": "sw-step-7-report", + "gate-checks": "sw-step-7-report", "7": "sw-step-7-report", # Standalone Lab Module "scal": "sw-standalone-core-pc", diff --git a/quick_pp/app/backend/services/workspace.py b/quick_pp/app/backend/services/workspace.py index 5bf45112..024ecee5 100644 --- a/quick_pp/app/backend/services/workspace.py +++ b/quick_pp/app/backend/services/workspace.py @@ -24,6 +24,7 @@ from sqlalchemy.orm.attributes import flag_modified from quick_pp.app.backend.schemas.fluid_density import FluidDensityConfig +from quick_pp.app.backend.services.ancillary import _canonical_well_token from quick_pp.app.backend.services.database import ( _ephemeral_well_headers, _ephemeral_wells, @@ -150,7 +151,7 @@ sample_lhs_parameters, ) from quick_pp.upscaling import expand_blocked_logs, upscale_logs -from quick_pp.utils import nd_triangle_coords +from quick_pp.utils import nd_triangle_coords, survey_tvd_stations DRY_SILT_RHOB = float(Config.SSC_ENDPOINTS["DRY_SILT_POINT"][1]) @@ -729,6 +730,54 @@ def _contact_depth(name: str) -> Optional[float]: return zone +def _load_well_hole_sections( + project_id: int, well_name: str +) -> List[Dict[str, Any]]: + """Load hole sections (mud program intervals) for a well from ephemeral config or DB.""" + if _isolated_evaluation.get() is not None: + return [] + eph = _ephemeral_well_configs.get( + (project_id, well_name) + ) or _ephemeral_well_configs.get( + (project_id, resolve_db_well_name(project_id, well_name)) + ) + if isinstance(eph, dict) and isinstance(eph.get("hole_sections"), list): + return list(eph["hole_sections"]) + try: + with get_db() as session: + proj = db_objects.Project.load(session, project_id=project_id) + well_obj = proj.get_well(resolve_db_well_name(project_id, well_name)) + hs_df = well_obj.get_hole_sections() + if isinstance(hs_df, pd.DataFrame) and not hs_df.empty: + return hs_df.to_dict(orient="records") + except Exception: + pass + return [] + + +def _synthesize_bitsize_series( + depths: pd.Series, hole_sections: List[Dict[str, Any]] +) -> pd.Series: + """Synthesize a depth-aligned nominal Bit Size (BS) series from hole sections.""" + d_arr = pd.to_numeric(depths, errors="coerce").to_numpy(dtype=float) + bs_arr = np.full(len(d_arr), np.nan, dtype=float) + for sec in hole_sections or []: + try: + top_v = float(sec.get("top")) + bot_v = float(sec.get("bottom")) + bs_v = sec.get("bit_size") + if bs_v is None or not np.isfinite(float(bs_v)) or float(bs_v) <= 0: + continue + bs_f = float(bs_v) + except (TypeError, ValueError): + continue + if bot_v < top_v: + top_v, bot_v = bot_v, top_v + mask = np.isfinite(d_arr) & (d_arr >= top_v) & (d_arr <= bot_v) + bs_arr[mask] = bs_f + return pd.Series(bs_arr, index=depths.index, dtype=float) + + def _compute_continuous_rho_fluid( df: pd.DataFrame, depth: pd.Series, @@ -738,6 +787,7 @@ def _compute_continuous_rho_fluid( well_header: Optional[Dict[str, Any]] = None, contacts: Optional[List[Dict[str, Any]]] = None, badhole_mask: Optional[pd.Series] = None, + hole_sections: Optional[List[Dict[str, Any]]] = None, ) -> Dict[str, np.ndarray]: """Run the continuous RHO_FL engine for the valid samples of a well. @@ -912,6 +962,124 @@ def _curve(name: Optional[str]) -> Optional[np.ndarray]: else np.zeros(n, dtype=bool) ) + # Apply per-interval mud properties from Hole Sections when enabled and available + if getattr(cfg, "use_hole_sections", True) and hole_sections: + d_arr = pd.to_numeric(depth, errors="coerce").to_numpy(dtype=float) + sec_mud_types = np.full(n, mud_type, dtype=object) + default_sal = float(salinity_ppm) if salinity_ppm is not None else np.nan + sec_sal = np.full(n, default_sal, dtype=float) + sec_rmf = np.full( + n, + float(rmf_surface) if (rmf_surface is not None and rmf_surface > 0) else np.nan, + dtype=float, + ) + sec_rmf_t = np.full(n, float(rmf_temp_c), dtype=float) + any_matched = False + for sec in hole_sections: + try: + t_v = float(sec.get("top")) + b_v = float(sec.get("bottom")) + except (TypeError, ValueError): + continue + if b_v < t_v: + t_v, b_v = b_v, t_v + sel = np.isfinite(d_arr) & (d_arr >= t_v) & (d_arr <= b_v) + if not sel.any(): + continue + any_matched = True + s_mt = str(sec.get("mud_type") or mud_type).strip().upper() + if s_mt in ("WBM", "OBM", "SBM"): + sec_mud_types[sel] = s_mt + s_sal = sec.get("mud_salinity") + if s_sal is not None and np.isfinite(float(s_sal)): + sec_sal[sel] = float(s_sal) + s_rmf = sec.get("rmf") + if s_rmf is not None and np.isfinite(float(s_rmf)) and float(s_rmf) > 0: + sec_rmf[sel] = float(s_rmf) + s_rmft = sec.get("rmf_temp") + if s_rmft is not None and np.isfinite(float(s_rmft)): + sec_rmf_t[sel] = float(s_rmft) + + if any_matched: + from quick_pp.environment import arps_resistivity + from quick_pp.fluid_type import brine_density + from quick_pp.porosity import salinity_from_rmf + + is_obm_mask = np.isin(sec_mud_types, ["OBM", "SBM"]) + # Back-fill WBM salinity from section Rmf where salinity wasn't explicitly set + need_sal = (~is_obm_mask) & (~np.isfinite(sec_sal)) & np.isfinite(sec_rmf) + if need_sal.any(): + for idx_s in np.flatnonzero(need_sal): + sec_sal[idx_s] = salinity_from_rmf( + float(sec_rmf[idx_s]), float(sec_rmf_t[idx_s]) + ) + + rmf_dh_sec = np.full(n, np.nan, dtype=float) + has_s_rmf = (~is_obm_mask) & np.isfinite(sec_rmf) & (sec_rmf > 0) + if has_s_rmf.any(): + rmf_dh_sec[has_s_rmf] = arps_resistivity( + sec_rmf[has_s_rmf], sec_rmf_t[has_s_rmf], temp_arr[has_s_rmf] + ) + need_rmf_dh = (~is_obm_mask) & (~np.isfinite(rmf_dh_sec)) & np.isfinite(sec_sal) + if need_rmf_dh.any(): + rho_mf_p = brine_density( + temp_arr[need_rmf_dh], pres_arr[need_rmf_dh], sec_sal[need_rmf_dh] + ) + rmf_dh_sec[need_rmf_dh] = np.where( + rho_mf_p > 0, 0.9 / np.maximum(rho_mf_p, 0.5), np.nan + ) + + def _run_slice(mask: np.ndarray, m_type: str) -> Dict[str, np.ndarray]: + sal_in = ( + None + if m_type != "WBM" + else np.where(np.isfinite(sec_sal[mask]), sec_sal[mask], 5000.0) + ) + rmf_dh_in = None if m_type != "WBM" else rmf_dh_sec[mask] + return estimate_continuous_rho_fluid( + rhob=rhob_v[mask], + rhoma=rho_ma[mask] if np.ndim(rho_ma) > 0 else rho_ma, + tvd=tvd_v[mask], + temp_c=temp_arr[mask], + pressure_mpa=pres_arr[mask], + mud_type=m_type, + salinity_ppm=sal_in, + rmf=None, + rmf_temp_c=rmf_temp_c, + obm_base_density=obm_base, + rho_w=None, + rho_h_app=rho_h_app[mask], + rxo=rxo[mask] if rxo is not None else None, + rt=rt[mask] if rt is not None else None, + rmf_downhole=rmf_dh_in, + rw_downhole=rw_downhole[mask], + badhole_flag=badhole_arr[mask], + fluid_zone=fluid_zone[mask], + a=cfg.a, + m=cfg.m, + n=cfg.n, + flush_exponent=cfg.flush_exponent, + default_shr_gas=cfg.default_shr_gas, + default_shr_oil=cfg.default_shr_oil, + max_iter=cfg.max_iter, + tol=cfg.tol, + ) + + if is_obm_mask.all(): + return _run_slice(np.ones(n, dtype=bool), "OBM") + if (~is_obm_mask).all(): + return _run_slice(np.ones(n, dtype=bool), "WBM") + wbm_mask = ~is_obm_mask + res_w = _run_slice(wbm_mask, "WBM") + res_o = _run_slice(is_obm_mask, "OBM") + combined_res: Dict[str, np.ndarray] = {} + for k in res_w.keys(): + arr = np.empty(n, dtype=res_w[k].dtype) + arr[wbm_mask] = res_w[k] + arr[is_obm_mask] = res_o[k] + combined_res[k] = arr + return combined_res + result = estimate_continuous_rho_fluid( rhob=rhob_v, rhoma=rho_ma, @@ -1048,7 +1216,9 @@ def _apply_grain_density_correlation( ) -def _resolve_baseline_badhole_mask(df: pd.DataFrame, auto_detect_if_missing: bool = False) -> pd.Series: +def _resolve_baseline_badhole_mask( + df: pd.DataFrame, auto_detect_if_missing: bool = False +) -> pd.Series: """Resolve pristine baseline boolean mask for badhole intervals prior to interactive manual overrides.""" for col in ("BADHOLE_BASE", "BADHOLE_QAQC", "BADHOLE_RAW"): if col in df.columns: @@ -1070,9 +1240,12 @@ def _resolve_baseline_badhole_mask(df: pd.DataFrame, auto_detect_if_missing: boo drho_threshold=0.15, ) if "BADHOLE" in bh_df.columns: - return (pd.to_numeric(bh_df["BADHOLE"], errors="coerce").reindex(df.index).fillna(0.0) >= 0.5).astype( - bool - ) + return ( + pd.to_numeric(bh_df["BADHOLE"], errors="coerce") + .reindex(df.index) + .fillna(0.0) + >= 0.5 + ).astype(bool) except Exception: pass @@ -1103,9 +1276,13 @@ def _resolve_baseline_badhole_mask(df: pd.DataFrame, auto_detect_if_missing: boo return pd.Series(False, index=df.index, dtype=bool) -def _resolve_badhole_mask(df: pd.DataFrame, auto_detect_if_missing: bool = False) -> pd.Series: +def _resolve_badhole_mask( + df: pd.DataFrame, auto_detect_if_missing: bool = False +) -> pd.Series: """Resolve boolean mask for badhole intervals from BADHOLE or on-the-fly detection.""" - return _resolve_baseline_badhole_mask(df, auto_detect_if_missing=auto_detect_if_missing) + return _resolve_baseline_badhole_mask( + df, auto_detect_if_missing=auto_detect_if_missing + ) def _resolve_baseline_coal_mask( @@ -1293,7 +1470,95 @@ class WorkspaceFilterBase(BaseModel): ) +class QcWeightedInputsMixin(BaseModel): + """Confidence-weighted input curves (only active once QC columns exist).""" + + confidence_weighting: bool = Field( + True, + description="Blend GR/NPHI/RHOB/RT/DTC toward a local high-confidence trend by _QC_CONF", + ) + use_env_corrected: bool = Field( + True, + description="Use _ENV_CORR as the input curve when it exists", + ) + qc_good_conf: float = Field(0.8, ge=0.0, le=1.0) + qc_min_conf: float = Field(0.2, ge=0.0, le=1.0) + + +_QC_WEIGHTED_LOGS = { + "GR": "GR", + "NPHI": "NPHI", + "RHOB": "RHOB", + "RT": "RT", + "DTC": "DT", +} + + +def _apply_qc_weighted_inputs(df: pd.DataFrame, req: Any) -> pd.DataFrame: + """Replace raw input curves with environment-corrected, confidence-weighted curves. + + For each log with a ``_QC_CONF`` column the input becomes + ``confidence_weighted_curve(base, conf)`` where ``base`` is ``_ENV_CORR`` + (if ``use_env_corrected``) or the raw curve. RT is blended in log10 space. + Only the in-memory copy used for the computation is changed. + No-op when no QC columns are present or the request disables it. + """ + if not getattr(req, "confidence_weighting", False) and not getattr( + req, "use_env_corrected", False + ): + return df + from quick_pp.borehole_corrections import confidence_weighted_curve + + out = df + applied: List[str] = [] + depth = df["DEPTH"].to_numpy(dtype=float) if "DEPTH" in df.columns else None + for log, qc in _QC_WEIGHTED_LOGS.items(): + if log not in df.columns: + continue + conf_col, corr_col = f"{qc}_QC_CONF", f"{qc}_ENV_CORR" + has_conf = ( + conf_col in df.columns + and pd.to_numeric(df[conf_col], errors="coerce").notna().any() + ) + has_corr = ( + corr_col in df.columns + and pd.to_numeric(df[corr_col], errors="coerce").notna().any() + ) + if not has_conf and not (has_corr and req.use_env_corrected): + continue + raw = pd.to_numeric(df[log], errors="coerce") + base = raw + if req.use_env_corrected and has_corr: + base = pd.to_numeric(df[corr_col], errors="coerce").fillna(raw) + if req.confidence_weighting and has_conf: + conf = pd.to_numeric(df[conf_col], errors="coerce").fillna(1.0) + if log == "RT": + lb = np.log10(base.clip(lower=1e-3)) + blended = confidence_weighted_curve( + lb, conf, depth, req.qc_good_conf, req.qc_min_conf + ) + new = pd.Series(10.0 ** blended.to_numpy(), index=df.index) + else: + new = confidence_weighted_curve( + base, conf, depth, req.qc_good_conf, req.qc_min_conf + ) + new.index = df.index + else: + new = base + if out is df: + out = df.copy() + out[log] = new.where(raw.notna() | new.notna()) + applied.append(log) + if applied: + out.attrs["qc_weighted_inputs"] = applied + return out + + class WorkspaceBadholeRequest(WorkspaceFilterBase): + use_hole_sections: bool = Field( + True, + description="Use nominal bit sizes per depth interval from Hole Sections table when available (False = manual/auto override)", + ) use_cali: bool = Field( True, description="Flag badhole using Differential Caliper |CALI - BS|" ) @@ -1353,7 +1618,9 @@ class GammaParameters(BaseModel): ) -class WorkspaceHCCorrectionRequest(WorkspaceFilterBase, GammaParameters): +class WorkspaceHCCorrectionRequest( + WorkspaceFilterBase, GammaParameters, QcWeightedInputsMixin +): dry_sand_point: Tuple[float, float] = Field((-0.02, 2.65)) dry_silt_point: Optional[Tuple[float, float]] = Field(None) dry_clay_point: Tuple[float, float] = Field((0.33, 2.7)) @@ -1515,7 +1782,9 @@ class WorkspaceDenCorrectionRequest(WorkspaceFilterBase, GammaParameters): ) -class WorkspaceLithologyRequest(WorkspaceFilterBase, GammaParameters): +class WorkspaceLithologyRequest( + WorkspaceFilterBase, GammaParameters, QcWeightedInputsMixin +): model: str = Field( "ssc", description="Lithology model: 'ssc', 'sand_shale', 'multi_mineral', or 'vsh_gr'", @@ -1669,7 +1938,9 @@ class GrainDensityCorrelation(BaseModel): ) -class WorkspacePorosityRequest(WorkspaceFilterBase, GammaParameters): +class WorkspacePorosityRequest( + WorkspaceFilterBase, GammaParameters, QcWeightedInputsMixin +): method: Literal[ "den", "neu_den", @@ -1954,7 +2225,7 @@ class WorkspacePermeabilityRequest(WorkspaceFilterBase): ) -class WorkspaceSaturationRequest(WorkspaceFilterBase): +class WorkspaceSaturationRequest(WorkspaceFilterBase, QcWeightedInputsMixin): lithology_model: Optional[str] = Field(None, description="Active lithology model") use_enhanced_logs: bool = Field( False, @@ -2171,6 +2442,24 @@ class WorkspaceMultiWellVolumetricsRequest(WorkspaceFilterBase): ) +class WorkspaceCutoffsSensitivityRequest(WorkspaceFilterBase): + percentile: float = Field( + 95.0, + ge=50.0, + le=99.9, + description="Target recovery percentile of maximum hydrocarbon pore volume (HCPV) (PRMS recommended: 95%)", + ) + + +class WorkspaceMultiWellCutoffsSensitivityRequest(WorkspaceCutoffsSensitivityRequest): + well_names: Optional[List[str]] = Field( + None, description="Optional subset of well names to include" + ) + + +WorkspaceWellCutoffsSensitivityRequest = WorkspaceCutoffsSensitivityRequest + + class WorkspaceRockTypingRequest(BaseModel): well_names: Optional[List[str]] = Field( None, description="Optional subset of well names to include" @@ -2817,6 +3106,53 @@ def _df_or_list(val: Any) -> List[Dict[str, Any]]: if p.get("top") is not None ] + hs_raw = ( + list(eph_cfg["hole_sections"]) + if (isinstance(eph_cfg, dict) and isinstance(eph_cfg.get("hole_sections"), list)) + else _df_or_list(ancillary.get("hole_sections")) + ) + hole_sections = [ + { + "id": f"hs-{i}-{s.get('name', i)}", + "name": str(s.get("name") or f"Section-{i + 1}"), + "top": float(s.get("top", 0.0)), + "bottom": float(s.get("bottom", s.get("top", 0.0))), + "bit_size": float(s["bit_size"]) + if s.get("bit_size") is not None and pd.notna(s.get("bit_size")) + else None, + "mud_type": str(s.get("mud_type") or "WBM").upper(), + "mud_weight": float(s["mud_weight"]) + if s.get("mud_weight") is not None and pd.notna(s.get("mud_weight")) + else None, + "mud_salinity": float(s["mud_salinity"]) + if s.get("mud_salinity") is not None and pd.notna(s.get("mud_salinity")) + else None, + "rmf": float(s["rmf"]) + if s.get("rmf") is not None and pd.notna(s.get("rmf")) + else None, + "rmf_temp": float(s["rmf_temp"]) + if s.get("rmf_temp") is not None and pd.notna(s.get("rmf_temp")) + else None, + } + for i, s in enumerate(hs_raw) + if s.get("top") is not None + ] + if ( + hole_sections + and depth_s is not None + and ( + "BS" not in curves_map + or not any(v is not None for v in curves_map.get("BS", [])) + ) + ): + bs_synth = _synthesize_bitsize_series(depth_s, hole_sections) + if bs_synth.notna().any(): + curves_map["BS"] = [ + round(float(x), 4) if pd.notna(x) else None + for x in bs_synth.tolist() + ] + stats["BS"] = _curve_summary_stats(bs_synth, depth_s) + core_samples_list: List[Dict[str, Any]] = [] scal_pc_list: List[Dict[str, Any]] = [] pc_scale_saved = ( @@ -3056,6 +3392,7 @@ def _df_or_list(val: Any) -> List[Dict[str, Any]]: "tops": tops, "contacts": contacts, "perforations": perforations, + "hole_sections": hole_sections, "core_samples": core_samples_list, "scal_pc": scal_pc_list, "pressure_tests": _df_or_list(ancillary.get("pressure_tests")), @@ -3096,6 +3433,7 @@ def workspace_hc_correction( df = _get_filtered_well_df( project_id, well_name, req.min_depth, req.max_depth, req.zones ) + df = _apply_qc_weighted_inputs(df, req) nphi, rhob = _select_nphi_rhob(df, use_hc_corrected=False) valid_mask = nphi.notna() & rhob.notna() if not valid_mask.any(): @@ -3382,14 +3720,28 @@ def workspace_hc_correction( mask = (depth_series >= t_val) & (depth_series <= b_val) if not mask.any(): continue - bh_mode_ov = str(ov.get("badholeMode") or ov.get("badhole_mode") or "").lower().strip() - target = str(ov.get("target") or ov.get("flag_type") or "").upper().strip() + bh_mode_ov = ( + str(ov.get("badholeMode") or ov.get("badhole_mode") or "") + .lower() + .strip() + ) + target = ( + str(ov.get("target") or ov.get("flag_type") or "") + .upper() + .strip() + ) action = str(ov.get("action") or "").lower().strip() if target in ("BADHOLE", "BOTH"): bh_mode_ov = action or "flag" if bh_mode_ov in ("flag", "force_badhole", "badhole", "1", "true"): badhole_mask.loc[mask] = True - elif bh_mode_ov in ("clear", "clear_badhole", "good_hole", "0", "false"): + elif bh_mode_ov in ( + "clear", + "clear_badhole", + "good_hole", + "0", + "false", + ): badhole_mask.loc[mask] = False if badhole_mask.any(): nphi_hc_full.loc[badhole_mask] = nphi.loc[badhole_mask] @@ -3793,8 +4145,15 @@ def workspace_badhole_flagging( project_id, well_name, req.min_depth, req.max_depth, req.zones ) # Drop any previously generated BS column so re-running with updated - # auto_bitsize / bitsize_default parameters always recomputes BS fresh. + # auto_bitsize / bitsize_default / hole_sections parameters always recomputes BS fresh. df_bh_input = df.drop(columns=["BS"], errors="ignore") + if req.use_hole_sections and "DEPTH" in df_bh_input.columns: + hs_list = _load_well_hole_sections(project_id, well_name) + if hs_list: + bs_from_hs = _synthesize_bitsize_series(df_bh_input["DEPTH"], hs_list) + if bs_from_hs.notna().any(): + df_bh_input = df_bh_input.copy() + df_bh_input["BS"] = bs_from_hs bh_df = badhole_flagging( df_bh_input, thold=float(req.cali_threshold), @@ -3819,7 +4178,9 @@ def workspace_badhole_flagging( if "DCALI" in bh_df.columns and bh_df["DCALI"].notna().any(): out_cols.append("DCALI") - out_df = bh_df[[c for c in out_cols if c in bh_df.columns or c in ("DEPTH", "BADHOLE")]].copy() + out_df = bh_df[ + [c for c in out_cols if c in bh_df.columns or c in ("DEPTH", "BADHOLE")] + ].copy() out_df["BADHOLE"] = pd.to_numeric(out_df["BADHOLE"], errors="coerce").fillna( 0.0 ) @@ -4467,7 +4828,9 @@ def workspace_batch_evaluation_apply( if module in ("saturation", "litho-poro"): clean_params.pop("manualOverrides", None) clean_params.pop("manual_overrides", None) - if "litho" in clean_params and isinstance(clean_params["litho"], dict): + if "litho" in clean_params and isinstance( + clean_params["litho"], dict + ): clean_params["litho"] = dict(clean_params["litho"]) clean_params["litho"].pop("manualOverrides", None) clean_params["litho"].pop("manual_overrides", None) @@ -4560,6 +4923,7 @@ def workspace_lithology( df = _get_filtered_well_df( project_id, well_name, req.min_depth, req.max_depth, req.zones ) + df = _apply_qc_weighted_inputs(df, req) model = req.model.lower() source = (req.gamma_source or "gr").lower() out_df = pd.DataFrame({"DEPTH": df["DEPTH"]}) @@ -4952,7 +5316,9 @@ def workspace_lithology( # Badhole interval treatment for lithology volumes bh_mode = (req.badhole_treatment or "none").strip().lower() - baseline_badhole = _resolve_baseline_badhole_mask(df, auto_detect_if_missing=(bh_mode != "none")) + baseline_badhole = _resolve_baseline_badhole_mask( + df, auto_detect_if_missing=(bh_mode != "none") + ) badhole_mask = baseline_badhole.copy() # Apply manual interactive overrides if provided @@ -4974,9 +5340,17 @@ def workspace_lithology( if not mask.any(): continue - c_mode = str(ov.get("coalMode") or ov.get("coal_mode") or "").lower().strip() - bh_mode_ov = str(ov.get("badholeMode") or ov.get("badhole_mode") or "").lower().strip() - target = str(ov.get("target") or ov.get("flag_type") or "").upper().strip() + c_mode = ( + str(ov.get("coalMode") or ov.get("coal_mode") or "").lower().strip() + ) + bh_mode_ov = ( + str(ov.get("badholeMode") or ov.get("badhole_mode") or "") + .lower() + .strip() + ) + target = ( + str(ov.get("target") or ov.get("flag_type") or "").upper().strip() + ) action = str(ov.get("action") or "").lower().strip() if target in ("COAL", "BOTH"): c_mode = action or "flag" @@ -4990,7 +5364,13 @@ def workspace_lithology( if bh_mode_ov in ("flag", "force_badhole", "badhole", "1", "true"): badhole_mask.loc[mask] = True - elif bh_mode_ov in ("clear", "clear_badhole", "good_hole", "0", "false"): + elif bh_mode_ov in ( + "clear", + "clear_badhole", + "good_hole", + "0", + "false", + ): badhole_mask.loc[mask] = False coal_flag_s = pd.Series(np.nan, index=df.index, dtype=float) @@ -5001,7 +5381,9 @@ def workspace_lithology( # Preserve COAL_FLAG_BASE out_df["COAL_FLAG_BASE"] = pd.Series(np.nan, index=df.index, dtype=float) - out_df["COAL_FLAG_BASE"].loc[valid_mask] = np.where(baseline_coal.loc[valid_mask], 1.0, 0.0) + out_df["COAL_FLAG_BASE"].loc[valid_mask] = np.where( + baseline_coal.loc[valid_mask], 1.0, 0.0 + ) if "COAL_FLAG_BASE" not in save_cols: save_cols.append("COAL_FLAG_BASE") @@ -5659,6 +6041,7 @@ def workspace_porosity( df = _get_filtered_well_df( project_id, well_name, req.min_depth, req.max_depth, req.zones ) + df = _apply_qc_weighted_inputs(df, req) nphi, rhob = _select_nphi_rhob( df, use_hc_corrected=req.use_hc_corrected, @@ -5833,6 +6216,11 @@ def workspace_porosity( well_header = {**well_header, **eph_hdr} bh_mask = _resolve_badhole_mask(df, auto_detect_if_missing=False) + hs_for_rho = ( + _load_well_hole_sections(project_id, well_name) + if getattr(fd_cfg, "use_hole_sections", True) + else [] + ) rho_fl_result = _compute_continuous_rho_fluid( df=df.loc[valid_mask], depth=df.loc[valid_mask, "DEPTH"], @@ -5842,6 +6230,7 @@ def workspace_porosity( well_header=well_header, contacts=contacts, badhole_mask=bh_mask.loc[valid_mask], + hole_sections=hs_for_rho, ) phid_engine = np.asarray(rho_fl_result["PHID"], dtype=float) phid_v = np.where(np.isfinite(phid_engine), phid_engine, phid_v) @@ -5969,7 +6358,9 @@ def workspace_porosity( coal_mask = baseline_coal.copy() bh_mode = (req.badhole_treatment or "none").strip().lower() - baseline_badhole = _resolve_baseline_badhole_mask(df, auto_detect_if_missing=(bh_mode != "none")) + baseline_badhole = _resolve_baseline_badhole_mask( + df, auto_detect_if_missing=(bh_mode != "none") + ) badhole_mask = baseline_badhole.copy() # Apply manual interactive overrides if provided @@ -5991,9 +6382,17 @@ def workspace_porosity( if not mask.any(): continue - c_mode = str(ov.get("coalMode") or ov.get("coal_mode") or "").lower().strip() - bh_mode_ov = str(ov.get("badholeMode") or ov.get("badhole_mode") or "").lower().strip() - target = str(ov.get("target") or ov.get("flag_type") or "").upper().strip() + c_mode = ( + str(ov.get("coalMode") or ov.get("coal_mode") or "").lower().strip() + ) + bh_mode_ov = ( + str(ov.get("badholeMode") or ov.get("badhole_mode") or "") + .lower() + .strip() + ) + target = ( + str(ov.get("target") or ov.get("flag_type") or "").upper().strip() + ) action = str(ov.get("action") or "").lower().strip() if target in ("COAL", "BOTH"): c_mode = action or "flag" @@ -6007,7 +6406,13 @@ def workspace_porosity( if bh_mode_ov in ("flag", "force_badhole", "badhole", "1", "true"): badhole_mask.loc[mask] = True - elif bh_mode_ov in ("clear", "clear_badhole", "good_hole", "0", "false"): + elif bh_mode_ov in ( + "clear", + "clear_badhole", + "good_hole", + "0", + "false", + ): badhole_mask.loc[mask] = False active_coal = valid_mask & coal_mask @@ -6788,6 +7193,7 @@ def workspace_saturation( df = _get_filtered_well_df( project_id, well_name, req.min_depth, req.max_depth, req.zones ) + df = _apply_qc_weighted_inputs(df, req) df = _merge_request_fallback_curves( df, depths=req.depths, @@ -7750,13 +8156,17 @@ def workspace_reservoir_summary( ) if req.save: - eph_cfg = _ephemeral_well_configs.setdefault((project_id, str(well_name)), {}) + eph_cfg = _ephemeral_well_configs.setdefault( + (project_id, str(well_name)), {} + ) eph_cfg["ressum_cutoffs"] = dict(req.cut_offs) if not is_demo_mode(): try: with get_db() as session: well_orm = session.scalar( - select(db_models.Well).filter_by(project_id=project_id, name=str(well_name)) + select(db_models.Well).filter_by( + project_id=project_id, name=str(well_name) + ) ) if well_orm: cfg_data = dict(well_orm.config_data or {}) @@ -7845,6 +8255,20 @@ def workspace_reservoir_summary( "cpi": dataframe_to_columnar(unc_res["cpi_df"][cpi_cols].round(4)), } + # Empirical cutoffs sensitivity analysis (PRMS / SEC HCPV recovery) + try: + from quick_pp.ressum import cutoffs_analysis + + cutoffs_sens_data = cutoffs_analysis( + df, + percentile=95.0, + plot=False, + return_dict=True, + ) + response["cutoffs_sensitivity"] = _sanitize_for_json(cutoffs_sens_data) + except Exception as exc: + logger.debug(f"cutoffs_analysis in reservoir_summary skipped: {exc}") + return response except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) from e @@ -7854,6 +8278,45 @@ def workspace_reservoir_summary( ) from e +@router.post( + "/wells/{well_name}/cutoffs_sensitivity", + summary="Run empirical cutoffs sensitivity analysis (Vsh, Phi, Sw vs HCPV & Net Pay) for a single well", +) +def workspace_well_cutoffs_sensitivity( + project_id: int, well_name: str, req: WorkspaceWellCutoffsSensitivityRequest +) -> Dict[str, Any]: + """Perform cutoffs sensitivity analysis on a single well evaluated logs using PRMS HCPV recovery percentiles.""" + try: + df = _get_filtered_well_df( + project_id, well_name, req.min_depth, req.max_depth, req.zones + ) + df = _merge_request_fallback_curves(df) + if df.empty: + raise ValueError(f"No valid data found for well '{well_name}'.") + + from quick_pp.ressum import cutoffs_analysis + + sens = cutoffs_analysis( + df, + percentile=req.percentile, + plot=False, + return_dict=True, + ) + return _sanitize_for_json(sens) + except HTTPException: + raise + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) from e + except Exception as e: + logger.error( + f"Failed cutoffs sensitivity analysis for well {well_name}: {e}", + exc_info=True, + ) + raise HTTPException( + status_code=500, detail=f"Cutoffs sensitivity analysis failed: {e}" + ) from e + + def _normalize_drt_method(method: Optional[str]) -> str: """Normalize DRT method string to 'fzi', 'winland', or 'lucia'.""" m = str(method or "fzi").strip().lower() @@ -9662,8 +10125,20 @@ def workspace_shf_compute(project_id: int, req: WorkspaceShfRequest) -> Dict[str core_rows: List[Dict[str, Any]] = [] with get_db() as session: proj = db_objects.Project.load(session, project_id=project_id) + allowed_wn_tokens = ( + { + _canonical_well_token(w) + for w in req.well_names + if _canonical_well_token(w) + } + if req.well_names + else None + ) for wn in proj.get_well_names(): - if req.well_names and wn not in req.well_names: + if ( + allowed_wn_tokens + and _canonical_well_token(wn) not in allowed_wn_tokens + ): continue try: anc = proj.get_well_ancillary_data(wn) @@ -9727,8 +10202,6 @@ def workspace_shf_compute(project_id: int, req: WorkspaceShfRequest) -> Dict[str if not raw_d_r.empty and pd.notna(raw_d_r["value"].iloc[0]): s_raw_depth = float(raw_d_r["value"].iloc[0]) - has_sample_core_props = cperm is not None and cpore is not None - # Fallback 1: check companion RCA core sample in this well by sister sample name (e.g. 1A -> 1) # or nearest depth (matching against both shifted depth and RAW_DEPTH / CORE_DEPTH_RAW within 0.50m) if cpore is None or cperm is None: @@ -9822,8 +10295,6 @@ def _norm_plug_stem(val: Any) -> str: cpore = best_poro_cand[1] if cperm is None and best_perm_cand is not None: cperm = best_perm_cand[1] - if cpore is not None and cperm is not None: - has_sample_core_props = True # Fallback 2: lookup well's merged CPORE/CPERM (within ±0.50m) or log PHIT & PERM_TRANS/PERM at nearest depth near_rock_flag: Optional[int] = None @@ -9942,7 +10413,9 @@ def _norm_plug_stem(val: Any) -> str: ind_val_plug, req.cutoffs, higher_is_better=hib_plug ).item() ) - if not has_sample_core_props and near_rock_flag is not None: + if ( + not np.isfinite(rf_val) or rf_val < 1 + ) and near_rock_flag is not None: rf_val = near_rock_flag pc_col = next( ( @@ -9984,11 +10457,57 @@ def _norm_plug_stem(val: Any) -> str: if np.nanmax(sw_vals) > 1.5: sw_vals = sw_vals / 100.0 sw_vals = np.clip(sw_vals, 0.01, 1.0) - # Convert lab mercury-air MICP to reservoir oil-brine Pc if unscaled - if np.nanmax(pc_vals) > 200.0: - res_num = max( - req.ift * abs(math.cos(math.radians(req.theta))), 1.0 + # Determine experiment type + exp_type = "porous_plate" + col_map = {str(c).strip().upper(): c for c in pc_df.columns} + for tc in ("TYPE", "EXPERIMENT_TYPE", "METHOD", "TEST_TYPE"): + if tc in col_map: + vals = pc_df[col_map[tc]].dropna().astype(str).tolist() + if vals and vals[0].strip(): + exp_type = vals[0].strip().lower() + break + if exp_type in ("porous_plate", "unknown", "", "none"): + s_meth = ( + sample.get("experiment_type") + or sample.get("type") + or sample.get("method") ) + if s_meth and str(s_meth).strip(): + exp_type = str(s_meth).strip().lower() + + # Convert lab capillary pressure to reservoir conditions for Leverett J / height fitting + res_num = max(req.ift * abs(math.cos(math.radians(req.theta))), 1.0) + if any(m in exp_type for m in ("micp", "mercury", "hg")) or ( + exp_type in ("unknown", "", "none") + and np.nanmax(pc_vals) > 1000.0 + ): + lab_den = 485.0 * abs(math.cos(math.radians(140.0))) + pc_vals = pc_vals * (res_num / lab_den) + elif any( + m in exp_type + for m in ( + "porous_plate", + "centrifuge", + "air_brine", + "brine_air", + "air_water", + ) + ): + lab_den = 72.0 * abs(math.cos(math.radians(0.0))) + pc_vals = pc_vals * (res_num / lab_den) + elif any( + m in exp_type + for m in ( + "oil_brine", + "brine_oil", + "water_oil", + "oil_water", + "res", + "reservoir", + ) + ): + pass + elif np.nanmax(pc_vals) > 1000.0: lab_den = 485.0 * abs(math.cos(math.radians(140.0))) pc_vals = pc_vals * (res_num / lab_den) swirr_src_mode = ( @@ -10217,6 +10736,38 @@ def _norm_plug_stem(val: Any) -> str: for rf_k, f_val in src_fits.items(): fits[rf_k] = dict(f_val) + # Ensure all defined rock types exist in fits + all_expected_rts = ( + [str(r) for r in range(1, len(req.cutoffs or []) + 2)] + if req.cutoffs + else [str(r) for r in reservoir_flags] + ) + if fits and all_expected_rts: + fallback_fit = next( + iter(fits.values()), + {"a": 0.2, "b": 0.3, "rmse": 0.0, "r2": 0.0, "count": 0}, + ) + for r_key in all_expected_rts: + if r_key not in fits: + numeric_keys = [k for k in fits.keys() if k.isdigit()] + if numeric_keys and r_key.isdigit(): + nearest_key = min( + numeric_keys, key=lambda k: abs(int(k) - int(r_key)) + ) + fits[r_key] = { + **fits[nearest_key], + "rmse": 0.0, + "r2": 0.0, + "count": 0, + } + else: + fits[r_key] = { + **fallback_fit, + "rmse": 0.0, + "r2": 0.0, + "count": 0, + } + # Recompute fit diagnostics (rmse, r2, count) against SCAL points for all entries in fits if not scal_df_fit.empty and fits: j_sat_col = "SW" if j_sat_mode == "sw" else "SWN" @@ -10316,8 +10867,14 @@ def _norm_plug_stem(val: Any) -> str: if model == "leverett_j": if j_sat_mode == "sw": fits_sw = {k: dict(v) for k, v in fits.items()} + for k, v in fits.items(): + if k not in fits_swn: + fits_swn[k] = dict(v) else: fits_swn = {k: dict(v) for k, v in fits.items()} + for k, v in fits.items(): + if k not in fits_sw: + fits_sw[k] = dict(v) fwl_zone_map: Dict[str, float] = {} if req.fwl_by_zone: @@ -10872,13 +11429,73 @@ def _norm_plug_stem(val: Any) -> str: ) from e +class EnvMudIntervalModel(BaseModel): + """One hole section of the mud program (depths in the log depth unit).""" + + top: float + bottom: float + bit_size_in: Optional[float] = None + mud_type: Literal["WBM", "OBM", "SBM"] = "WBM" + mud_weight_ppg: Optional[float] = None + rm: Optional[float] = None + rm_temp_c: Optional[float] = None + rmf: Optional[float] = None + rmf_temp_c: Optional[float] = None + rmc: Optional[float] = None + rmc_temp_c: Optional[float] = None + salinity_ppm: Optional[float] = None + + +class EnvBhtRecordModel(BaseModel): + depth_m: float + temp_c: float + + class WorkspaceEnvCorrectionRequest(WorkspaceFilterBase): + """Environmental correction settings. + + ``None`` means "take it from the well header / config, otherwise use a + documented default". Legacy scalar fields (``surface_temp`` degF, + ``temp_grad`` degF/100 ft, ``mud_weight`` ppg) are still accepted. + """ + bitsize_default: float = Field(8.5) - mud_weight: float = Field(9.0) - surface_temp: float = Field(75.0) - temp_grad: float = Field(1.5) - salinity_ppm: float = Field(35000.0) + mud_weight: Optional[float] = Field(None, description="Mud weight (ppg or g/cc)") + surface_temp: Optional[float] = Field( + None, description="Surface temperature (degF)" + ) + temp_grad: Optional[float] = Field( + None, description="Geothermal gradient (degF/100 ft)" + ) + salinity_ppm: Optional[float] = Field( + None, description="Borehole mud salinity (ppm NaCl)" + ) rho_mudcake: float = Field(1.5) + tool_type: Literal["WL", "LWD"] = Field("WL") + mud_type: Optional[Literal["WBM", "OBM", "SBM"]] = Field(None) + res_tool: Optional[Literal["induction", "laterolog", "propagation"]] = Field(None) + depth_unit: Optional[Literal["m", "ft"]] = Field( + None, description="Log depth unit; defaults to the well depth unit" + ) + water_depth: Optional[float] = Field( + None, description="Water depth (log depth unit); > 0 = offshore" + ) + seabed_temp_c: Optional[float] = Field(None) + temp_gradient_c_per_km: Optional[float] = Field(None) + bht_records: Optional[List[EnvBhtRecordModel]] = Field(None) + formation_salinity_ppm: Optional[float] = Field(None) + rm: Optional[float] = Field(None) + rm_temp_c: Optional[float] = Field(None) + rmf: Optional[float] = Field(None) + rmf_temp_c: Optional[float] = Field(None) + mud_program: Optional[List[EnvMudIntervalModel]] = Field(None) + use_hole_sections: bool = Field( + True, + description="Use mud program intervals from Hole Sections table when available (False = manual scalar override)", + ) + washout_thold: float = Field(2.0, gt=0) + good_conf: float = Field(0.8, ge=0, le=1) + unreliable_conf: float = Field(0.4, ge=0, le=1) class WorkspaceStratNormalizationRequest(BaseModel): @@ -11370,6 +11987,36 @@ def _interp_or_extrapolate_depth( return out +def _align_and_interp_depth( + md_values: np.ndarray, ref_md: np.ndarray, ref_tvd: np.ndarray +) -> np.ndarray: + """Interpolate ref_tvd along md_values, reconciling unit differences (metres vs feet).""" + target_md = np.asarray(md_values, dtype=float).copy() + valid_t = target_md[np.isfinite(target_md)] + valid_r = ref_md[np.isfinite(ref_md)] + valid_z = ref_tvd[np.isfinite(ref_tvd)] + med_t = float(np.median(valid_t)) if len(valid_t) > 0 else 0.0 + med_r = float(np.median(valid_r)) if len(valid_r) > 0 else 0.0 + med_z = float(np.median(valid_z)) if len(valid_z) > 0 else 0.0 + + scale_back = 1.0 + # 1. Reconcile target_md scale to ref_md scale for proper interpolation bracket + if med_t > 0 and med_r > 0: + ratio_tr = med_t / med_r + if 2.7 < ratio_tr < 3.7: # target in ft, ref in m + target_md *= 0.3048 + elif 0.27 < ratio_tr < 0.37: # target in m, ref in ft + target_md /= 0.3048 + scale_back = 0.3048 # ref_tvd is in ft, scale back to m to match target_md + + # 2. Check if ref_tvd itself is in ft while ref_md is in m (ratio ~ 3.28) + if med_r > 0 and med_z > 0 and 2.5 < (med_z / med_r) < 3.8: + ref_tvd = ref_tvd * 0.3048 + + res = _interp_or_extrapolate_depth(target_md, ref_md, ref_tvd) + return res * scale_back + + def _resolve_well_tvd_array( md_values: np.ndarray, well_df: Optional[pd.DataFrame], @@ -11416,7 +12063,7 @@ def _resolve_well_tvd_array( .drop_duplicates(subset=["DEPTH"], keep="last") ) if len(sub) >= 2: - return _interp_or_extrapolate_depth( + return _align_and_interp_depth( md_values, sub["DEPTH"].to_numpy(dtype=float), sub["TVDSS"].to_numpy(dtype=float), @@ -11438,7 +12085,7 @@ def _resolve_well_tvd_array( .drop_duplicates(subset=["DEPTH"], keep="last") ) if len(sub) >= 2: - return _interp_or_extrapolate_depth( + return _align_and_interp_depth( md_values, sub["DEPTH"].to_numpy(dtype=float), sub["TVDSS"].to_numpy(dtype=float), @@ -11475,7 +12122,7 @@ def _resolve_well_tvd_array( if mds[0] > 1.0: mds = np.insert(mds, 0, 0.0) tvds = np.insert(tvds, 0, -elev if is_already_subsea else 0.0) - interp_tvd = _interp_or_extrapolate_depth(md_values, mds, tvds) + interp_tvd = _align_and_interp_depth(md_values, mds, tvds) return interp_tvd if is_already_subsea else (interp_tvd - elev) if md_c and inc_c and azi_c: @@ -11492,43 +12139,15 @@ def _resolve_well_tvd_array( .drop_duplicates(subset=["md"]) ) if len(s_sorted) >= 2: - mds = s_sorted["md"].to_numpy(dtype=float) - incs = s_sorted["inc"].to_numpy(dtype=float) - azis = s_sorted["azim"].to_numpy(dtype=float) - if mds[0] > 1.0: + # Station TVD from the shared minimum-curvature helper; the + # existing unit-reconciling interpolation is kept for MD grids. + mds, tvds, _ = survey_tvd_stations( + s_sorted["md"], s_sorted["inc"], s_sorted["azim"] + ) + if mds[0] > 0.0: mds = np.insert(mds, 0, 0.0) - incs = np.insert(incs, 0, 0.0) - azis = np.insert(azis, 0, azis[0] if len(azis) > 0 else 0.0) - try: - import wellpathpy as wpp - - dev = wpp.deviation(mds, incs, azis) - pos = dev.minimum_curvature() - return ( - _interp_or_extrapolate_depth( - md_values, - np.asarray(pos.md, dtype=float), - np.asarray(pos.depth, dtype=float), - ) - - elev - ) - except Exception: - inc_rad = np.deg2rad(incs) - azi_rad = np.deg2rad(azis) - dmd = np.diff(mds) - i1, i2 = inc_rad[:-1], inc_rad[1:] - a1, a2 = azi_rad[:-1], azi_rad[1:] - cos_dl = np.clip( - np.cos(i2 - i1) - - np.sin(i1) * np.sin(i2) * (1.0 - np.cos(a2 - a1)), - -1.0, - 1.0, - ) - dl = np.arccos(cos_dl) - rf = np.where(dl > 1e-6, (2.0 / dl) * np.tan(dl / 2.0), 1.0) - dz = 0.5 * dmd * (np.cos(i1) + np.cos(i2)) * rf - tvd_calc = np.concatenate([[0.0], np.cumsum(dz)]) - return _interp_or_extrapolate_depth(md_values, mds, tvd_calc) - elev + tvds = np.insert(tvds, 0, 0.0) + return _align_and_interp_depth(md_values, mds, tvds) - elev # 3. No TVDSS/TVD curve and no valid directional survey -> do NOT assume TVDSS == MD return np.full(len(md_values), np.nan, dtype=float) @@ -11888,18 +12507,7 @@ def workspace_stick_plot( pd.to_numeric(wdf_sorted["VOIL"], errors="coerce").fillna(0.0) > 0.01 ).astype(int) - else: - oil_flag_s = ((bvo_s > 0.005) & (gas_flag_s == 0)).astype(int) - - bvg_s = bvo_s.where(gas_flag_s == 1, 0.0) - bvo_pure_s = bvo_s.where(gas_flag_s == 0, 0.0) - - wdf_sorted["GAS_FLAG"] = gas_flag_s - wdf_sorted["OIL_FLAG"] = oil_flag_s - wdf_sorted["BVG"] = bvg_s - wdf_sorted["BVO_PURE"] = bvo_pure_s - # Extract fluid contacts & map MD -> TVD contacts_raw = anc.get("fluid_contacts") if isinstance(contacts_raw, pd.DataFrame): contacts_list = ( @@ -12039,6 +12647,8 @@ def workspace_stick_plot( wdf_sorted["SWT"] = swt_s wdf_sorted["BVO"] = bvo_s wdf_sorted["BVOH"] = bvoh_s + wdf_sorted["GAS_FLAG"] = gas_flag_s + wdf_sorted["OIL_FLAG"] = oil_flag_s try: wdf_sorted = update_fluid_contacts(wdf_sorted, contact_dict_tvd) except Exception: @@ -12318,6 +12928,244 @@ class WorkspaceOptimizeFwlRequest(BaseModel): save: bool = Field(False) +ENV_QC_OUTPUT_CURVES = ("GR", "NPHI", "RHOB", "RT", "DT") +ENV_QC_SUFFIXES = ("_ENV_CORR", "_CORR_DELTA", "_SIGMA", "_QC_CONF", "_QC_STATUS") +ENV_QC_SHARED_COLS = ( + "ENV_QC_REASON", + "HOLE_SEVERITY", + "ENV_TEMP_C", + "ENV_BS", + "ENV_RM", + "ENV_RMF", + "ENV_RW", + "INVASION_FLAG", + "INVASION_PROFILE", + "RXO_EST", + "DI_EST", +) + + +def _load_well_env_config( + project_id: int, well_name: str +) -> Tuple[Dict[str, Any], Optional[str]]: + """Merge LAS header metadata, DB well config and ephemeral config for environment inputs. + + Returns ``(config, depth_unit)``. ``depth_unit`` is the stored well depth unit + (``'m'``/``'ft'``) or ``None`` when unknown. + """ + cfg: Dict[str, Any] = {} + depth_uom: Optional[str] = None + if _isolated_evaluation.get() is not None: + return cfg, None + try: + with get_db() as session: + proj = db_objects.Project.load(session, project_id=project_id) + well_obj = proj.get_well(resolve_db_well_name(project_id, well_name)) + orm = getattr(well_obj, "_orm_well", None) + if orm is not None: + depth_uom = orm.depth_uom + if isinstance(orm.header_data, dict): + meta = extract_las_metadata( + dict(orm.header_data), fallback_well_name=well_name + ) + cfg.update({k: v for k, v in dict(meta).items() if v is not None}) + ovr = orm.header_data.get("header_overrides") + if isinstance(ovr, dict): + cfg.update({k: v for k, v in ovr.items() if v is not None}) + if isinstance(orm.config_data, dict): + cfg.update( + {k: v for k, v in orm.config_data.items() if v is not None} + ) + except Exception as exc: + logger.debug(f"[env_corr] could not load well config for {well_name}: {exc}") + eph = _ephemeral_well_configs.get( + (project_id, well_name) + ) or _ephemeral_well_configs.get( + (project_id, resolve_db_well_name(project_id, well_name)) + ) + if isinstance(eph, dict): + cfg.update({k: v for k, v in eph.items() if v is not None}) + unit = str(depth_uom or cfg.get("datum_unit") or "").strip().lower() + unit_norm = ( + "ft" + if unit in ("ft", "f", "feet", "foot") + else ("m" if unit in ("m", "meter", "metre", "meters", "metres") else None) + ) + return cfg, unit_norm + + +def _run_env_corrections( + project_id: int, + well_name: str, + df: pd.DataFrame, + req: "WorkspaceEnvCorrectionRequest", +) -> Tuple[pd.DataFrame, List[str], Dict[str, Any]]: + """Build the environment for one well and run the generic corrections. + + Request values override the well header/config. Returns the corrected + DataFrame, the output column list and response metadata. + """ + from quick_pp.environment import environment_from_config + + cfg, well_unit = _load_well_env_config(project_id, well_name) + depth_unit = req.depth_unit or well_unit + unit_note = None + if depth_unit is None: + depth_unit = "m" + unit_note = "Well depth unit unknown; metres assumed." + + overrides: Dict[str, Any] = { + "mud_type": req.mud_type, + "water_depth": req.water_depth, + "seabed_temp_c": req.seabed_temp_c, + "temp_gradient_c_per_km": req.temp_gradient_c_per_km, + "formation_salinity_ppm": req.formation_salinity_ppm, + "mud_salinity_ppm": req.salinity_ppm, + "rm": req.rm, + "rm_temp": req.rm_temp_c, + "rmf": req.rmf, + "rmf_temp": req.rmf_temp_c, + "rm_temp_unit": "degC" if req.rm_temp_c is not None else None, + "rmf_temp_unit": "degC" if req.rmf_temp_c is not None else None, + } + if req.mud_weight is not None: + overrides["mud_weight_ppg"] = req.mud_weight + if req.surface_temp is not None: + overrides["surface_temp"] = req.surface_temp + overrides["surface_temp_unit"] = "degF" + if req.temp_grad is not None and req.temp_gradient_c_per_km is None: + overrides["temp_gradient_c_per_km"] = ( + float(req.temp_grad) * (5.0 / 9.0) * (1000.0 / 30.48) + ) + if req.bht_records: + overrides["bht_records"] = [r.model_dump() for r in req.bht_records] + if req.mud_program: + overrides["mud_program"] = [iv.model_dump() for iv in req.mud_program] + elif getattr(req, "use_hole_sections", True): + hs_rows = _load_well_hole_sections(project_id, well_name) + if hs_rows: + overrides["mud_program"] = [ + { + "top": float(s["top"]), + "bottom": float(s["bottom"]), + "bit_size_in": float(s["bit_size"]) + if s.get("bit_size") is not None + else None, + "mud_type": str(s.get("mud_type") or "WBM").upper(), + "mud_weight_ppg": float(s["mud_weight"]) + if s.get("mud_weight") is not None + else None, + "salinity_ppm": float(s["mud_salinity"]) + if s.get("mud_salinity") is not None + else None, + "rmf": float(s["rmf"]) if s.get("rmf") is not None else None, + "rmf_temp_c": float(s["rmf_temp"]) + if s.get("rmf_temp") is not None + else None, + } + for s in hs_rows + if s.get("top") is not None and s.get("bottom") is not None + ] + use_hs = bool(getattr(req, "use_hole_sections", True)) + if not use_hs: + cfg.pop("mud_program", None) + if req.bitsize_default is not None: + overrides["bit_size"] = float(req.bitsize_default) + elif req.bitsize_default is not None and not cfg.get("bit_size"): + overrides["bit_size"] = float(req.bitsize_default) + if cfg.get("mud_type") is None and req.mud_type is None: + cfg["mud_type"] = "WBM" + if cfg.get("mud_type") is not None and str(cfg["mud_type"]).upper() not in ( + "WBM", + "OBM", + "SBM", + ): + cfg.pop("mud_type") + env = environment_from_config(cfg, overrides, depth_unit=depth_unit) + if unit_note: + env.assumptions.insert(0, unit_note) + + df_env_in = df if use_hs else df.drop(columns=["BS"], errors="ignore") + eff_bs_default = ( + float(cfg.get("bit_size") or req.bitsize_default) + if use_hs + else float(req.bitsize_default or 8.5) + ) + + corr_df = apply_environmental_corrections( + df_env_in, + bitsize_default=eff_bs_default, + rho_mudcake=req.rho_mudcake, + depth_unit=depth_unit, + mud_type=env.default_mud_type, + washout_thold=req.washout_thold, + good_conf=req.good_conf, + unreliable_conf=req.unreliable_conf, + tool_type=req.tool_type, + environment=env, + res_tool=req.res_tool, + auto_bitsize=use_hs, + ) + out_cols = [ + f"{log}{suf}" + for log in ENV_QC_OUTPUT_CURVES + for suf in ENV_QC_SUFFIXES + if f"{log}{suf}" in corr_df.columns + ] + [c for c in ENV_QC_SHARED_COLS if c in corr_df.columns] + + qc_summary: Dict[str, Any] = {} + for log in ENV_QC_OUTPUT_CURVES: + st_col, cf_col, dl_col = ( + f"{log}_QC_STATUS", + f"{log}_QC_CONF", + f"{log}_CORR_DELTA", + ) + if st_col not in corr_df.columns: + continue + st = pd.to_numeric(corr_df[st_col], errors="coerce") + valid = st >= 0 + nv = int(valid.sum()) + delta = pd.to_numeric(corr_df[dl_col], errors="coerce").abs()[valid] + qc_summary[log] = { + "samples": nv, + "good_pct": round(float((st == 0).sum()) * 100.0 / nv, 1) if nv else 0.0, + "corrected_pct": round(float((st == 1).sum()) * 100.0 / nv, 1) + if nv + else 0.0, + "unreliable_pct": round(float((st == 2).sum()) * 100.0 / nv, 1) + if nv + else 0.0, + "mean_conf": round( + float(pd.to_numeric(corr_df[cf_col], errors="coerce")[valid].mean()), 3 + ) + if nv + else None, + "mean_abs_delta": round(float(delta.mean()), 5) + if nv and delta.notna().any() + else None, + "p95_abs_delta": round(float(delta.quantile(0.95)), 5) + if nv and delta.notna().any() + else None, + } + meta = { + "qc_summary": qc_summary, + "assumptions": list(corr_df.attrs.get("env_assumptions") or []), + "environment": { + "tool_type": req.tool_type, + "depth_unit": depth_unit, + "offshore": env.offshore, + "water_depth_m": round(env.water_depth_m, 2), + "top_temp_c": round(env.top_temp_c, 2), + "gradient_c_per_km": round(env.gradient_c_per_km, 2), + "mud_type": env.default_mud_type, + "mud_weight_ppg": round(env.default_mud_weight_ppg, 2), + "formation_salinity_ppm": env.formation_salinity_ppm, + "mud_program_sections": len(env.mud_program), + }, + } + return corr_df, out_cols, meta + + @router.post( "/wells/{well_name}/environmental_corrections", summary="Apply borehole environmental and invasion corrections to well logs", @@ -12325,41 +13173,31 @@ class WorkspaceOptimizeFwlRequest(BaseModel): def workspace_environmental_corrections( project_id: int, well_name: str, req: WorkspaceEnvCorrectionRequest ) -> Dict[str, Any]: - """Apply environmental corrections (GR_ENV_CORR, NPHI_ENV_CORR, RHOB_ENV_CORR, RT_ENV_CORR) to a well.""" + """Apply generic environmental corrections and return corrected curves with QC outputs. + + Returns ``_ENV_CORR`` plus per-curve ``_CORR_DELTA``, ``_SIGMA``, + ``_QC_CONF``, ``_QC_STATUS``, and ``ENV_QC_REASON``, ``HOLE_SEVERITY``, + ``ENV_TEMP_C`` and resistivity invasion outputs, together with a per-curve + ``qc_summary`` and the list of ``assumptions`` that were made. + """ try: df = _get_filtered_well_df( project_id, well_name, req.min_depth, req.max_depth, req.zones ) - corr_df = apply_environmental_corrections( - df, - bitsize_default=req.bitsize_default, - mud_weight=req.mud_weight, - surface_temp=req.surface_temp, - temp_grad=req.temp_grad, - salinity_ppm=req.salinity_ppm, - rho_mudcake=req.rho_mudcake, - ) - corr_cols = [ - c - for c in ( - "GR_ENV_CORR", - "NPHI_ENV_CORR", - "RHOB_ENV_CORR", - "RT_ENV_CORR", - "INVASION_FLAG", - ) - if c in corr_df.columns - ] - out_df = corr_df[["DEPTH"] + corr_cols].copy() + corr_df, out_cols, meta = _run_env_corrections(project_id, well_name, df, req) + out_df = corr_df[["DEPTH"] + out_cols].copy() saved_rows = 0 - if req.save and corr_cols: + if req.save and out_cols: saved_rows = _save_curves_to_well(project_id, well_name, out_df) - stats = {col: _curve_summary_stats(out_df[col]) for col in corr_cols} + elif out_cols: + _update_in_memory_well_cache(project_id, well_name, out_df) + stats = {col: _curve_summary_stats(out_df[col]) for col in out_cols} return { "well_name": well_name, "saved": req.save, "saved_rows": saved_rows, "stats": stats, + **meta, **dataframe_to_columnar(out_df), } except Exception as e: @@ -12832,8 +13670,16 @@ def workspace_multi_well_badhole_flagging( for wdf in dfs: wn = str(wdf["WELL_NAME"].iloc[0]) + wdf_bh = wdf.drop(columns=["BS"], errors="ignore") + if req.use_hole_sections and "DEPTH" in wdf_bh.columns: + hs_list = _load_well_hole_sections(project_id, wn) + if hs_list: + bs_from_hs = _synthesize_bitsize_series(wdf_bh["DEPTH"], hs_list) + if bs_from_hs.notna().any(): + wdf_bh = wdf_bh.copy() + wdf_bh["BS"] = bs_from_hs bh_df = badhole_flagging( - wdf, + wdf_bh, thold=req.cali_threshold, use_cali=req.use_cali, auto_bitsize=req.auto_bitsize, @@ -12851,7 +13697,11 @@ def workspace_multi_well_badhole_flagging( cali_spike_threshold=req.cali_spike_threshold, ) summary = dict(bh_df.attrs.get("badhole_summary", {})) - out_cols = [c for c in ("BADHOLE", "BADHOLE_BASE", "BS", "DCALI") if c in bh_df.columns] + out_cols = [ + c + for c in ("BADHOLE", "BADHOLE_BASE", "BS", "DCALI") + if c in bh_df.columns + ] if out_cols and "DEPTH" in bh_df.columns: sub_df = bh_df[["DEPTH"] + out_cols].copy() if "BADHOLE" in sub_df.columns and "BADHOLE_BASE" not in sub_df.columns: @@ -12923,26 +13773,9 @@ def workspace_multi_well_environmental_corrections( for wdf in dfs: wn = str(wdf["WELL_NAME"].iloc[0]) - corr_df = apply_environmental_corrections( - wdf, - bitsize_default=req.bitsize_default, - mud_weight=req.mud_weight, - surface_temp=req.surface_temp, - temp_grad=req.temp_grad, - salinity_ppm=req.salinity_ppm, - rho_mudcake=req.rho_mudcake, - ) - corr_cols = [ - c - for c in ( - "GR_ENV_CORR", - "NPHI_ENV_CORR", - "RHOB_ENV_CORR", - "RT_ENV_CORR", - "INVASION_FLAG", - ) - if c in corr_df.columns - ] + if "DEPTH" in wdf.columns: + wdf = wdf.sort_values("DEPTH").reset_index(drop=True) + corr_df, corr_cols, meta = _run_env_corrections(project_id, wn, wdf, req) all_corr_cols.update(corr_cols) if corr_cols and "DEPTH" in corr_df.columns: sub_df = corr_df[["DEPTH"] + corr_cols].copy() @@ -12956,7 +13789,18 @@ def workspace_multi_well_environmental_corrections( { "WELL_NAME": wn, "ROWS": len(corr_df), - "CURVES_CORRECTED": ", ".join(corr_cols), + "CURVES_CORRECTED": ", ".join( + c for c in corr_cols if c.endswith("_ENV_CORR") + ), + **{ + f"{log}_UNRELIABLE_PCT": s["unreliable_pct"] + for log, s in meta["qc_summary"].items() + }, + **{ + f"{log}_MEAN_CONF": s["mean_conf"] + for log, s in meta["qc_summary"].items() + }, + "ASSUMPTIONS": len(meta["assumptions"]), } ) @@ -15698,6 +16542,8 @@ class WorkspaceSwirrFitRequest(BaseModel): max_depth: Optional[float] = Field(None) extraction_mode: Optional[str] = Field(None) extractionMode: Optional[str] = Field(None) + pc_domain: Optional[str] = Field("lab") + pcDomain: Optional[str] = Field(None) reference_pc_psi: Optional[float] = Field(None) referencePcPsi: Optional[float] = Field(None) equation_type: Optional[str] = Field(None) @@ -15784,6 +16630,7 @@ def _extract_project_scal_plugs_for_swirr( zones: Optional[List[str]] = None, min_depth: Optional[float] = None, max_depth: Optional[float] = None, + pc_domain: str = "lab", ) -> List[Dict[str, Any]]: """Extract plug-level SCAL drainage curves and matched CPORE/CPERM/ROCK_FLAG across project wells.""" cutoffs_list = sorted(float(c) for c in (cutoffs or [0.5, 1.2, 2.5, 5.0])) @@ -15818,8 +16665,13 @@ def _extract_project_scal_plugs_for_swirr( plug_records: List[Dict[str, Any]] = [] with get_db() as session: proj = db_objects.Project.load(session, project_id=project_id) + allowed_wn_tokens = ( + {_canonical_well_token(w) for w in well_names if _canonical_well_token(w)} + if well_names + else None + ) for wn in proj.get_well_names(): - if well_names and wn not in well_names: + if allowed_wn_tokens and _canonical_well_token(wn) not in allowed_wn_tokens: continue try: anc = proj.get_well_ancillary_data(wn) @@ -15870,8 +16722,6 @@ def _extract_project_scal_plugs_for_swirr( if not raw_d_r.empty and pd.notna(raw_d_r["value"].iloc[0]): s_raw_depth = float(raw_d_r["value"].iloc[0]) - has_sample_core_props = cperm is not None and cpore is not None - if cpore is None or cperm is None: import re as _re @@ -15954,8 +16804,6 @@ def _norm_stem(val: Any) -> str: cpore = best_poro_cand[1] if cperm is None and best_perm_cand is not None: cperm = best_perm_cand[1] - if cpore is not None and cperm is not None: - has_sample_core_props = True near_rock_flag: Optional[int] = None if s_depth > 0 or allowed_zones_set is not None: @@ -16062,7 +16910,9 @@ def _norm_stem(val: Any) -> str: ind_val_plug, cutoffs_list, higher_is_better=hib_plug ).item() ) - if not has_sample_core_props and near_rock_flag is not None: + if ( + not np.isfinite(rf_val) or rf_val < 1 + ) and near_rock_flag is not None: rf_val = near_rock_flag pc_col = next( @@ -16105,10 +16955,67 @@ def _norm_stem(val: Any) -> str: if np.nanmax(sw_vals) > 1.5: sw_vals = sw_vals / 100.0 sw_vals = np.clip(sw_vals, 0.01, 1.0) - if np.nanmax(pc_vals) > 200.0: + # Detect experiment type from core sample pc table + exp_type = "porous_plate" + col_map = {str(c).strip().upper(): c for c in pc_df.columns} + for tc in ("TYPE", "EXPERIMENT_TYPE", "METHOD", "TEST_TYPE"): + if tc in col_map: + vals = pc_df[col_map[tc]].dropna().astype(str).tolist() + if vals and vals[0].strip(): + exp_type = vals[0].strip().lower() + break + if exp_type in ("porous_plate", "unknown", "", "none"): + s_meth = ( + sample.get("experiment_type") + or sample.get("type") + or sample.get("method") + ) + if s_meth and str(s_meth).strip(): + exp_type = str(s_meth).strip().lower() + + # Apply Lab-to-Reservoir conversion ONLY if requested (pc_domain == 'reservoir') + pc_dom = str(pc_domain or "lab").strip().lower() + if pc_dom == "reservoir": res_num = max(ift * abs(math.cos(math.radians(theta))), 1.0) - lab_den = 485.0 * abs(math.cos(math.radians(140.0))) - pc_vals = pc_vals * (res_num / lab_den) + if any(m in exp_type for m in ("micp", "mercury", "hg")) or ( + exp_type in ("unknown", "", "none") + and np.nanmax(pc_vals) > 1000.0 + ): + # Mercury-Air lab system: sigma=485 mN/m, theta=140 deg + lab_den = 485.0 * abs(math.cos(math.radians(140.0))) + pc_vals = pc_vals * (res_num / lab_den) + elif any( + m in exp_type + for m in ( + "porous_plate", + "centrifuge", + "air_brine", + "brine_air", + "air_water", + ) + ): + # Air-Brine lab system: sigma=72 mN/m, theta=0 deg + lab_den = 72.0 * abs(math.cos(math.radians(0.0))) + pc_vals = pc_vals * (res_num / lab_den) + elif any( + m in exp_type + for m in ( + "oil_brine", + "brine_oil", + "water_oil", + "oil_water", + "res", + "reservoir", + ) + ): + # Already reservoir oil-brine system + pass + else: + if np.nanmax(pc_vals) > 1000.0: + lab_den = 485.0 * abs(math.cos(math.radians(140.0))) + else: + lab_den = 72.0 * abs(math.cos(math.radians(0.0))) + pc_vals = pc_vals * (res_num / lab_den) order = np.argsort(pc_vals) pc_sorted = [round(float(x), 4) for x in pc_vals[order]] @@ -16124,6 +17031,8 @@ def _norm_stem(val: Any) -> str: "rt": int(rf_val), "cpore": round(float(cpore), 4), "cperm": round(float(cperm), 4), + "experiment_type": exp_type, + "pc_domain": pc_dom, "pc_curve": pc_sorted, "sw_curve": sw_sorted, } @@ -16220,6 +17129,9 @@ def workspace_swirr_fit( if req.reference_pc_psi is not None else (req.referencePcPsi if req.referencePcPsi is not None else 50.0) ) + pc_domain = str(req.pc_domain or req.pcDomain or "lab").strip().lower() + if pc_domain not in ("lab", "reservoir"): + pc_domain = "lab" equation_type = ( str(req.equation_type or req.equationType or "rqi_power").strip().lower() ) @@ -16257,6 +17169,9 @@ def workspace_swirr_fit( else: excluded_set.add(x_s) + cutoffs_list = sorted( + float(c) for c in (req.cutoffs or [0.5, 1.2, 2.5, 5.0]) if c is not None + ) raw_plugs = _extract_project_scal_plugs_for_swirr( project_id, well_names=req.well_names, @@ -16267,6 +17182,7 @@ def workspace_swirr_fit( zones=req.zones, min_depth=req.min_depth, max_depth=req.max_depth, + pc_domain=pc_domain, ) plug_rows: List[Dict[str, Any]] = [] @@ -16280,6 +17196,8 @@ def workspace_swirr_fit( cperm = float(p["cperm"]) rqi_ratio = math.sqrt(cperm / max(0.001, cpore)) rqi_um = 0.0314 * rqi_ratio + phiz = cpore / max(1e-4, 1.0 - cpore) + fzi_um = rqi_um / max(1e-6, phiz) pid = str(p["plug_id"]) is_excl = pid in excluded_set or pid.replace("::", ":", 1) in excluded_set is_incl = bool(valid_pc and not is_excl) @@ -16289,6 +17207,7 @@ def workspace_swirr_fit( **p, "rqi_ratio": round(rqi_ratio, 4), "rqi": round(rqi_um, 4), + "fzi": round(fzi_um, 3), "max_pc": round(max_pc, 2), "sw_at_max_pc": round(sw_at_max, 4), "extracted_swirr": round(ext_swirr, 4), @@ -16388,21 +17307,34 @@ def _fit_subset(subset: List[Dict[str, Any]], scope_key: str) -> Dict[str, Any]: global_rule = _fit_subset(incl_plugs, "global") rules_out["global"] = global_rule - all_rts = sorted({int(p["rt"]) for p in plug_rows if p.get("rt") is not None}) + # Ensure all rock types defined by cutoffs are included even if zero plugs fall into them + cutoff_rts = set(range(1, len(cutoffs_list) + 2)) + plug_rts = {int(p["rt"]) for p in plug_rows if p.get("rt") is not None} + all_rts = sorted(cutoff_rts | plug_rts) for rt_val in all_rts: rt_key = str(rt_val) rt_subset = [p for p in incl_plugs if int(p["rt"]) == rt_val] if len(rt_subset) >= 1: rules_out[rt_key] = _fit_subset(rt_subset, rt_key) + elif ( + isinstance(req.rules, dict) + and rt_key in req.rules + and isinstance(req.rules[rt_key], dict) + ): + rules_out[rt_key] = _fit_subset(rt_subset, rt_key) else: rules_out[rt_key] = { **global_rule, "scope": rt_key, "count": 0, + "r2": None, + "rmse": None, + "is_fallback": True, } cfg_eval = { "extractionMode": extraction_mode, + "pcDomain": pc_domain, "referencePcPsi": ref_pc, "equationType": equation_type, "fitScope": fit_scope, @@ -16773,6 +17705,46 @@ def _calc_dist_summary( } +@router.post( + "/multi_well_volumetrics/cutoffs_sensitivity", + summary="Run empirical cutoffs sensitivity analysis (Vsh, Phi, Sw vs HCPV & Net Pay) across project wells", +) +def workspace_multi_well_cutoffs_sensitivity( + project_id: int, req: WorkspaceMultiWellCutoffsSensitivityRequest +) -> Dict[str, Any]: + """Perform cutoffs sensitivity analysis across multi-well evaluated logs using PRMS HCPV recovery percentiles.""" + try: + well_dfs = _load_multi_well_dfs( + project_id, + well_names=req.well_names, + min_depth=req.min_depth, + max_depth=req.max_depth, + zones=req.zones, + ) + if not well_dfs: + raise ValueError("No wells found or selected in project.") + + merged_df = pd.concat(well_dfs, ignore_index=True) + from quick_pp.ressum import cutoffs_analysis + + sens = cutoffs_analysis( + merged_df, + percentile=req.percentile, + plot=False, + return_dict=True, + ) + return _sanitize_for_json(sens) + except HTTPException: + raise + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) from e + except Exception as e: + logger.error(f"Failed cutoffs sensitivity analysis: {e}", exc_info=True) + raise HTTPException( + status_code=500, detail=f"Cutoffs sensitivity analysis failed: {e}" + ) from e + + @router.post( "/multi_well_volumetrics", summary="Run multi-well volumetric assessment and Latin Hypercube Monte Carlo uncertainty across project wells", @@ -16803,8 +17775,11 @@ def workspace_multi_well_volumetrics( sw_cut = float(req.cut_offs.get("SWT", req.cut_offs.get("SWE", 0.80))) cutoffs_dict = {"VSHALE": vsh_cut, "PHIT": phi_cut, "SWT": sw_cut} - # 0. Load project ancillary data to inherit SHF FWL and fluid contacts + # 0. Load SHF parameters, module_params, and well fluid contacts to inherit Step 5 SHF & FPT contacts anc_data: Dict[str, Any] = {} + shf_mp_params: Dict[str, Any] = {} + shf_mp_fits: Dict[str, Any] = {} + well_contacts_map: Dict[str, Dict[str, float]] = {} try: with get_db() as session: proj_inst = db_objects.Project.load(session, project_id=project_id) @@ -16815,49 +17790,157 @@ def workspace_multi_well_volumetrics( ) if not isinstance(anc_data, dict): anc_data = {} + + # Query database fluid contacts across project wells + try: + all_wns = proj_inst.get_well_names() + for wn_item in all_wns: + try: + w_obj = proj_inst.get_well(wn_item) + fc_df = w_obj.get_fluid_contacts() + if isinstance(fc_df, pd.DataFrame) and not fc_df.empty: + for _, fc_row in fc_df.iterrows(): + c_t = ( + str( + fc_row.get("contact_type") + or fc_row.get("name") + or "" + ) + .strip() + .upper() + ) + c_d = fc_row.get("depth") + c_z = str(fc_row.get("zone") or "").strip() + if c_t and c_d is not None and pd.notna(c_d): + well_contacts_map.setdefault(wn_item, {})[ + c_t + ] = float(c_d) + if c_z: + well_contacts_map.setdefault(c_z, {})[ + c_t + ] = float(c_d) + except Exception: + continue + except Exception: + pass + except Exception: + pass + + # Load saved project module_params (where Step 5 SHF saves fwl, fwlByZone, fluidSystem, fits) + try: + mp_all, _ = _load_project_module_params(project_id) + shf_mp_dict = mp_all.get("shf") if isinstance(mp_all, dict) else {} + if isinstance(shf_mp_dict, dict) and shf_mp_dict: + # Look for matching zone entry or 'ALL' or first available entry + entry_candidates = [] + if req.zones: + for zk in req.zones: + entry_candidates.append(zk) + entry_candidates.append(f"zone:{zk}") + entry_candidates.extend(["all", "ALL", "default"]) + chosen_entry = None + for cand in entry_candidates: + if cand in shf_mp_dict: + chosen_entry = shf_mp_dict[cand] + break + if not chosen_entry and shf_mp_dict: + chosen_entry = next(iter(shf_mp_dict.values())) + if isinstance(chosen_entry, dict): + ep = chosen_entry.get("params") or {} + if isinstance(ep, dict): + shf_mp_params = ep.get("shfParams") or {} + shf_mp_fits = ep.get("fits") or chosen_entry.get("fits") or {} except Exception: pass + # Combine SHF parameters prioritizing request payload, then saved module_params, then ancillary + req_shf = req.shf_params or {} shf_anc = anc_data.get("shf_params") or {} shf_module_anc = anc_data.get("shf") or {} + + shf_global_fwl = ( + req_shf.get("fwl") + if req_shf.get("fwl") is not None + else ( + shf_mp_params.get("fwl") + if shf_mp_params.get("fwl") is not None + else shf_anc.get("fwl") + ) + ) + if shf_global_fwl is not None: + shf_global_fwl = float(shf_global_fwl) + + shf_zonal_fwl: Dict[str, float] = {} + for z_src in ( + shf_anc.get("fwlByZone"), + shf_mp_params.get("fwlByZone"), + req_shf.get("fwl_by_zone"), + ): + if isinstance(z_src, dict): + for zk, zv in z_src.items(): + if zv is not None and pd.notna(zv): + try: + shf_zonal_fwl[str(zk).strip()] = float(zv) + except (ValueError, TypeError): + pass + + shf_fluid_system = ( + req_shf.get("fluid_system") + or shf_mp_params.get("fluidSystem") + or shf_anc.get("fluid_system") + or ( + "gas" + if req.reservoir_type == "gas_only" + else ("oil" if req.reservoir_type == "oil_only" else "auto") + ) + ) + shf_fits_anc = ( - shf_anc.get("fits") + req_shf.get("fits") + or shf_mp_fits + or shf_anc.get("fits") or (shf_module_anc.get("fits") if isinstance(shf_module_anc, dict) else {}) or {} ) shf_a_default = 0.35 shf_b_default = -0.45 shf_swirr_default = 0.12 - shf_ift_default = float(shf_anc.get("ift", 30.0)) - shf_theta_default = float(shf_anc.get("theta", 30.0)) - shf_gw_default = float(shf_anc.get("gw", 1.05)) - shf_ghc_default = float(shf_anc.get("ghc", 0.80 if req.compute_oil else 0.20)) + shf_ift_default = float( + req_shf.get("ift") or shf_mp_params.get("ift") or shf_anc.get("ift", 30.0) + ) + shf_theta_default = float( + req_shf.get("theta") + or shf_mp_params.get("theta") + or shf_anc.get("theta", 30.0) + ) + shf_gw_default = float( + req_shf.get("gw") or shf_mp_params.get("gw") or shf_anc.get("gw", 1.05) + ) + shf_ghc_default = float( + req_shf.get("ghc") + or shf_mp_params.get("ghc") + or shf_anc.get("ghc", 0.80 if req.compute_oil else 0.20) + ) if isinstance(shf_fits_anc, dict) and shf_fits_anc: first_fit = next(iter(shf_fits_anc.values()), {}) if isinstance(first_fit, dict): shf_a_default = float(first_fit.get("a", shf_a_default)) shf_b_default = float(first_fit.get("b", shf_b_default)) - if shf_anc.get("swirr") is not None: + if req_shf.get("a") is not None: + shf_a_default = float(req_shf["a"]) + if req_shf.get("b") is not None: + shf_b_default = float(req_shf["b"]) + if req_shf.get("swirr") is not None: + shf_swirr_default = float(req_shf["swirr"]) + elif shf_anc.get("swirr") is not None: shf_swirr_default = float(shf_anc["swirr"]) elif shf_anc.get("swirr_params", {}).get("mean_swirr") is not None: shf_swirr_default = float(shf_anc["swirr_params"]["mean_swirr"]) - if req.shf_params: - shf_a_default = float(req.shf_params.get("a", shf_a_default)) - shf_b_default = float(req.shf_params.get("b", shf_b_default)) - shf_swirr_default = float(req.shf_params.get("swirr", shf_swirr_default)) - shf_ift_default = float(req.shf_params.get("ift", shf_ift_default)) - shf_theta_default = float(req.shf_params.get("theta", shf_theta_default)) - shf_gw_default = float(req.shf_params.get("gw", shf_gw_default)) - shf_ghc_default = float(req.shf_params.get("ghc", shf_ghc_default)) - + # Inherited database fluid contacts contacts_anc_raw = anc_data.get("fluid_contacts") inherited_contacts: Dict[str, float] = {} - - shf_global_fwl = shf_anc.get("fwl") - shf_zonal_fwl = shf_anc.get("fwlByZone") or {} - if isinstance(contacts_anc_raw, list): for c in contacts_anc_raw: if isinstance(c, dict): @@ -16874,92 +17957,336 @@ def workspace_multi_well_volumetrics( if c_name and c_tvd is not None and pd.notna(c_tvd): inherited_contacts[c_name] = float(c_tvd) + # Merge well-level database contacts into inherited_contacts if not present + for _, w_c_dict in well_contacts_map.items(): + for c_k, c_v in w_c_dict.items(): + if c_k not in inherited_contacts: + inherited_contacts[c_k] = c_v + + def _align_contact_depth( + c_val: Optional[float], ref_arr: np.ndarray + ) -> Optional[float]: + """Ensure contact TVDSS sign matches the depth array sign (subsea negative vs absolute positive).""" + if c_val is None or len(ref_arr) == 0: + return c_val + med = float(np.median(ref_arr)) + if med > 0 and c_val < 0: + return abs(c_val) + elif med < 0 and c_val > 0: + return -abs(c_val) + return c_val + def _get_zone_contacts(z_n: str) -> Dict[str, Optional[float]]: z_override = req.contacts_by_zone.get(z_n) or {} - owc_val = ( - z_override.get("owc") if z_override.get("owc") is not None else req.owc - ) - goc_val = ( - z_override.get("goc") if z_override.get("goc") is not None else req.goc + if req.contact_source == "custom": + owc_val = ( + z_override.get("owc") + if z_override.get("owc") is not None + else req.owc + ) + goc_val = ( + z_override.get("goc") + if z_override.get("goc") is not None + else req.goc + ) + gwc_val = ( + z_override.get("gwc") + if z_override.get("gwc") is not None + else req.gwc + ) + return {"owc": owc_val, "goc": goc_val, "gwc": gwc_val} + + # INHERIT (Step 5 SHF & FPT) MODE: + # 1. Check zone-specific override if explicitly provided + owc_val = z_override.get("owc") + goc_val = z_override.get("goc") + gwc_val = z_override.get("gwc") + + # 2. Check zonal FWL from Step 5 SHF + z_fwl = shf_zonal_fwl.get(z_n) + if z_fwl is None: + z_fwl = shf_global_fwl + + # Check database contacts for this zone + z_db = well_contacts_map.get(z_n, {}) + if z_fwl is None: + z_fwl = z_db.get("FWL") or inherited_contacts.get("FWL") + + if goc_val is None: + goc_val = z_db.get("GOC") or inherited_contacts.get("GOC") + + is_gas = ( + req.reservoir_type == "gas_only" + or shf_fluid_system in ("gas", "gas_water") + or (req.compute_gas and not req.compute_oil) ) - gwc_val = ( - z_override.get("gwc") if z_override.get("gwc") is not None else req.gwc + is_oil = ( + req.reservoir_type == "oil_only" + or shf_fluid_system in ("oil", "oil_water") + or (req.compute_oil and not req.compute_gas) ) - if req.contact_source == "inherit": - if owc_val is None and gwc_val is None: - if z_n in shf_zonal_fwl and shf_zonal_fwl[z_n] is not None: - owc_val = float(shf_zonal_fwl[z_n]) - elif shf_global_fwl is not None: - owc_val = float(shf_global_fwl) - elif "OWC" in inherited_contacts: - owc_val = inherited_contacts["OWC"] - elif "GWC" in inherited_contacts: - gwc_val = inherited_contacts["GWC"] - - if goc_val is None and "GOC" in inherited_contacts: - goc_val = inherited_contacts["GOC"] + if is_gas: + if gwc_val is None: + gwc_val = ( + z_fwl + or z_db.get("GWC") + or inherited_contacts.get("GWC") + or z_db.get("OWC") + or inherited_contacts.get("OWC") + ) + elif is_oil: + if owc_val is None: + owc_val = z_fwl or z_db.get("OWC") or inherited_contacts.get("OWC") + else: + # Dual / Auto regime: + if goc_val is not None: + if owc_val is None: + owc_val = ( + z_fwl or z_db.get("OWC") or inherited_contacts.get("OWC") + ) + else: + if owc_val is None and gwc_val is None: + if z_fwl is not None: + if req.compute_gas and not req.compute_oil: + gwc_val = z_fwl + else: + owc_val = z_fwl + elif "OWC" in inherited_contacts: + owc_val = inherited_contacts["OWC"] + elif "GWC" in inherited_contacts: + gwc_val = inherited_contacts["GWC"] return {"owc": owc_val, "goc": goc_val, "gwc": gwc_val} # 1. Compute per-well reservoir summary + def _find_curve(candidates: tuple, df: pd.DataFrame) -> Optional[str]: + for cand in candidates: + for c in df.columns: + if c.strip().upper() == cand.upper(): + if pd.to_numeric(df[c], errors="coerce").notna().any(): + return c + return None + well_records: List[Dict[str, Any]] = [] for wdf in well_dfs: wn = str(wdf["WELL_NAME"].iloc[0]) + + # Robust depth column detection + depth_col = next( + ( + c + for c in ("DEPTH", "DEPT", "MD") + if c in wdf.columns + and pd.to_numeric(wdf[c], errors="coerce").notna().any() + ), + "DEPTH", + ) depth = ( - pd.to_numeric(wdf["DEPTH"], errors="coerce") - if "DEPTH" in wdf.columns + pd.to_numeric(wdf[depth_col], errors="coerce") + if depth_col in wdf.columns else pd.Series([], dtype=float) ) + + # Robust TVDSS & TVD column detection + tvdss_col = next( + ( + c + for c in ("TVDSS", "DEPT_TVDSS", "DEPTH_TVDSS", "TVD_SS") + if c in wdf.columns + and pd.to_numeric(wdf[c], errors="coerce").notna().any() + ), + None, + ) + tvd_col = next( + ( + c + for c in ("TVD", "DEPT_TVD", "DEPTH_TVD") + if c in wdf.columns + and pd.to_numeric(wdf[c], errors="coerce").notna().any() + ), + None, + ) tvd = ( - pd.to_numeric(wdf["TVDSS"], errors="coerce") - if "TVDSS" in wdf.columns + pd.to_numeric(wdf[tvdss_col], errors="coerce") + if tvdss_col is not None else ( - pd.to_numeric(wdf["TVD"], errors="coerce") - if "TVD" in wdf.columns + pd.to_numeric(wdf[tvd_col], errors="coerce") + if tvd_col is not None else depth ) ) + + # Robust Vclay / Vshale curve detection (picks up saved interpreted curve from Lithology step) + vclay_candidates = ( + "VCLAY", + "VSHALE", + "VCL", + "VSH", + "VWCL", + "VSH_GR", + "VSHALE_COMP", + "VCLAY_COMP", + "VSH_STEIBER", + "VSH_CLAVIER", + "VSH_LARIONOV", + "VSH_LINEAR", + ) + vclay_col = _find_curve(vclay_candidates, wdf) vclay = ( - pd.to_numeric(wdf["VCLAY"], errors="coerce") - if "VCLAY" in wdf.columns - else ( - pd.to_numeric(wdf["VSHALE"], errors="coerce") - if "VSHALE" in wdf.columns - else pd.Series(0.0, index=wdf.index, dtype=float) - ) + pd.to_numeric(wdf[vclay_col], errors="coerce") + if vclay_col is not None + else pd.Series(0.0, index=wdf.index, dtype=float) ) + + # Robust Porosity curve detection (picks up saved interpreted curve from Porosity step) + phi_candidates = ( + "PHIT", + "PHIE", + "PHIT_COMP", + "PHIE_COMP", + "PHIT_ND", + "PHIT_D", + "PHIT_S", + "POROSITY", + "POR", + ) + phi_col = _find_curve(phi_candidates, wdf) phit = ( - pd.to_numeric(wdf["PHIT"], errors="coerce") - if "PHIT" in wdf.columns - else ( - pd.to_numeric(wdf["PHIE"], errors="coerce") - if "PHIE" in wdf.columns - else pd.Series(np.nan, index=wdf.index, dtype=float) - ) + pd.to_numeric(wdf[phi_col], errors="coerce") + if phi_col is not None + else pd.Series(np.nan, index=wdf.index, dtype=float) ) - swt = ( - pd.to_numeric(wdf["SWT"], errors="coerce") - if "SWT" in wdf.columns - else ( - pd.to_numeric(wdf["SWE"], errors="coerce") - if "SWE" in wdf.columns - else pd.Series(np.nan, index=wdf.index, dtype=float) + + # Robust Water Saturation curve detection: + # If saturation_method == "shf", prioritize saved SHF curve from Step 5 SHF! + if req.saturation_method == "shf": + sw_candidates = ( + "SHF", + "SW_SHF", + "SWT", + "SWE", + "SW", + "SW_ARCHIE", + "SW_SIMANDOUX", + "SW_DUAL_WATER", + "SW_WS", + "SWT_COMP", + "SWE_COMP", + ) + else: + sw_candidates = ( + "SWT", + "SWE", + "SW", + "SW_ARCHIE", + "SW_SIMANDOUX", + "SW_DUAL_WATER", + "SW_WS", + "SWT_COMP", + "SWE_COMP", + "SHF", + "SW_SHF", ) + sw_col = _find_curve(sw_candidates, wdf) + swt = ( + pd.to_numeric(wdf[sw_col], errors="coerce") + if sw_col is not None + else pd.Series(np.nan, index=wdf.index, dtype=float) ) - perm_col = ( - "PERM_TRANS" - if ("PERM_TRANS" in wdf.columns and wdf["PERM_TRANS"].notna().any()) - else "PERM" + + # Robust Permeability curve detection (picks up saved curve from Perm Transform step) + perm_candidates = ( + "PERM_TRANS", + "PERM", + "PERM_COMP", + "PERM_TIMUR", + "PERM_COATES", + "KLOGH", + "PERMEABILITY", + "K", + "CPERM", + "CORE_PERM", ) - perm = ( - pd.to_numeric(wdf[perm_col], errors="coerce") - if perm_col in wdf.columns - else pd.Series(0.0, index=wdf.index, dtype=float) + perm_col = _find_curve(perm_candidates, wdf) + if perm_col is not None: + perm = pd.to_numeric(wdf[perm_col], errors="coerce") + else: + # Fallback: empirical poro-perm estimate so permeability is not zero + # k = 10^(14 * phit - 1.5) bounded to [0.01, 10000.0] + perm = (10.0 ** (14.0 * phit.fillna(0.0) - 1.5)).clip(0.01, 10000.0) + + # SHF curve detection for dedicated Sw SHF column + shf_candidates = ( + "SHF", + "SW_SHF", + "SW_J", + "SW_HEIGHT", + "SW_LAMBDA", + ) + shf_col = _find_curve(shf_candidates, wdf) + shf_series = ( + pd.to_numeric(wdf[shf_col], errors="coerce") + if shf_col is not None + else None + ) + + # If SHF curve is not directly in well data, evaluate SHF on the fly if Step 5 params exist + if shf_series is None and shf_global_fwl is not None: + try: + zc_fwl = ( + _get_zone_contacts("ALL").get("owc") + or _get_zone_contacts("ALL").get("gwc") + or shf_global_fwl + ) + if zc_fwl is not None and len(tvd) > 0: + ref_fwl = _align_contact_depth( + zc_fwl, tvd.to_numpy(dtype=float) + ) + if ref_fwl is not None: + h_above_fwl = np.maximum( + 0.0, ref_fwl - tvd.to_numpy(dtype=float) + ) + shf_p = req.shf_params or shf_mp_params or {} + shf_a_val = float( + getattr(req, "shf_a", 0.0) + or shf_p.get("a", 0.0) + or shf_a_default + ) + shf_b_val = float( + getattr(req, "shf_b", 0.0) + or shf_p.get("b", 0.0) + or shf_b_default + ) + if shf_a_val > 0 and shf_b_val > 0: + h_safe = np.maximum(h_above_fwl, 0.01) + sw_eval = np.where( + h_above_fwl > 0, + np.clip( + (h_safe / shf_a_val) + ** (-1.0 / max(0.01, shf_b_val)), + 0.02, + 1.0, + ), + 1.0, + ) + shf_series = pd.Series( + sw_eval, index=wdf.index, dtype=float + ) + except Exception: + pass + + zones_col = next( + ( + c + for c in ("ZONES", "ZONE") + if c.upper() in [x.upper() for x in wdf.columns] + ), + None, ) zones = ( - wdf["ZONES"].fillna("ALL").astype(str) - if "ZONES" in wdf.columns + wdf[zones_col].fillna("ALL").astype(str) + if zones_col is not None else pd.Series("ALL", index=wdf.index, dtype=str) ) @@ -16972,7 +18299,7 @@ def _get_zone_contacts(z_n: str) -> Dict[str, Optional[float]]: vshale=vclay.fillna(0.0), phit=phit.fillna(0.0), swt=swt.fillna(1.0), - perm=perm.fillna(0.0), + perm=perm.fillna(0.01).clip(lower=0.001), zones=zones, cutoffs=cutoffs_dict, ) @@ -16999,90 +18326,198 @@ def _get_zone_contacts(z_n: str) -> Dict[str, Optional[float]]: if req.zones and z_name not in req.zones: continue + # 4 cutoff levels: ALL, ROCK (phit cut off), RES (phit + vshale cutoff), PAY (phit + vshale + swt cutoff) + raw_flag = str(row.get("flag", "pay")).strip().lower() + flag_label = { + "all": "ALL", + "rock": "ROCK", + "reservoir": "RES", + "pay": "PAY", + }.get(raw_flag, raw_flag.upper()) + top_v = float(row.get("top", 0.0)) bot_v = float(row.get("bottom", 0.0)) gross_v = float(row.get("gross", 0.0)) - net_res_v = float(row.get("net_res", row.get("net", 0.0))) - ntg_res_v = float(row.get("ntg_res", row.get("ntg", 0.0))) - net_pay_v = float(row.get("net_pay", row.get("net", 0.0))) - ntg_pay_v = float(row.get("ntg_pay", row.get("ntg", 0.0))) - phie_pay_v = float(row.get("av_phit", row.get("av_phie", 0.0))) - sw_pay_v = float(row.get("av_swt", row.get("av_sw", 1.0))) - perm_pay_v = float(row.get("av_perm", 0.0)) - hcpt_v = float( - row.get("hcpt", net_pay_v * phie_pay_v * (1.0 - sw_pay_v)) + net_v = float(row.get("net", 0.0)) + ntg_v = float(row.get("ntg", 0.0)) + + # Porosity (PHIT) for this cutoff stage + phi_v = float( + row.get("av_phit") + if pd.notna(row.get("av_phit")) and row.get("av_phit") > 0 + else ( + row.get("av_phit_pay") + if pd.notna(row.get("av_phit_pay")) + and row.get("av_phit_pay") > 0 + else 0.0 + ) ) - - # Contact partitioning for this well & zone - zc = _get_zone_contacts(z_name) - owc_d = zc.get("owc") - goc_d = zc.get("goc") - gwc_d = zc.get("gwc") - - z_mask = (zones == z_name) & pay_mask - z_tvd = ( - tvd[z_mask].to_numpy(dtype=float) - if z_mask.any() - else np.array([]) + # Water Saturation for this cutoff stage + sw_v = float( + row.get("av_swt") + if pd.notna(row.get("av_swt")) + else ( + row.get("av_sw_pay") + if pd.notna(row.get("av_sw_pay")) + else 1.0 + ) ) + # Geometric mean Permeability for this cutoff stage + perm_v = float( + row.get("av_perm_gm") + if pd.notna(row.get("av_perm_gm")) and row.get("av_perm_gm") > 0 + else ( + row.get("av_perm_geom_pay") + if pd.notna(row.get("av_perm_geom_pay")) + and row.get("av_perm_geom_pay") > 0 + else ( + row.get("av_perm_am") + if pd.notna(row.get("av_perm_am")) + and row.get("av_perm_am") > 0 + else 0.0 + ) + ) + ) + hcpt_v = float(row.get("hcpt", net_v * phi_v * (1.0 - sw_v))) + + # Average SHF water saturation for this flag interval (if available) + sw_shf_v = None + if shf_series is not None: + flag_samples_mask = zones == z_name + if flag_label == "ROCK": + flag_samples_mask = flag_samples_mask & ( + phit.fillna(0.0) >= phi_cut + ) + elif flag_label == "RES": + flag_samples_mask = ( + flag_samples_mask + & (vclay.fillna(1.0) <= vsh_cut) + & (phit.fillna(0.0) >= phi_cut) + ) + elif flag_label == "PAY": + flag_samples_mask = flag_samples_mask & pay_mask - oil_count = 0 - gas_count = 0 - if len(z_tvd) > 0: - for d_val in z_tvd: - if goc_d is not None and d_val <= goc_d: - gas_count += 1 - elif ( - goc_d is not None - and owc_d is not None - and goc_d < d_val <= owc_d - ): - oil_count += 1 - elif goc_d is None and owc_d is not None: - if d_val <= owc_d: - oil_count += 1 - elif goc_d is None and gwc_d is not None: - if d_val <= gwc_d: - gas_count += 1 + z_shf = shf_series[flag_samples_mask].to_numpy(dtype=float) + z_phi = phit[flag_samples_mask].to_numpy(dtype=float) + valid_shf = ( + np.isfinite(z_shf) & np.isfinite(z_phi) & (z_shf > 0) + ) + if np.any(valid_shf): + pv = np.maximum(0.0, z_phi[valid_shf]) + pv_sum = float(np.sum(pv)) + if pv_sum > 0: + sw_shf_v = float(np.sum(pv * z_shf[valid_shf]) / pv_sum) else: - if req.reservoir_type == "gas_only": + sw_shf_v = float(np.mean(z_shf[valid_shf])) + sw_shf_v = round(min(1.0, max(0.0, sw_shf_v)), 4) + + # Fluid contact partitioning applies to PAY interval + oil_pay_m = 0.0 + gas_pay_m = 0.0 + + if flag_label == "PAY" and net_v > 0: + zc = _get_zone_contacts(z_name) + owc_d = zc.get("owc") + goc_d = zc.get("goc") + gwc_d = zc.get("gwc") + + z_mask = (zones == z_name) & pay_mask + z_tvd = ( + tvd[z_mask].to_numpy(dtype=float) + if z_mask.any() + else np.array([]) + ) + + ref_goc = _align_contact_depth(goc_d, z_tvd) + ref_owc = _align_contact_depth(owc_d, z_tvd) + ref_gwc = _align_contact_depth(gwc_d, z_tvd) + + oil_count = 0 + gas_count = 0 + if len(z_tvd) > 0: + for d_val in z_tvd: + if ref_goc is not None and d_val <= ref_goc: gas_count += 1 - else: + elif ( + ref_goc is not None + and ref_owc is not None + and ref_goc < d_val <= ref_owc + ): oil_count += 1 + elif ref_goc is None and ref_owc is not None: + if d_val <= ref_owc: + oil_count += 1 + elif ref_goc is None and ref_gwc is not None: + if d_val <= ref_gwc: + gas_count += 1 + else: + if req.reservoir_type == "gas_only": + gas_count += 1 + elif req.reservoir_type == "oil_only": + oil_count += 1 + else: + if req.compute_gas and not req.compute_oil: + gas_count += 1 + else: + oil_count += 1 - oil_pay_m = round(oil_count * sample_dz, 2) - gas_pay_m = round(gas_count * sample_dz, 2) + oil_pay_m = round(oil_count * sample_dz, 2) + gas_pay_m = round(gas_count * sample_dz, 2) - if oil_pay_m == 0 and gas_pay_m == 0 and net_pay_v > 0: - if req.reservoir_type == "gas_only": - gas_pay_m = net_pay_v - elif req.reservoir_type == "oil_only": - oil_pay_m = net_pay_v - else: - oil_pay_m = net_pay_v if req.compute_oil else 0.0 - gas_pay_m = ( - net_pay_v - if (req.compute_gas and not req.compute_oil) - else 0.0 - ) + tot_pay_calc = oil_pay_m + gas_pay_m + if tot_pay_calc > 0 and abs(tot_pay_calc - net_v) > 0.05: + oil_pay_m = round(oil_pay_m * (net_v / tot_pay_calc), 2) + gas_pay_m = round(net_v - oil_pay_m, 2) + + if oil_pay_m == 0 and gas_pay_m == 0: + if req.reservoir_type == "gas_only": + gas_pay_m = net_v + elif req.reservoir_type == "oil_only": + oil_pay_m = net_v + else: + oil_pay_m = net_v if req.compute_oil else 0.0 + gas_pay_m = ( + net_v + if (req.compute_gas and not req.compute_oil) + else 0.0 + ) well_records.append( { "well_name": wn, "zone": z_name, + "flag": flag_label, "top": round(top_v, 2), "bottom": round(bot_v, 2), "gross": round(gross_v, 2), - "net_res": round(net_res_v, 2), - "ntg_res": round(ntg_res_v, 4), - "net_pay": round(net_pay_v, 2), + "net": round(net_v, 2), + "ntg": round(ntg_v, 4), "net_oil_pay": oil_pay_m, "net_gas_pay": gas_pay_m, - "ntg_pay": round(ntg_pay_v, 4), - "phie": round(phie_pay_v, 4), - "sw": round(sw_pay_v, 4), - "perm_geom": round(perm_pay_v, 2), + "phit": round(phi_v, 4), + "sw": round(sw_v, 4), + "sw_shf": sw_shf_v, + "perm_geom": round(perm_v, 2), "hcpt": round(hcpt_v, 2), + # Backward compatibility aliases + "net_res": round(net_v, 2), + "ntg_res": round(ntg_v, 4), + "net_pay": round(net_v, 2), + "ntg_pay": round(ntg_v, 4), + "phie": round(phi_v, 4), + "curves_used": { + "vsh": vclay_col or "None", + "phi": phi_col or "None", + "sw": sw_col or "None", + "perm": perm_col + or ("Estimated (phi)" if perm_col is None else "None"), + "shf": shf_col + or ( + "Computed (Step 5)" + if shf_series is not None + else "None" + ), + }, } ) except Exception: @@ -17142,15 +18577,30 @@ def _pct(arr: np.ndarray) -> Dict[str, float]: rows = zone_groups[z_name] w_count = len({r["well_name"] for r in rows}) - gross_vals = [r["gross"] for r in rows if r["gross"] > 0] - net_res_vals = [r["net_res"] for r in rows] - net_pay_vals = [r["net_pay"] for r in rows] - net_oil_pay_vals = [r.get("net_oil_pay", r["net_pay"]) for r in rows] - net_gas_pay_vals = [r.get("net_gas_pay", 0.0) for r in rows] - phie_vals = [r["phie"] for r in rows if r["phie"] > 0] - sw_vals = [r["sw"] for r in rows if r["sw"] > 0] - perm_vals = [r["perm_geom"] for r in rows if r["perm_geom"] > 0] - hcpt_vals = [r["hcpt"] for r in rows] + # For volumetric Monte Carlo distributions, strictly use the PAY rows (or RES if pay is 0) + pay_rows = [r for r in rows if r.get("flag") == "PAY"] + if not pay_rows: + pay_rows = [r for r in rows if r.get("flag") == "RES"] or rows + + res_rows = [r for r in rows if r.get("flag") == "RES"] + + gross_vals = [r["gross"] for r in pay_rows if r["gross"] > 0] + net_res_vals = ( + [r["net"] for r in res_rows] + if res_rows + else [r["net"] for r in pay_rows] + ) + net_pay_vals = [r["net"] for r in pay_rows] + net_oil_pay_vals = [r.get("net_oil_pay", r["net"]) for r in pay_rows] + net_gas_pay_vals = [r.get("net_gas_pay", 0.0) for r in pay_rows] + phie_vals = [ + r.get("phit", r.get("phie", 0.0)) + for r in pay_rows + if r.get("phit", r.get("phie", 0.0)) > 0 + ] + sw_vals = [r["sw"] for r in pay_rows if r["sw"] > 0] + perm_vals = [r["perm_geom"] for r in pay_rows if r["perm_geom"] > 0] + hcpt_vals = [r["hcpt"] for r in pay_rows] mean_gross = float(np.mean(gross_vals)) if gross_vals else 0.0 mean_net_res = float(np.mean(net_res_vals)) if net_res_vals else 0.0 @@ -17613,6 +19063,7 @@ def _eval_vol( "mean_gas_pay": round(mean_gas_pay, 2), "ntg_pay": round(ntg_pay, 3), "mean_phie": round(mean_phie, 3), + "mean_phit": round(mean_phie, 3), "mean_sw": round(mean_sw, 3), "mean_perm_geom": round(mean_perm, 2), "mean_hcpt": round(mean_hcpt, 2), @@ -17729,9 +19180,54 @@ def _eval_vol( } # Basis of Estimate & Assumptions Register - primary_owc = req.owc or inherited_contacts.get("OWC") or shf_global_fwl - primary_goc = req.goc or inherited_contacts.get("GOC") - primary_gwc = req.gwc or inherited_contacts.get("GWC") + is_gas_regime = ( + req.reservoir_type == "gas_only" + or shf_fluid_system in ("gas", "gas_water") + or (req.compute_gas and not req.compute_oil) + ) + is_oil_regime = ( + req.reservoir_type == "oil_only" + or shf_fluid_system in ("oil", "oil_water") + or (req.compute_oil and not req.compute_gas) + ) + + if req.contact_source == "custom": + primary_owc = req.owc + primary_goc = req.goc + primary_gwc = req.gwc + else: + # Inherit from Step 5 SHF & FPT / well contacts + if is_gas_regime: + primary_gwc = ( + shf_global_fwl + or inherited_contacts.get("GWC") + or inherited_contacts.get("FWL") + or inherited_contacts.get("OWC") + ) + primary_owc = None + primary_goc = inherited_contacts.get("GOC") + elif is_oil_regime: + primary_owc = ( + shf_global_fwl + or inherited_contacts.get("OWC") + or inherited_contacts.get("FWL") + ) + primary_gwc = None + primary_goc = inherited_contacts.get("GOC") + else: + primary_owc = inherited_contacts.get("OWC") or shf_global_fwl + primary_goc = inherited_contacts.get("GOC") + primary_gwc = inherited_contacts.get("GWC") + + # If a single zone was evaluated, reflect its specific contacts + if len(zonal_summaries) == 1: + z_c_first = zonal_summaries[0].get("contacts") or {} + if z_c_first.get("owc") is not None: + primary_owc = z_c_first["owc"] + if z_c_first.get("goc") is not None: + primary_goc = z_c_first["goc"] + if z_c_first.get("gwc") is not None: + primary_gwc = z_c_first["gwc"] assumptions_register = { "standard": "SPE-PRMS (2018) Guidelines for Evaluation of Petroleum Reserves and Resources", @@ -17756,9 +19252,19 @@ def _eval_vol( "swt_max": sw_cut, }, "contacts": { - "source": "Inherited from Step 5 SHF / FPT" - if req.contact_source == "inherit" - else "Custom In-Situ TVDSS", + "source": "Inherited from Step 5 SHF" + if ( + req.contact_source == "inherit" + and (shf_global_fwl is not None or shf_zonal_fwl) + ) + else ( + "Inherited from FPT / Database" + if req.contact_source == "inherit" + else "Custom In-Situ TVDSS" + ), + "fwl": round(float(shf_global_fwl), 1) + if shf_global_fwl is not None + else None, "owc": round(float(primary_owc), 1) if primary_owc is not None else None, @@ -17768,13 +19274,25 @@ def _eval_vol( "gwc": round(float(primary_gwc), 1) if primary_gwc is not None else None, + "fluid_system": shf_fluid_system, "field_regime": ( - "Gas Cap + Oil Leg" - if (field_st["p50"] > 0 and field_gi["p50"] > field_ag["p50"]) + "Gas Reservoir" + if req.reservoir_type == "gas_only" else ( "Oil Reservoir (Solution Gas)" - if field_st["p50"] > 0 - else "Gas Reservoir" + if req.reservoir_type == "oil_only" + else ( + "Gas Cap + Oil Leg" + if ( + field_st["p50"] > 0 + and field_gi["p50"] > field_ag["p50"] + ) + else ( + "Oil Reservoir (Solution Gas)" + if field_st["p50"] > 0 + else "Gas Reservoir" + ) + ) ) ), }, @@ -17875,6 +19393,21 @@ def _eval_vol( except Exception: pass + # Empirical cutoffs sensitivity analysis (PRMS / SEC HCPV recovery) + cutoffs_sens_data = None + try: + from quick_pp.ressum import cutoffs_analysis + + merged_all_df = pd.concat(well_dfs, ignore_index=True) + cutoffs_sens_data = cutoffs_analysis( + merged_all_df, + percentile=95.0, + plot=False, + return_dict=True, + ) + except Exception as exc: + logger.debug(f"cutoffs_analysis in multi_well_volumetrics skipped: {exc}") + return _sanitize_for_json( { "project_id": project_id, @@ -17886,6 +19419,7 @@ def _eval_vol( "field_totals": field_totals, "contacts": assumptions_register["contacts"], "assumptions_register": assumptions_register, + "cutoffs_sensitivity": cutoffs_sens_data, } ) except HTTPException: diff --git a/quick_pp/app/backend/template/reports/report_print.css b/quick_pp/app/backend/template/reports/report_print.css index 0ddb28e1..d90ef761 100644 --- a/quick_pp/app/backend/template/reports/report_print.css +++ b/quick_pp/app/backend/template/reports/report_print.css @@ -89,6 +89,25 @@ body.qpp-report-print { border-collapse: collapse; margin: 10px 0 14px 0; font-size: 8.5pt; + table-layout: auto; +} + +.qpp-report-body td, +.qpp-report-body th { + overflow-wrap: break-word; + word-break: normal; +} + +.qpp-report-body td { + min-width: 3.2em; +} + +.qpp-report-body thead { + display: table-header-group; +} + +.qpp-report-body tr { + break-inside: avoid; page-break-inside: avoid; } @@ -227,7 +246,27 @@ body.qpp-report-print { break-before: page; } +@page { + @bottom-center { + content: "Page " counter(page); + font-size: 8pt; + color: #64748b; + } +} + @media print { + .qpp-report-container { + max-width: none !important; + padding: 0 !important; + margin: 0 !important; + } + .qpp-report-body table { + font-size: 7.5pt; + } + .qpp-report-body th, + .qpp-report-body td { + padding: 3px 5px; + } .no-print { display: none !important; } diff --git a/quick_pp/app/backend/template/reports/sections/01_executive_summary.md.j2 b/quick_pp/app/backend/template/reports/sections/01_executive_summary.md.j2 index eaaf34eb..aa22fc68 100644 --- a/quick_pp/app/backend/template/reports/sections/01_executive_summary.md.j2 +++ b/quick_pp/app/backend/template/reports/sections/01_executive_summary.md.j2 @@ -13,6 +13,16 @@ This Single-Well Computer-Processed Interpretation (CPI) & Formation Evaluation > **Petrophysicist Note:** {{ custom_notes }} {% endif %} +{% if gate_summary and (gate_summary.n_blocking > 0 or gate_summary.n_review > 0) %} +> **Evaluation QC status: {{ gate_summary.overall }}.** {{ gate_summary.n_blocking }} blocking and {{ gate_summary.n_review }} review item(s) were raised by the automated gate checks (Section 7). +{% for g in gate_summary.blocking %} +> * **{{ g.id }} (blocking):** {{ g.measured }} {{ g.action }} +{% endfor %} +{% for g in gate_summary.review %} +> * **{{ g.id }} (review):** {{ g.measured }} {{ g.action }} +{% endfor %} +{% endif %} + ### Table 1.1: Zonal Net Reservoir & Net Pay Summary — Well `{{ focal_well }}` | Zone | Interval (m MD) | Interval (m TVDss) | Gross (m) | Net Res (m) | $NTG_{res}$ | $\bar{V}_{sh,res}$ | $\bar{\phi}_{e,res}$ | $K_{geom,res}$ (mD) | Net Pay (m) | $NTG_{pay}$ | $\bar{\phi}_{e,pay}$ | $\bar{S}_{w,pay}$ | $HCPT$ (m) | @@ -33,13 +43,23 @@ This Single-Well Computer-Processed Interpretation (CPI) & Formation Evaluation {% if include_ai_commentary and ai_commentary.executive_summary %} {{ ai_commentary.executive_summary }} {% else %} -This technical petrophysical evaluation report documents the deterministic and probabilistic log, core, and special core analysis (SCAL) interpretation for **{{ project_name }}** across **{{ wells|length }}** evaluated well(s) (`{{ well_names|join(', ') }}`) targeting **{{ target_zones|join(', ') }}**, prepared for Static Geological Modeling (Petrel/RMS) and Dynamic Reservoir Simulation (Eclipse/Intersect) handover. +This technical petrophysical evaluation report documents the deterministic and probabilistic log, core, and special core analysis (SCAL) interpretation for **{{ project_name }}** across **{{ wells|length }}** evaluated {{ (wells|length) | pluralize('well') }} (`{{ well_names|join(', ') }}`) targeting **{{ target_zones|join(', ') }}**, prepared for Static Geological Modeling (Petrel/RMS) and Dynamic Reservoir Simulation (Eclipse/Intersect) handover. {% endif %} {% if custom_notes %} > **Petrophysicist Note:** {{ custom_notes }} {% endif %} +{% if gate_summary and (gate_summary.n_blocking > 0 or gate_summary.n_review > 0) %} +> **Handover status: {{ gate_summary.overall }}.** {{ gate_summary.n_blocking }} blocking and {{ gate_summary.n_review }} review item(s) were raised by the automated gate checks (Section 10). +{% for g in gate_summary.blocking %} +> * **{{ g.id }} (blocking):** {{ g.measured }} {{ g.action }} +{% endfor %} +{% for g in gate_summary.review %} +> * **{{ g.id }} (review):** {{ g.measured }} {{ g.action }} +{% endfor %} +{% endif %} + ### Table 1.1: Field-Wide Zonal Net Reservoir & Net Pay Summary (Thickness & Pore-Volume Weighted) | Zone | Wells | Mean Gross (m) | Mean Net Res (m) | $NTG_{res}$ | $\bar{V}_{sh,res}$ | $\bar{\phi}_{e,res}$ | $K_{geom,res}$ (mD) | Mean Net Pay (m) | $NTG_{pay}$ | $\bar{\phi}_{e,pay}$ | $\bar{S}_{w,pay}$ | Mean $HCPT$ (m) | diff --git a/quick_pp/app/backend/template/reports/sections/02_data_inventory.md.j2 b/quick_pp/app/backend/template/reports/sections/02_data_inventory.md.j2 index b7d9cb6d..800ee9e5 100644 --- a/quick_pp/app/backend/template/reports/sections/02_data_inventory.md.j2 +++ b/quick_pp/app/backend/template/reports/sections/02_data_inventory.md.j2 @@ -1,10 +1,6 @@ # 2. Well Inventory & Data Availability -A total of **{{ wells|length }}** well(s) were evaluated in this Field Development Study (`{{ project_name }}`), comprising **{{ "%.1f"|format(total_logged_thickness) }} m** of logged borehole section across **{{ all_zones|length }}** stratigraphic zone(s) (Target Reservoir Zones: `{{ target_zones|join(', ') }}`). Across the field dataset, **{{ poro_params.total_core_count }}** total Routine Core Analysis (RCA) plugs are loaded in the database, of which **{{ poro_params.core_count }}** valid depth-matched plugs reside within the target reservoir zones and have non-null overlapping log porosity. - -{% if include_ai_commentary and ai_commentary.inventory_narrative %} -{{ ai_commentary.inventory_narrative }} -{% endif %} +A total of **{{ wells|length }}** {{ (wells|length) | pluralize('well') }} were evaluated in this Field Development Study (`{{ project_name }}`), comprising **{{ "%.1f"|format(total_logged_thickness) }} m** of logged borehole section across **{{ all_zones|length }}** stratigraphic {{ (all_zones|length) | pluralize('zone') }} (Target Reservoir Zones: `{{ target_zones|join(', ') }}`). Across the field dataset, **{{ poro_params.total_core_count }}** total Routine Core Analysis (RCA) plugs are loaded in the database, of which **{{ poro_params.core_count }}** valid depth-matched plugs reside within the target reservoir zones and have non-null overlapping log porosity. {% if custom_notes %} > **Petrophysicist Note:** {{ custom_notes }} @@ -12,12 +8,26 @@ A total of **{{ wells|length }}** well(s) were evaluated in this Field Developme ### 2.1 Multi-Well Wireline, Deviation Survey, Core & Pressure Inventory -| Well Name | UWI | KB (m) | TVD Survey | Top–Bottom (m MD) | Logged (m) | Raw Curves Available | Core (RCA/SCAL) | Pressure Data | Tops | -| :--- | :--- | :---: | :---: | :---: | :---: | :--- | :---: | :---: | :---: | +Curves are grouped by origin. **Raw** curves are measurements as loaded, shown with the percentage of the logged interval that holds valid data. **Edited** curves are conditioned versions of raw curves (for example `*_ENV_CORR`, `*_ENH`, `*_ORI`, `*_RECONSTRUCTED`, `*_DEN_CORR`). **Computed** curves are interpretation and QC outputs (volumes, porosity, saturation, uncertainties `*_SIGMA`, confidences `*_QC_CONF`, flags) and are counted rather than listed. + +| Well Name | UWI | KB (m) | TVD Survey | Top–Bottom (m MD) | Logged (m) | Raw Logs (valid data %) | Edited / Computed Curves | Hole Sections | Core (RCA / SCAL) | Pressure Data | Tops | +| :--- | :--- | :---: | :---: | :---: | :---: | :--- | :---: | :---: | :---: | :---: | :---: | {% for w in wells %} -| **{{ w.name }}** | {{ w.uwi }} | {{ w.kb }} | {{ "✓" if w.has_tvd else "Missing" }} | `{{ "%.1f"|format(w.min_depth) }}–{{ "%.1f"|format(w.max_depth) }}` | {{ "%.1f"|format(w.td) }} | `{{ w.curves|join(', ') }}` | {{ w.has_core }} | {{ w.has_pressure }} | {{ w.formation_top_count }} | +| **{{ w.name }}** | {{ w.uwi }} | {{ w.kb }} | {{ "✓" if w.has_tvd else "Missing" }} | `{{ "%.1f"|format(w.min_depth) }}–{{ "%.1f"|format(w.max_depth) }}` | {{ "%.1f"|format(w.td) }} | {% if w.raw_curves %}{% for c in w.raw_curves %}`{{ c }}` ({{ "%.0f"|format(w.raw_coverage[c]) if w.raw_coverage and c in w.raw_coverage else "—" }}%){{ ", " if not loop.last else "" }}{% endfor %}{% else %}`{{ w.curves|join(', ') }}`{% endif %} | {{ (w.edited_curves|length) if w.edited_curves is defined else 0 }} / {{ (w.computed_curves|length) if w.computed_curves is defined else 0 }} | {{ w.hole_section_count if w.hole_section_count is defined else 0 }} | {{ (w.core_status if w.core_status else w.has_core)|string|replace(" | ", " / ") }} | {{ w.has_pressure }} | {{ w.formation_top_count }} | {% endfor %} +{% set eval_union = [] %} +{% for w in wells %}{% for c in (w.eval_curves or []) %}{% if c not in eval_union %}{% set _ = eval_union.append(c) %}{% endif %}{% endfor %}{% endfor %} +{% if eval_union %} +**Evaluated interpretation curves (all wells):** {% for c in eval_union %}`{{ c }}`{{ ", " if not loop.last else "" }}{% endfor %}. +{% endif %} +{% set edited_union = [] %} +{% for w in wells %}{% for c in (w.edited_curves or []) %}{% if c not in edited_union %}{% set _ = edited_union.append(c) %}{% endif %}{% endfor %}{% endfor %} +{% if edited_union %} + +**Edited / conditioned curves present:** {% for c in edited_union %}`{{ c }}`{{ ", " if not loop.last else "" }}{% endfor %}. +{% endif %} + {% if assets.inventory_heatmap %} ![Figure 2.1: Multi-Well Data Inventory Matrix]({{ assets.inventory_heatmap }}) diff --git a/quick_pp/app/backend/template/reports/sections/03_qaqc.md.j2 b/quick_pp/app/backend/template/reports/sections/03_qaqc.md.j2 index c5a4177d..87c5892d 100644 --- a/quick_pp/app/backend/template/reports/sections/03_qaqc.md.j2 +++ b/quick_pp/app/backend/template/reports/sections/03_qaqc.md.j2 @@ -1,6 +1,7 @@ {% set is_single_well = (report_type == 'SINGLE_WELL_CPI') %} -{% if is_single_well %} -# 2. Borehole Environment & Log Curve Quality Control +{% set sec_num = '2' if is_single_well else '3' %} +{% set sec_title = 'Borehole Environment & Log Curve Quality Control' if is_single_well else 'Data Quality Control (QA/QC) & Conditioning' %} +# {{ sec_num }}. {{ sec_title }} {% if include_ai_commentary and ai_commentary.qaqc_narrative %} {{ ai_commentary.qaqc_narrative }} @@ -10,52 +11,71 @@ > **Petrophysicist Note:** {{ custom_notes }} {% endif %} -### 2.1 Borehole Washout Flagging & Environmental Conditioning Criteria +### {{ sec_num }}.1 Borehole Environment, Bad-Hole Flagging & Conditioning Criteria -* **Bad-Hole Flagging Criteria (`BADHOLE`):** Caliper washout $> {{ qaqc_params.caliper_limit }}$ in (inches) above bit size (`{{ qaqc_params.bitsize_in }} in`), density pad-standoff correction $\Delta\rho > {{ qaqc_params.drho_limit }}$ g/cc, or rugose bulk density $\rho_b < {{ qaqc_params.rhob_min }}$ g/cc. +* **Logging Environment & Mud System:** Tool profile `{{ qaqc_params.tool_type|default('WL') }}`, drilling fluid `{{ qaqc_params.mud_type|default('WBM') }}` (`{{ "%.1f"|format(qaqc_params.mud_weight_ppg|default(9.0)) }} ppg`), {% if qaqc_params.offshore %}offshore ($WD = {{ "%.0f"|format(qaqc_params.water_depth_m|default(0.0)) }}\text{ m}$, seabed anchor ${{ "%.1f"|format(qaqc_params.top_temp_c|default(4.0)) }}^\circ\text{C}$){% else %}onshore (surface anchor ${{ "%.1f"|format(qaqc_params.top_temp_c|default(15.0)) }}^\circ\text{C}$){% endif %}, geothermal gradient ${{ "%.1f"|format(qaqc_params.gradient_c_per_km|default(30.0)) }}^\circ\text{C/km}$, mud-program hole sections loaded: `{{ qaqc_params.hole_section_count|default(0) }}`. +* **Bad-Hole Flagging Criteria (`BADHOLE`):** Caliper washout $> {{ qaqc_params.caliper_limit }}$ in (inches) above bit size (`{{ qaqc_params.bitsize_in }} in` fallback), density pad-standoff correction $\Delta\rho > {{ qaqc_params.drho_limit }}$ g/cc, or rugose bulk density $\rho_b < {{ qaqc_params.rhob_min }}$ g/cc. +* **Borehole Conditioning Curves Evaluated:** {{ qaqc_params.badhole_criteria_used if qaqc_params.badhole_criteria_used else 'CALI, DRHO, RHOB multi-curve evaluation' }}. * **Bad-Hole Mitigation Mode:** `{{ qaqc_params.badhole_treatment }}` (automatic fallback in rugose washouts to prevent optimistic density-porosity spikes). * **Light-Hydrocarbon Invasion Correction:** Gaymard-Poupon neutron-density response correction applied where $\rho_{hc} = {{ qaqc_params.rho_hc }}$ g/cc and $HI_{hc} = {{ qaqc_params.hi_hc }}$. +{% if not is_single_well %} +* **Normalization Method:** {{ qaqc_params.norm_method }} across target reservoir zones. +{% endif %} + +{% if env_corr_summary is defined and env_corr_summary.hole_sections_table and env_corr_summary.hole_sections_table|length > 0 %} +#### Borehole Mud-Program & Casing / Hole Sections + +| Well Name | Section | Interval (m MD) | Bit Size (in) | Mud System | Mud Weight (ppg) | Salinity (ppm) | $R_{mf}$ ($\Omega\cdot\text{m}$ @ $^\circ\text{C}$) | +| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | +{% for hs in env_corr_summary.hole_sections_table %} +| **{{ hs.well_name }}** | {{ hs.name }} | `{{ "%.1f"|format(hs.top) }}–{{ "%.1f"|format(hs.bottom) }}` | {{ "%.3g"|format(hs.bit_size) if hs.bit_size is not none else "—" }} | `{{ hs.mud_type }}` | {{ "%.2f"|format(hs.mud_weight) if hs.mud_weight is not none else "—" }} | {{ hs.mud_salinity if hs.mud_salinity is not none else "—" }} | {% if hs.rmf is not none %}{{ "%.3f"|format(hs.rmf) }}{% if hs.rmf_temp is not none %} @ {{ "%.0f"|format(hs.rmf_temp) }}°C{% endif %}{% else %}—{% endif %} | +{% endfor %} +{% endif %} -### 2.2 Well Curve Conditioning & Washout Audit Summary +### {{ sec_num }}.2 {{ "Well Curve Conditioning & Washout Audit Summary" if is_single_well else "Well-by-Well QA/QC, Conditioning & Normalization Shift Audit" }} -| Well Name | Evaluated Samples | Bad-Hole Samples | Bad-Hole (%) | HC-Corrected (%) | Tight / Coal Flags | GR P50 (gAPI) | RHOB P50 (g/cc) | QC Status | -| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | +| Well Name | Evaluated Samples | Bad-Hole (%) | Env-Corrected Curves | Mean QC Conf | HC-Corrected (%) | Tight / Coal Flags | GR P50 (gAPI) | RHOB P50 (g/cc) | ΔGR (gAPI) | ΔRHOB (g/cc) | ΔNPHI (v/v) | QC Status | +| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | {% for q in qaqc_table %} -| **{{ q.well_name }}** | {{ q.samples }} | {{ q.badhole_count }} | {{ "%.1f"|format(q.badhole_pct) }}% | {{ "%.1f"|format(q.hc_pct) }}% | {{ q.tight_count }} / {{ q.coal_count }} | {{ "%.1f"|format(q.gr_p50) }} | {{ "%.3f"|format(q.rhob_p50) }} | **{{ q.status }}** | +| **{{ q.well_name }}** | {{ q.samples }} | {{ "%.1f"|format(q.badhole_pct) }}% ({{ q.badhole_count }}) | {{ ("`" ~ q.env_curves ~ "`") if q.env_curves is defined and q.env_curves != "—" else "—" }} | {{ "%.2f"|format(q.mean_qc_conf) if q.mean_qc_conf is defined and q.mean_qc_conf is not none else "—" }} | {{ "%.1f"|format(q.hc_pct) }}% | {{ q.tight_count }} / {{ q.coal_count }} | {{ "%.1f"|format(q.gr_p50) }} | {{ "%.3f"|format(q.rhob_p50) }} | {{ q.delta_gr if q.delta_gr is defined else "—" }} | {{ q.delta_rhob if q.delta_rhob is defined else "—" }} | {{ q.delta_nphi if q.delta_nphi is defined else "—" }} | **{{ q.status }}** | {% endfor %} {% if assets.norm_plot %} -![Figure 2.1: Well Curve Distributions & Borehole Washout Quality Audit]({{ assets.norm_plot }}) +![Figure {{ sec_num }}.1: {{ "Well Curve Distributions & Borehole Washout Quality Audit" if is_single_well else "Curve Distribution Pre- and Post-Normalization & Bad-Hole Audit" }}]({{ assets.norm_plot }}) {% endif %} -{% else %} -# 3. Data Quality Control (QA/QC) & Conditioning -{% if include_ai_commentary and ai_commentary.qaqc_narrative %} -{{ ai_commentary.qaqc_narrative }} -{% endif %} +{% if env_corr_summary is defined and env_corr_summary.any_applied %} +### {{ sec_num }}.3 Borehole Environmental Correction, Uncertainty ($\sigma$) & Sensor Confidence Audit -{% if custom_notes %} -> **Petrophysicist Note:** {{ custom_notes }} -{% endif %} +Generic borehole environmental corrections (`*_ENV_CORR`) and perturbation-propagated per-sample standard deviations (`*_SIGMA`) were evaluated across **{{ env_corr_summary.wells_applied }}/{{ env_corr_summary.total_wells }}** {{ (env_corr_summary.total_wells) | pluralize('well') }}: -### 3.1 Borehole Environment, Bad-Hole Flagging & Normalization Criteria +* **In-Situ Temperature & Fluid Resistivity Profile:** {% if env_corr_summary.temp_min_c is not none and env_corr_summary.temp_max_c is not none %}$T_{form} = {{ "%.1f"|format(env_corr_summary.temp_min_c) }}\text{–}{{ "%.1f"|format(env_corr_summary.temp_max_c) }}^\circ\text{C}$ (median ${{ "%.1f"|format(env_corr_summary.temp_median_c) }}^\circ\text{C}$){% else %}Geothermal gradient ${{ "%.1f"|format(env_corr_summary.gradient_c_per_km) }}^\circ\text{C/km}${% endif %}{% if env_corr_summary.median_rw is not none %}, median $R_w = {{ "%.4f"|format(env_corr_summary.median_rw) }}\text{ }\Omega\cdot\text{m}${% endif %}{% if env_corr_summary.median_rmf is not none %}, $R_{mf} = {{ "%.4f"|format(env_corr_summary.median_rmf) }}\text{ }\Omega\cdot\text{m}${% endif %}{% if env_corr_summary.median_rm is not none %}, $R_m = {{ "%.4f"|format(env_corr_summary.median_rm) }}\text{ }\Omega\cdot\text{m}${% endif %}. +* **Composite Sensor Reliability:** Mean confidence $\overline{C} = {{ "%.2f"|format(env_corr_summary.mean_conf) if env_corr_summary.mean_conf is not none else "—" }}$, maximum unreliable interval $= {{ "%.1f"|format(env_corr_summary.max_unreliable_pct) }}\%$, sonic cycle-skip samples removed $= {{ env_corr_summary.cycle_skip_count }}${% if env_corr_summary.sigma_propagated %} (`*_SIGMA` propagated into Section {{ '5' if is_single_well else '8' }} Monte Carlo uncertainty){% endif %}. -* **Bad-Hole Criteria Applied:** Caliper washout $> {{ qaqc_params.caliper_limit }}$ in (inches) above bit size (`{{ qaqc_params.bitsize_in }} in`), Density correction $\Delta\rho > {{ qaqc_params.drho_limit }}$ g/cc, or density washout $\rho_b < {{ qaqc_params.rhob_min }}$ g/cc. -* **Bad-Hole Mitigation Mode:** `{{ qaqc_params.badhole_treatment }}` (shale/porosity fallback in rugose washouts to prevent optimistic density porosity spikes). -* **Hydrocarbon Light-Fluid Correction:** Gaymard-Poupon crossplot rotation applied where $\rho_{hc} = {{ qaqc_params.rho_hc }}$ g/cc and $HI_{hc} = {{ qaqc_params.hi_hc }}$. -* **Normalization Method:** {{ qaqc_params.norm_method }} across target reservoir zones. +| Sensor | Corrected Curve | Samples | Good (%) | Corrected (%) | Unreliable (%) | Mean Conf (`*_QC_CONF`) | Mean $1\sigma$ (`*_SIGMA`) | Mean $|\Delta|$ | P95 $|\Delta|$ | Dominant QC Flag | +| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :--- | +{% for r in env_corr_summary.curve_table %} +| **{{ r.curve }}** | `{{ r.corr_curve }}` | {{ r.samples }} | {{ "%.1f"|format(r.good_pct) }}% | {{ "%.1f"|format(r.corrected_pct) }}% | {{ "%.1f"|format(r.unreliable_pct) }}% | {{ "%.3f"|format(r.mean_conf) if r.mean_conf is not none else "—" }} | {{ ("%.4f"|format(r.mean_sigma) ~ " " ~ r.unit) if r.mean_sigma is not none else "—" }} | {{ ("%.4f"|format(r.mean_abs_delta) ~ " " ~ r.unit) if r.mean_abs_delta is not none else "—" }} | {{ ("%.4f"|format(r.p95_abs_delta) ~ " " ~ r.unit) if r.p95_abs_delta is not none else "—" }} | {{ r.dominant_reason }} | +{% endfor %} -### 3.2 Well-by-Well QA/QC & Conditioning Summary +{% if env_corr_summary.assumptions and env_corr_summary.assumptions|length > 0 %} +> [!NOTE] +> **Documented Environmental Assumptions (Widening `*_SIGMA`):** {{ env_corr_summary.assumptions|join(' · ') }} +{% endif %} -| Well Name | Evaluated Samples | Bad-Hole Samples | Bad-Hole (%) | HC-Corrected (%) | Tight / Coal Flags | GR P50 (gAPI) | RHOB P50 (g/cc) | QC Status | -| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | -{% for q in qaqc_table %} -| **{{ q.well_name }}** | {{ q.samples }} | {{ q.badhole_count }} | {{ "%.1f"|format(q.badhole_pct) }}% | {{ "%.1f"|format(q.hc_pct) }}% | {{ q.tight_count }} / {{ q.coal_count }} | {{ "%.1f"|format(q.gr_p50) }} | {{ "%.3f"|format(q.rhob_p50) }} | **{{ q.status }}** | +{% if env_corr_summary.has_invasion and env_corr_summary.invasion_table %} +### {{ sec_num }}.4 Step-Profile Radial Resistivity Invasion Interpretation ($R_{xo}/R_t$ vs. $R_{mf}/R_w$) + +| Well Name | Mud System | Samples | Invaded (%) | Movable HC-like (%) | Water-like (%) | Anomalous (%) | Tight / No Invasion (%) | Median $d_i$ (in) | P90 $d_i$ (in) | +| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | +{% for inv in env_corr_summary.invasion_table %} +| **{{ inv.well_name }}** | `{{ inv.mud_type }}` | {{ inv.samples }} | {{ "%.1f"|format(inv.invaded_pct) }}% | **{{ "%.1f"|format(inv.hc_like_pct) }}%** | {{ "%.1f"|format(inv.water_like_pct) }}% | {{ "%.1f"|format(inv.anomalous_pct) }}% | {{ "%.1f"|format(inv.tight_pct) }}% | {{ "%.1f"|format(inv.median_di_in) if inv.median_di_in is not none else "—" }} | {{ "%.1f"|format(inv.p90_di_in) if inv.p90_di_in is not none else "—" }} | {% endfor %} +{% endif %} +{% endif %} -{% if assets.norm_plot %} +{% if assets.env_corr_plot %} -![Figure 3.1: Curve Distribution Pre- and Post-Normalization & Bad-Hole Audit]({{ assets.norm_plot }}) -{% endif %} +![Figure {{ sec_num }}.2: Borehole Environment, Sensor Corrections (±1σ) & Radial Invasion QC]({{ assets.env_corr_plot }}) {% endif %} diff --git a/quick_pp/app/backend/template/reports/sections/04_lithology_porosity.md.j2 b/quick_pp/app/backend/template/reports/sections/04_lithology_porosity.md.j2 index 705b0b7e..04e6ab58 100644 --- a/quick_pp/app/backend/template/reports/sections/04_lithology_porosity.md.j2 +++ b/quick_pp/app/backend/template/reports/sections/04_lithology_porosity.md.j2 @@ -47,21 +47,21 @@ $$V_{sand} + V_{silt} + V_{clay} = 1, \quad \phi_D = \frac{\rho_{ma} - \rho_b}{\ {% else %} | Dry Clay Density | $\rho_{clay}$ | {{ litho_params.rho_clay }} | $\text{g/cc}$ | Clay Mineralogy Endpoint | | Dry Clay Neutron | $NPHI_{clay}$ | {{ litho_params.nphi_clay }} | $\text{v/v}$ | Neutron-Density Crossplot Clay Point | +{% if not litho_params.gamma or litho_params.gamma.get('gamma_source', 'gr') == 'gr' %} | Clean GR Endpoint | $GR_{clean}$ | {{ litho_params.gr_clean }} | $\text{gAPI}$ | P5 Clean Reservoir Baseline | | Shale GR Endpoint | $GR_{shale}$ | {{ litho_params.gr_shale }} | $\text{gAPI}$ | P95 Intra-Reservoir Shale Baseline | -{% if litho_params.model_key == 'vsh_gr' and litho_params.gamma %} -| Gamma source | $\gamma$ | {{ litho_params.gamma.get('gamma_source', 'gr') }} | — | Calibrate for the selected response | +{% endif %} +{% if litho_params.model_key == 'vsh_gr' and litho_params.gamma and litho_params.gamma.get('gamma_source') != 'gr' %} +| Gamma source | $\gamma$ | {{ litho_params.gamma.get('gamma_source') }} | — | Calibrate for the selected response | {% if litho_params.gamma.get('gamma_source') == 'cgr' %} | Gamma curve | — | {{ litho_params.gamma.get('gamma_curve') }} | — | Selected curve | {% elif litho_params.gamma.get('gamma_source') == 'derived_cgr' %} | Derived CGR inputs | — | {{ litho_params.gamma.get('thorium_curve') }} / {{ litho_params.gamma.get('potassium_curve') }} | ppm / % | Th / K | | CGR coefficients | $a_{Th}$ / $a_K$ | {{ litho_params.gamma.get('cgr_th_coefficient') }} / {{ litho_params.gamma.get('cgr_k_coefficient') }} | gAPI/ppm / gAPI/% | Verify tool calibration | {% endif %} -{% if litho_params.gamma.get('gamma_source') != 'gr' %} | Clean / shale gamma endpoints | — | {{ litho_params.gamma.get('gamma_clean') }} / {{ litho_params.gamma.get('gamma_shale') }} | gAPI | Selected gamma response | {% endif %} {% endif %} -{% endif %} | Total Core Plugs Loaded | $N_{core,total}$ | {{ poro_params.total_core_count }} | plugs | Full-Wellbore RCA Inventory (Table 2.1) | | Target-Zone Calibration Plugs | $N_{core,target}$ | {{ poro_params.core_count }} | plugs | Valid Overlapping Plugs (`{{ target_zones|join(', ') }}`) | {% if poro_params.core_shift_applied %} @@ -74,6 +74,19 @@ $$V_{sand} + V_{silt} + V_{clay} = 1, \quad \phi_D = \frac{\rho_{ma} - \rho_b}{\ {% if poro_params.core_count > 0 %} | Core-to-Log Calibration | $R^2$ / $\text{RMSE}$ | {{ "%.2f"|format(poro_params.core_r2) }} / {{ "%.3f"|format(poro_params.core_rmse) }} | $\text{v/v}$ | Mean Bias ($\phi_{log} - \phi_{core}$) $= {{ "%+.3f"|format(poro_params.core_bias) }}\text{ v/v}$ | {% endif %} +{% if is_single_well and poro_params.core_perm_count and poro_params.core_perm_count > 0 %} +| Core Permeability Parity | $R^2$ / Factor Error | {{ "%.2f"|format(poro_params.core_perm_r2) }} / {{ "%.1f"|format(poro_params.core_perm_factor_err) }}$\times$ | $\text{log}_{10}\text{ mD}$ | Valid target-zone permeability plugs ($n = {{ poro_params.core_perm_count }}$) | +{% endif %} + +{% if well_core_parity and (poro_params.core_r2 < 0.40 or poro_params.core_count == 0) and not is_single_well %} +#### Well-by-Well Core-to-Log Porosity Parity & Depth Alignment Diagnostics + +| Well Name | Valid Plugs | Applied Shift (m) | $R^2$ ($\phi_t$) | $R^2$ ($\phi_e$) | RMSE (v/v) | Mean Bias (v/v) | Parity Status | Diagnostic Recommendation | +| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :--- | +{% for wp in well_core_parity %} +| **{{ wp.well_name }}** | {{ wp.n_plugs }} | {{ "%+.2f"|format(wp.mean_shift_m) }} | {{ "%.2f"|format(wp.r2_phit) }} | {{ "%.2f"|format(wp.r2_phie) }} | {{ "%.3f"|format(wp.rmse_phi) }} | {{ "%+.3f"|format(wp.bias_phi) }} | **{{ wp.status }}** | {{ wp.recommendation }} | +{% endfor %} +{% endif %} {% if poro_params.core_shift_applied %} > **Core-to-Log Depth Matching Lineage:** Driller's core plug depths were depth-matched to wireline logs using **{{ poro_params.core_shift_mode_label }}** ($\Delta d = {{ "%+.2f"|format(poro_params.core_shift_delta) }}\text{ m}$, stretch factor $s = {{ "%.4f"|format(poro_params.core_stretch_factor) }}\times${% if poro_params.core_pivot_depth %}, anchor pivot $d_{ref} = {{ "%.1f"|format(poro_params.core_pivot_depth) }}\text{ m}${% endif %}, mean plug shift $= {{ "%+.2f"|format(poro_params.core_shift_mean_m) }}\text{ m}$). Original unshifted driller's depths (`RAW_DEPTH`) and per-plug shifts (`SHIFT_M`) are preserved on every RCA sample, while unshifted log-grid curves are retained as `CPORE_UNSHIFTED` and `CPERM_UNSHIFTED`. diff --git a/quick_pp/app/backend/template/reports/sections/05_rock_typing_perm.md.j2 b/quick_pp/app/backend/template/reports/sections/05_rock_typing_perm.md.j2 index 0be4bfd2..4b672551 100644 --- a/quick_pp/app/backend/template/reports/sections/05_rock_typing_perm.md.j2 +++ b/quick_pp/app/backend/template/reports/sections/05_rock_typing_perm.md.j2 @@ -4,14 +4,28 @@ Rock typing and continuous permeability ($K$) prediction were established using **{{ rt_summary.basis if rt_summary else 'Routine Core Analysis (RCA) & Log-Derived Hydraulic Flow Units' }}** via the Reservoir Quality Index ($RQI$), Normalized Porosity ($\phi_z$), Flow Zone Indicator ($FZI$), and Discrete Rock Typing ($DRT$) formulation: -$$RQI = 0.0314 \sqrt{\frac{K}{\phi_e}}, \quad \phi_z = \frac{\phi_e}{1 - \phi_e}, \quad FZI = \frac{RQI}{\phi_z}, \quad DRT = \text{round}(2 \ln(FZI) + 10.6)$$ +$$RQI = 0.0314 \sqrt{\frac{K}{\phi_e}}, \quad \phi_z = \frac{\phi_e}{1 - \phi_e}, \quad FZI = \frac{RQI}{\phi_z}$$ + +Discrete Rock Types (DRT) are assigned by binning $FZI$ at the cut-offs below ({{ rt_summary.cutoff_source if rt_summary and rt_summary.cutoff_source else 'unspecified source' }}). | Rock Type | $DRT$ / Class | FZI Range ($\mu\text{m}$) | Samples ($n$) | Sample Share (%) | Semi-Log Porosity-Permeability Transform | Regression $R^2$ | | :--- | :---: | :---: | :---: | :---: | :--- | :---: | {% for rt in rock_types %} -| **{{ rt.name }}** | {{ rt.code }} | {{ rt.fzi_range }} | {{ rt.n_samples if rt.n_samples is defined else "—" }} | {{ "%.1f"|format(rt.share_pct) }}% | $\log_{10}(K) = {{ rt.slope }} \cdot \phi_e + ({{ rt.intercept }})$ | {{ "%.2f"|format(rt.r2) }} | +| **{{ rt.name }}** | {{ rt.code }} | {{ rt.fzi_range }} | {{ rt.n_samples if rt.n_samples is defined else "—" }} | {{ ("%.1f"|format(rt.share_pct) ~ "%") if rt.share_pct is not none else "—" }} | {% if rt.slope is not none and rt.intercept is not none %}$\log_{10}(K) = {{ rt.slope }} \cdot \phi_e + ({{ rt.intercept }})${% else %}Insufficient data (fewer than 3 samples or no porosity spread){% endif %} | {{ ("%.2f"|format(rt.r2)) if rt.r2 is not none else "—" }} | +{% endfor %} + +{% if saved_flag_rows %} +#### Table 5.1b: Saved Workbench `ROCK_FLAG` Classes — Power-Law Permeability Transform ($K = a\,\phi^{b}$) + +The classes below come from the `ROCK_FLAG` curve saved by the workbench on the same samples, so they reflect the cut-offs and classifier actually used (including any ML propagation) rather than the FZI re-binning above. + +| `ROCK_FLAG` | Samples ($n$) | Sample Share (%) | $\sum K$ Share (%) | $a$ | $b$ | Regression $R^2$ ($\log_{10}K$) | Transform Source | +| :---: | :---: | :---: | :---: | :---: | :---: | :---: | :--- | +{% for f in saved_flag_rows %} +| **{{ f.rock_flag }}** | {{ f.n_samples }} | {{ "%.1f"|format(f.share_pct) }}% | {{ "%.1f"|format(f.kh_pct) }}% | {{ f.a if f.a is not none else "—" }} | {{ f.b if f.b is not none else "—" }} | {{ ("%.2f"|format(f.r2)) if f.r2 is not none else "—" }} | {{ f.source }} | {% endfor %} +{% endif %} {% if poro_params.core_perm_count > 0 or poro_params.core_shift_applied or poro_params.core_corrected %} ### 5.2 Core Permeability Calibration (`PERM` $\times$ `CPERM`) & Data Lineage @@ -29,6 +43,16 @@ $$RQI = 0.0314 \sqrt{\frac{K}{\phi_e}}, \quad \phi_z = \frac{\phi_e}{1 - \phi_e} {% endif %} {% endif %} +{% if well_core_parity and (poro_params.core_perm_r2 < 0.40 or poro_params.core_perm_count == 0) and not is_single_well %} +#### Well-by-Well Core-to-Log Permeability Parity Diagnostics + +| Well Name | Valid Plugs | Applied Shift (m) | $R^2$ ($\log_{10} K$) | RMSE ($\text{dec}$) | Factor Error | Parity Status | Diagnostic Recommendation | +| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :--- | +{% for wp in well_core_parity %} +| **{{ wp.well_name }}** | {{ wp.n_perm_plugs if wp.n_perm_plugs is defined else wp.n_plugs }} | {{ "%+.2f"|format(wp.mean_shift_m) }} | {{ "%.2f"|format(wp.r2_perm if wp.r2_perm is defined else 0.0) }} | {{ "%.3f"|format(wp.rmse_log_perm if wp.rmse_log_perm is defined else 0.0) }} | {{ "%.2f"|format(wp.factor_err_perm if wp.factor_err_perm is defined else 1.0) }}× | **{{ wp.perm_status if wp.perm_status is defined else wp.status }}** | {{ wp.perm_recommendation if wp.perm_recommendation is defined else wp.recommendation }} | +{% endfor %} +{% endif %} + {% if include_ai_commentary and ai_commentary.rock_typing_narrative %} {{ ai_commentary.rock_typing_narrative }} {% endif %} diff --git a/quick_pp/app/backend/template/reports/sections/06_saturation_contacts.md.j2 b/quick_pp/app/backend/template/reports/sections/06_saturation_contacts.md.j2 index fe2cac4b..cf234a6c 100644 --- a/quick_pp/app/backend/template/reports/sections/06_saturation_contacts.md.j2 +++ b/quick_pp/app/backend/template/reports/sections/06_saturation_contacts.md.j2 @@ -6,11 +6,22 @@ ### {{ sec_num }}.1 Electrical Properties, Formation Water Resistivity & Saturation Equation * **Saturation Model:** `{{ sw_params.model_name }}` -* **Free Water Level ($FWL$):** ${{ "%.1f"|format(sw_params.fwl) }}\text{ m TVDss}$ -* **Formation Water Salinity & Resistivity:** ${{ sw_params.salinity|int }}\text{ ppm NaCl equivalent}$, $R_w = {{ "%.3f"|format(sw_params.rw) }}\text{ }\Omega\cdot\text{m} \text{ @ } {{ "%.1f"|format(sw_params.temp) }}^\circ\text{C}$ (Arps temperature scaling). +* **Free Water Level ($FWL$):** ${{ "%.1f"|format(sw_params.fwl) }}\text{ m TVDss}$ (Basis: `{{ sw_params.fwl_basis }}`) +* **Formation Water Salinity & Resistivity:** ${{ sw_params.salinity|int }}\text{ ppm NaCl equivalent}$, $R_w = {{ "%.3f"|format(sw_params.rw) }}\text{ }\Omega\cdot\text{m} \text{ @ } {{ "%.1f"|format(sw_params.temp) }}^\circ\text{C}$ ({{ sw_params.temp_basis }}). * **Electrical Tortuosity, Cementation & Saturation Exponents:** $a = {{ sw_params.a }}$, $m = {{ sw_params.m }}$, $n = {{ sw_params.n }}$ -$$S_w^n + R_w \cdot B \cdot Q_v \cdot S_w^{n-1} = \frac{a \cdot R_w}{\phi_t^m \cdot R_t} \quad \text{(Waxman-Smits Shaly-Sand)} \qquad S_w = \left(\frac{a \cdot R_w}{\phi_t^m \cdot R_t}\right)^{1/n} \quad \text{(Archie)}$$ +{% if sw_params.model_key == 'waxman_smits' %} +$$S_w^n + B \cdot Q_v \cdot R_w \cdot S_w^{n-1} = \frac{a \cdot R_w}{\phi_t^m \cdot R_t} \quad \text{(Active Waxman-Smits Shaly-Sand)}$$ +$$\text{Clean-Sand Baseline (Archie Reference): } S_w = \left(\frac{a \cdot R_w}{\phi_t^m \cdot R_t}\right)^{1/n}$$ +{% elif sw_params.model_key == 'dual_water' %} +$$\frac{1}{R_t} = \frac{\phi_t^m}{a} \left( S_{wt}^n \frac{1}{R_{wf}} + S_{wb} \left( \frac{1}{R_{wb}} - \frac{1}{R_{wf}} \right) S_{wt}^{n-1} \right) \quad \text{(Active Dual-Water Model)}$$ +$$\text{Clean-Sand Baseline (Archie Reference): } S_w = \left(\frac{a \cdot R_w}{\phi_t^m \cdot R_t}\right)^{1/n}$$ +{% elif sw_params.model_key in ('simandoux', 'indonesian') %} +$$\frac{1}{R_t} = \frac{\phi_e^m \cdot S_w^n}{a \cdot R_w (1 - V_{sh})} + \frac{V_{sh} \cdot S_w}{R_{sh}} \quad \text{(Active Shaly-Sand Model)}$$ +$$\text{Clean-Sand Baseline (Archie Reference): } S_w = \left(\frac{a \cdot R_w}{\phi_t^m \cdot R_t}\right)^{1/n}$$ +{% else %} +$$S_w = \left(\frac{a \cdot R_w}{\phi_t^m \cdot R_t}\right)^{1/n} \quad \text{(Active Archie Equation)}$$ +{% endif %} | Parameter | Symbol | Value | Unit | Basis / Calibration | | :--- | :---: | :---: | :---: | :--- | @@ -18,7 +29,18 @@ $$S_w^n + R_w \cdot B \cdot Q_v \cdot S_w^{n-1} = \frac{a \cdot R_w}{\phi_t^m \c | Cementation Exponent | $m$ | {{ sw_params.m }} | unitless | Formation Factor ($F = a / \phi^m$) | | Saturation Exponent | $n$ | {{ sw_params.n }} | unitless | Resistivity Index ($RI = S_w^{-n}$) | | Formation Water Resistivity | $R_w$ | {{ "%.3f"|format(sw_params.rw) }} | $\Omega\cdot\text{m}$ | Water Zone Pickett $S_w = 100\%$ Ro Trend | -| Free Water Level | $FWL$ | {{ "%.1f"|format(sw_params.fwl) }} | $\text{m TVDss}$ | Resistivity-Porosity Fluid Contact Interpretation | +| Formation Temperature | $T_{res}$ | {{ "%.1f"|format(sw_params.temp) }} | $^\circ\text{C}$ | {{ sw_params.temp_basis }} | +| Free Water Level | $FWL$ | {{ "%.1f"|format(sw_params.fwl) }} | $\text{m TVDss}$ | {{ sw_params.fwl_basis }} | +{% if sw_params.model_key == 'waxman_smits' %} +| Clay Counter-Ion Conductance | $B$ | {{ sw_params.b_conductance }} | $\text{L}\cdot\text{equiv}^{-1}\cdot\Omega^{-1}\cdot\text{m}^{-1}$ | Juhasz (1981) Empirical Model @ $T_{res}$ & $R_w$ | +| Cation Exchange Capacity / Pore Vol | $Q_v$ | {{ sw_params.qv }} | $\text{meq/mL}$ | {{ sw_params.qv_method }} | +| Shale Porosity | $\phi_{sh}$ | {{ sw_params.phish }} | $\text{v/v}$ | Clay-Bound Water ($CBW$) Partitioning Endpoint | +{% elif sw_params.model_key == 'dual_water' %} +| Bound Water Resistivity | $R_{wb}$ | {{ "%.3f"|format(sw_params.rwb) }} | $\Omega\cdot\text{m}$ | Dual Water Bound-Water Calibration | +| Bound Water Saturation Endpoint | $S_{wb}$ | {{ "%.2f"|format(sw_params.swb) }} | $\text{v/v}$ | Clay-Bound Water Saturation Limit | +{% elif sw_params.model_key in ('simandoux', 'indonesian') %} +| Shale Resistivity | $R_{sh}$ | {{ "%.2f"|format(sw_params.rsh) }} | $\Omega\cdot\text{m}$ | Adjacent Pure Shale Bed Resistivity Baseline | +{% endif %} {% if include_ai_commentary and ai_commentary.saturation_narrative %} {{ ai_commentary.saturation_narrative }} @@ -62,7 +84,7 @@ Accurate delineation of fluid contacts is fundamental to volumetric in-place est - **Oil-Water Contact (OWC):** ${{ "%.1f"|format(z.owc) }}\text{ m TVDss}$ (Bracket: ${{ "%.1f"|format(z.odt) if z.odt else "N/A" }}\text{ m}$ to ${{ "%.1f"|format(z.wut) if z.wut else "N/A" }}\text{ m}$). {% endif %} {% if z.fwl is not none %} - - **Free Water Level (FWL):** ${{ "%.1f"|format(z.fwl) }}\text{ m TVDss}$ (Capillary $P_c = 0$ Datum). + - **Free Water Level (FWL):** ${{ "%.1f"|format(z.fwl) if z.fwl is number else z.fwl }}\text{ m TVDss}$ (Capillary $P_c = 0$ Datum). {% endif %} {% endfor %} {% endif %} @@ -70,3 +92,57 @@ Accurate delineation of fluid contacts is fundamental to volumetric in-place est > [!NOTE] > Discrete single-well fluid contact markers (GUT/GDT/OUT/ODT/WUT/OWC/GOC/FWL) have not yet been extracted or committed to ancillary data for this project. Global saturation model uses $FWL = {{ "%.1f"|format(sw_params.fwl) }}\text{ m TVDss}$. {% endif %} + +{% if fpt_summary and fpt_summary.has_data %} +### {{ sec_num }}.3 Formation Pressure Testing (RFT/MDT/XPT) & Fluid Gradient Regimes + +Formation Pressure Tester (RFT/MDT/XPT) data were gathered across the evaluated wells to establish in-situ reservoir pressure regimes, verify vertical fluid communication, and determine independent fluid contact datums from hydrostatic gradient intersections. + +{% if fpt_summary.filter_note %} +> **Station screening:** {{ fpt_summary.filter_note }} Only stations inside the target reservoir zones, with valid quality and plausible pressure, enter the regime table and gradient fits. +{% endif %} + +#### Table {{ sec_num }}.3: Multi-Well Formation Pressure Regimes & Fitted Fluid Gradients + +| Well Name | Total Stations | Valid Stations | Depth Range (m TVDss) | Formation Pressure (psia) | Mobility Range (mD/cP) | Hydrostatic Regime | +| :--- | :---: | :---: | :---: | :---: | :---: | :--- | +{% for w in fpt_summary.well_fpt_rows %} +| **{{ w.well_name }}** | {{ w.total_count }} | {{ w.valid_count }} | {{ w.depth_range }} | {{ w.pressure_range }} | {{ w.mobility_range }} | {{ w.overpressure_regime }} | +{% endfor %} + +{% if fpt_summary.fpt_gradient_rows and fpt_summary.fpt_gradient_rows|length > 0 %} +**Fitted Fluid Pressure Gradients & In-Situ Densities:** + +| Zone / Reservoir Segment | Inferred Phase | Pressure Gradient (psi/ft) | In-Situ Density (g/cc) | Datum Pressure @ FWL (psia) | $R^2$ | Stations ($n$) | TVDss Depth Range | +| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | +{% for g in fpt_summary.fpt_gradient_rows %} +| **{{ g.zone or "Target Reservoir" }}** | **{{ g.fluid_type }}**{% if g.accepted is defined and not g.accepted %} (rejected){% endif %} | {{ "%.4f"|format(g.gradient_psi_ft) }} | {{ "%.3f"|format(g.density_gcc) }} | {{ "%.1f"|format(g.datum_pressure) if g.datum_pressure is defined else "—" }} | {{ "%.3f"|format(g.r_squared) if g.r_squared is defined else "—" }} | {{ g.n_points }} | {{ g.tvdss_range }} | +{% endfor %} + +{% if fpt_summary.rejected_fits %} +> **Fits not used downstream:** +{% for g in fpt_summary.rejected_fits %} +> * {{ g.fluid_type }} ({{ g.zone }}): {{ g.reject_reason }}. Not used for saturation-height density or contact estimation. +{% endfor %} +{% endif %} +{% endif %} + +{% if fpt_summary.fpt_contacts and fpt_summary.fpt_contacts|length > 0 %} +#### Table {{ sec_num }}.4: Pressure-Gradient Contact Reconciliation vs. Log/Capillary Contacts + +{% if not fpt_summary.fwl_is_committed %} +> **Indicative only:** no committed fluid contact exists for this project. The reference FWL ({{ "%.1f"|format(sw_params.fwl) }} m TVDss) is inferred from the log saturation transition, so the pressure-derived contacts below are not reconciled against an independent datum. +{% endif %} + +| Contact Type | FPT TVDss P50 (m) | FPT Bracket P10–P90 (m) | Log / Capillary TVDss (m) | Contact Reconciliation Delta ($\Delta\text{TVDss}$) | Audit Reconciliation Status | +| :--- | :---: | :---: | :---: | :---: | :---: | +{% for c in fpt_summary.fpt_contacts %} +| **{{ c.contact_type }}** | **{{ "%.1f"|format(c.tvdss_p50) }}** | {{ "%.1f"|format(c.tvdss_p10) }} – {{ "%.1f"|format(c.tvdss_p90) }} | {{ "%.1f"|format(sw_params.fwl) }} | {{ "%+.1f"|format(c.delta_log_tvdss) if c.delta_log_tvdss is defined else "0.0" }} m | **{{ c.status or "✓ RECONCILED" }}** | +{% endfor %} +{% endif %} + +{% if assets.fpt_pressure_plot %} + +![Figure {{ sec_num }}.2: {{ "Well" if is_single_well else "Multi-Well" }} Formation Pressure vs. TVDss & Fluid Gradient Regimes]({{ assets.fpt_pressure_plot }}) +{% endif %} +{% endif %} diff --git a/quick_pp/app/backend/template/reports/sections/07_shf_scal.md.j2 b/quick_pp/app/backend/template/reports/sections/07_shf_scal.md.j2 index 1e56bca6..2ca1bc72 100644 --- a/quick_pp/app/backend/template/reports/sections/07_shf_scal.md.j2 +++ b/quick_pp/app/backend/template/reports/sections/07_shf_scal.md.j2 @@ -4,7 +4,7 @@ ### {{ sec_num }}.1 Leverett $J$-Function, Lab-to-Reservoir $P_c$ Scaling & Core Stress Lineage -To initialize continuous 3D water saturation in the static geological cellular model above the Free Water Level ($FWL = {{ "%.1f"|format(sw_params.fwl) }}\text{ m TVDss}$, Basis: `{{ sw_params.fwl_basis }}`), log-derived $S_w$ was reconciled with capillary pressure ($P_c$) curves via the Leverett $J$-Function and Lab-to-Reservoir interfacial tension scaling: +To initialize continuous 3D water saturation in the static geological cellular model above the Free Water Level ($FWL = {{ "%.1f"|format(shf_params.fwl if shf_params.fwl is defined else sw_params.fwl) }}\text{ m TVDss}$, Basis: `{{ shf_params.fwl_basis if shf_params.fwl_basis is defined else sw_params.fwl_basis }}`), log-derived $S_w$ was reconciled with capillary pressure ($P_c$) curves via the Leverett $J$-Function and Lab-to-Reservoir interfacial tension scaling: $$P_{c,res} = P_{c,lab} \cdot \frac{(\sigma \cos\theta)_{res}}{(\sigma \cos\theta)_{lab}}, \quad h = TVD_{ss}(FWL) - TVD_{ss}, \quad J(S_w) = \frac{0.2166 \cdot P_{c,res}}{\sigma_{res} \cos\theta_{res}} \sqrt{\frac{K}{\phi}}$$ @@ -13,16 +13,44 @@ $$P_{c,res} = P_{c,lab} \cdot \frac{(\sigma \cos\theta)_{res}}{(\sigma \cos\thet {% if poro_params.core_corrected %} * **Core Overburden & Klinkenberg Stress Lineage:** $\sigma_{eff} = {{ "%.0f"|format(poro_params.net_confining_stress) }}\text{ psi}$ ({{ poro_params.core_lithology }}, $c_\phi = {{ "%.1e"|format(poro_params.compaction_coeff) }}\text{ psi}^{-1}$, $c_k = {{ "%.1e"|format(poro_params.perm_compaction_coeff) }}\text{ psi}^{-1}$), $P_m = {{ "%.1f"|format(poro_params.mean_pore_pressure) }}\text{ psi}$ ({{ poro_params.klinkenberg_method }}); baseline preserved in `CPORE_AMB` / `CPORE_ORI` and `CPERM_AIR` / `CPERM_ORI`, active curves updated in `CPORE` and `CPERM`. {% endif %} -* **Fluid Density Gradient:** $\rho_w = {{ shf_params.gw }}\text{ g/cc}$, $\rho_{hc} = {{ shf_params.ghc }}\text{ g/cc}$ ($\Delta\rho = {{ "%.2f"|format(shf_params.gw - shf_params.ghc) }}\text{ g/cc}$). -* **Log $S_w$ vs. $SHF$ Reconciliation:** Mean RMSE $= {{ "%.3f"|format(shf_params.reconciliation_rmse) }}\text{ v/v}$, Mean Bias ($S_w - SHF$) $= {{ "%+.3f"|format(shf_params.reconciliation_bias) }}\text{ v/v}$. +* **Fluid Density Gradient:** $\rho_w = {{ shf_params.gw }}\text{ g/cc}$, $\rho_{hc} = {{ shf_params.ghc }}\text{ g/cc}$ ($\Delta\rho = {{ "%.2f"|format(shf_params.gw - shf_params.ghc) }}\text{ g/cc}$, {{ shf_params.ghc_basis if shf_params.ghc_basis else 'Formation Fluid System' }}). +* **$J$-Function Fit Source:** {{ shf_params.fit_source if shf_params.fit_source else 'unspecified' }}. +{% if shf_params.reconciliation_rmse is not none %} +* **Log $S_w$ vs. $SHF$ Reconciliation:** RMSE $= {{ "%.3f"|format(shf_params.reconciliation_rmse) }}\text{ v/v}$, Mean Bias ($S_w - SHF$) $= {{ "%+.3f"|format(shf_params.reconciliation_bias) }}\text{ v/v}$ ($n = {{ shf_params.reconciliation_n }}$ target-zone samples above the FWL). +{% else %} +* **Log $S_w$ vs. $SHF$ Reconciliation:** not computed (fewer than 20 overlapping target-zone samples above the FWL). +{% endif %} +{% if shf_params.reconciliation_rmse is not none and shf_params.reconciliation_rmse > 0.12 %} + +> **QA ALERT:** SHF vs log $S_w$ RMSE exceeds the 0.12 v/v acceptance limit. The saturation-height function does not reproduce the log saturation and should not initialise the static model until the rock-type fits, FWL and fluid densities are reviewed. +{% endif %} + +{% if shf_params.fit_rows %} +#### Table {{ sec_num }}.1: Saved Leverett $J$-Function Fit by Rock Type -### {{ sec_num }}.2 Dynamic Simulation Relative Permeability ($K_{rw}, K_{ro}$) — {{ scal_params.source_label if scal_params.source_label else 'Analogue / Default North Sea Turbidite SCAL Parameterization' }} +| ROCK_FLAG | $a$ | $b$ | Fit $R^2$ | Fit RMSE | SCAL Points | Log vs SHF RMSE | Log Samples | +| :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | +{% for f in shf_params.fit_rows %} +| **{{ f.rock_flag }}** | {{ f.a }} | {{ f.b }} | {{ ("%.2f"|format(f.r2)) if f.r2 is not none else "—" }} | {{ ("%.3f"|format(f.rmse)) if f.rmse is not none else "—" }} | {{ f.n_scal }} | {{ ("%.3f"|format(f.log_rmse)) if f.log_rmse is not none else "—" }} | {{ f.n_log if f.n_log is not none else "—" }} | +{% endfor %} + +{% if shf_params.fit_rows|selectattr('n_scal', 'equalto', 0)|list|length > 0 %} +> Rock types with 0 SCAL points carry parameters borrowed from the nearest calibrated class; they are not independently constrained. +{% endif %} +{% endif %} + +### {{ sec_num }}.2 Dynamic Simulation Relative Permeability ($K_{rw}, K_{ro}$) — {{ scal_params.source_label if scal_params.source_label else 'Regional Analogue / Screening Parameterization' }} {% if scal_params.is_analogue %} -> **SCAL Data Provenance Notice:** Project-specific steady-state / unsteady-state coreflood relative permeability ($K_{rw}, K_{ro}$) tables are not loaded (`0 SCAL plugs` in Table 2.1). The parameters below represent an **Analogue / Default North Sea Turbidite SCAL Parameterization** for preliminary simulation sensitivity only. +> **SCAL Data Provenance Notice:** Project-specific steady-state / unsteady-state coreflood relative permeability ($K_{rw}, K_{ro}$) tables are not loaded (`0 SCAL plugs` in Table 2.1). The parameters below represent a **{{ scal_params.source_label }}** for preliminary simulation sensitivity only. {% endif %} +{% set scal_model = (scal_params.model or 'corey')|lower %} +{% if scal_model == 'let' %} +$$S_e = \frac{S_w - S_{wc}}{1 - S_{wc} - S_{or}}, \quad K_{rw}(S_w) = K_{rw}^0 \frac{S_e^{L_w}}{S_e^{L_w} + E_w (1 - S_e)^{T_w}}, \quad K_{ro}(S_w) = K_{ro}^0 \frac{(1 - S_e)^{L_o}}{(1 - S_e)^{L_o} + E_o S_e^{T_o}}$$ +{% else %} $$S_e = \frac{S_w - S_{wc}}{1 - S_{wc} - S_{or}}, \quad K_{rw}(S_w) = K_{rw}^0 \cdot (S_e)^{N_w}, \quad K_{ro}(S_w) = K_{ro}^0 \cdot (1 - S_e)^{N_o}$$ +{% endif %} | Parameter | Symbol | Value | Unit | Provenance / Dynamic Simulation Role | | :--- | :---: | :---: | :---: | :--- | @@ -31,7 +59,7 @@ $$S_e = \frac{S_w - S_{wc}}{1 - S_{wc} - S_{or}}, \quad K_{rw}(S_w) = K_{rw}^0 \ | Residual Oil Saturation | $S_{or}$ | {{ "%.2f"|format(scal_params.sor) }} | $\text{v/v}$ | Waterflood Residual Hydrocarbon ({{ scal_params.source_label }}) | | Max Water RelPerm | $K_{rw}^0$ | {{ "%.2f"|format(scal_params.krw_max) }} | $\text{frac}$ | Endpoint @ $S_w = 1 - S_{or}$ ({{ scal_params.source_label }}) | | Max Oil RelPerm | $K_{ro}^0$ | {{ "%.2f"|format(scal_params.kro_max) }} | $\text{frac}$ | Endpoint @ $S_w = S_{wc}$ ({{ scal_params.source_label }}) | -{% if scal_params.model == 'let' %} +{% if scal_model == 'let' %} | LET Water Parameters | $L_w / E_w / T_w$ | {{ "%.1f"|format(scal_params.lw) }} / {{ "%.1f"|format(scal_params.ew) }} / {{ "%.1f"|format(scal_params.tw) }} | unitless | Lomeland-Ebeltoft-Thomas Water Curve | | LET Oil Parameters | $L_o / E_o / T_o$ | {{ "%.1f"|format(scal_params.lo) }} / {{ "%.1f"|format(scal_params.eo) }} / {{ "%.1f"|format(scal_params.to) }} | unitless | Lomeland-Ebeltoft-Thomas Oil Curve | {% else %} diff --git a/quick_pp/app/backend/template/reports/sections/08_ressum_uncertainty.md.j2 b/quick_pp/app/backend/template/reports/sections/08_ressum_uncertainty.md.j2 index 349d3a1e..e7e8d8e9 100644 --- a/quick_pp/app/backend/template/reports/sections/08_ressum_uncertainty.md.j2 +++ b/quick_pp/app/backend/template/reports/sections/08_ressum_uncertainty.md.j2 @@ -26,6 +26,10 @@ Probabilistic petrophysical uncertainty ranges were quantified across $N = 1000$ | **{{ u.zone }}** | {{ u.metric }} | {{ u.p90 }} | **{{ u.p50 }}** | {{ u.p10 }} | {{ u.spread }} | {% endfor %} +{% if uncertainty_drivers_text %} +> **Tornado Sensitivity Drivers:** {{ uncertainty_drivers_text }} +{% endif %} + {% if volumetric_summary and volumetric_summary.field_totals %} ### {{ sec_num }}.4 Volumetric Hydrocarbon Resources (SPE-PRMS Latin Hypercube Monte Carlo) @@ -37,6 +41,16 @@ Probabilistic in-place and recoverable volumes were evaluated under **{{ volumet {% for z in volumetric_summary.zonal_summaries %} | **{{ z.zone }}** | {{ "%.2f"|format(z.stoiip.p90) }} | **{{ "%.2f"|format(z.stoiip.p50) }}** | {{ "%.2f"|format(z.stoiip.p10) }} | {{ "%.2f"|format(z.rec_oil.p50) }} | {{ "%.2f"|format(z.giip.p90) }} | **{{ "%.2f"|format(z.giip.p50) }}** | {{ "%.2f"|format(z.giip.p10) }} | {{ "%.2f"|format(z.rec_gas.p50) }} | {% endfor %} +{% else %} +### {{ sec_num }}.4 Volumetric Resource In-Place Readiness Note + +> [!NOTE] +> **Static Geomodel Handover & Volumetric Readiness:** 3D structural-framework gross rock volume (GRV) or drainage area boundaries have not been committed in this project snapshot. Petrophysical evaluation inputs are verified and primed for dynamic simulation and static geomodel populating: +> * **Cumulative Hydrocarbon Pore Thickness (HCPT), all {{ volumetric_readiness.evaluated_zones if volumetric_readiness and volumetric_readiness.evaluated_zones is defined else "—" }} zones:** ${{ "%.2f"|format(volumetric_readiness.column_hcpt) if volumetric_readiness and volumetric_readiness.column_hcpt is defined else "—" }}\text{ m}$ (sum of per-zone means; matches the Executive Summary) +> * **Mean HCPT per Evaluated Zone:** ${{ "%.2f"|format(volumetric_readiness.mean_hcpt) if volumetric_readiness and volumetric_readiness.mean_hcpt is defined else "—" }}\text{ m}$ +> * **Cumulative Net Pay Thickness:** ${{ "%.1f"|format(volumetric_readiness.column_net_pay) if volumetric_readiness and volumetric_readiness.column_net_pay is defined else "—" }}\text{ m}$ (mean per zone ${{ "%.1f"|format(volumetric_readiness.mean_net_pay) if volumetric_readiness and volumetric_readiness.mean_net_pay is defined else "—" }}\text{ m}$) +> * **Net-to-Gross Ratio (pay, total net pay / total gross):** ${{ "%.3f"|format(volumetric_readiness.mean_ntg) if volumetric_readiness and volumetric_readiness.mean_ntg is defined else "—" }}\text{ v/v}$ +> * **Average Reservoir Porosity & Water Saturation:** $\bar{\phi}_{e,pay} = {{ "%.3f"|format(volumetric_readiness.mean_phie) if volumetric_readiness and volumetric_readiness.mean_phie is defined else "—" }}\text{ v/v}$, $\bar{S}_{w,pay} = {{ "%.3f"|format(volumetric_readiness.mean_sw) if volumetric_readiness and volumetric_readiness.mean_sw is defined else "—" }}\text{ v/v}$ {% endif %} {% if include_ai_commentary and ai_commentary.uncertainty_narrative %} diff --git a/quick_pp/app/backend/template/reports/sections/09_upscaling.md.j2 b/quick_pp/app/backend/template/reports/sections/09_upscaling.md.j2 index 1ed10176..6b962ebb 100644 --- a/quick_pp/app/backend/template/reports/sections/09_upscaling.md.j2 +++ b/quick_pp/app/backend/template/reports/sections/09_upscaling.md.j2 @@ -8,18 +8,28 @@ Fine-scale evaluated CPI logs ($0.1524\text{ m}$ sampling) were upscaled onto ce * **Water Saturation ($S_w$):** Pore-volume weighted average: $\bar{S}_{w,cell} = \frac{\sum h_i \phi_i S_{w,i}}{\sum h_i \phi_i}$. * **Horizontal Permeability Proxy ($K_h$):** Arithmetic mean: $K_{arith} = \frac{\sum h_i K_i}{\sum h_i}$. * **Effective Heterogeneous Permeability ($K_{eff}$):** Geometric mean ($\omega \to 0$): $K_{geom} = \exp\left(\frac{\sum h_i \ln K_i}{\sum h_i}\right)$. -* **Vertical Permeability Proxy ($K_v$):** Harmonic mean ($\omega = -1$): $K_{harm} = \frac{\sum h_i}{\sum (h_i / K_i)}$, yielding vertical anisotropy ratio $K_v / K_h = K_{harm} / K_{arith}$. +* **Vertical Permeability Proxy ($K_v$):** Harmonic mean ($\omega = -1$): $K_{harm} = \frac{\sum h_i}{\sum (h_i / K_i)}$, yielding vertical anisotropy ratio $K_v / K_h = K_{harm} / K_{arith}${% if upscaling_summary and upscaling_summary.mean_kv_kh is defined %}{% endif %}. -| Well Name | Fine-Scale Samples | Blocked Grid Cells ({{ "%.1f"|format(upscaling_params.cell_size) }}m) | Mean $\phi_{blocked}$ (v/v) | Mean $S_{w,blocked}$ (v/v) | $K_{arith}$ ($K_h$, mD) | $K_{geom}$ ($K_{eff}$, mD) | $K_{harm}$ ($K_v$, mD) | Mean $K_v / K_h$ | -| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | +#### Table 9.1: All-Cell Blocked Cellular Grid Architecture & Permeability Anisotropy + +| Well Name | Fine-Scale Samples | Blocked Grid Cells ({{ "%.1f"|format(upscaling_params.cell_size) }}m) | Gross Logged (m) | Mean $\phi_{blocked}$ (v/v) | Mean $S_{w,blocked}$ (v/v) | $K_{arith}$ ($K_h$, mD) | $K_{geom}$ ($K_{eff}$, mD) | $K_{harm}$ ($K_v$, mD) | Mean $K_v / K_h$ | +| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | {% for up in upscaling_table %} -| **{{ up.well_name }}** | {{ up.fine_samples }} | {{ up.n_cells }} | {{ "%.3f"|format(up.phit_up) }} | {{ "%.3f"|format(up.swt_up) }} | {{ "%.1f"|format(up.k_arith) }} | {{ "%.1f"|format(up.k_geom) }} | {{ "%.2f"|format(up.k_harm) }} | {{ "%.3f"|format(up.kv_kh) }} | +| **{{ up.well_name }}** | {{ up.fine_samples }} | {{ up.n_cells }} | {{ "%.1f"|format(up.gross_m) if up.gross_m is defined else "—" }} | {{ "%.3f"|format(up.phit_up) }} | {{ "%.3f"|format(up.swt_up) }} | {{ "%.1f"|format(up.k_arith) }} | {{ "%.1f"|format(up.k_geom) }} | {{ "%.2f"|format(up.k_harm) }} | {{ "%.3f"|format(up.kv_kh) }} | {% endfor %} -{% if include_ai_commentary and ai_commentary.upscaling_narrative %} -{{ ai_commentary.upscaling_narrative }} +{% if upscaling_summary and upscaling_summary.mean_kv_kh is defined %} +Cardwell-Parsons directional permeability bounds yield a field-mean vertical-to-horizontal anisotropy ratio of **$K_v / K_h = {{ '%.3f'|format(upscaling_summary.mean_kv_kh) }}$** (range `{{ '%.3f'|format(upscaling_summary.min_kv_kh) }}–{{ '%.3f'|format(upscaling_summary.max_kv_kh) }}`) across the evaluated {{ wells|length }} {{ (wells|length) | pluralize('well') }}, preserving thin-bed vertical baffles for Eclipse/Intersect dynamic simulation. {% endif %} +#### Table 9.2: Active Net-Reservoir Cellular Blocked Averages & Volumetric Conservation Audit + +| Well Name | Active Res Cells | Blocked NTG (v/v) | Blocked $\bar{\phi}_{e,res}$ (v/v) | Fine-Scale $\bar{\phi}_{e,res}$ (v/v) | Blocked $\bar{S}_{w,res}$ (v/v) | Fine-Scale $\bar{S}_{w,res}$ (v/v) | $\Delta\phi$ Conservation | Audit Status | +| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | +{% for up in upscaling_table %} +| **{{ up.well_name }}** | {{ up.n_res_cells if up.n_res_cells is defined else up.n_cells }} | {{ "%.3f"|format(up.ntg_res_up if up.ntg_res_up is defined else 1.0) }} | {{ "%.3f"|format(up.phie_res_up if up.phie_res_up is defined else up.phit_up) }} | {{ "%.3f"|format(up.phie_res_fine if up.phie_res_fine is defined else up.phit_up) }} | {{ "%.3f"|format(up.swt_res_up if up.swt_res_up is defined else up.swt_up) }} | {{ "%.3f"|format(up.swt_res_fine if up.swt_res_fine is defined else up.swt_up) }} | {{ "%+.4f"|format(up.delta_phi_res if up.delta_phi_res is defined else 0.0) }} | **{{ up.conservation_status if up.conservation_status is defined else "✓ CONSERVED" }}** | +{% endfor %} + {% if custom_notes %} > **Petrophysicist Note:** {{ custom_notes }} {% endif %} diff --git a/quick_pp/app/backend/template/reports/sections/10_appendix_cpi.md.j2 b/quick_pp/app/backend/template/reports/sections/10_appendix_cpi.md.j2 index 3c82ae5d..4a5d4f2e 100644 --- a/quick_pp/app/backend/template/reports/sections/10_appendix_cpi.md.j2 +++ b/quick_pp/app/backend/template/reports/sections/10_appendix_cpi.md.j2 @@ -21,3 +21,10 @@ Composite 6-track Computer-Processed Interpretation (CPI) log plot displaying ga {% endif %} {% endfor %} + +{% if assets.cpi_skipped %} +> **Wells without a CPI log:** +{% for s in assets.cpi_skipped %} +> * `{{ s.well_name }}`: {{ s.reason }} +{% endfor %} +{% endif %} diff --git a/quick_pp/app/backend/template/reports/sections/10_gate_checks.md.j2 b/quick_pp/app/backend/template/reports/sections/10_gate_checks.md.j2 new file mode 100644 index 00000000..aab81ee7 --- /dev/null +++ b/quick_pp/app/backend/template/reports/sections/10_gate_checks.md.j2 @@ -0,0 +1,30 @@ +{% set is_single_well = (report_type == 'SINGLE_WELL_CPI') %} +{% set sec_num = '7' if is_single_well else '10' %} +# {{ sec_num }}. Petrophysical QA/QC Gate-Check & Peer-Review Audit Log + +Automated subsurface verification rules (`CHK-01` through `CHK-{{ "%02d"|format(gate_checks|length) if gate_checks else "00" }}`) evaluate borehole environmental conditioning, sensor confidence, depth matching, core porosity and permeability calibration, saturation-height reconciliation, formation pressure and uncertainty propagation prior to {{ "well CPI sign-off and reservoir modeling handover" if is_single_well else "static geomodel and dynamic simulation handover" }}.{% if gate_summary %} Overall status: **{{ gate_summary.overall }}** ({{ gate_summary.n_blocking }} blocking, {{ gate_summary.n_review }} review).{% endif %} + +### {{ sec_num }}.1 Automated Subsurface Gate-Check Matrix + +| Gate ID | Check Category | Acceptance Criterion | Measured Value / Finding | Status | Action / Sign-off Note | +| :---: | :--- | :--- | :--- | :---: | :--- | +{% for c in gate_checks %} +| **{{ c.id }}** | {{ c.category }} | {{ c.criterion }} | {{ c.measured }} | **{{ c.status }}** | {{ c.action_note }} | +{% endfor %} + +### {{ sec_num }}.2 Detected Subsurface Anomalies & Handover Remediation + +{% if anomaly_flags and anomaly_flags|length > 0 %} +| Anomaly Category | Target Well / Zone | Severity | Root-Cause Analysis | Required Remediation / Action Prior to Handover | +| :--- | :--- | :---: | :--- | :--- | +{% for a in anomaly_flags %} +| **{{ a.category }}** | `{{ a.target }}` | `{{ a.severity if a.severity else ("HIGH" if "CHK-03" in a.category or "Missing" in a.category else "MEDIUM") }}` | {{ a.message }} | {{ a.mitigation }} | +{% endfor %} +{% else %} +> [!NOTE] +> Zero critical subsurface anomalies or unmitigated flag conditions were detected for this project dataset. +{% endif %} + +{% if custom_notes %} +> **Petrophysicist Peer-Review Note:** {{ custom_notes }} +{% endif %} diff --git a/quick_pp/app/backend/utils/auth.py b/quick_pp/app/backend/utils/auth.py index 753f7d12..f6f3de7f 100644 --- a/quick_pp/app/backend/utils/auth.py +++ b/quick_pp/app/backend/utils/auth.py @@ -118,7 +118,9 @@ def validate_password_policy(password: str) -> Tuple[bool, List[str]]: if not re.search(r"\d", password): errors.append("Password must contain at least one number (0-9).") if not re.search(r"[^A-Za-z0-9]", password): - errors.append("Password must contain at least one special character (e.g. !@#$%^&*).") + errors.append( + "Password must contain at least one special character (e.g. !@#$%^&*)." + ) return (len(errors) == 0, errors) @@ -197,7 +199,9 @@ def verify_totp_code( ts = time.time() if timestamp is None else timestamp try: for step in range(-valid_window, valid_window + 1): - candidate = get_totp_code(secret, timestamp=ts + step * interval, interval=interval) + candidate = get_totp_code( + secret, timestamp=ts + step * interval, interval=interval + ) if hmac.compare_digest(candidate, cleaned_code): return True except Exception: @@ -239,8 +243,12 @@ def create_jwt_token( if extra_claims: payload.update(extra_claims) - header_b64 = _b64url_encode(json.dumps(header, separators=(",", ":")).encode("utf-8")) - payload_b64 = _b64url_encode(json.dumps(payload, separators=(",", ":")).encode("utf-8")) + header_b64 = _b64url_encode( + json.dumps(header, separators=(",", ":")).encode("utf-8") + ) + payload_b64 = _b64url_encode( + json.dumps(payload, separators=(",", ":")).encode("utf-8") + ) signing_input = f"{header_b64}.{payload_b64}".encode("ascii") sig = hmac.new(_get_secret_key(), signing_input, hashlib.sha256).digest() sig_b64 = _b64url_encode(sig) @@ -279,21 +287,20 @@ def decode_jwt_token(token: str, expected_type: Optional[str] = None) -> Dict[st # --------------------------------------------------------------------------- -def serialize_user(user: db_models.User, session: Optional[Session] = None) -> Dict[str, Any]: +def serialize_user( + user: db_models.User, session: Optional[Session] = None +) -> Dict[str, Any]: """Serialize a `User` ORM instance into a safe dictionary (never exposing password/MFA secret).""" memberships: List[Dict[str, Any]] = [] if session is not None: - rows = ( - session.execute( - select(db_models.ProjectMember, db_models.Project.name) - .join( - db_models.Project, - db_models.ProjectMember.project_id == db_models.Project.project_id, - ) - .where(db_models.ProjectMember.user_id == user.user_id) + rows = session.execute( + select(db_models.ProjectMember, db_models.Project.name) + .join( + db_models.Project, + db_models.ProjectMember.project_id == db_models.Project.project_id, ) - .all() - ) + .where(db_models.ProjectMember.user_id == user.user_id) + ).all() memberships = [ { "project_id": pm.project_id, @@ -359,7 +366,9 @@ def record_audit_event( def extract_token_from_request(request: Request) -> Optional[str]: """Extract JWT token from `Authorization: Bearer ` header or `qpp_access_token` cookie.""" - auth_header = request.headers.get("Authorization") or request.headers.get("authorization") + auth_header = request.headers.get("Authorization") or request.headers.get( + "authorization" + ) if auth_header and auth_header.lower().startswith("bearer "): return auth_header[7:].strip() cookie_token = request.cookies.get(AUTH_COOKIE_NAME) @@ -439,7 +448,12 @@ def get_current_user(request: Request) -> Dict[str, Any]: def require_admin(user: Dict[str, Any] = Depends(get_current_user)) -> Dict[str, Any]: - """Require the current user to have global `admin` role.""" + """Require the current user to have global `admin` role (disabled in public demo mode).""" + if is_demo_mode(): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="User Access Management (UAM) is disabled in public demo mode.", + ) if user.get("role") != "admin": raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, @@ -584,12 +598,17 @@ def send_invitation_email( """Send an invitation email via SMTP if `SMTP_HOST` is configured in environment variables.""" smtp_host = os.environ.get("SMTP_HOST", "").strip() if not smtp_host: - return False, "SMTP_HOST not configured; use the generated invite link and temporary password." + return ( + False, + "SMTP_HOST not configured; use the generated invite link and temporary password.", + ) smtp_port = int(os.environ.get("SMTP_PORT", "587")) smtp_user = os.environ.get("SMTP_USER", "").strip() smtp_pass = os.environ.get("SMTP_PASSWORD", "").strip() - smtp_from = os.environ.get("SMTP_FROM", smtp_user or "noreply@quickpp.local").strip() + smtp_from = os.environ.get( + "SMTP_FROM", smtp_user or "noreply@quickpp.local" + ).strip() use_tls = os.environ.get("SMTP_TLS", "true").lower() in ("1", "true", "yes") msg = EmailMessage() @@ -616,4 +635,3 @@ def send_invitation_email( except Exception as exc: log.warning("Failed to send SMTP invitation email to %s: %s", to_email, exc) return False, f"SMTP delivery failed ({exc}); share the invite link manually." - diff --git a/quick_pp/app/backend/utils/db.py b/quick_pp/app/backend/utils/db.py index 63426615..293920ec 100644 --- a/quick_pp/app/backend/utils/db.py +++ b/quick_pp/app/backend/utils/db.py @@ -1,5 +1,6 @@ import logging import os +import time from contextlib import contextmanager from typing import Any, Generator @@ -8,26 +9,77 @@ log = logging.getLogger(__name__) +def _allow_sqlite_fallback(db_url: str) -> bool: + """Only fall back from an explicit non-SQLite database when explicitly opted in. + + Silently rewriting QPP_DATABASE_URL to local SQLite inside a single Gunicorn worker + causes multi-worker split-brain where some workers read/write PostgreSQL while others + read/write a worker-local SQLite file. + """ + if not db_url or db_url.startswith("sqlite"): + return True + return os.environ.get("QPP_ALLOW_SQLITE_FALLBACK", "").strip().lower() in ( + "1", + "true", + "yes", + ) + + +def _init_connector(db_url: str) -> tuple[str, DBConnector]: + """Initialize DBConnector and run schema setup with retry backoff for network DBs.""" + if not db_url or db_url.startswith("sqlite:///./data"): + os.makedirs("./data", exist_ok=True) + connector = DBConnector(db_url) + max_attempts = 1 if db_url.startswith("sqlite") else 3 + last_exc: Exception | None = None + for attempt in range(1, max_attempts + 1): + try: + connector.setup_db() + return db_url, connector + except Exception as exc: + last_exc = exc + if attempt < max_attempts: + log.warning( + "Database setup attempt %d/%d for %s failed (%s); retrying...", + attempt, + max_attempts, + db_url, + exc, + ) + time.sleep(0.75 * attempt) + connector.dispose() + connector = DBConnector(db_url) + + if _allow_sqlite_fallback(db_url): + log.warning( + "Primary database (%s) unreachable (%s); falling back to local SQLite database.", + db_url, + last_exc, + ) + os.makedirs("./data", exist_ok=True) + connector.dispose() + fallback_url = _FALLBACK_SQLITE_URL + os.environ["QPP_DATABASE_URL"] = fallback_url + connector = DBConnector(fallback_url) + connector.setup_db() + return fallback_url, connector + + log.error( + "Configured database (%s) failed setup after %d attempts (%s). " + "Refusing silent SQLite fallback to prevent multi-worker split-brain.", + db_url, + max_attempts, + last_exc, + ) + if last_exc is not None: + raise last_exc + return db_url, connector + + # Initialize application-wide DBConnector singleton _FALLBACK_SQLITE_URL = "sqlite:///./data/quick_pp.db" -_DB_URL = os.environ.get("QPP_DATABASE_URL") or _FALLBACK_SQLITE_URL -if not _DB_URL or _DB_URL.startswith("sqlite:///./data"): - os.makedirs("./data", exist_ok=True) -_connector = DBConnector(_DB_URL) -try: - _connector.setup_db() -except Exception as exc: - log.warning( - "Primary database (%s) unreachable (%s); falling back to local SQLite database.", - _DB_URL, - exc, - ) - os.makedirs("./data", exist_ok=True) - _connector.dispose() - _DB_URL = _FALLBACK_SQLITE_URL - os.environ["QPP_DATABASE_URL"] = _DB_URL - _connector = DBConnector(_DB_URL) - _connector.setup_db() +_INITIAL_DB_URL = os.environ.get("QPP_DATABASE_URL") or _FALLBACK_SQLITE_URL +_DB_URL, _connector = _init_connector(_INITIAL_DB_URL) @contextmanager @@ -40,27 +92,16 @@ def get_db() -> Generator[Any, None, None]: """ global _DB_URL, _connector env_url = os.environ.get("QPP_DATABASE_URL") or _FALLBACK_SQLITE_URL - if env_url != _DB_URL or DBConnector._engine is None or DBConnector._engine_url != _DB_URL: + if ( + env_url != _DB_URL + or DBConnector._engine is None + or DBConnector._engine_url != _DB_URL + ): try: _connector.dispose() except Exception: pass - _DB_URL = env_url - _connector = DBConnector(_DB_URL) - try: - _connector.setup_db() - except Exception as exc: - log.warning( - "Database (%s) unreachable (%s); falling back to local SQLite database.", - _DB_URL, - exc, - ) - os.makedirs("./data", exist_ok=True) - _connector.dispose() - _DB_URL = _FALLBACK_SQLITE_URL - os.environ["QPP_DATABASE_URL"] = _DB_URL - _connector = DBConnector(_DB_URL) - _connector.setup_db() + _DB_URL, _connector = _init_connector(env_url) with _connector.get_session() as session: yield session diff --git a/quick_pp/app/docker/Dockerfile b/quick_pp/app/docker/Dockerfile index 91a2b1f5..982f44b9 100644 --- a/quick_pp/app/docker/Dockerfile +++ b/quick_pp/app/docker/Dockerfile @@ -9,8 +9,13 @@ WORKDIR /code RUN apt-get update && \ apt-get install -y --no-install-recommends \ postgresql-client \ + chromium \ + fonts-liberation \ && rm -rf /var/lib/apt/lists/* +# kaleido (plotly PNG export for report figures) drives this browser +ENV BROWSER_PATH=/usr/bin/chromium + COPY pyproject.toml . # Copy the rest of the repository into the image diff --git a/quick_pp/app/docker/docker-compose.yaml b/quick_pp/app/docker/docker-compose.yaml index 991e4cfe..c83b38d0 100644 --- a/quick_pp/app/docker/docker-compose.yaml +++ b/quick_pp/app/docker/docker-compose.yaml @@ -94,14 +94,19 @@ services: networks: - qpp-network - # Cloudflare Quick Tunnel — free random *.trycloudflare.com HTTPS URL. - # No Cloudflare account or token required. The URL changes on every restart. + # Cloudflare Tunnel — uses permanent Named Tunnel (e.g. https://app.example.com) + # when CF_TUNNEL_TOKEN is set in .env, or falls back to a free *.trycloudflare.com Quick Tunnel. quicktunnel: image: cloudflare/cloudflared:latest restart: unless-stopped depends_on: - web - command: tunnel --no-autoupdate --url http://web:80 + environment: + - TUNNEL_TOKEN=${CF_TUNNEL_TOKEN:-} + command: + - tunnel + - --no-autoupdate + - ${CF_TUNNEL_ARG:---url=http://web:80} networks: - qpp-network diff --git a/quick_pp/app/frontend/package-lock.json b/quick_pp/app/frontend/package-lock.json index 1e2f3b9a..c030e593 100644 --- a/quick_pp/app/frontend/package-lock.json +++ b/quick_pp/app/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "frontend", - "version": "0.3.7", + "version": "0.3.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "frontend", - "version": "0.3.7", + "version": "0.3.8", "devDependencies": { "@dnd-kit-svelte/svelte": "^0.1.5", "@dnd-kit/abstract": "^0.1.21", diff --git a/quick_pp/app/frontend/package.json b/quick_pp/app/frontend/package.json index cd711cc4..be257082 100644 --- a/quick_pp/app/frontend/package.json +++ b/quick_pp/app/frontend/package.json @@ -1,11 +1,11 @@ { "name": "frontend", "private": true, - "version": "0.3.7", + "version": "0.3.8", "type": "module", "scripts": { "dev": "vite dev", - "build": "vite build", + "build": "svelte-kit sync && vite build", "preview": "vite preview", "prepare": "svelte-kit sync || echo ''", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", diff --git a/quick_pp/app/frontend/src/lib/api/client.ts b/quick_pp/app/frontend/src/lib/api/client.ts index 1db6cd8d..32369be7 100644 --- a/quick_pp/app/frontend/src/lib/api/client.ts +++ b/quick_pp/app/frontend/src/lib/api/client.ts @@ -22,6 +22,49 @@ function resolveApiBase(): string { export const API_BASE = resolveApiBase(); export const TOKEN_STORAGE_KEY = 'qpp_access_token'; +export const DEMO_SESSION_STORAGE_KEY = 'qpp_demo_session_id'; + +let cachedDemoSessionId: string | null = null; +let onDemoCapacityCallback: ((online: number, max: number) => void) | null = null; +let onClientActivityCallback: (() => void) | null = null; + +export function registerDemoClientHooks(hooks: { + onCapacityReached?: (online: number, max: number) => void; + onActivity?: () => void; +}): void { + onDemoCapacityCallback = hooks.onCapacityReached ?? null; + onClientActivityCallback = hooks.onActivity ?? null; +} + +export function getDemoSessionId(): string { + if (cachedDemoSessionId) return cachedDemoSessionId; + if (typeof window === 'undefined') return ''; + try { + const existing = sessionStorage.getItem(DEMO_SESSION_STORAGE_KEY); + if (existing && /^[A-Za-z0-9_-]{6,64}$/.test(existing)) { + cachedDemoSessionId = existing; + return existing; + } + const bytes = new Uint8Array(12); + if (typeof crypto !== 'undefined' && crypto.getRandomValues) { + crypto.getRandomValues(bytes); + } else { + for (let i = 0; i < bytes.length; i++) { + bytes[i] = Math.floor(Math.random() * 256); + } + } + const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); + const generated = `demo_${hex}`; + sessionStorage.setItem(DEMO_SESSION_STORAGE_KEY, generated); + cachedDemoSessionId = generated; + return generated; + } catch { + if (!cachedDemoSessionId) { + cachedDemoSessionId = `demo_${Math.random().toString(36).slice(2, 14)}`; + } + return cachedDemoSessionId; + } +} export function getStoredToken(): string | null { if (typeof window === 'undefined') return null; @@ -43,6 +86,10 @@ export function authHeaders(extra: Record = {}): Record(); -export const api = createClient({ baseUrl: API_BASE }); +export const api = createClient({ baseUrl: API_BASE, credentials: 'include' }); api.use({ async onRequest({ request }) { @@ -476,6 +532,13 @@ api.use({ if (token) { request.headers.set('Authorization', `Bearer ${token}`); } + const demoSid = getDemoSessionId(); + if (demoSid) { + request.headers.set('X-Demo-Session-Id', demoSid); + } + if (!request.url.includes('/quick_pp/demo/')) { + onClientActivityCallback?.(); + } const desc = describeApiEndpoint(request.method, request.url); if (!desc.silent) { const taskId = appStatus.startTask(desc.active, desc.detail); @@ -523,6 +586,12 @@ async function parseErrorResponse(res: Response, fallbackMsg: string): Promise[], replace: boolean = true ) { @@ -652,6 +730,7 @@ export async function deleteAncillaryItem( | 'formation_tops' | 'fluid_contacts' | 'perforations' + | 'hole_sections' | 'core_samples' | 'scal_pc' | 'pressure_tests', @@ -915,8 +994,10 @@ export interface HandoverInventoryCounts { formation_tops?: number; fluid_contacts?: number; perforations?: number; + hole_sections?: number; well_surveys?: number; core_rca_samples?: number; + core_measurements_long?: number; pressure_tests?: number; scal_pc_points?: number; scal_relperm_points?: number; @@ -936,6 +1017,7 @@ export interface HandoverInspectionResult { has_tops: boolean; has_contacts: boolean; has_perforations: boolean; + has_hole_sections?: boolean; has_surveys: boolean; has_core: boolean; has_pressure: boolean; @@ -952,7 +1034,8 @@ export interface HandoverCommitResult { project_name: string; wells_imported: number; well_names: string[]; - counts: HandoverInventoryCounts; + counts?: HandoverInventoryCounts; + summary?: HandoverInventoryCounts; warnings?: string[]; } diff --git a/quick_pp/app/frontend/src/lib/components/BulkAncillaryImporter.svelte b/quick_pp/app/frontend/src/lib/components/BulkAncillaryImporter.svelte index 17cb1b49..5274ef96 100644 --- a/quick_pp/app/frontend/src/lib/components/BulkAncillaryImporter.svelte +++ b/quick_pp/app/frontend/src/lib/components/BulkAncillaryImporter.svelte @@ -2,6 +2,7 @@ import WellSelector from './WellSelector.svelte'; export let projectId: string | number; export let type: + | 'hole_sections' | 'formation_tops' | 'fluid_contacts' | 'perforations' @@ -61,6 +62,7 @@ let importMode: 'merge' | 'append_only' | 'replace' = 'merge'; const BACKEND_DATA_TYPE_MAP: Record = { + hole_sections: 'hole_sections', formation_tops: 'tops', fluid_contacts: 'contacts', perforations: 'perforations', @@ -71,6 +73,7 @@ }; const DATA_TYPE_DESCRIPTIONS: Record = { + hole_sections: 'Map columns for Well Name (or select Target Well), Top MD, Bottom MD, Bit Size (in), Mud Type (WBM/OBM/SBM), Mud Weight (ppg), Mud Salinity (ppm), and Rmf.', formation_tops: 'Map columns for Well Name (or select Target Well), Formation/Marker Name, and Measured Depth (MD).', fluid_contacts: 'Map columns for Well Name (or select Target Well), Contact Type (OWC/GOC/GWC/FWL), and Depth.', perforations: 'Map columns for Well Name (or select Target Well), Perforation Name, Top MD, Bottom MD, and Description.', @@ -81,6 +84,18 @@ }; const TARGET_COLUMN_OPTIONS: Record> = { + hole_sections: [ + { key: 'WELL_NAME', label: 'WELL_NAME — Well Name / UWI' }, + { key: 'SECTION_NAME', label: 'SECTION_NAME — Hole / Casing Section Name' }, + { key: 'TOP', label: 'TOP — Section Top MD *', required: true }, + { key: 'BOTTOM', label: 'BOTTOM — Section Bottom MD *', required: true }, + { key: 'BIT_SIZE', label: 'BIT_SIZE — Bit Size (in; mm auto-converted)' }, + { key: 'MUD_TYPE', label: 'MUD_TYPE — Mud System (WBM / OBM / SBM)' }, + { key: 'MUD_WEIGHT', label: 'MUD_WEIGHT — Mud Weight (ppg; g/cc & SG auto-converted)' }, + { key: 'MUD_SALINITY', label: 'MUD_SALINITY — Mud Filtrate Salinity (ppm; kppm auto-converted)' }, + { key: 'RMF', label: 'RMF — Mud Filtrate Resistivity (ohm.m)' }, + { key: 'RMF_TEMP', label: 'RMF_TEMP — Rmf Measurement Temperature (degC; degF auto-converted)' } + ], formation_tops: [ { key: 'WELL_NAME', label: 'WELL_NAME — Well Name / UWI' }, { key: 'TOP_NAME', label: 'TOP_NAME — Formation / Marker Name *', required: true }, @@ -494,6 +509,7 @@ bind:value={type} class="h-7 rounded-sm border border-[var(--border-hairline)] bg-[var(--bg-surface)] px-2.5 pr-7 py-0 text-xs font-medium text-[var(--text-primary)]" > + diff --git a/quick_pp/app/frontend/src/lib/components/HandoverImporter.svelte b/quick_pp/app/frontend/src/lib/components/HandoverImporter.svelte index 8cba7e6a..f9d26585 100644 --- a/quick_pp/app/frontend/src/lib/components/HandoverImporter.svelte +++ b/quick_pp/app/frontend/src/lib/components/HandoverImporter.svelte @@ -107,12 +107,25 @@ }); commitResult = res; - appStatus.success(`Successfully imported Handover Package into "${res.project_name}"!`); + const resolvedName = (res.project_name || targetProjectName).trim(); + appStatus.success(`Successfully imported Handover Package into "${resolvedName}"!`); - // Refresh project inventory and select the newly imported project + // Optimistically register project, refresh inventory, and select the newly imported project + if (res.project_id != null) { + projectData.upsertProject({ + project_id: Number(res.project_id), + name: resolvedName, + description: inspectionResult?.description + }); + } await projectData.loadProjects(); - if (res.project_id) { - await projectData.selectProject(res.project_id); + if (res.project_id != null) { + projectData.upsertProject({ + project_id: Number(res.project_id), + name: resolvedName, + description: inspectionResult?.description + }); + await projectData.selectProject(res.project_id, res.well_names?.[0] ?? null); } // Automatically close modal after brief delay or user interaction @@ -136,10 +149,13 @@

Round-Trip Petrophysical Handover Package Importer

-

- Import a complete quick_pp handover package archive (.zip). - This restores evaluated LAS well logs, formation tops, fluid contacts, perforations, directional surveys, - core RCA plugs, MDT pressure tests, and project CPI interpretation parameters into your workspace. +

+ Import a complete quick_pp handover package archive (.zip). This restores evaluated LAS well logs, formation tops, fluid contacts, + perforations, hole sections & mud program, directional surveys, core RCA + plugs, SCAL ($P_c$ & $k_r$), MDT pressure tests, and CPI interpretation + parameters.

@@ -147,7 +163,9 @@ {#if errorMessage} -
+
⚠
Import Error
@@ -166,12 +184,13 @@ {#if commitResult}
-
+
✓ Handover Package Successfully Imported!

- Project {commitResult.project_name} (ID #{commitResult.project_id}) has been created with + Project {commitResult.project_name} (ID #{commitResult.project_id}) + has been created with {commitResult.wells_imported} well(s). Switching active project now...

{#if commitResult.warnings && commitResult.warnings.length > 0} @@ -209,7 +228,9 @@ /> {#if inspecting}
-
+
Inspecting handover package archive & manifest... @@ -225,26 +246,38 @@
or click to browse from your computer
-
+
Standard format: exported by quick_pp Handover Package export
{/if}
{:else} -
+
-
+
- + {inspectionResult.project_name} - - {inspectionResult.wells_count} Well{inspectionResult.wells_count === 1 ? '' : 's'} + + {inspectionResult.wells_count} Well{inspectionResult.wells_count === 1 + ? '' + : 's'} {#if inspectionResult.quick_pp_version} - + v{inspectionResult.quick_pp_version} {/if} @@ -267,12 +300,16 @@ {#if inspectionResult.well_names && inspectionResult.well_names.length > 0}
- + Wells in Package ({inspectionResult.well_names.length}):
{#each inspectionResult.well_names as w} - + {w} {/each} @@ -282,56 +319,82 @@
- + Package Ancillary Content: -
-
+
+
Formation Tops
-
+
{inspectionResult.inventory_counts.formation_tops ?? 0}
-
+
Fluid Contacts
-
+
{inspectionResult.inventory_counts.fluid_contacts ?? 0}
-
+
Perforations
-
+
{inspectionResult.inventory_counts.perforations ?? 0}
-
+
+
Hole Sections
+
+ {inspectionResult.inventory_counts.hole_sections ?? 0} +
+
+
Well Surveys
-
+
{inspectionResult.inventory_counts.well_surveys ?? 0}
-
+
Core RCA Plugs
-
+
{inspectionResult.inventory_counts.core_rca_samples ?? 0}
-
+
MDT Pressure Tests
-
+
{inspectionResult.inventory_counts.pressure_tests ?? 0}
-
+
SCAL (Pc / RelPerm)
-
+
{(inspectionResult.inventory_counts.scal_pc_points ?? 0) + (inspectionResult.inventory_counts.scal_relperm_points ?? 0)}
-
+
CPI Parameters
-
+
{inspectionResult.has_manifest ? 'Preserved' : 'Default'}
@@ -340,12 +403,14 @@
-
+
Import Target Configuration
-
-
+
{#if selectedFile} - File: {selectedFile.name} ({formatBytes(selectedFile.size)}) + File: {selectedFile.name} + ({formatBytes(selectedFile.size)}) {/if}
@@ -395,7 +471,9 @@ class="flex h-7 items-center gap-1.5 rounded-sm bg-[var(--accent-primary)] px-4 text-xs font-semibold text-white shadow-xs hover:bg-blue-700 disabled:opacity-50" > {#if committing} -
+
Ingesting Package... {:else} 📥 Ingest & Load Project @@ -406,4 +484,3 @@
{/if}
- diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorAncillary.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorAncillary.svelte index 63ad3166..b14a50f2 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorAncillary.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorAncillary.svelte @@ -10,27 +10,165 @@ import { workbench } from '$lib/state/workbench.svelte'; import { depthDisplay } from '$lib/state/depthDisplay.svelte'; import { depthFromMeters, depthToMeters } from '$lib/utils/depthUnits'; + import { salinityFromRmf } from '$lib/utils/fluidUnits'; + import { fmtNum } from '$lib/utils/formatters'; import { computeMinimumCurvature, interpolateTrajectoryOnGrid } from '$lib/utils/trajectory'; - type AncillaryTab = 'tops' | 'contacts' | 'perfs' | 'core' | 'scal' | 'pressure' | 'survey'; - let { initialTab = 'tops' }: { initialTab?: AncillaryTab } = $props(); + type AncillaryTab = + | 'hole_sections' + | 'tops' + | 'contacts' + | 'perfs' + | 'core' + | 'scal' + | 'pressure' + | 'survey'; + let { initialTab }: { initialTab?: AncillaryTab } = $props(); // svelte-ignore state_referenced_locally - let activeTab = $state(initialTab); + if (initialTab) workbench.ancillarySubTab = initialTab; + let activeTab = $derived(workbench.ancillarySubTab); + function setActiveTab(tab: AncillaryTab) { + workbench.ancillarySubTab = tab; + } let isSaving = $state(false); let statusMsg = $state(null); + // Well Header & Metadata Editor state + let showWellHeader = $state(true); + let editingWellHeader = $state(false); + let savingWellHeader = $state(false); + let headerDraft = $state>({}); + + const derivedFiltrateSalinity = $derived.by(() => { + const r = Number(headerDraft.rmf); + if (!Number.isFinite(r) || r <= 0) return null; + const t = Number(headerDraft.rmf_temp); + return salinityFromRmf(r, Number.isFinite(t) ? t : 20); + }); + + const filtrateQcWarning = $derived.by(() => { + const r = Number(headerDraft.rmf); + const t = Number(headerDraft.rmf_temp); + const s = Number(headerDraft.mud_filtrate_salinity); + + if (Number.isFinite(r)) { + if (r <= 0) return 'Rmf must be greater than 0.'; + if (r > 15) + return `Rmf (${r} Ωm) is unusually high for mud filtrate (typically 0.02 – 5 Ωm).`; + } + if (Number.isFinite(t)) { + if (t < 0 || t > 70) + return `Rmf measurement temperature (${t}°C) is outside typical surface pit range (10 – 40°C).`; + } + if (Number.isFinite(s) && s > 350000) { + return `Mud filtrate salinity (${s.toLocaleString()} ppm) exceeds NaCl saturation limit (~350,000 ppm).`; + } + if ( + Number.isFinite(r) && + r > 0 && + Number.isFinite(s) && + s > 0 && + derivedFiltrateSalinity != null + ) { + const ratio = s / derivedFiltrateSalinity; + if (ratio > 1.4 || ratio < 0.6) { + const tempStr = Number.isFinite(t) ? `${t}°C` : '20°C'; + return `Input salinity (${s.toLocaleString()} ppm) differs from Rmf-derived NaCl equivalent (~${derivedFiltrateSalinity.toLocaleString()} ppm @ ${tempStr}). Verify if mud contains non-NaCl salts or check units.`; + } + } + return null; + }); + + function handleRmfInput() { + const derived = derivedFiltrateSalinity; + if ( + derived != null && + (headerDraft.mud_filtrate_salinity == null || headerDraft.mud_filtrate_salinity === '') + ) { + headerDraft.mud_filtrate_salinity = derived; + } + } + + let lastSyncedWellGen = -1; + $effect(() => { + const gen = wellData.wellLoadGeneration; + const hdr = wellData.header || {}; + if (gen !== lastSyncedWellGen && Object.keys(hdr).length > 0) { + lastSyncedWellGen = gen; + editingWellHeader = false; + } + }); + + function openHeaderEditor() { + const h = wellData.header || {}; + headerDraft = { + uwi: h.uwi ?? workbench.wellId ?? '', + company: h.company ?? '', + field: h.field ?? '', + country: h.country ?? '', + location: h.location ?? '', + province: h.province ?? '', + service_company: h.service_company ?? '', + log_date: h.log_date ?? '', + spud_date: h.spud_date ?? '', + latitude: h.latitude ?? null, + longitude: h.longitude ?? null, + x_coord: h.x_coord ?? null, + y_coord: h.y_coord ?? null, + crs: h.crs ?? '', + datum_unit: h.datum_unit || 'm', + kb_elev: h.kb_elev ?? null, + df_elev: h.df_elev ?? null, + gl_elev: h.gl_elev ?? null, + water_depth: h.water_depth ?? null, + bht: h.bht ?? null, + bht_unit: h.bht_unit || 'degC', + bit_size: h.bit_size ?? null, + rmf: h.rmf ?? null, + rmf_temp: h.rmf_temp ?? h.surface_temp ?? null, + mud_density: h.mud_density ?? null, + mud_filtrate_salinity: h.mud_filtrate_salinity ?? null, + mud_filtrate_density: h.mud_filtrate_density ?? null, + mud_type: h.mud_type ?? '', + obm_base_density: h.obm_base_density ?? null + }; + showWellHeader = true; + editingWellHeader = true; + } + + async function saveHeaderDraft() { + savingWellHeader = true; + try { + await wellData.saveWellHeader(headerDraft, true); + editingWellHeader = false; + } catch (e: any) { + wellData.lastError = e?.message || 'Failed to save well header'; + } finally { + savingWellHeader = false; + } + } + // New item quick-entry drafts (expressed directly in depthDisplay.unit) let newName = $state(''); let newDepth = $state(null); let newPerfTop = $state(null); let newPerfBottom = $state(null); let newPerfDesc = $state(''); + let newHoleTop = $state(null); + let newHoleBottom = $state(null); + let newHoleBitSize = $state(8.5); + let newHoleMudType = $state<'WBM' | 'OBM' | 'SBM'>('WBM'); + let newHoleMudWeight = $state(9.5); + let newHoleSalinity = $state(30000); + let newHoleRmf = $state(null); + let newHoleRmfTemp = $state(null); let newVal1 = $state(0.2); let newVal2 = $state(100); let newScalPc = $state(15); let newScalSw = $state(0.35); let newScalCpore = $state(null); let newScalCperm = $state(null); + let newScalExpType = $state('porous_plate'); // Formation pressure test quick-entry drafts (optional fields may be left blank) let newPressMob = $state(null); let newPressPerm = $state(null); @@ -46,17 +184,52 @@ previousDepthUnit = unit; if (oldUnit === unit) return; if (newDepth !== null && Number.isFinite(newDepth)) { - newDepth = Number(depthFromMeters(depthToMeters(newDepth, oldUnit), unit).toFixed(2)); + newDepth = Number( + depthFromMeters(depthToMeters(newDepth, oldUnit), unit).toFixed(2) + ); } if (newPerfTop !== null && Number.isFinite(newPerfTop)) { - newPerfTop = Number(depthFromMeters(depthToMeters(newPerfTop, oldUnit), unit).toFixed(2)); + newPerfTop = Number( + depthFromMeters(depthToMeters(newPerfTop, oldUnit), unit).toFixed(2) + ); } if (newPerfBottom !== null && Number.isFinite(newPerfBottom)) { - newPerfBottom = Number(depthFromMeters(depthToMeters(newPerfBottom, oldUnit), unit).toFixed(2)); + newPerfBottom = Number( + depthFromMeters(depthToMeters(newPerfBottom, oldUnit), unit).toFixed(2) + ); + } + if (newHoleTop !== null && Number.isFinite(newHoleTop)) { + newHoleTop = Number( + depthFromMeters(depthToMeters(newHoleTop, oldUnit), unit).toFixed(2) + ); + } + if (newHoleBottom !== null && Number.isFinite(newHoleBottom)) { + newHoleBottom = Number( + depthFromMeters(depthToMeters(newHoleBottom, oldUnit), unit).toFixed(2) + ); } }); }); + const HOLE_SECTION_COLS: GridColumn[] = [ + { key: 'name', label: 'Section', editable: true }, + { key: 'top', label: 'Top', unit: 'm', numeric: true, decimals: 1, editable: true }, + { key: 'bottom', label: 'Bottom', unit: 'm', numeric: true, decimals: 1, editable: true }, + { key: 'bit_size', label: 'Bit', unit: 'in', numeric: true, decimals: 3, editable: true }, + { key: 'mud_type', label: 'Mud', editable: true }, + { key: 'mud_weight', label: 'MW', unit: 'ppg', numeric: true, decimals: 2, editable: true }, + { + key: 'mud_salinity', + label: 'Salinity', + unit: 'ppm', + numeric: true, + decimals: 0, + editable: true + }, + { key: 'rmf', label: 'Rmf', unit: 'Ωm', numeric: true, decimals: 3, editable: true }, + { key: 'rmf_temp', label: 'Rmf T', unit: '°C', numeric: true, decimals: 1, editable: true } + ]; + const TOP_COLS: GridColumn[] = [ { key: 'name', label: 'Formation / Zone', editable: true }, { key: 'depth', label: 'Depth', unit: 'm', numeric: true, decimals: 1, editable: true } @@ -108,6 +281,7 @@ const SCAL_PC_COLS: GridColumn[] = [ { key: 'sample_name', label: 'Sample', editable: true }, { key: 'depth', label: 'Depth', unit: 'm', numeric: true, decimals: 2, editable: true }, + { key: 'experiment_type', label: 'Method', editable: true, width: '100px' }, { key: 'porosity', label: 'CPORE', @@ -310,6 +484,46 @@ async function addQuickRow() { if (!workbench.projectId || !workbench.wellId) return; + if (activeTab === 'hole_sections') { + if ( + newHoleTop === null || + !Number.isFinite(newHoleTop) || + newHoleBottom === null || + !Number.isFinite(newHoleBottom) + ) { + statusMsg = 'Enter valid top and bottom depths before adding a hole section.'; + return; + } + const t = depthToMeters(Number(newHoleTop), depthDisplay.unit); + const b = depthToMeters(Number(newHoleBottom), depthDisplay.unit); + if (Math.abs(b - t) < 1e-6) { + statusMsg = 'Hole section bottom depth must differ from top depth.'; + return; + } + const bsVal = optNum(newHoleBitSize); + wellData.holeSections = [ + ...wellData.holeSections, + { + id: `hs-${Date.now()}`, + name: + newName.trim() || + (bsVal != null ? `${bsVal}" Section` : `Section-${wellData.holeSections.length + 1}`), + top: Math.min(t, b), + bottom: Math.max(t, b), + bit_size: bsVal, + mud_type: (newHoleMudType || 'WBM').toUpperCase(), + mud_weight: optNum(newHoleMudWeight), + mud_salinity: optNum(newHoleSalinity), + rmf: optNum(newHoleRmf), + rmf_temp: optNum(newHoleRmfTemp) + } + ].sort((a, b2) => a.top - b2.top); + newName = ''; + newHoleTop = newHoleBottom; + newHoleBottom = null; + await saveCurrentTab(); + return; + } if (activeTab === 'perfs') { if ( newPerfTop === null || @@ -409,7 +623,9 @@ porosity: effPor, permeability: effPerm, rock_type: rt, - experiment_type: 'micp', + experiment_type: (newScalExpType || lastScal?.experiment_type || 'porous_plate') + .trim() + .toLowerCase(), cycle: 'drainage' } ]; @@ -443,7 +659,10 @@ const removeSet = new Set(indices); const removedCount = removeSet.size; try { - if (activeTab === 'tops') { + if (activeTab === 'hole_sections') { + wellData.holeSections = wellData.holeSections.filter((_, i) => !removeSet.has(i)); + wellData.syncBitSizeCurveFromHoleSections(); + } else if (activeTab === 'tops') { wellData.tops = wellData.tops.filter((_, i) => !removeSet.has(i)); if (workbench.selectedZones.length > 0) { const remainingNames = new Set(wellData.tops.map((t) => t.name)); @@ -480,7 +699,42 @@ async function handlePasteRows(pastedRows: Record[]) { if (!pastedRows.length) return; const now = Date.now(); - if (activeTab === 'tops') { + if (activeTab === 'hole_sections') { + const mapped = pastedRows + .map((r, i) => { + const t = Number(r.top ?? r.top_md ?? r.depth); + const b = Number(r.bottom ?? r.bottom_md ?? r.base); + const bs = optNum(r.bit_size ?? r.bs ?? r.bit); + const mtRaw = String(r.mud_type ?? r.mud ?? '').trim().toUpperCase(); + const mt = mtRaw.startsWith('OB') + ? 'OBM' + : mtRaw.startsWith('SB') + ? 'SBM' + : mtRaw.startsWith('WB') + ? 'WBM' + : mtRaw; + return { + id: `hs-${now}-${i}`, + name: String( + r.name || + r.section_name || + (bs != null ? `${bs}" Section` : `Section-${wellData.holeSections.length + i + 1}`) + ).trim(), + top: Math.min(t, b), + bottom: Math.max(t, b), + bit_size: bs, + mud_type: mt, + mud_weight: optNum(r.mud_weight ?? r.mw ?? r.mud_density), + mud_salinity: optNum(r.mud_salinity ?? r.salinity), + rmf: optNum(r.rmf), + rmf_temp: optNum(r.rmf_temp ?? r.rmf_temp_c) + }; + }) + .filter((s) => Number.isFinite(s.top) && Number.isFinite(s.bottom) && s.bottom > s.top); + wellData.holeSections = [...wellData.holeSections, ...mapped].sort( + (a, b) => a.top - b.top + ); + } else if (activeTab === 'tops') { const mapped = pastedRows .map((r, i) => ({ id: `top-${now}-${i}`, @@ -578,7 +832,11 @@ porosity: por, permeability: perm, rock_type: projectData.classifyRockType(por, perm), - experiment_type: r.experiment_type || 'micp', + experiment_type: String( + r.experiment_type || r.type || r.method || 'porous_plate' + ) + .trim() + .toLowerCase(), cycle: r.cycle || 'drainage' }; }) @@ -610,7 +868,59 @@ isSaving = true; statusMsg = null; try { - if (activeTab === 'tops') { + if (activeTab === 'hole_sections') { + wellData.holeSections = wellData.holeSections + .filter( + (s) => Number.isFinite(Number(s.top)) && Number.isFinite(Number(s.bottom)) + ) + .map((s, i) => { + const t = Number(s.top); + const b = Number(s.bottom); + const bs = optNum(s.bit_size); + const mtRaw = String(s.mud_type ?? '').trim().toUpperCase(); + const mt = mtRaw.startsWith('OB') + ? 'OBM' + : mtRaw.startsWith('SB') + ? 'SBM' + : mtRaw.startsWith('WB') + ? 'WBM' + : mtRaw; + return { + id: s.id || `hs-${i}`, + name: + String(s.name || '').trim() || + (bs != null ? `${bs}" Section` : `Section-${i + 1}`), + top: Math.min(t, b), + bottom: Math.max(t, b), + bit_size: bs, + mud_type: mt, + mud_weight: optNum(s.mud_weight), + mud_salinity: optNum(s.mud_salinity), + rmf: optNum(s.rmf), + rmf_temp: optNum(s.rmf_temp) + }; + }) + .filter((s) => s.bottom > s.top) + .sort((a, b) => a.top - b.top); + wellData.syncBitSizeCurveFromHoleSections(); + await saveAncillaryItems( + workbench.projectId, + workbench.wellId, + 'hole_sections', + 'hole_sections', + wellData.holeSections.map((s) => ({ + name: s.name, + top: s.top, + bottom: s.bottom, + bit_size: s.bit_size ?? null, + mud_type: s.mud_type || '', + mud_weight: s.mud_weight ?? null, + mud_salinity: s.mud_salinity ?? null, + rmf: s.rmf ?? null, + rmf_temp: s.rmf_temp ?? null + })) + ); + } else if (activeTab === 'tops') { await saveAncillaryItems( workbench.projectId, workbench.wellId, @@ -678,10 +988,11 @@ wellData.coreSamples ); } else if (activeTab === 'scal') { - // Propagate shared depth, porosity, and permeability for same sample_name if user edited one row + // Propagate shared depth, porosity, permeability, and experiment_type for same sample_name if user edited one row const depthBySample = new Map(); const cporeBySample = new Map(); const cpermBySample = new Map(); + const expBySample = new Map(); for (const r of wellData.scalPc) { const sname = String(r.sample_name || '').trim(); if (sname) { @@ -703,6 +1014,9 @@ ) { cpermBySample.set(sname, Number(r.permeability)); } + if (r.experiment_type) { + expBySample.set(sname, String(r.experiment_type).trim().toLowerCase()); + } } } const normalizedScal = wellData.scalPc.map((r, i) => { @@ -728,7 +1042,11 @@ porosity: por, permeability: perm, rock_type: projectData.classifyRockType(por, perm), - experiment_type: r.experiment_type || 'micp', + experiment_type: String( + expBySample.get(sname) || r.experiment_type || 'porous_plate' + ) + .trim() + .toLowerCase(), cycle: r.cycle || 'drainage' }; }); @@ -741,6 +1059,7 @@ 'pc_data', normalizedScal ); + void projectData.ensureSwirrDataLoaded(true); } else if (activeTab === 'pressure') { // Normalize (blank optional cells -> null) & drop rows missing depth/pressure wellData.pressureTests = wellData.pressureTests @@ -800,7 +1119,10 @@ async function handleScalCellChange(rowIndex: number, key: string, _newValue: any) { const row = wellData.scalPc[rowIndex]; - if (row && ['porosity', 'permeability', 'depth', 'sample_name'].includes(key)) { + if ( + row && + ['porosity', 'permeability', 'depth', 'sample_name', 'experiment_type'].includes(key) + ) { const sname = String(row.sample_name || '').trim(); if (sname) { const por = @@ -817,12 +1139,16 @@ ? Number(row.permeability) : null; const depth = Number.isFinite(Number(row.depth)) ? Number(row.depth) : null; + const expType = row.experiment_type + ? String(row.experiment_type).trim().toLowerCase() + : null; for (const r of wellData.scalPc) { if (String(r.sample_name || '').trim() === sname) { if (key === 'porosity') r.porosity = normPor; if (key === 'permeability') r.permeability = perm; if (key === 'depth' && depth !== null) r.depth = depth; + if (key === 'experiment_type' && expType) r.experiment_type = expType; r.rock_type = projectData.classifyRockType(r.porosity, r.permeability); } } @@ -841,30 +1167,616 @@ } await saveCurrentTab(); } + + let hdr = $derived(wellData.header || {}); + let dUnit = $derived(hdr.datum_unit || 'm');
- + +
+
+ +
+ +
+
+ + {#if showWellHeader} +
+ {#if hdr.company || hdr.field || hdr.country || hdr.crs} +
+ {#if hdr.company} + + {hdr.company} + + {/if} + {#if hdr.field} + + {hdr.field} + + {/if} + {#if hdr.country} + + {hdr.country} + + {/if} + {#if hdr.crs} + + CRS: {hdr.crs} + + {/if} +
+ {/if} + + {#if !editingWellHeader} +
+
+
Well Name / UWI
+
+ {hdr.well_name || workbench.wellId || '—'} + + ({hdr.uwi || hdr.api || '—'}) + +
+
+
+
Company / Operator
+
+ {hdr.company || '—'} +
+
+
+
Field / Block
+
+ {hdr.field || '—'}{hdr.location ? ` • ${hdr.location}` : ''} +
+
+
+
Country / Province
+
+ {hdr.country || '—'}{hdr.province ? ` (${hdr.province})` : ''} +
+
+
+
Latitude
+
+ {hdr.latitude != null ? `${Number(hdr.latitude).toFixed(6)}°` : '—'} + {#if hdr.latitude_raw && hdr.latitude_raw !== String(hdr.latitude)} + ({hdr.latitude_raw}) + {/if} +
+
+
+
Longitude
+
+ {hdr.longitude != null ? `${Number(hdr.longitude).toFixed(6)}°` : '—'} + {#if hdr.longitude_raw && hdr.longitude_raw !== String(hdr.longitude)} + ({hdr.longitude_raw}) + {/if} +
+
+ {#if hdr.x_coord != null || hdr.y_coord != null} +
+
X / Easting
+
+ {hdr.x_coord != null ? fmtNum(hdr.x_coord, 2) : '—'} +
+
+
+
Y / Northing
+
+ {hdr.y_coord != null ? fmtNum(hdr.y_coord, 2) : '—'} +
+
+ {/if} +
+
KB / DF Elevation
+
+ KB: {hdr.kb_elev != null ? `${hdr.kb_elev} ${dUnit}` : '—'} + {#if hdr.df_elev != null} + • DF: {hdr.df_elev} {dUnit} + {/if} +
+
+
+
GL / Water Depth
+
+ GL: {hdr.gl_elev != null ? `${hdr.gl_elev} ${dUnit}` : '—'} + {#if hdr.water_depth != null} + • WD: {hdr.water_depth} {dUnit} + {/if} +
+
+
+
Service Co. / Date
+
+ {hdr.service_company || '—'} + {#if hdr.log_date || hdr.spud_date} + • {hdr.log_date || hdr.spud_date} + {/if} +
+
+
+
+ BHT / Bit Size / Rmf +
+
+ {hdr.bht != null ? `${hdr.bht}°` : '—'} • {hdr.bit_size != null + ? `${hdr.bit_size}"` + : '—'} • {hdr.rmf != null + ? `${hdr.rmf} Ωm${hdr.rmf_temp != null ? ` @ ${hdr.rmf_temp}°C` : ''}` + : '—'} +
+
+
+
+ Mud Filtrate Density / Salinity / Type +
+
+ {hdr.mud_filtrate_density != null + ? `${fmtNum(hdr.mud_filtrate_density, 3)} g/cc` + : '—'} • {hdr.mud_filtrate_salinity != null + ? `${fmtNum(hdr.mud_filtrate_salinity, 0)} ppm` + : '—'} • {hdr.mud_type ? hdr.mud_type : '—'} +
+
+
+ + {#if Array.isArray(hdr.curve_lineage) && hdr.curve_lineage.length > 0} +
+ + Imported LAS curve lineage ({hdr.curve_lineage.length}) + +
+ {#each hdr.curve_lineage as entry} +
+ {entry.filename}: {entry.source_mnemonic}{entry.source_unit + ? ` (${entry.source_unit})` + : ''} + → {entry.stored_curve}{entry.raw_curve + ? ` (raw: ${entry.raw_curve})` + : ''} +
+ {/each} +
+
+ {/if} + {#if (hdr.raw_well_header && Object.keys(hdr.raw_well_header).length > 0) || (hdr.raw_parameters && Object.keys(hdr.raw_parameters).length > 0)} +
+ + Raw LAS/DLIS Header Tags ({Object.keys(hdr.raw_well_header || {}) + .length} ~Well, {Object.keys(hdr.raw_parameters || {}).length} ~Parameter) + +
+ {#each Object.entries( { ...(hdr.raw_well_header || {}), ...(hdr.raw_parameters || {}) } ) as [rk, rv]} +
+ {rk}: + {rv ?? '—'} +
+ {/each} +
+
+ {/if} + {:else} +
+
+ + + + + + + + + + + + + + + + + + + + + + {#if filtrateQcWarning} +
+
+ ⚠️ QC: + {filtrateQcWarning} +
+ {#if derivedFiltrateSalinity != null && Number(headerDraft.mud_filtrate_salinity) !== derivedFiltrateSalinity} + + {/if} +
+ {/if} +
+
+ + +
+
+ {/if} +
+ {/if} +
+ +
- {#each [['tops', `Tops (${wellData.tops.length})`], ['contacts', `Contacts (${wellData.contacts.length})`], ['perfs', `Perfs (${wellData.perforations.length})`], ['core', `RCA (${wellData.coreSamples.length})`], ['scal', `SCAL (${wellData.scalPc.length})`], ['pressure', `Press (${wellData.pressureTests.length})`], ['survey', `Survey (${wellData.survey.length})`]] as [key, lbl]} + {#each [['hole_sections', `Hole (${wellData.holeSections.length})`], ['tops', `Tops (${wellData.tops.length})`], ['contacts', `Contacts (${wellData.contacts.length})`], ['perfs', `Perfs (${wellData.perforations.length})`], ['core', `RCA (${wellData.coreSamples.length})`], ['scal', `SCAL (${wellData.scalPc.length})`], ['pressure', `Press (${wellData.pressureTests.length})`], ['survey', `Survey (${wellData.survey.length})`]] as [key, lbl]} @@ -875,7 +1787,81 @@
- {#if activeTab === 'tops' || activeTab === 'contacts'} + {#if activeTab === 'hole_sections'} + + + + + + + {#if newHoleMudType === 'WBM'} + + + + {/if} + {:else if activeTab === 'tops' || activeTab === 'contacts'} +
- {#if activeTab === 'tops'} + {#if activeTab === 'hole_sections'} + saveCurrentTab()} + onpasteRows={handlePasteRows} + ondeleteRow={handleDeleteRow} + ondeleteRows={handleDeleteRows} + /> + {:else if activeTab === 'tops'} + import { untrack } from 'svelte'; import { api, getJson, postJson } from '$lib/api/client'; import { authState } from '$lib/state/auth.svelte'; import NumericScrubber from '$lib/components/workbench/NumericScrubber.svelte'; @@ -6,11 +7,18 @@ import SavedParamsIndicator from '$lib/components/workbench/SavedParamsIndicator.svelte'; import VshCalibrationPanel from '$lib/components/workbench/VshCalibrationPanel.svelte'; import GammaSource from '$lib/components/workbench/GammaSource.svelte'; + import { moduleParams } from '$lib/state/moduleParams.svelte'; import { wellData } from '$lib/state/wellData.svelte'; import { workbench, computeSiltIntersection, type LithoOverride } from '$lib/state/workbench.svelte'; import { fmtNum } from '$lib/utils/formatters'; import { calculateMethodComparison } from '$lib/utils/methodComparison'; - import { gammaParameters, fluidDensityParameters, gammaEndpoints, gammaLabel } from '$lib/utils/lithology'; + import { + gammaParameters, + fluidDensityParameters, + gammaEndpoints, + gammaLabel, + syncHeaderToLithoParams + } from '$lib/utils/lithology'; import { gorMetricToScfStb, gorScfStbToMetric, @@ -18,7 +26,8 @@ pressureGradientPsiFtToMpaKm, pressureMpaToPsi, pressurePsiToMpa, - saturationTemperatureToMetric + saturationTemperatureToMetric, + salinityFromRmf } from '$lib/utils/fluidUnits'; import { ALL_LITHOLOGY_CURVES, @@ -382,6 +391,40 @@ return zeroedUpdates; } + let lastLithoHeaderSyncGen = -1; + $effect(() => { + const gen = wellData.wellLoadGeneration; + const hdr = wellData.header || {}; + if (gen !== lastLithoHeaderSyncGen && Object.keys(hdr).length > 0) { + lastLithoHeaderSyncGen = gen; + if (!untrack(() => moduleParams.status['litho-poro']?.matched)) { + syncHeaderToLithoParams(hdr, workbench.lithoParams); + } + } + }); + + const derivedFiltrateSalinity = $derived.by(() => { + const r = Number(workbench.lithoParams.fluidDensityRmf); + if (!Number.isFinite(r) || r <= 0) return null; + const t = Number(workbench.lithoParams.fluidDensityRmfTempC); + return salinityFromRmf(r, Number.isFinite(t) ? t : 20); + }); + + const filtrateMismatchWarning = $derived.by(() => { + if (workbench.lithoParams.fluidDensityMudType !== 'WBM') return null; + const r = Number(workbench.lithoParams.fluidDensityRmf); + const t = Number(workbench.lithoParams.fluidDensityRmfTempC); + const s = Number(workbench.lithoParams.fluidDensitySalinityPpm); + if (Number.isFinite(r) && r > 0 && Number.isFinite(s) && s > 0 && derivedFiltrateSalinity != null) { + const ratio = s / derivedFiltrateSalinity; + if (ratio > 1.4 || ratio < 0.6) { + const tempStr = Number.isFinite(t) ? `${t}°C` : '20°C'; + return `Mud Salinity (${s.toLocaleString()} ppm) differs significantly from Rmf-derived NaCl equivalent (~${derivedFiltrateSalinity.toLocaleString()} ppm @ ${tempStr}).`; + } + } + return null; + }); + let lithoPoroRunId = 0; async function executeLithoPoro(persist: boolean = false) { if (!workbench.projectId || !workbench.wellId) return; @@ -999,6 +1042,71 @@ )} g/cc).

{:else} + {#if wellData.holeSections.length > 0} +
+
+ Mud Filtrate Source + +
+
+ + +
+ {#if workbench.lithoParams.fluidDensityUseHoleSections} +
+ Using per-section mud system & salinity/Rmf from Hole Sections; controls below act as fallback outside defined sections (or OBM base oil density). +
+ {/if} +
+ {/if}
{#each [ ['WBM', 'WBM'], @@ -1020,17 +1128,35 @@ {/each}
- {#if wellData.header?.mud_type || wellData.header?.mud_filtrate_density != null} -

- Well metadata: - {#if wellData.header?.mud_type}{wellData.header.mud_type}{/if} - {#if wellData.header?.mud_filtrate_density != null} - • ρmf {fmtNum(wellData.header.mud_filtrate_density, 3)} g/cc - {/if} - {#if wellData.header?.mud_filtrate_salinity != null} - • {fmtNum(wellData.header.mud_filtrate_salinity, 0)} ppm - {/if} -

+ {#if wellData.header?.mud_type || wellData.header?.mud_filtrate_density != null || wellData.header?.rmf != null || wellData.header?.mud_filtrate_salinity != null} +
+
+ Header: + {#if wellData.header?.mud_type} {wellData.header.mud_type}{/if} + {#if wellData.header?.rmf != null} + • Rmf {wellData.header.rmf} Ωm{wellData.header.rmf_temp != null ? ` @ ${wellData.header.rmf_temp}°C` : ''} + {/if} + {#if wellData.header?.mud_filtrate_salinity != null} + • {fmtNum(wellData.header.mud_filtrate_salinity, 0)} ppm + {/if} + {#if wellData.header?.mud_filtrate_density != null} + • ρmf {fmtNum(wellData.header.mud_filtrate_density, 3)} g/cc + {/if} +
+ +
{/if} {#if workbench.lithoParams.fluidDensityMudType === 'WBM'} @@ -1062,6 +1188,31 @@ step={1} onrun={() => executeLithoPoro(false)} /> + {#if derivedFiltrateSalinity != null && derivedFiltrateSalinity !== workbench.lithoParams.fluidDensitySalinityPpm} +
+ Rmf implies ~{derivedFiltrateSalinity.toLocaleString()} ppm + +
+ {/if} + {#if filtrateMismatchWarning} +
+ ⚠️ {filtrateMismatchWarning} +
+ {/if} {:else} Uses mud-filtrate density/salinity from well metadata and estimates invaded-zone HC saturation in 0.01 increments to best match the binary solid-relative clay fraction to VSH_GR. {#if wellData.header?.mud_filtrate_density == null || wellData.header?.mud_filtrate_salinity == null} - Set both mud-filtrate properties in QAQC → Well Header before running. + Set both mud-filtrate properties in Well & Ancillary → Well Header before running. {/if}
{ - const values = c === target - ? ((!c.endsWith('_ORI') ? wellData.curves[`${c}_ORI`] : undefined) ?? wellData.originalCurves[c] ?? wellData.curves[c]) - : wellData.curves[c]; + const values = + c === target + ? ((!c.endsWith('_ORI') ? wellData.curves[`${c}_ORI`] : undefined) ?? + wellData.originalCurves[c] ?? + wellData.curves[c]) + : wellData.curves[c]; const selected = selectSpliceInterval(dept, values ?? [], spliceIntervals[c]); let top = Infinity; let bottom = -Infinity; @@ -439,7 +445,9 @@ ? Number(((gapTop + gapBottom) / 2).toFixed(1)) : Number.isFinite(combTop) && Number.isFinite(combBot) ? Number(((combTop + combBot) / 2).toFixed(1)) - : Number(((wellData.depthRange.min + wellData.depthRange.max) / 2).toFixed(1)); + : Number( + ((wellData.depthRange.min + wellData.depthRange.max) / 2).toFixed(1) + ); return { validCols, @@ -489,7 +497,9 @@ const candidate = curveName && curveList.includes(curveName) ? curveName - : (curveList.find((c) => !used.has(c) && !c.endsWith('_ORI')) ?? curveList[0] ?? ''); + : (curveList.find((c) => !used.has(c) && !c.endsWith('_ORI')) ?? + curveList[0] ?? + ''); if (!candidate) return; if (curveName && spliceRuns.includes(curveName)) return; spliceRuns = [...spliceRuns, candidate]; @@ -560,7 +570,13 @@ $effect(() => { const active = workbench.selectedQaqcCurve; const st = wellData.stats[active]; - if (st && st.min !== null && st.min !== undefined && st.max !== null && st.max !== undefined) { + if ( + st && + st.min !== null && + st.min !== undefined && + st.max !== null && + st.max !== undefined + ) { clipMin = Number(st.min.toFixed(4)); clipMax = Number(st.max.toFixed(4)); } @@ -582,14 +598,10 @@ } } - let missingStandardCurves = $derived( - REQUIRED_STANDARD.filter((m) => !curveList.includes(m)) - ); + let missingStandardCurves = $derived(REQUIRED_STANDARD.filter((m) => !curveList.includes(m))); let customOrExtraCurves = $derived( - curveList.filter( - (c) => !REQUIRED_STANDARD.includes(c) && !EVALUATED_CURVES.includes(c) - ) + curveList.filter((c) => !REQUIRED_STANDARD.includes(c) && !EVALUATED_CURVES.includes(c)) ); let activeOriCurveName = $derived.by(() => { @@ -600,11 +612,17 @@ let canRevertActiveCurve = $derived.by(() => { const c = workbench.selectedQaqcCurve; - const orig = (c && !c.endsWith('_ORI') ? wellData.curves[`${c}_ORI`] : undefined) ?? wellData.originalCurves[c]; + const orig = + (c && !c.endsWith('_ORI') ? wellData.curves[`${c}_ORI`] : undefined) ?? + wellData.originalCurves[c]; const cur = wellData.curves[c]; if (!orig || !cur || orig.length !== cur.length) return false; for (let i = 0; i < orig.length; i += Math.max(1, Math.floor(orig.length / 50))) { - if (Number.isFinite(orig[i]) && Number.isFinite(cur[i]) && Math.abs(orig[i] - cur[i]) > 1e-7) { + if ( + Number.isFinite(orig[i]) && + Number.isFinite(cur[i]) && + Math.abs(orig[i] - cur[i]) > 1e-7 + ) { return true; } if (Number.isFinite(orig[i]) !== Number.isFinite(cur[i])) { @@ -672,11 +690,7 @@ } } - async function applyQuickPreset( - op: CurveEditOperation, - val: number, - persist: boolean = false - ) { + async function applyQuickPreset(op: CurveEditOperation, val: number, persist: boolean = false) { if (op !== editOp && workbench.selectedQaqcCurve) { wellData.commitCurveEditBase(workbench.selectedQaqcCurve); editOp = op; @@ -756,8 +770,12 @@ $effect(() => { const dr = wellData.depthRange; const df = workbench.depthFilter; - workingTopDepth = Number(depthFromMeters(df ? df.min : dr.min, depthDisplay.unit).toFixed(4)); - workingBottomDepth = Number(depthFromMeters(df ? df.max : dr.max, depthDisplay.unit).toFixed(4)); + workingTopDepth = Number( + depthFromMeters(df ? df.min : dr.min, depthDisplay.unit).toFixed(4) + ); + workingBottomDepth = Number( + depthFromMeters(df ? df.max : dr.max, depthDisplay.unit).toFixed(4) + ); }); async function applyWorkingDepthInterval(persist: boolean = true) { @@ -791,26 +809,64 @@ // switches and are restored per zone / depth interval from saved well config. const ep = workbench.envCorrParams; - // Well Header & Metadata Editor state - let editingWellHeader = $state(false); - let savingWellHeader = $state(false); - let headerDraft = $state>({}); + function seedManualFromHoleSections() { + const sections = wellData.holeSections; + if (!sections || sections.length === 0) return; + const deepest = [...sections].sort((a, b) => b.bottom - a.bottom)[0]; + if (!deepest) return; + if (deepest.bit_size != null && Number.isFinite(deepest.bit_size) && deepest.bit_size > 0) { + ep.bitsizeDefault = deepest.bit_size; + workbench.badholeParams.bitsizeDefault = deepest.bit_size; + } + if ( + deepest.mud_type === 'WBM' || + deepest.mud_type === 'OBM' || + deepest.mud_type === 'SBM' + ) { + ep.mudType = deepest.mud_type; + } + if ( + deepest.mud_weight != null && + Number.isFinite(deepest.mud_weight) && + deepest.mud_weight > 0 + ) { + ep.mudWeight = deepest.mud_weight; + } + if ( + deepest.mud_salinity != null && + Number.isFinite(deepest.mud_salinity) && + deepest.mud_salinity >= 0 + ) { + ep.salinityPpm = deepest.mud_salinity; + } + if (deepest.rmf != null && Number.isFinite(deepest.rmf) && deepest.rmf > 0) { + ep.rmf = deepest.rmf; + } + if (deepest.rmf_temp != null && Number.isFinite(deepest.rmf_temp) && deepest.rmf_temp > 0) { + ep.rmfTempC = deepest.rmf_temp; + } + } + + function jumpToHoleSections() { + workbench.ancillarySubTab = 'hole_sections'; + workbench.singleWellStep = 'ancillary'; + } - let lastSyncedWellGen = -1; $effect(() => { const gen = wellData.wellLoadGeneration; const hdr = wellData.header || {}; - if (gen !== lastSyncedWellGen && Object.keys(hdr).length > 0) { - lastSyncedWellGen = gen; - editingWellHeader = false; - } - // Seed env-correction defaults from the well header once per well load, unless saved + // Seed env-correction defaults from the well header / hole sections once per well load, unless saved // parameters were restored for the active zone / depth selection. - if (gen !== lastEnvHeaderSyncGen && Object.keys(hdr).length > 0) { + if (gen !== lastEnvHeaderSyncGen && (Object.keys(hdr).length > 0 || wellData.holeSections.length > 0)) { lastEnvHeaderSyncGen = gen; if (untrack(() => moduleParams.status['qaqc-env']?.matched)) return; - if (typeof hdr.bit_size === 'number' && Number.isFinite(hdr.bit_size) && hdr.bit_size > 0) { + if ( + typeof hdr.bit_size === 'number' && + Number.isFinite(hdr.bit_size) && + hdr.bit_size > 0 + ) { ep.bitsizeDefault = hdr.bit_size; + workbench.badholeParams.bitsizeDefault = hdr.bit_size; } if ( typeof hdr.mud_density === 'number' && @@ -826,55 +882,40 @@ ) { ep.surfaceTemp = hdr.surface_temp; } + if (wellData.holeSections.length > 0) { + seedManualFromHoleSections(); + } } }); - function openHeaderEditor() { - const h = wellData.header || {}; - headerDraft = { - uwi: h.uwi ?? workbench.wellId ?? '', - company: h.company ?? '', - field: h.field ?? '', - country: h.country ?? '', - location: h.location ?? '', - province: h.province ?? '', - service_company: h.service_company ?? '', - log_date: h.log_date ?? '', - spud_date: h.spud_date ?? '', - latitude: h.latitude ?? null, - longitude: h.longitude ?? null, - x_coord: h.x_coord ?? null, - y_coord: h.y_coord ?? null, - crs: h.crs ?? '', - datum_unit: h.datum_unit || 'm', - kb_elev: h.kb_elev ?? null, - df_elev: h.df_elev ?? null, - gl_elev: h.gl_elev ?? null, - water_depth: h.water_depth ?? null, - bht: h.bht ?? null, - bht_unit: h.bht_unit || 'degC', - bit_size: h.bit_size ?? null, - rmf: h.rmf ?? null, - mud_density: h.mud_density ?? null, - mud_filtrate_salinity: h.mud_filtrate_salinity ?? null, - mud_filtrate_density: h.mud_filtrate_density ?? null, - mud_type: h.mud_type ?? '', - obm_base_density: h.obm_base_density ?? null - }; - editingWellHeader = true; - } - - async function saveHeaderDraft() { - savingWellHeader = true; - try { - await wellData.saveWellHeader(headerDraft, true); - editingWellHeader = false; - } catch (e: any) { - wellData.lastError = e?.message || 'Failed to save well header'; - } finally { - savingWellHeader = false; - } - } + // Environmental correction QC outputs (per-curve reliability, assumed inputs, resolved environment) + type EnvQcCurveSummary = { + samples: number; + good_pct: number; + corrected_pct: number; + unreliable_pct: number; + mean_conf: number | null; + mean_abs_delta: number | null; + p95_abs_delta: number | null; + }; + let envQcSummary = $state | null>(null); + let envAssumptions = $state([]); + let envInfo = $state<{ + tool_type: string; + depth_unit: string; + offshore: boolean; + top_temp_c: number; + gradient_c_per_km: number; + mud_type: string; + mud_weight_ppg: number; + } | null>(null); + const ENV_DELTA_UNITS: Record = { + GR: 'API', + NPHI: 'v/v', + RHOB: 'g/cc', + RT: 'dec', + DT: 'us/ft' + }; // Badhole Flagging diagnostics summary let badholeSummary = $state<{ @@ -925,6 +966,7 @@ { use_cali: bp.useCali, cali_threshold: bp.caliThreshold, + use_hole_sections: bp.useHoleSections && wellData.holeSections.length > 0, auto_bitsize: bp.autoBitsize, bitsize_default: bp.bitsizeDefault, use_drho: bp.useDrho, @@ -998,11 +1040,23 @@ const res = await postJson( `/quick_pp/workspace/projects/${encodeURIComponent(workbench.projectId)}/wells/${encodeURIComponent(workbench.wellId)}/environmental_corrections`, { + use_hole_sections: ep.useHoleSections && wellData.holeSections.length > 0, bitsize_default: ep.bitsizeDefault, mud_weight: ep.mudWeight, - surface_temp: ep.surfaceTemp, + surface_temp: ep.offshore ? null : ep.surfaceTemp, temp_grad: ep.tempGrad, - salinity_ppm: ep.salinityPpm, + salinity_ppm: ep.mudType === 'WBM' ? ep.salinityPpm : 0, + rho_mudcake: ep.rhoMudcake, + tool_type: ep.toolType, + mud_type: ep.mudType, + res_tool: ep.resTool === 'auto' ? null : ep.resTool, + depth_unit: ep.depthUnit === 'auto' ? null : ep.depthUnit, + water_depth: ep.offshore && ep.waterDepth > 0 ? ep.waterDepth : null, + seabed_temp_c: ep.offshore ? ep.seabedTempC : null, + rmf: ep.mudType === 'WBM' && ep.rmf > 0 ? ep.rmf : null, + rmf_temp_c: ep.mudType === 'WBM' && ep.rmf > 0 ? ep.rmfTempC : null, + formation_salinity_ppm: ep.formationSalinityPpm, + washout_thold: ep.washoutThold, min_depth: workbench.depthFilter?.min ?? null, max_depth: workbench.depthFilter?.max ?? null, zones: workbench.selectedZones.length > 0 ? workbench.selectedZones : null, @@ -1013,6 +1067,9 @@ wellData.mergeComputedCurves(res.data, res.stats, selectionIndices); wellData.markModuleComputed('qaqc-env', res.data); } + envQcSummary = res.qc_summary ?? null; + envAssumptions = Array.isArray(res.assumptions) ? res.assumptions : []; + envInfo = res.environment ?? null; if (persist) { if (selectionMode) { await wellData.saveModuleComputed('qaqc-env', 'Env Corrections Saved ✓'); @@ -1035,392 +1092,38 @@
- - {@const hdr = wellData.header || {}} - {@const dUnit = hdr.datum_unit || 'm'} -
-
- {#if hdr.company} - - {hdr.company} - - {/if} - {#if hdr.field} - - {hdr.field} - - {/if} - {#if hdr.country} - - {hdr.country} - - {/if} - {#if hdr.crs} - - CRS: {hdr.crs} - - {/if} -
- -
- - {#if !editingWellHeader} -
-
-
Well Name / UWI
-
- {hdr.well_name || workbench.wellId || '—'} - - ({hdr.uwi || hdr.api || '—'}) - -
-
-
-
Company / Operator
-
- {hdr.company || '—'} -
-
-
-
Field / Block
-
- {hdr.field || '—'}{hdr.location ? ` • ${hdr.location}` : ''} -
-
-
-
Country / Province
-
- {hdr.country || '—'}{hdr.province ? ` (${hdr.province})` : ''} -
-
-
-
Latitude
-
- {hdr.latitude != null ? `${Number(hdr.latitude).toFixed(6)}°` : '—'} - {#if hdr.latitude_raw && hdr.latitude_raw !== String(hdr.latitude)} - ({hdr.latitude_raw}) - {/if} -
-
-
-
Longitude
-
- {hdr.longitude != null ? `${Number(hdr.longitude).toFixed(6)}°` : '—'} - {#if hdr.longitude_raw && hdr.longitude_raw !== String(hdr.longitude)} - ({hdr.longitude_raw}) - {/if} -
-
- {#if hdr.x_coord != null || hdr.y_coord != null} -
-
X / Easting
-
- {hdr.x_coord != null ? fmtNum(hdr.x_coord, 2) : '—'} -
-
-
-
Y / Northing
-
- {hdr.y_coord != null ? fmtNum(hdr.y_coord, 2) : '—'} -
-
- {/if} -
-
KB / DF Elevation
-
- KB: {hdr.kb_elev != null ? `${hdr.kb_elev} ${dUnit}` : '—'} - {#if hdr.df_elev != null} - • DF: {hdr.df_elev} {dUnit} - {/if} -
-
-
-
GL / Water Depth
-
- GL: {hdr.gl_elev != null ? `${hdr.gl_elev} ${dUnit}` : '—'} - {#if hdr.water_depth != null} - • WD: {hdr.water_depth} {dUnit} - {/if} -
-
-
-
Service Co. / Date
-
- {hdr.service_company || '—'} - {#if hdr.log_date || hdr.spud_date} - • {hdr.log_date || hdr.spud_date} - {/if} -
-
-
-
BHT / Bit Size / Rmf
-
- {hdr.bht != null ? `${hdr.bht}°` : '—'} • {hdr.bit_size != null ? `${hdr.bit_size}"` : '—'} • {hdr.rmf != null ? `${hdr.rmf} Ωm` : '—'} -
-
-
-
Mud Filtrate Density / Salinity
-
- {hdr.mud_filtrate_density != null ? `${fmtNum(hdr.mud_filtrate_density, 3)} g/cc` : '—'} • {hdr.mud_filtrate_salinity != null ? `${fmtNum(hdr.mud_filtrate_salinity, 0)} ppm` : '—'} • {hdr.mud_type ? hdr.mud_type : '—'} -
-
-
- - {#if Array.isArray(hdr.curve_lineage) && hdr.curve_lineage.length > 0} -
- - Imported LAS curve lineage ({hdr.curve_lineage.length}) - -
- {#each hdr.curve_lineage as entry} -
- {entry.filename}: {entry.source_mnemonic}{entry.source_unit ? ` (${entry.source_unit})` : ''} - → {entry.stored_curve}{entry.raw_curve ? ` (raw: ${entry.raw_curve})` : ''} -
- {/each} -
-
- {/if} - {#if (hdr.raw_well_header && Object.keys(hdr.raw_well_header).length > 0) || (hdr.raw_parameters && Object.keys(hdr.raw_parameters).length > 0)} -
- - Raw LAS/DLIS Header Tags ({Object.keys(hdr.raw_well_header || {}).length} ~Well, {Object.keys(hdr.raw_parameters || {}).length} ~Parameter) - -
- {#each Object.entries({ ...(hdr.raw_well_header || {}), ...(hdr.raw_parameters || {}) }) as [rk, rv]} -
- {rk}: - {rv ?? '—'} -
- {/each} -
-
- {/if} - {:else} -
-
- - - - - - - - - - - - - - - - - - - -
-
- - -
-
- {/if} -
- -
+
Full Log Range: - {fmtDepth(depthFromMeters(wellData.depthRange.min, depthDisplay.unit), depthDisplay.unit)} – {fmtDepth(depthFromMeters(wellData.depthRange.max, depthDisplay.unit), depthDisplay.unit)} + {fmtDepth( + depthFromMeters(wellData.depthRange.min, depthDisplay.unit), + depthDisplay.unit + )} – {fmtDepth( + depthFromMeters(wellData.depthRange.max, depthDisplay.unit), + depthDisplay.unit + )} {#if hasCustomWorkingInterval} - + Saved for {workbench.wellId} {/if}
-
- + Computed & Custom Curves {#if wellData.calculatedCurvesPresent.length > 0} @@ -1525,14 +1231,18 @@ class="rounded-sm border border-red-200 bg-red-50 px-1.5 py-0.5 text-[9.5px] font-semibold text-red-700 hover:bg-red-100" title="Clear calculated curves top-to-bottom or by formation" > - {showClearCalcPanel ? 'Close Clear ✕' : `Clear Calc (${wellData.calculatedCurvesPresent.length})`} + {showClearCalcPanel + ? 'Close Clear ✕' + : `Clear Calc (${wellData.calculatedCurvesPresent.length})`} {/if}
{#if showClearCalcPanel && wellData.calculatedCurvesPresent.length > 0} -
+
- + Clear Calculated Curves @@ -1582,7 +1292,8 @@
-
+
{#each wellData.availableZones as zone (zone)} {@const active = clearCalcFormations.includes(zone)} {/each}
@@ -1664,7 +1379,8 @@
{/if}
- {#each [...EVALUATED_CURVES.filter((m) => curveList.includes(m)), ...customOrExtraCurves] as mnem (mnem)} + {#each [...EVALUATED_CURVES.filter( (m) => curveList.includes(m) ), ...customOrExtraCurves] as mnem (mnem)}
- Curve: + Curve: @@ -1743,7 +1462,8 @@
{#if activeOriCurveName} -
- Original backup preserved as {activeOriCurveName} +
+ Original backup preserved as {activeOriCurveName}
{#if runSt} -
+
- Interval: {fmtNum(runSt.top, 1)} – {fmtNum(runSt.bottom, 1)} m ({runSt.count} pts) + Interval: {fmtNum(runSt.top, 1)} – {fmtNum(runSt.bottom, 1)} m + ({runSt.count} pts) μ={fmtNum(runSt.mean, 2)} | σ={fmtNum(runSt.std, 2)} @@ -2102,7 +1856,9 @@
{/if}
-
-

Diagnostics compare the selected intervals of the first two runs.

-
+

+ Diagnostics compare the selected intervals of the first two runs. +

+
{#if spliceDiagnostics.hasOverlap}
- Overlap: {fmtNum(spliceDiagnostics.overlapTop, 1)} – {fmtNum(spliceDiagnostics.overlapBottom, 1)} m ({spliceDiagnostics.overlapCount} pts) + Overlap: {fmtNum(spliceDiagnostics.overlapTop, 1)} – {fmtNum( + spliceDiagnostics.overlapBottom, + 1 + )} m + ({spliceDiagnostics.overlapCount} pts) - ΔMean: {spliceDiagnostics.overlapDeltaMean !== null && spliceDiagnostics.overlapDeltaMean >= 0 ? '+' : ''}{fmtNum(spliceDiagnostics.overlapDeltaMean, 3)} + ΔMean: {spliceDiagnostics.overlapDeltaMean !== null && + spliceDiagnostics.overlapDeltaMean >= 0 + ? '+' + : ''}{fmtNum(spliceDiagnostics.overlapDeltaMean, 3)}
{:else if spliceDiagnostics.gapSpan !== null}
- Unlogged Gap: {fmtNum(spliceDiagnostics.gapTop, 1)} – {fmtNum(spliceDiagnostics.gapBottom, 1)} m + Unlogged Gap: {fmtNum(spliceDiagnostics.gapTop, 1)} – {fmtNum( + spliceDiagnostics.gapBottom, + 1 + )} m {fmtNum(spliceDiagnostics.gapSpan, 1)} m gap @@ -2153,7 +1939,13 @@
{:else}
- Combined Interval: {fmtNum(spliceDiagnostics.combinedTop, 1)} – {fmtNum(spliceDiagnostics.combinedBottom, 1)} m + Combined Interval: {fmtNum(spliceDiagnostics.combinedTop, 1)} – {fmtNum( + spliceDiagnostics.combinedBottom, + 1 + )} m
{/if}
@@ -2161,7 +1953,9 @@
- Overlap Mode + Overlap Mode Auto-level secondary run to match mean in overlap -