From 0c4fbf869ea8fb665b651c1a4080cf5850e6afb4 Mon Sep 17 00:00:00 2001 From: imranfadhil Date: Wed, 4 Nov 2026 12:35:06 +0800 Subject: [PATCH 01/30] revisit well deletion from project handling --- quick_pp/app/backend/services/database.py | 25 ++++++++--- tests/test_ancillary.py | 53 +++++++++++++++++++++++ 2 files changed, 71 insertions(+), 7 deletions(-) diff --git a/quick_pp/app/backend/services/database.py b/quick_pp/app/backend/services/database.py index 28e9427d..1cfbcf1d 100644 --- a/quick_pp/app/backend/services/database.py +++ b/quick_pp/app/backend/services/database.py @@ -576,13 +576,24 @@ def delete_well(project_id: int, well_name: str, request: Request): if target_orm_well is not None: wid = target_orm_well.well_id session.expunge_all() - session.execute( - text( - "DELETE FROM curve_data WHERE curve_id IN (" - "SELECT curve_id FROM curves WHERE well_id = :wid)" - ), - {"wid": wid}, - ) + for statement in ( + "DELETE FROM curve_data WHERE curve_id IN " + "(SELECT curve_id FROM curves WHERE well_id = :wid)", + "DELETE FROM core_measurements WHERE sample_id IN " + "(SELECT sample_id FROM core_samples WHERE well_id = :wid)", + "DELETE FROM relative_permeability WHERE sample_id IN " + "(SELECT sample_id FROM core_samples WHERE well_id = :wid)", + "DELETE FROM capillary_pressure WHERE sample_id IN " + "(SELECT sample_id FROM core_samples WHERE well_id = :wid)", + "DELETE FROM formation_tops WHERE well_id = :wid", + "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 well_surveys WHERE well_id = :wid", + "DELETE FROM core_samples WHERE well_id = :wid", + "DELETE FROM curves WHERE well_id = :wid", + ): + session.execute(text(statement), {"wid": wid}) session.execute( text("DELETE FROM wells WHERE well_id = :wid"), {"wid": wid}, diff --git a/tests/test_ancillary.py b/tests/test_ancillary.py index fdbad015..9d0e95fc 100644 --- a/tests/test_ancillary.py +++ b/tests/test_ancillary.py @@ -1,3 +1,5 @@ +from uuid import uuid4 + from fastapi import FastAPI from fastapi.testclient import TestClient @@ -9,6 +11,57 @@ client = TestClient(app) +def test_well_delete_clears_tops_and_surveys_before_reupload(): + project_name = f"WellDeleteAncillary-{uuid4().hex}" + well_name = f"Well-{uuid4().hex}" + uwi = f"UWI-{uuid4().hex}" + project_res = client.post( + "/quick_pp/database/projects", json={"name": project_name} + ) + assert project_res.status_code == 200 + pid = project_res.json()["project_id"] + + well_res = client.post( + f"/quick_pp/database/projects/{pid}/wells", + json={"name": well_name, "uwi": uwi}, + ) + assert well_res.status_code == 200 + + tops_res = client.post( + f"/quick_pp/database/projects/{pid}/wells/{well_name}/formation_tops", + json={"tops": [{"name": "Top-A", "depth": 1000.0}]}, + ) + assert tops_res.status_code == 200 + surveys_res = client.post( + f"/quick_pp/database/projects/{pid}/wells/{well_name}/well_surveys", + json={"surveys": [{"md": 1000.0, "inc": 15.0, "azim": 90.0}]}, + ) + assert surveys_res.status_code == 200 + + delete_res = client.delete( + f"/quick_pp/database/projects/{pid}/wells/{well_name}" + ) + assert delete_res.status_code == 200 + + reupload_res = client.post( + f"/quick_pp/database/projects/{pid}/wells", + json={"name": well_name, "uwi": uwi}, + ) + assert reupload_res.status_code == 200 + + tops_after = client.get( + f"/quick_pp/database/projects/{pid}/wells/{well_name}/formation_tops" + ) + surveys_after = client.get( + f"/quick_pp/database/projects/{pid}/well_surveys", + params={"well_name": well_name}, + ) + assert tops_after.status_code == 200 + assert tops_after.json()["tops"] == [] + assert surveys_after.status_code == 200 + assert surveys_after.json()["well_surveys"] == [] + + def test_formation_tops_lifecycle(): # Create a project res = client.post("/quick_pp/database/projects", json={"name": "TestProj"}) From ade4722f45e9cce6247d4cfa13183f9392bd2b63 Mon Sep 17 00:00:00 2001 From: imranfadhil Date: Wed, 4 Nov 2026 12:40:27 +0800 Subject: [PATCH 02/30] improve saturation module --- quick_pp/app/backend/services/report.py | 16 ++- quick_pp/app/backend/services/workspace.py | 123 ++++++++++++++++-- .../components/modules/InspectorReport.svelte | 3 + .../modules/InspectorSaturation.svelte | 56 +++++++- .../workbench/CrossplotCanvas.svelte | 91 ++++++++++++- .../workbench/ReportPreviewCanvas.svelte | 5 +- .../src/lib/state/moduleParams.svelte.ts | 17 ++- .../frontend/src/lib/state/wellData.svelte.ts | 3 + .../src/lib/state/workbench.svelte.ts | 11 +- tests/test_backend_workspace_api.py | 36 ++++- 10 files changed, 336 insertions(+), 25 deletions(-) diff --git a/quick_pp/app/backend/services/report.py b/quick_pp/app/backend/services/report.py index 408004ad..73082837 100644 --- a/quick_pp/app/backend/services/report.py +++ b/quick_pp/app/backend/services/report.py @@ -1738,12 +1738,15 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: raw_sw_key = str( merged_configs.get("sw_model_key") or merged_configs.get("sw_model") - or "waxman_smits" + or "archie" ).strip().lower() - if raw_sw_key == "archie": - sw_model_display = "Archie Clean-Sand Water Saturation Model" - else: - sw_model_display = "Waxman-Smits Shaly-Sand Cation Exchange ($Q_v$) Model" + sw_model_display = { + "archie": "Archie Clean-Sand Water Saturation Model", + "waxman_smits": "Waxman-Smits Shaly-Sand Cation Exchange ($Q_v$) Model", + "simandoux": "Simandoux Shaly-Sand Water Saturation Model", + "indonesian": "Indonesian Shaly-Sand Water Saturation Model", + "dual_water": "Dual-Water Shaly-Sand Water Saturation Model", + }.get(raw_sw_key, "Archie Clean-Sand Water Saturation Model") dry_sand_pt = merged_configs.get("dry_sand_point") dry_clay_pt = merged_configs.get("dry_clay_point") @@ -1958,6 +1961,9 @@ def _has_positive_col(col_name: str, threshold: float = 0.005) -> bool: "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), + "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"))), diff --git a/quick_pp/app/backend/services/workspace.py b/quick_pp/app/backend/services/workspace.py index 0aee8163..6ec72bf4 100644 --- a/quick_pp/app/backend/services/workspace.py +++ b/quick_pp/app/backend/services/workspace.py @@ -6,7 +6,7 @@ """ import math -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Literal, Optional, Tuple import numpy as np import pandas as pd @@ -98,13 +98,16 @@ ) from quick_pp.saturation import ( archie_saturation, + dual_water_saturation, estimate_b_waxman_smits, estimate_qv, estimate_qvn, estimate_rw_temperature_salinity, extract_fluid_contacts_and_limits, fit_swirr_correlation, + indonesian_saturation, optimize_fwl, + simandoux_saturation, swirr_rqi, swirr_semilog_k, swirr_timur, @@ -780,9 +783,11 @@ class WorkspacePermeabilityRequest(WorkspaceFilterBase): class WorkspaceSaturationRequest(WorkspaceFilterBase): - method: str = Field( - "waxman_smits", - description="Primary saturation curve to save/highlight: 'waxman_smits' or 'archie'", + method: Literal[ + "archie", "waxman_smits", "simandoux", "indonesian", "dual_water" + ] = Field( + "archie", + description="Primary saturation curve to save: 'archie', 'waxman_smits', 'simandoux', 'indonesian', or 'dual_water'", ) rw_mode: str = Field( "salinity_temp", @@ -810,12 +815,24 @@ class WorkspaceSaturationRequest(WorkspaceFilterBase): ) cec_clay: float = Field(0.1, description="Clay cation exchange capacity (meq/g)") rho_dry_clay: float = Field(2.71, description="Dry clay bulk density (g/cc)") + rsh: float = Field( + 2.0, gt=0, description="Shale resistivity used by Simandoux and Indonesian (ohm.m)" + ) + swb: float = Field( + 0.2, ge=0, le=1, description="Bound-water saturation used by Dual Water (fraction)" + ) + rwb: float = Field( + 0.1, gt=0, description="Bound-water resistivity used by Dual Water (ohm.m)" + ) depths: Optional[List[float]] = Field( None, description="Optional client-side depth array fallback" ) phit: Optional[List[Optional[float]]] = Field( None, description="Optional client-side PHIT array fallback" ) + phie: Optional[List[Optional[float]]] = Field( + None, description="Optional client-side PHIE array fallback" + ) vclay: Optional[List[Optional[float]]] = Field( None, description="Optional client-side VCLAY array fallback" ) @@ -3747,12 +3764,12 @@ def workspace_permeability( @router.post( "/wells/{well_name}/saturation", - summary="Compute single-pass depth-aligned water saturation (Archie + Waxman-Smits) on server", + summary="Compute depth-aligned Archie and shaly-sand water saturation models on server", ) def workspace_saturation( project_id: int, well_name: str, req: WorkspaceSaturationRequest ) -> Dict[str, Any]: - """Compute TEMP_GRAD, RW, B, QVN, M_STAR, SWT_ARCHIE, SWT_WAXMAN, and crossplot data in one pass.""" + """Compute Archie and alternative water saturation curves in one depth-aligned pass.""" try: df = _get_filtered_well_df( project_id, well_name, req.min_depth, req.max_depth, req.zones @@ -3762,6 +3779,7 @@ def workspace_saturation( depths=req.depths, curve_arrays={ "PHIT": req.phit, + "PHIE": req.phie, "VCLAY": req.vclay, "PHIT_SAND": req.phit_sand, "VSH_LAM": req.vsh_lam, @@ -3812,6 +3830,12 @@ def workspace_saturation( if (use_ts and "VSH_DIS" in df.columns) else vclay_bulk ) + phie_fallback = phit * (1.0 - vclay.fillna(0.0).clip(0.0, 1.0)) + phie = ( + pd.to_numeric(df["PHIE"], errors="coerce").fillna(phie_fallback) + if "PHIE" in df.columns and not use_ts + else phie_fallback + ) vsh_lam_s = ( pd.to_numeric(df["VSH_LAM"], errors="coerce").fillna(0.0).clip(0.0, 0.99) if (use_ts and "VSH_LAM" in df.columns) @@ -3969,6 +3993,64 @@ def workspace_saturation( np.asarray(swt_w, dtype=float).ravel(), 0.0, 1.0 ) + shale_mask = archie_mask & vclay.notna() + swt_simandoux_s = pd.Series(np.nan, index=df.index, dtype=float) + if shale_mask.any(): + swt_simandoux = simandoux_saturation( + rt[shale_mask].to_numpy(dtype=float), + rw_s[shale_mask].to_numpy(dtype=float), + phit[shale_mask].to_numpy(dtype=float), + vclay[shale_mask].clip(0.0, 1.0).to_numpy(dtype=float), + float(req.rsh), + float(req.a), + float(req.m), + ) + swt_simandoux_s.loc[shale_mask] = np.clip( + np.asarray(swt_simandoux, dtype=float).ravel(), 0.0, 1.0 + ) + + indonesian_mask = ( + rt.notna() + & (rt > 0) + & rw_s.notna() + & (rw_s > 0) + & phie.notna() + & (phie > 0) + & vclay.notna() + ) + swt_indonesian_s = pd.Series(np.nan, index=df.index, dtype=float) + if indonesian_mask.any(): + swt_indonesian = indonesian_saturation( + rt[indonesian_mask].to_numpy(dtype=float), + rw_s[indonesian_mask].to_numpy(dtype=float), + phie[indonesian_mask].to_numpy(dtype=float), + vclay[indonesian_mask].clip(0.0, 1.0).to_numpy(dtype=float), + np.full(int(indonesian_mask.sum()), float(req.rsh), dtype=float), + float(req.a), + float(req.m), + float(req.n), + ) + swt_indonesian_s.loc[indonesian_mask] = np.clip( + np.asarray(swt_indonesian, dtype=float).ravel(), 0.0, 1.0 + ) + + dual_water_mask = archie_mask & phit.notna() + swt_dual_water_s = pd.Series(np.nan, index=df.index, dtype=float) + if dual_water_mask.any(): + swt_dual_water = dual_water_saturation( + rt[dual_water_mask].to_numpy(dtype=float), + rw_s[dual_water_mask].to_numpy(dtype=float), + phit[dual_water_mask].to_numpy(dtype=float), + float(req.a), + float(req.m), + float(req.n), + float(req.swb), + float(req.rwb), + ) + swt_dual_water_s.loc[dual_water_mask] = np.clip( + np.asarray(swt_dual_water, dtype=float).ravel(), 0.0, 1.0 + ) + coal_or_zero_phi = rt.notna() & phit.notna() & (phit <= 0.0) if "COAL_FLAG" in df.columns: coal_or_zero_phi = coal_or_zero_phi | ( @@ -3981,13 +4063,22 @@ def workspace_saturation( if coal_or_zero_phi.any(): swt_archie_s.loc[coal_or_zero_phi] = 1.0 swt_ws_s.loc[coal_or_zero_phi] = 1.0 + swt_simandoux_s.loc[coal_or_zero_phi] = 1.0 + swt_indonesian_s.loc[coal_or_zero_phi] = 1.0 + swt_dual_water_s.loc[coal_or_zero_phi] = 1.0 if use_ts: # Map sand-lamina water saturation Sw_sand back to bulk SWT so bulk HCPV = PHIT_bulk * (1 - SWT) # equals thin-bed sand HCPV = (1 - VSH_LAM) * PHIT_SAND * (1 - Sw_sand) sand_frac = (1.0 - vsh_lam_s).clip(0.0, 1.0) denom_phi = phit_bulk.clip(lower=1e-4) - for sw_series in (swt_archie_s, swt_ws_s): + for sw_series in ( + swt_archie_s, + swt_ws_s, + swt_simandoux_s, + swt_indonesian_s, + swt_dual_water_s, + ): valid_sw = sw_series.notna() & phit_bulk.notna() & (phit_bulk > 1e-4) if valid_sw.any(): hcpv_lam = ( @@ -4002,7 +4093,14 @@ def workspace_saturation( sw_series.loc[valid_sw], swt_bulk_mapped ) - primary_swt = swt_ws_s if req.method.lower() == "waxman_smits" else swt_archie_s + saturation_curves = { + "archie": swt_archie_s, + "waxman_smits": swt_ws_s, + "simandoux": swt_simandoux_s, + "indonesian": swt_indonesian_s, + "dual_water": swt_dual_water_s, + } + primary_swt = saturation_curves[req.method.lower()] bvw_s = phit_bulk * primary_swt # Crossplot helper columns (CWA vs VCLAY/PHIT) @@ -4030,6 +4128,9 @@ def workspace_saturation( "M_STAR": m_star_s, "SWT_ARCHIE": swt_archie_s, "SWT_WAXMAN": swt_ws_s, + "SWT_SIMANDOUX": swt_simandoux_s, + "SWT_INDONESIAN": swt_indonesian_s, + "SWT_DUAL_WATER": swt_dual_water_s, "SWT": primary_swt, "BVW": bvw_s, "VCL_OVER_PHI": vcl_phi_s, @@ -4062,6 +4163,9 @@ def workspace_saturation( "sw_n": float(req.n), "water_salinity": float(salinity_ppm), "rw_val": float(np.nanmedian(rw_arr)) if len(rw_arr) > 0 else 0.08, + "sw_rsh": float(req.rsh), + "sw_swb": float(req.swb), + "sw_rwb": float(req.rwb), }, persist_db=bool(req.save), ) @@ -4074,6 +4178,9 @@ def workspace_saturation( "SWT": _curve_summary_stats(primary_swt), "SWT_ARCHIE": _curve_summary_stats(swt_archie_s), "SWT_WAXMAN": _curve_summary_stats(swt_ws_s), + "SWT_SIMANDOUX": _curve_summary_stats(swt_simandoux_s), + "SWT_INDONESIAN": _curve_summary_stats(swt_indonesian_s), + "SWT_DUAL_WATER": _curve_summary_stats(swt_dual_water_s), "RW": _curve_summary_stats(rw_s), }, **dataframe_to_columnar(out_df), diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorReport.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorReport.svelte index aba0a276..b9c67d82 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorReport.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorReport.svelte @@ -205,6 +205,9 @@ sw_n: workbench.saturationParams.n, water_salinity: workbench.saturationParams.waterSalinity, rw_val: workbench.saturationParams.rwPickett, + sw_rsh: workbench.saturationParams.rsh, + sw_swb: workbench.saturationParams.swb, + sw_rwb: workbench.saturationParams.rwb, scal_params: { ...workbench.scalParams }, core_corrected: workbench.scalParams.core_corrected, core_lithology: workbench.scalParams.core_lithology, diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte index 01474df3..25c9d65a 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte @@ -54,6 +54,13 @@ let estimatedRwAtSurface = $derived.by(() => estimateTempAndRwAtDepth(0)); let estimatedRwAtRefDepth = $derived.by(() => estimateTempAndRwAtDepth(refDepth)); + const saturationModelLabels: Record = { + archie: 'ARCHIE', + waxman_smits: 'WAXMAN-SMITS', + simandoux: 'SIMANDOUX', + indonesian: 'INDONESIAN', + dual_water: 'DUAL WATER' + }; let hasTsAvailable = $derived.by(() => { const ps = wellData.curves['PHIT_SAND']; @@ -100,9 +107,13 @@ qv_method: sp.qvMethod, cec_clay: sp.cecClay, rho_dry_clay: sp.rhoDryClay, + rsh: sp.rsh, + swb: sp.swb, + rwb: sp.rwb, use_thomas_stieber: useTs, depths: cleanArr(deptArr) as number[] | undefined, phit: cleanArr(phitArr), + phie: cleanArr(wellData.curves['PHIE'] ?? []), vclay: cleanArr(vclayArr), phit_sand: useTs ? cleanArr(phitSandArr) : undefined, vsh_lam: useTs ? cleanArr(vshLamArr) : undefined, @@ -148,18 +159,59 @@
Primary Solver
+ {#if workbench.saturationParams.method === 'simandoux' || + workbench.saturationParams.method === 'indonesian'} + +
+ Indonesian uses PHIE when available, otherwise PHIT × (1 − VCLAY). +
+ {:else if workbench.saturationParams.method === 'dual_water'} + + +
+ Dual Water uses constant bound-water Swb and Rwb values. +
+ {/if}
Rw Source Mode diff --git a/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte b/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte index fa92819c..f1742d3c 100644 --- a/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte +++ b/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte @@ -43,7 +43,7 @@ case 'perm': return 'phi-k'; case 'saturation': - return 'pickett'; + return 'sw-comparison'; case 'scal': return 'core-qc'; default: @@ -1893,10 +1893,82 @@ return { traces, layout: baseLayout }; } + if (effectiveMode === 'sw-comparison') { + const archie = wellData.curves['SWT_ARCHIE'] ?? []; + const models = [ + { key: 'SWT_WAXMAN', label: 'Waxman-Smits', color: '#2563EB', method: 'waxman_smits' }, + { key: 'SWT_SIMANDOUX', label: 'Simandoux', color: '#D97706', method: 'simandoux' }, + { key: 'SWT_INDONESIAN', label: 'Indonesian', color: '#059669', method: 'indonesian' }, + { key: 'SWT_DUAL_WATER', label: 'Dual Water', color: '#7C3AED', method: 'dual_water' } + ] as const; + + traces.push({ + type: 'scatter', + mode: 'lines', + name: '1:1 agreement', + x: [0, 1], + y: [0, 1], + line: { color: '#64748B', width: 1.2, dash: 'dash' }, + hoverinfo: 'skip' + }); + + for (const model of models) { + const modelSw = wellData.curves[model.key] ?? []; + const xs: number[] = []; + const ys: number[] = []; + const customIdx: number[] = []; + const depths: number[] = []; + for (const idx of indices) { + const archieSw = archie[idx]; + const modelValue = modelSw[idx]; + if ( + Number.isFinite(archieSw) && + Number.isFinite(modelValue) && + archieSw >= 0 && + archieSw <= 1 && + modelValue >= 0 && + modelValue <= 1 + ) { + xs.push(archieSw); + ys.push(modelValue); + customIdx.push(idx); + depths.push(deptAll[idx]); + } + } + const isSelected = workbench.saturationParams.method === model.method; + traces.push({ + type: 'scatter', + mode: 'markers', + name: `${model.label} vs Archie`, + x: xs, + y: ys, + customdata: customIdx, + text: depths, + marker: { + size: isSelected ? 7 : 5, + color: model.color, + opacity: isSelected ? 0.9 : 0.45, + line: { color: '#FFFFFF', width: 0.5 } + }, + hovertemplate: + 'Depth: %{text:.2f} m
Archie Sw: %{x:.3f}
' + + `${model.label} Sw: %{y:.3f}` + }); + } + + baseLayout.dragmode = 'lasso'; + baseLayout.xaxis.title = { text: 'Archie Water Saturation (v/v)' }; + baseLayout.xaxis.range = [0, 1]; + baseLayout.yaxis.title = { text: 'Alternative Model Water Saturation (v/v)' }; + baseLayout.yaxis.range = [0, 1]; + return { traces, layout: baseLayout }; + } + if (effectiveMode === 'pickett') { const phiArr = wellData.curves['PHIT'] ?? wellData.curves['PHIE'] ?? wellData.curves['NPHI'] ?? []; const rtArr = wellData.curves['RT'] ?? []; + const colorCurve = wellData.curves['VCLAY'] !== undefined ? 'VCLAY' : 'GR'; const vclArr = wellData.curves['VCLAY'] ?? wellData.curves['GR'] ?? []; const xs: number[] = []; @@ -1926,7 +1998,14 @@ size: 5.5, color: cols, colorscale: 'YlGnBu', - opacity: 0.85 + showscale: true, + opacity: 0.85, + colorbar: { + title: { text: colorCurve, font: { size: 9 } }, + thickness: 10, + len: 0.75, + tickfont: { family: 'JetBrains Mono', size: 8 } + } }, hovertemplate: 'Rt: %{x:.2f} ohm.m
Φ: %{y:.3f} v/v' }); @@ -4231,6 +4310,13 @@ void wellData.curves[cName]; void wellData.curves[`${cName}_ORI`]; void wellData.stats[cName]; + } else if (mode === 'sw-comparison') { + void wellData.curves['SWT_ARCHIE']; + void wellData.curves['SWT_WAXMAN']; + void wellData.curves['SWT_SIMANDOUX']; + void wellData.curves['SWT_INDONESIAN']; + void wellData.curves['SWT_DUAL_WATER']; + void workbench.saturationParams.method; } else if (mode === 'pickett') { void wellData.curves['PHIT']; void wellData.curves['PHIE']; @@ -4612,6 +4698,7 @@ > + diff --git a/quick_pp/app/frontend/src/lib/components/workbench/ReportPreviewCanvas.svelte b/quick_pp/app/frontend/src/lib/components/workbench/ReportPreviewCanvas.svelte index 0753673f..633e36ef 100644 --- a/quick_pp/app/frontend/src/lib/components/workbench/ReportPreviewCanvas.svelte +++ b/quick_pp/app/frontend/src/lib/components/workbench/ReportPreviewCanvas.svelte @@ -275,7 +275,10 @@ sw_m: workbench.saturationParams.m, sw_n: workbench.saturationParams.n, water_salinity: workbench.saturationParams.waterSalinity, - rw_val: workbench.saturationParams.rwPickett + rw_val: workbench.saturationParams.rwPickett, + sw_rsh: workbench.saturationParams.rsh, + sw_swb: workbench.saturationParams.swb, + sw_rwb: workbench.saturationParams.rwb }, sections: activeCfg.sections, cutoffs: activeCfg.cutoffs, diff --git a/quick_pp/app/frontend/src/lib/state/moduleParams.svelte.ts b/quick_pp/app/frontend/src/lib/state/moduleParams.svelte.ts index 7c14c412..2a06aca7 100644 --- a/quick_pp/app/frontend/src/lib/state/moduleParams.svelte.ts +++ b/quick_pp/app/frontend/src/lib/state/moduleParams.svelte.ts @@ -60,7 +60,7 @@ export const SINGLE_WELL_REGIONAL_DEFAULTS: Record({ - method: 'waxman_smits', + method: 'archie', rwMode: 'salinity_temp', measSystem: 'metric', waterSalinity: 35000, @@ -741,6 +745,9 @@ class WorkbenchState { qvMethod: 'cec', cecClay: 0.1, rhoDryClay: 2.71, + rsh: 2.0, + swb: 0.2, + rwb: 0.1, fwl: 0 }); diff --git a/tests/test_backend_workspace_api.py b/tests/test_backend_workspace_api.py index 7a10e0cc..7a08f49c 100644 --- a/tests/test_backend_workspace_api.py +++ b/tests/test_backend_workspace_api.py @@ -206,7 +206,7 @@ def test_end_to_end_workspace_compute_workflow(client_and_project): assert perm_body["saved_rows"] == 10 assert perm_body["core_metrics"]["count"] == 5 - # 5. Saturation (single-pass Archie + Waxman-Smits, save=True) + # 5. Saturation (single-pass Archie and alternative models, save=True) r_sat = client.post( f"/quick_pp/workspace/projects/{pid}/wells/Well-A/saturation", json={"method": "waxman_smits", "water_salinity": 35000.0, "save": True}, @@ -368,6 +368,40 @@ def test_end_to_end_workspace_compute_workflow(client_and_project): assert r_put.json()["rows"] == 2 +def test_saturation_model_comparison_curves_and_archie_default(client_and_project): + client, pid = client_and_project + endpoint = f"/quick_pp/workspace/projects/{pid}/wells/Well-A/saturation" + fallback = { + "depths": np.linspace(1000.0, 1009.0, 10).tolist(), + "phit": np.linspace(0.12, 0.25, 10).tolist(), + "phie": np.linspace(0.1, 0.2, 10).tolist(), + "vclay": np.linspace(0.1, 0.4, 10).tolist(), + "save": False, + } + + default_response = client.post(endpoint, json=fallback) + assert default_response.status_code == 200, default_response.text + default_body = default_response.json() + assert default_body["method"] == "archie" + assert default_body["data"]["SWT"] == default_body["data"]["SWT_ARCHIE"] + + model_curves = { + "waxman_smits": "SWT_WAXMAN", + "simandoux": "SWT_SIMANDOUX", + "indonesian": "SWT_INDONESIAN", + "dual_water": "SWT_DUAL_WATER", + } + for method, curve in model_curves.items(): + response = client.post(endpoint, json={**fallback, "method": method}) + assert response.status_code == 200 + body = response.json() + assert body["method"] == method + assert len(body["data"][curve]) == 10 + assert any(value is not None for value in body["data"][curve]) + assert body["data"]["SWT"] == body["data"][curve] + assert len(body["data"]["SWT_ARCHIE"]) == 10 + + def test_petrophysical_mcp_server_and_agent_assistant(client_and_project): client, pid = client_and_project From afe00735cfb23eb8cb5a3532251e00845b052745 Mon Sep 17 00:00:00 2001 From: imranfadhil Date: Wed, 4 Nov 2026 12:41:04 +0800 Subject: [PATCH 03/30] corrected silent replacement of PHIT with PHIE in the workflow --- quick_pp/app/backend/services/workspace.py | 48 +++++++------------ .../components/modules/InspectorPerm.svelte | 2 +- .../modules/InspectorSaturation.svelte | 5 +- .../shell/WorkflowGuideSheet.svelte | 2 +- .../components/shell/WorkflowStepper.svelte | 2 +- .../workbench/CrossplotCanvas.svelte | 14 ++---- .../workbench/LogTrackCanvas.svelte | 46 ++++++++++++++---- .../frontend/src/lib/state/wellData.svelte.ts | 4 +- quick_pp/app/frontend/src/routes/+page.svelte | 23 ++++++--- tests/test_backend_workspace_api.py | 12 ++++- 10 files changed, 90 insertions(+), 68 deletions(-) diff --git a/quick_pp/app/backend/services/workspace.py b/quick_pp/app/backend/services/workspace.py index 6ec72bf4..69b64c99 100644 --- a/quick_pp/app/backend/services/workspace.py +++ b/quick_pp/app/backend/services/workspace.py @@ -830,9 +830,6 @@ class WorkspaceSaturationRequest(WorkspaceFilterBase): phit: Optional[List[Optional[float]]] = Field( None, description="Optional client-side PHIT array fallback" ) - phie: Optional[List[Optional[float]]] = Field( - None, description="Optional client-side PHIE array fallback" - ) vclay: Optional[List[Optional[float]]] = Field( None, description="Optional client-side VCLAY array fallback" ) @@ -3556,12 +3553,6 @@ def _merge_request_fallback_curves( except Exception: pass - if ( - "PHIT" not in out.columns - or pd.to_numeric(out["PHIT"], errors="coerce").isna().all() - ) and "PHIE" in out.columns: - out["PHIT"] = pd.to_numeric(out["PHIE"], errors="coerce") - return out @@ -3779,7 +3770,6 @@ def workspace_saturation( depths=req.depths, curve_arrays={ "PHIT": req.phit, - "PHIE": req.phie, "VCLAY": req.vclay, "PHIT_SAND": req.phit_sand, "VSH_LAM": req.vsh_lam, @@ -3830,12 +3820,6 @@ def workspace_saturation( if (use_ts and "VSH_DIS" in df.columns) else vclay_bulk ) - phie_fallback = phit * (1.0 - vclay.fillna(0.0).clip(0.0, 1.0)) - phie = ( - pd.to_numeric(df["PHIE"], errors="coerce").fillna(phie_fallback) - if "PHIE" in df.columns and not use_ts - else phie_fallback - ) vsh_lam_s = ( pd.to_numeric(df["VSH_LAM"], errors="coerce").fillna(0.0).clip(0.0, 0.99) if (use_ts and "VSH_LAM" in df.columns) @@ -4014,8 +3998,8 @@ def workspace_saturation( & (rt > 0) & rw_s.notna() & (rw_s > 0) - & phie.notna() - & (phie > 0) + & phit.notna() + & (phit > 0) & vclay.notna() ) swt_indonesian_s = pd.Series(np.nan, index=df.index, dtype=float) @@ -4023,7 +4007,7 @@ def workspace_saturation( swt_indonesian = indonesian_saturation( rt[indonesian_mask].to_numpy(dtype=float), rw_s[indonesian_mask].to_numpy(dtype=float), - phie[indonesian_mask].to_numpy(dtype=float), + phit[indonesian_mask].to_numpy(dtype=float), vclay[indonesian_mask].clip(0.0, 1.0).to_numpy(dtype=float), np.full(int(indonesian_mask.sum()), float(req.rsh), dtype=float), float(req.a), @@ -4541,14 +4525,14 @@ def _populate_well_zones_and_focused_mask( mask &= False # If propagate_focused_only is True and no explicit zone/depth filter narrowed the well, - # restrict to the evaluated porosity interval [min_eval_depth, max_eval_depth] if PHIT/PHIE/CPORE is present on a sub-interval + # restrict to the evaluated porosity interval if PHIT/CPORE is present on a sub-interval if ( propagate_focused_only and not allowed_zones and eff_min_d is None and eff_max_d is None ): - for pcol in ("PHIT", "PHIE", "CPORE", "POROSITY", "POR", "CORE_POR"): + for pcol in ("PHIT", "CPORE", "POROSITY", "POR", "CORE_POR"): if pcol in df_out.columns: ps = pd.to_numeric(df_out[pcol], errors="coerce") valid_p = ps.notna() & (ps > 0) & d_num.notna() @@ -4582,7 +4566,7 @@ def _compute_well_non_res_mask( return pd.Series(dtype=bool) phit_s = pd.Series(np.nan, index=w_df.index, dtype=float) - for pcol in ("PHIT", "PHIE", "POROSITY", "POR", "PHIT_CONSTRUCTED", "CPORE"): + for pcol in ("PHIT", "POROSITY", "POR", "PHIT_CONSTRUCTED", "CPORE"): if pcol in w_df.columns: ps = pd.to_numeric(w_df[pcol], errors="coerce") if ps.notna().any(): @@ -5782,9 +5766,9 @@ def workspace_perm_transform_compute( d_series = pd.to_numeric(w_df["DEPTH"], errors="coerce") - # Resolve continuous log PHIT first, with fallback estimation when no PHIT/PHIE exists + # Resolve continuous log PHIT first, with fallback estimation when it is absent phit_s = pd.Series(np.nan, index=w_df.index, dtype=float) - for pcol in ("PHIT", "PHIE", "POROSITY", "POR"): + for pcol in ("PHIT", "POROSITY", "POR"): if pcol in w_df.columns: ps = pd.to_numeric(w_df[pcol], errors="coerce") ps = ps.where(ps > 0, np.nan) @@ -5826,7 +5810,7 @@ def workspace_perm_transform_compute( ks = ks.where(ks > 0, np.nan) scatter_perm_s = scatter_perm_s.combine_first(ks) else: - for pcol in ("PHIT", "PHIE", "POROSITY", "POR"): + for pcol in ("PHIT", "POROSITY", "POR"): if pcol in w_df.columns: ps = pd.to_numeric(w_df[pcol], errors="coerce") ps = ps.where(ps > 0, np.nan) @@ -6327,7 +6311,7 @@ def _norm_plug_stem(val: Any) -> str: has_core_perm = True if cpore is None: - for pcol in ("CPORE", "PHIT", "PHIE"): + for pcol in ("CPORE", "PHIT"): if ( pcol in near_row and pd.notna(near_row[pcol]) @@ -6813,9 +6797,9 @@ def _norm_plug_stem(val: Any) -> str: continue wells_with_tvd.add(wn) - # Continuous porosity: PHIT -> PHIE -> POROSITY -> POR -> CPORE + # Continuous porosity: PHIT -> POROSITY -> POR -> CPORE p_s = pd.Series(np.nan, index=w_sorted.index, dtype=float) - for pcol in ("PHIT", "PHIE", "POROSITY", "POR", "CPORE", "CORE_POR"): + for pcol in ("PHIT", "POROSITY", "POR", "CPORE", "CORE_POR"): if pcol in w_sorted.columns: ps = pd.to_numeric(w_sorted[pcol], errors="coerce") ps = ps.where(ps > 0, np.nan) @@ -7826,9 +7810,9 @@ def workspace_stick_plot( if full_well_ref_df is None or full_well_ref_df.empty: full_well_ref_df = wdf_sorted - # Resolve PHIT (combine across PHIT, PHIE, CPORE, POROSITY, POR so sparse gaps are filled) + # Resolve PHIT (combine across PHIT, CPORE, POROSITY, and POR so sparse gaps are filled) phit_s = pd.Series(np.nan, index=wdf_sorted.index, dtype=float) - for c in ("PHIT", "PHIE", "CPORE", "POROSITY", "POR"): + for c in ("PHIT", "CPORE", "POROSITY", "POR"): if c in wdf_sorted.columns and wdf_sorted[c].notna().any(): phit_s = phit_s.combine_first( pd.to_numeric(wdf_sorted[c], errors="coerce").clip(0.0, 0.5) @@ -11578,7 +11562,7 @@ def _norm_stem(val: Any) -> str: cperm = float(valid_ck.loc[ck_idx]) has_core_perm = True if cpore is None: - for pcol in ("CPORE", "PHIT", "PHIE"): + for pcol in ("CPORE", "PHIT"): if pcol in near_row and pd.notna(near_row[pcol]) and float(near_row[pcol]) > 0: cpore = float(near_row[pcol]) break @@ -12266,7 +12250,7 @@ def workspace_multi_well_volumetrics( raise ValueError("No wells with valid data found for volumetric evaluation.") vsh_cut = float(req.cut_offs.get("VSHALE", 0.40)) - phi_cut = float(req.cut_offs.get("PHIT", req.cut_offs.get("PHIE", 0.05))) + phi_cut = float(req.cut_offs.get("PHIT", 0.05)) 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} diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorPerm.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorPerm.svelte index bc53aa8a..f0899777 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorPerm.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorPerm.svelte @@ -23,7 +23,7 @@ wellData.isCalculating = true; wellData.lastError = null; const deptArr = wellData.curves['DEPT'] ?? wellData.curves['DEPTH'] ?? []; - const phitArr = wellData.curves['PHIT'] ?? wellData.curves['PHIE'] ?? []; + const phitArr = wellData.curves['PHIT'] ?? []; const vclayArr = wellData.curves['VCLAY'] ?? wellData.curves['VSHALE'] ?? []; const vsiltArr = wellData.curves['VSILT'] ?? []; const phitSandArr = wellData.curves['PHIT_SAND'] ?? []; diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte index 25c9d65a..8680bbba 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte @@ -75,7 +75,7 @@ wellData.lastError = null; const sp = workbench.saturationParams; const deptArr = wellData.curves['DEPT'] ?? wellData.curves['DEPTH'] ?? []; - const phitArr = wellData.curves['PHIT'] ?? wellData.curves['PHIE'] ?? []; + const phitArr = wellData.curves['PHIT'] ?? []; const vclayArr = wellData.curves['VCLAY'] ?? wellData.curves['VSHALE'] ?? []; const phitSandArr = wellData.curves['PHIT_SAND'] ?? []; const vshLamArr = wellData.curves['VSH_LAM'] ?? []; @@ -113,7 +113,6 @@ use_thomas_stieber: useTs, depths: cleanArr(deptArr) as number[] | undefined, phit: cleanArr(phitArr), - phie: cleanArr(wellData.curves['PHIE'] ?? []), vclay: cleanArr(vclayArr), phit_sand: useTs ? cleanArr(phitSandArr) : undefined, vsh_lam: useTs ? cleanArr(vshLamArr) : undefined, @@ -187,7 +186,7 @@ decimals={2} />
- Indonesian uses PHIE when available, otherwise PHIT × (1 − VCLAY). + Indonesian uses bulk PHIT with the shale correction from VCLAY.
{:else if workbench.saturationParams.method === 'dual_water'}
-
Inputs: RT, PHIT, PHIE, VSH, VCLAY, Formation Temp
+
Inputs: RT, PHIT, VSH, VCLAY, Formation Temp. PHIE is retained as a QC curve.
Outputs: SWT, SWE, BVW, BVW_IRR, Hydrocarbon Bulk Vol (BVHC)
diff --git a/quick_pp/app/frontend/src/lib/components/shell/WorkflowStepper.svelte b/quick_pp/app/frontend/src/lib/components/shell/WorkflowStepper.svelte index 838304e9..e374916c 100644 --- a/quick_pp/app/frontend/src/lib/components/shell/WorkflowStepper.svelte +++ b/quick_pp/app/frontend/src/lib/components/shell/WorkflowStepper.svelte @@ -106,7 +106,7 @@ id: 'litho-poro', num: 3, label: 'Lithology & Porosity', - readyCheck: () => Boolean(wellData.curves['PHIE'] || wellData.curves['PHIT']) + readyCheck: () => Boolean(wellData.curves['PHIT']) }, { id: 'perm', diff --git a/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte b/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte index f1742d3c..887d7e71 100644 --- a/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte +++ b/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte @@ -875,7 +875,7 @@ } if (effectiveMode === 'thomas-stieber') { - const phitArr = wellData.curves['PHIT'] ?? wellData.curves['PHIE'] ?? []; + const phitArr = wellData.curves['PHIT'] ?? []; const vshTsArr = wellData.curves['VSH_TS']; const vclayArr = wellData.curves['VCLAY'] ?? wellData.curves['VSHALE'] ?? []; const grArr = wellData.curves['GR'] ?? []; @@ -1689,11 +1689,7 @@ }); } } else { - const phitArr = - wellData.curves['PHIT'] ?? - wellData.curves['PHIE'] ?? - wellData.curves['NPHI'] ?? - []; + const phitArr = wellData.curves['PHIT'] ?? []; const permArr = wellData.curves['PERM'] ?? []; const cporeArr = wellData.curves['CPORE'] ?? []; const cpermArr = wellData.curves['CPERM'] ?? []; @@ -1965,8 +1961,7 @@ } if (effectiveMode === 'pickett') { - const phiArr = - wellData.curves['PHIT'] ?? wellData.curves['PHIE'] ?? wellData.curves['NPHI'] ?? []; + const phiArr = wellData.curves['PHIT'] ?? []; const rtArr = wellData.curves['RT'] ?? []; const colorCurve = wellData.curves['VCLAY'] !== undefined ? 'VCLAY' : 'GR'; const vclArr = wellData.curves['VCLAY'] ?? wellData.curves['GR'] ?? []; @@ -4298,7 +4293,6 @@ void workbench.lithoParams.coalNphiMin; } else if (mode === 'thomas-stieber') { void wellData.curves['PHIT']; - void wellData.curves['PHIE']; void wellData.curves['VSH_TS']; void wellData.curves['VCLAY']; void wellData.curves['VSHALE']; @@ -4319,8 +4313,6 @@ void workbench.saturationParams.method; } else if (mode === 'pickett') { void wellData.curves['PHIT']; - void wellData.curves['PHIE']; - void wellData.curves['NPHI']; void wellData.curves['RT']; void wellData.curves['VCLAY']; void wellData.curves['GR']; diff --git a/quick_pp/app/frontend/src/lib/components/workbench/LogTrackCanvas.svelte b/quick_pp/app/frontend/src/lib/components/workbench/LogTrackCanvas.svelte index 470910f3..9b7e7bba 100644 --- a/quick_pp/app/frontend/src/lib/components/workbench/LogTrackCanvas.svelte +++ b/quick_pp/app/frontend/src/lib/components/workbench/LogTrackCanvas.svelte @@ -535,7 +535,7 @@ // Live fallback calculation from PHIT & PERM if ROCK_FLAG is still absent if (!flags.some((v) => v !== null && v >= 1)) { - const phitCurve = wellData.curves['PHIT'] ?? wellData.curves['PHIE']; + const phitCurve = wellData.curves['PHIT']; const permCurve = wellData.curves['PERM'] ?? wellData.curves['PERM_TRANS'] ?? wellData.curves['CPERM']; if (phitCurve && permCurve) { @@ -1420,7 +1420,8 @@ } // Track 4 (xaxis4): Evaluated Lithology & Porosity (stacked mineral volumes + PHIT + CPORE) - const phit = pick('PHIT').length ? pick('PHIT') : pick('PHIE'); + const phit = pick('PHIT'); + const phie = pick('PHIE'); const lithoToPlot = activeLithoSpecs; if (lithoToPlot.length > 0) { const decLithArrs = lithoToPlot.map(({ arr }) => decimateSvg(arr)); @@ -1528,10 +1529,25 @@ y: svgDepth, xaxis: 'x4', yaxis: 'y', - line: { color: PETRO_COLORS.phie, width: 1.6 }, + line: { color: PETRO_COLORS.phit, width: 1.6 }, hovertemplate: 'PHIT: %{customdata:.3f} v/v' }); } + if (phie.some((v) => v !== null)) { + const phieDec = decimateSvg(phie); + traces.push({ + type: 'scatter', + mode: 'lines', + name: 'PHIE (QC)', + x: scalePoro(phieDec), + customdata: phieDec, + y: svgDepth, + xaxis: 'x4', + yaxis: 'y', + line: { color: '#64748B', width: 1.2, dash: '4px,3px' }, + hovertemplate: 'PHIE (QC): %{customdata:.3f} v/v' + }); + } if (tsOverlayActive) { const phitSand = pick('PHIT_SAND'); @@ -3233,7 +3249,7 @@
0 PHIT / CORE ► @@ -3290,7 +3306,7 @@ PHIT / CORE ► 0.5
-
+
{/if}
@@ -3729,9 +3745,15 @@ {/if}
- PHIT - {fmtNum(readout.PHIT ?? readout.PHIE, 3)} v/v + PHIT + {fmtNum(readout.PHIT, 3)} v/v
+ {#if readout.PHIE !== null && readout.PHIE !== undefined} +
+ PHIE (QC) + {fmtNum(readout.PHIE, 3)} v/v +
+ {/if} {#if tsOverlayActive && readout.PHIT_SAND !== null && readout.PHIT_SAND !== undefined}
PHIT_S @@ -3952,9 +3974,15 @@ {/if} - PHIT: - {fmtNum(readout.PHIT ?? readout.PHIE, 3)} + PHIT: + {fmtNum(readout.PHIT, 3)} + {#if readout.PHIE !== null && readout.PHIE !== undefined} + + PHIE QC: + {fmtNum(readout.PHIE, 3)} + + {/if} {#if tsOverlayActive && readout.PHIT_SAND !== null && readout.PHIT_SAND !== undefined} PHIT_SAND: diff --git a/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts b/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts index ebcda872..9060a873 100644 --- a/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts +++ b/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts @@ -311,7 +311,7 @@ class WellDataState { ); hcFlagCurve = $derived(this.curves['HC_FLAG'] ?? WellDataState.EMPTY_ARR); swCurve = $derived(this.curves['SWT'] ?? this.curves['SWE'] ?? WellDataState.EMPTY_ARR); - phitCurve = $derived(this.curves['PHIT'] ?? this.curves['PHIE'] ?? WellDataState.EMPTY_ARR); + phitCurve = $derived(this.curves['PHIT'] ?? WellDataState.EMPTY_ARR); permCurve = $derived( this.curves['PERM'] ?? this.curves['PERM_TRANS'] ?? WellDataState.EMPTY_ARR ); @@ -3255,7 +3255,7 @@ class WellDataState { const maxShift = opts?.maxShiftM ?? 5.0; const dept = this.curves['DEPT'] ?? this.curves['DEPTH'] ?? []; - const phitArr = this.curves['PHIT'] ?? this.curves['PHIE'] ?? []; + const phitArr = this.curves['PHIT'] ?? []; const permArr = this.curves['PERM'] ?? this.curves['PERM_TRANS'] ?? []; const allPlugs = this.getBaseCorePlugs(); diff --git a/quick_pp/app/frontend/src/routes/+page.svelte b/quick_pp/app/frontend/src/routes/+page.svelte index c01ba9cb..36d0f42a 100644 --- a/quick_pp/app/frontend/src/routes/+page.svelte +++ b/quick_pp/app/frontend/src/routes/+page.svelte @@ -763,7 +763,8 @@ if (wellData.tops.length > 0) { const sorted = [...wellData.tops].sort((a, b) => a.depth - b.depth); const dept = wellData.curves['DEPT'] ?? wellData.curves['DEPTH'] ?? []; - const phie = wellData.curves['PHIE'] ?? wellData.curves['PHIT'] ?? []; + const phit = wellData.curves['PHIT'] ?? []; + const phie = wellData.curves['PHIE'] ?? []; const vcl = wellData.curves['VCLAY'] ?? wellData.curves['GR'] ?? []; const sw = wellData.curves['SWT'] ?? wellData.curves['SWE'] ?? []; @@ -773,8 +774,10 @@ idx + 1 < sorted.length ? sorted[idx + 1].depth : wellData.depthRange.max; const gross = Math.max(0, botD - topD); - let phiSum = 0; - let phiN = 0; + let phitSum = 0; + let phitN = 0; + let phieSum = 0; + let phieN = 0; let vclSum = 0; let vclN = 0; let swSum = 0; @@ -782,9 +785,13 @@ dept.forEach((d, i) => { if (d >= topD && d < botD) { + if (Number.isFinite(phit[i])) { + phitSum += phit[i]; + phitN++; + } if (Number.isFinite(phie[i])) { - phiSum += phie[i]; - phiN++; + phieSum += phie[i]; + phieN++; } if (Number.isFinite(vcl[i])) { vclSum += vcl[i]; @@ -801,7 +808,8 @@ Zone: t.name, depth: topD, Gross: gross, - PHIE: phiN > 0 ? phiSum / phiN : null, + PHIT: phitN > 0 ? phitSum / phitN : null, + PHIE_QC: phieN > 0 ? phieSum / phieN : null, VCLAY: vclN > 0 ? vclSum / vclN : null, SW: swN > 0 ? swSum / swN : null }; @@ -813,7 +821,8 @@ { key: 'Zone', label: 'Zone' }, { key: 'depth', label: 'Top', unit: 'm', numeric: true, decimals: 1 }, { key: 'Gross', label: 'Gross', unit: 'm', numeric: true, decimals: 1 }, - { key: 'PHIE', label: 'PHIE', unit: 'v/v', numeric: true, decimals: 3 }, + { key: 'PHIT', label: 'PHIT', unit: 'v/v', numeric: true, decimals: 3 }, + { key: 'PHIE_QC', label: 'PHIE (QC)', unit: 'v/v', numeric: true, decimals: 3 }, { key: 'VCLAY', label: 'VCLAY', unit: 'v/v', numeric: true, decimals: 3 }, { key: 'SW', label: 'SW', unit: 'v/v', numeric: true, decimals: 3 } ], diff --git a/tests/test_backend_workspace_api.py b/tests/test_backend_workspace_api.py index 7a08f49c..0a3df7d1 100644 --- a/tests/test_backend_workspace_api.py +++ b/tests/test_backend_workspace_api.py @@ -374,7 +374,7 @@ def test_saturation_model_comparison_curves_and_archie_default(client_and_projec fallback = { "depths": np.linspace(1000.0, 1009.0, 10).tolist(), "phit": np.linspace(0.12, 0.25, 10).tolist(), - "phie": np.linspace(0.1, 0.2, 10).tolist(), + "phie": np.full(10, 0.01).tolist(), "vclay": np.linspace(0.1, 0.4, 10).tolist(), "save": False, } @@ -384,6 +384,16 @@ def test_saturation_model_comparison_curves_and_archie_default(client_and_projec default_body = default_response.json() assert default_body["method"] == "archie" assert default_body["data"]["SWT"] == default_body["data"]["SWT_ARCHIE"] + expected_archie = np.sqrt( + np.asarray(default_body["data"]["RW"], dtype=float) + / ( + np.asarray(default_body["data"]["RT"], dtype=float) + * np.asarray(fallback["phit"], dtype=float) ** 2 + ) + ).clip(0.0, 1.0) + np.testing.assert_allclose( + default_body["data"]["SWT_ARCHIE"], expected_archie, equal_nan=True + ) model_curves = { "waxman_smits": "SWT_WAXMAN", From a238644adae9e9f03f8b71a437c63a7e4a4d13d9 Mon Sep 17 00:00:00 2001 From: imranfadhil Date: Wed, 4 Nov 2026 15:15:03 +0800 Subject: [PATCH 04/30] improve saturation module with relevant crossplots --- quick_pp/app/backend/services/workspace.py | 13 +- .../modules/InspectorSaturation.svelte | 184 +++++++++++++- .../workbench/CrossplotCanvas.svelte | 226 +++++++++++++++--- .../workbench/LogTrackCanvas.svelte | 2 +- .../src/lib/state/workbench.svelte.ts | 9 +- .../src/lib/utils/petrophysicsColors.ts | 3 +- .../app/frontend/src/lib/utils/saturation.ts | 87 +++++++ quick_pp/lithology/sand_silt_clay.py | 29 ++- quick_pp/plotter/report_plots.py | 24 +- tests/test_backend_workspace_api.py | 14 ++ tests/test_sand_silt_clay.py | 79 ++++++ 11 files changed, 600 insertions(+), 70 deletions(-) create mode 100644 quick_pp/app/frontend/src/lib/utils/saturation.ts create mode 100644 tests/test_sand_silt_clay.py diff --git a/quick_pp/app/backend/services/workspace.py b/quick_pp/app/backend/services/workspace.py index 69b64c99..dc4e2b2e 100644 --- a/quick_pp/app/backend/services/workspace.py +++ b/quick_pp/app/backend/services/workspace.py @@ -809,9 +809,9 @@ class WorkspaceSaturationRequest(WorkspaceFilterBase): b_intercept: Optional[float] = Field( None, description="Optional Waxman-Smits m* intercept override (defaults to m)" ) - qv_method: str = Field( + qv_method: Literal["cec", "qvn", "crossplot"] = Field( "cec", - description="Qv estimation method: 'cec' (from cec_clay & rho_dry_clay) or 'qvn' (Juhasz normalized Qvn)", + description="Qv estimation method: 'cec' (from cec_clay & rho_dry_clay), 'qvn' (Juhasz normalized Qvn), or 'crossplot' (crossplot-calibrated effective CEC)", ) cec_clay: float = Field(0.1, description="Clay cation exchange capacity (meq/g)") rho_dry_clay: float = Field(2.71, description="Dry clay bulk density (g/cc)") @@ -3913,8 +3913,8 @@ def workspace_saturation( ), dtype=float, ).ravel() - else: - # Default 'cec': compute Qv (meq/cm3) from VCLAY, dry clay density, and clay CEC + elif req.qv_method.lower() in {"cec", "crossplot"}: + # Crossplot mode supplies its calibrated effective CEC through cec_clay. qv_mask = vclay.notna() & phit.notna() & (phit > 0) if qv_mask.any(): qvn_s.loc[qv_mask] = np.asarray( @@ -3926,6 +3926,11 @@ def workspace_saturation( ), dtype=float, ).ravel() + else: + raise HTTPException( + status_code=422, + detail=f"Unsupported Qv estimation method: {req.qv_method}", + ) # 3. Archie SWT (strictly depth-aligned) swt_archie_s = pd.Series(np.nan, index=df.index, dtype=float) diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte index 8680bbba..2387faca 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte @@ -5,6 +5,7 @@ import SavedParamsIndicator from '$lib/components/workbench/SavedParamsIndicator.svelte'; import { wellData } from '$lib/state/wellData.svelte'; import { workbench } from '$lib/state/workbench.svelte'; + import { fillMissingCurve, fitBqvCrossplot } from '$lib/utils/saturation'; // Default reference depth is the bottom of the active filtered interval (or well max depth) let defaultRefDepth = $derived.by(() => { @@ -34,7 +35,7 @@ function estimateTempAndRwAtDepth(depthM: number) { const sp = workbench.saturationParams; - const d = Number.isFinite(depthM) ? Math.max(0, depthM) : 0; + const d = Number.isFinite(depthM) ? depthM : 0; let tempC: number; if (sp.measSystem === 'imperial') { const tvdKft = (d * 3.28084) / 1000.0; @@ -48,12 +49,84 @@ const rw = Math.pow(400000.0 / (sal * tempF), 0.88); return { tempC: Number(tempC.toFixed(1)), - rw: Number(rw.toFixed(4)) + rw: Number(rw.toFixed(4)), + tempCExact: tempC, + rwExact: rw }; } let estimatedRwAtSurface = $derived.by(() => estimateTempAndRwAtDepth(0)); let estimatedRwAtRefDepth = $derived.by(() => estimateTempAndRwAtDepth(refDepth)); + let bqvReferenceRw = $derived.by(() => { + const md = wellData.curves['DEPT'] ?? wellData.curves['DEPTH'] ?? []; + const tvd = + wellData.curves['TVDSS'] ?? wellData.curves['TVD'] ?? wellData.curves['DEPTH'] ?? md; + const fallbackTvd = wellData.curves['DEPTH'] ?? md; + let closestIndex = -1; + let closestDistance = Infinity; + for (const index of wellData.visibleIndices) { + const measuredDepth = md[index]; + if ( + Number.isFinite(measuredDepth) && + Math.abs(measuredDepth - refDepth) < closestDistance + ) { + closestIndex = index; + closestDistance = Math.abs(measuredDepth - refDepth); + } + } + const temperatureDepth = + closestIndex >= 0 + ? Number.isFinite(tvd[closestIndex]) + ? tvd[closestIndex] + : (fallbackTvd[closestIndex] ?? refDepth) + : refDepth; + return estimateTempAndRwAtDepth(temperatureDepth); + }); + let bqvFit = $derived.by(() => { + const rawRt = wellData.curves['RT'] ?? []; + const rawPhit = wellData.curves['PHIT'] ?? []; + const rawVclay = wellData.curves['VCLAY'] ?? wellData.curves['VSHALE'] ?? []; + const phitSand = wellData.curves['PHIT_SAND']; + const useTs = + workbench.tsParams.useInSaturation && + Boolean(phitSand?.some((value) => Number.isFinite(value))); + return fitBqvCrossplot( + useTs ? fillMissingCurve(wellData.curves['RSAND_TS'], rawRt) : rawRt, + useTs ? fillMissingCurve(phitSand, rawPhit) : rawPhit, + useTs ? fillMissingCurve(wellData.curves['VSH_DIS'], rawVclay) : rawVclay, + wellData.curves['DEPT'] ?? wellData.curves['DEPTH'] ?? [], + wellData.visibleIndices, + workbench.saturationParams.m + ); + }); + let crossplotCalibration = $derived.by(() => { + const fit = bqvFit; + if (fit.slope === null || fit.slope <= 0) return null; + const sp = workbench.saturationParams; + const rw = sp.rwMode === 'pickett' ? sp.rwPickett : bqvReferenceRw.rwExact; + const tempC = bqvReferenceRw.tempCExact; + const b = + (-1.28 + 0.225 * tempC - 0.0004059 * tempC ** 2) / + (1 + (0.045 * tempC - 0.27) * Math.pow(rw, 1.23)); + const cec = (fit.slope * sp.a) / (b * sp.rhoDryClay); + return Number.isFinite(b) && b > 0 && Number.isFinite(cec) && cec > 0 ? { b, cec } : null; + }); + let isCrossplotCalibrationStale = $derived.by(() => { + const sp = workbench.saturationParams; + if (sp.qvMethod !== 'crossplot') return false; + const fit = bqvFit; + return ( + fit.slope === null || + !crossplotCalibration || + sp.bqvAppliedSlope === null || + sp.bqvAppliedRefDepth === null || + sp.bqvAppliedRhoClay === null || + Math.abs(fit.slope - sp.bqvAppliedSlope) > Math.max(1e-6, Math.abs(fit.slope) * 1e-4) || + Math.abs(refDepth - sp.bqvAppliedRefDepth) > 0.05 || + Math.abs(sp.rhoDryClay - sp.bqvAppliedRhoClay) > 1e-6 || + Math.abs(crossplotCalibration.cec - sp.cecClay) > 1e-4 + ); + }); const saturationModelLabels: Record = { archie: 'ARCHIE', waxman_smits: 'WAXMAN-SMITS', @@ -71,6 +144,11 @@ async function executeSaturation(persist: boolean = false) { if (!workbench.projectId || !workbench.wellId) return; + if (workbench.saturationParams.qvMethod === 'crossplot' && isCrossplotCalibrationStale) { + wellData.lastError = + 'Apply the current BQv crossplot fit before calculating Waxman-Smits saturation.'; + return; + } wellData.isCalculating = true; wellData.lastError = null; const sp = workbench.saturationParams; @@ -151,6 +229,18 @@ async function saveSaturation() { await wellData.saveModuleComputed('saturation', 'Saturation Saved ✓'); } + + function applyCrossplotCalibration() { + const fit = bqvFit; + const calibration = crossplotCalibration; + if (fit.slope === null || !calibration) return; + const sp = workbench.saturationParams; + sp.cecClay = Number(calibration.cec.toFixed(4)); + sp.bqvAppliedSlope = fit.slope; + sp.bqvAppliedRefDepth = refDepth; + sp.bqvAppliedRhoClay = sp.rhoDryClay; + sp.qvMethod = 'crossplot'; + }
@@ -391,7 +481,11 @@ {#if workbench.saturationParams.method === 'waxman_smits'}
Qv Method @@ -401,10 +495,11 @@ > +
- {#if workbench.saturationParams.qvMethod !== 'qvn'} + {#if workbench.saturationParams.qvMethod === 'cec'} + {:else if workbench.saturationParams.qvMethod === 'crossplot'} +
+
+ Applied clay CEC: {workbench.saturationParams.cecClay.toFixed(4)} meq/g +
+ {#if isCrossplotCalibrationStale} +
+ The fit, reference depth, or clay density has changed. Apply the + current fit again before running saturation. +
+ {/if} +
+ {:else} +
+ Computes normalized Qvn = VCLAY × PHIT_SH / PHIT from log-derived shale porosity (Juhasz, 1981). +
+ {/if} + + {#if workbench.saturationParams.qvMethod !== 'qvn'} - {:else} -
- Computes normalized Qvn = VCLAY × PHIT_SH / PHIT from log-derived shale porosity (Juhasz, 1981). -
{/if} + +
+
+ {#if bqvFit.slope !== null && crossplotCalibration} + Current filtered fit slope: {bqvFit.slope.toFixed(4)} + (BQv/a), + a × slope = {(bqvFit.slope * workbench.saturationParams.a).toFixed( + 4 + )}, + R² = {bqvFit.r2 === null ? '—' : bqvFit.r2.toFixed(3)}, + n = {bqvFit.points.length}. At {refDepth.toFixed( + 1 + )} m, B = {crossplotCalibration.b.toFixed(3)} and implied CEC = + {crossplotCalibration.cec.toFixed(4)} meq/g. + {:else} + Select an interval with at least two valid crossplot samples and a + positive fitted slope. + {/if} +
+
+ + Fit uses the current depth/zone filters. Use a water-bearing interval; + the crossplot slope is an effective estimate. + + +
+ {#if crossplotCalibration && (crossplotCalibration.cec < 0.01 || crossplotCalibration.cec > 1.5)} +
+ Implied CEC is outside the supported 0.01–1.5 meq/g range; adjust the + fit interval or reference depth. +
+ {/if} +
{/if} diff --git a/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte b/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte index 887d7e71..20e3fb0e 100644 --- a/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte +++ b/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte @@ -10,6 +10,7 @@ PETRO_COLORS } from '$lib/utils/petrophysicsColors'; import { fmtDepth, fmtNum } from '$lib/utils/formatters'; + import { fillMissingCurve, fitBqvCrossplot } from '$lib/utils/saturation'; import CoreDepthShiftPanel from '$lib/components/workbench/CoreDepthShiftPanel.svelte'; import VshCalibrationPanel from '$lib/components/workbench/VshCalibrationPanel.svelte'; @@ -1890,22 +1891,56 @@ } if (effectiveMode === 'sw-comparison') { - const archie = wellData.curves['SWT_ARCHIE'] ?? []; + const vshKey = wellData.curves['VSHALE'] !== undefined ? 'VSHALE' : 'VCLAY'; + const vshale = wellData.curves[vshKey] ?? []; const models = [ - { key: 'SWT_WAXMAN', label: 'Waxman-Smits', color: '#2563EB', method: 'waxman_smits' }, + { key: 'SWT_ARCHIE', label: 'Archie', color: '#64748B', method: 'archie' }, + { + key: 'SWT_WAXMAN', + label: 'Waxman-Smits', + color: '#2563EB', + method: 'waxman_smits' + }, { key: 'SWT_SIMANDOUX', label: 'Simandoux', color: '#D97706', method: 'simandoux' }, - { key: 'SWT_INDONESIAN', label: 'Indonesian', color: '#059669', method: 'indonesian' }, - { key: 'SWT_DUAL_WATER', label: 'Dual Water', color: '#7C3AED', method: 'dual_water' } + { + key: 'SWT_INDONESIAN', + label: 'Indonesian', + color: '#059669', + method: 'indonesian' + }, + { + key: 'SWT_DUAL_WATER', + label: 'Dual Water', + color: '#7C3AED', + method: 'dual_water' + } ] as const; + const vshX: number[] = []; + const vshY: number[] = []; + const vshIndices: number[] = []; + for (const idx of indices) { + const vsh = vshale[idx]; + const depth = deptAll[idx]; + if (Number.isFinite(vsh) && vsh >= 0 && vsh <= 1 && Number.isFinite(depth)) { + vshX.push(vsh); + vshY.push(depth); + vshIndices.push(idx); + } + } + traces.push({ type: 'scatter', mode: 'lines', - name: '1:1 agreement', - x: [0, 1], - y: [0, 1], - line: { color: '#64748B', width: 1.2, dash: 'dash' }, - hoverinfo: 'skip' + name: vshKey, + x: vshX, + y: vshY, + xaxis: 'x', + customdata: vshIndices, + line: { color: '#16A34A', width: 1.5 }, + fill: 'tozerox', + fillcolor: 'rgba(22, 163, 74, 0.16)', + hovertemplate: `${vshKey}: %{x:.3f} v/v
Depth: %{y:.2f} m` }); for (const model of models) { @@ -1913,50 +1948,158 @@ const xs: number[] = []; const ys: number[] = []; const customIdx: number[] = []; - const depths: number[] = []; + const vshAtDepth: (number | null)[] = []; for (const idx of indices) { - const archieSw = archie[idx]; const modelValue = modelSw[idx]; if ( - Number.isFinite(archieSw) && Number.isFinite(modelValue) && - archieSw >= 0 && - archieSw <= 1 && modelValue >= 0 && - modelValue <= 1 + modelValue <= 1 && + Number.isFinite(deptAll[idx]) ) { - xs.push(archieSw); - ys.push(modelValue); + xs.push(modelValue); + ys.push(deptAll[idx]); customIdx.push(idx); - depths.push(deptAll[idx]); + const vsh = vshale[idx]; + vshAtDepth.push(Number.isFinite(vsh) ? vsh : null); } } const isSelected = workbench.saturationParams.method === model.method; traces.push({ type: 'scatter', - mode: 'markers', - name: `${model.label} vs Archie`, + mode: 'lines+markers', + name: model.label, x: xs, y: ys, + xaxis: 'x2', customdata: customIdx, - text: depths, + text: vshAtDepth, marker: { - size: isSelected ? 7 : 5, + size: isSelected ? 4 : 2.5, color: model.color, - opacity: isSelected ? 0.9 : 0.45, - line: { color: '#FFFFFF', width: 0.5 } + opacity: isSelected ? 0.95 : 0.65, + line: { color: '#FFFFFF', width: 0.4 } }, - hovertemplate: - 'Depth: %{text:.2f} m
Archie Sw: %{x:.3f}
' + - `${model.label} Sw: %{y:.3f}` + line: { color: model.color, width: isSelected ? 2.2 : 1.2 }, + hovertemplate: `Depth: %{y:.2f} m
${model.label} Sw: %{x:.3f}
${vshKey}: %{text:.3f}` }); } baseLayout.dragmode = 'lasso'; - baseLayout.xaxis.title = { text: 'Archie Water Saturation (v/v)' }; + baseLayout.xaxis.domain = [0, 0.24]; + baseLayout.xaxis.title = { text: `${vshKey} (v/v)` }; baseLayout.xaxis.range = [0, 1]; - baseLayout.yaxis.title = { text: 'Alternative Model Water Saturation (v/v)' }; - baseLayout.yaxis.range = [0, 1]; + baseLayout.xaxis.anchor = 'y'; + baseLayout.xaxis2 = { + ...baseLayout.xaxis, + domain: [0.34, 1], + title: { text: 'Water Saturation Sw (v/v)' }, + range: [0, 1], + anchor: 'y' + }; + baseLayout.yaxis.autorange = 'reversed'; + baseLayout.yaxis.title = { text: 'Depth (m)' }; + return { traces, layout: baseLayout }; + } + + if (effectiveMode === 'bqv') { + const tsPhit = wellData.curves['PHIT_SAND']; + const useTs = + workbench.tsParams.useInSaturation && + Boolean(tsPhit?.some((value) => Number.isFinite(value))); + const rawRt = wellData.curves['RT'] ?? []; + const rawPhi = wellData.curves['PHIT'] ?? []; + const rawVcl = wellData.curves['VCLAY'] ?? wellData.curves['VSHALE'] ?? []; + const rtArr = useTs + ? fillMissingCurve(wellData.curves['RSAND_TS'], rawRt) + : rawRt; + const phiArr = useTs ? fillMissingCurve(tsPhit, rawPhi) : rawPhi; + const vclKey = useTs && wellData.curves['VSH_DIS'] !== undefined + ? 'VSH_DIS' + : wellData.curves['VCLAY'] !== undefined + ? 'VCLAY' + : 'VSHALE'; + const vclArr = + useTs && vclKey === 'VSH_DIS' + ? fillMissingCurve(wellData.curves['VSH_DIS'], rawVcl) + : rawVcl; + const rtKey = useTs && wellData.curves['RSAND_TS'] !== undefined ? 'RSAND_TS' : 'RT'; + const phiKey = useTs && tsPhit !== undefined ? 'PHIT_SAND' : 'PHIT'; + const m = workbench.saturationParams.m; + const fit = fitBqvCrossplot(rtArr, phiArr, vclArr, deptAll, indices, m); + const xs = fit.points.map((point) => point.x); + const ys = fit.points.map((point) => point.y); + const depths = fit.points.map((point) => point.depth); + const customIdx = fit.points.map((point) => point.index); + + traces.push({ + type: 'scatter', + mode: 'markers', + name: 'Log samples', + x: xs, + y: ys, + customdata: customIdx, + text: depths, + marker: { + size: 6, + color: '#2563EB', + opacity: 0.7, + line: { color: '#FFFFFF', width: 0.6 } + }, + hovertemplate: + `Depth: %{text:.2f} m
${vclKey}/${phiKey}: %{x:.4f}
` + + `1/(${rtKey}·${phiKey}${m}): %{y:.4f} 1/ohm·m` + }); + + if (fit.slope !== null && fit.intercept !== null) { + const { slope, intercept, r2 } = fit; + const a = workbench.saturationParams.a; + const effectiveBqv = slope * a; + const minX = Math.min(...xs); + const maxX = Math.max(...xs); + traces.push({ + type: 'scatter', + mode: 'lines', + name: `Linear fit · a×slope=${fmtNum(effectiveBqv, 3)}`, + x: [minX, maxX], + y: [slope * minX + intercept, slope * maxX + intercept], + line: { color: '#DC2626', width: 2, dash: 'dash' }, + hovertemplate: + `Fit slope (BQv/a): ${fmtNum(slope, 4)}
` + + `Effective BQv (a×slope): ${fmtNum(effectiveBqv, 4)}
` + + `Intercept (1/aRw): ${fmtNum(intercept, 4)} 1/ohm·m
` + + `R²: ${r2 === null ? '—' : fmtNum(r2, 4)}` + }); + baseLayout.annotations = [ + { + xref: 'paper', + yref: 'paper', + x: 0.02, + y: 1.04, + xanchor: 'left', + yanchor: 'bottom', + showarrow: false, + text: + `Fit slope (BQv/a): ${fmtNum(slope, 4)} · ` + + `a×slope: ${fmtNum(effectiveBqv, 4)} · ` + + `1/aRw intercept: ${fmtNum(intercept, 4)} · ` + + `R²: ${r2 === null ? '—' : fmtNum(r2, 4)} · n=${xs.length}`, + font: { family: 'Inter', size: 10, color: '#334155' } + } + ]; + } + + baseLayout.title = { + text: 'Waxman–Smits Conductivity Crossplot', + font: { family: 'Inter', size: 13, color: '#0F172A' } + }; + baseLayout.margin.t = 58; + baseLayout.xaxis.title = { text: `${vclKey} / ${phiKey} (v/v)` }; + baseLayout.xaxis.rangemode = 'tozero'; + baseLayout.yaxis.title = { + text: `1 / (${rtKey} · ${phiKey}${m}) (1 / ohm·m)` + }; + baseLayout.yaxis.rangemode = 'tozero'; return { traces, layout: baseLayout }; } @@ -4305,12 +4448,26 @@ void wellData.curves[`${cName}_ORI`]; void wellData.stats[cName]; } else if (mode === 'sw-comparison') { + void wellData.curves['DEPT']; + void wellData.curves['DEPTH']; + void wellData.curves['VSHALE']; + void wellData.curves['VCLAY']; void wellData.curves['SWT_ARCHIE']; void wellData.curves['SWT_WAXMAN']; void wellData.curves['SWT_SIMANDOUX']; void wellData.curves['SWT_INDONESIAN']; void wellData.curves['SWT_DUAL_WATER']; void workbench.saturationParams.method; + } else if (mode === 'bqv') { + void wellData.curves['RT']; + void wellData.curves['PHIT']; + void wellData.curves['VCLAY']; + void wellData.curves['VSHALE']; + void wellData.curves['PHIT_SAND']; + void wellData.curves['RSAND_TS']; + void wellData.curves['VSH_DIS']; + void workbench.tsParams.useInSaturation; + void workbench.saturationParams.m; } else if (mode === 'pickett') { void wellData.curves['PHIT']; void wellData.curves['RT']; @@ -4676,7 +4833,11 @@ bind:value={workbench.crossplotTemplateOverride} class="h-5 max-w-[195px] truncate rounded-xs border border-[var(--border-hairline)] bg-[var(--bg-surface)] px-1.5 py-0 text-[11px] font-medium text-[var(--text-primary)] focus:outline-none" > - + @@ -4690,7 +4851,8 @@ > - + + diff --git a/quick_pp/app/frontend/src/lib/components/workbench/LogTrackCanvas.svelte b/quick_pp/app/frontend/src/lib/components/workbench/LogTrackCanvas.svelte index 9b7e7bba..04d1e56b 100644 --- a/quick_pp/app/frontend/src/lib/components/workbench/LogTrackCanvas.svelte +++ b/quick_pp/app/frontend/src/lib/components/workbench/LogTrackCanvas.svelte @@ -1544,7 +1544,7 @@ y: svgDepth, xaxis: 'x4', yaxis: 'y', - line: { color: '#64748B', width: 1.2, dash: '4px,3px' }, + line: { color: PETRO_COLORS.phie, width: 1.2, dash: '4px,3px' }, hovertemplate: 'PHIE (QC): %{customdata:.3f} v/v' }); } diff --git a/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts b/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts index f858664b..a9e61c8c 100644 --- a/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts +++ b/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts @@ -151,9 +151,12 @@ export interface SaturationModelParams { tempGradient: number; surfaceTemp: number; bMethod: string; - qvMethod: string; + qvMethod: 'cec' | 'qvn' | 'crossplot'; cecClay: number; rhoDryClay: number; + bqvAppliedSlope: number | null; + bqvAppliedRefDepth: number | null; + bqvAppliedRhoClay: number | null; rsh: number; swb: number; rwb: number; @@ -568,6 +571,7 @@ class WorkbenchState { | 'phi-k' | 'pickett' | 'sw-comparison' + | 'bqv' | 'histogram' | 'mw-distribution' | 'swirr-fit' @@ -745,6 +749,9 @@ class WorkbenchState { qvMethod: 'cec', cecClay: 0.1, rhoDryClay: 2.71, + bqvAppliedSlope: null, + bqvAppliedRefDepth: null, + bqvAppliedRhoClay: null, rsh: 2.0, swb: 0.2, rwb: 0.1, diff --git a/quick_pp/app/frontend/src/lib/utils/petrophysicsColors.ts b/quick_pp/app/frontend/src/lib/utils/petrophysicsColors.ts index 17f4e51b..480e278b 100644 --- a/quick_pp/app/frontend/src/lib/utils/petrophysicsColors.ts +++ b/quick_pp/app/frontend/src/lib/utils/petrophysicsColors.ts @@ -78,7 +78,7 @@ export const PETRO_COLORS = { core: '#0F172A', perm: '#0284C7', phie: '#2563EB', - phit: '#0F172A', + phit: '#2563EB', phitSand: '#047857', pota: '#EC4899', thor: '#06B6D4', @@ -577,4 +577,3 @@ export function getRockTypeFillRgba( } return hex; } - diff --git a/quick_pp/app/frontend/src/lib/utils/saturation.ts b/quick_pp/app/frontend/src/lib/utils/saturation.ts new file mode 100644 index 00000000..61ea9c3f --- /dev/null +++ b/quick_pp/app/frontend/src/lib/utils/saturation.ts @@ -0,0 +1,87 @@ +export interface BqvCrossplotPoint { + index: number; + x: number; + y: number; + depth: number; +} + +export interface BqvCrossplotFit { + points: BqvCrossplotPoint[]; + slope: number | null; + intercept: number | null; + r2: number | null; +} + +export function fillMissingCurve(primary: number[] | undefined, fallback: number[]): number[] { + if (!primary) return fallback; + return fallback.map((value, index) => + Number.isFinite(primary[index]) ? primary[index] : value + ); +} + +export function fitBqvCrossplot( + rt: number[], + phit: number[], + vclay: number[], + depths: number[], + indices: number[], + m: number +): BqvCrossplotFit { + const points: BqvCrossplotPoint[] = []; + for (const index of indices) { + const resistivity = rt[index]; + const porosity = phit[index]; + const clayVolume = vclay[index]; + const depth = depths[index]; + if ( + !Number.isFinite(resistivity) || + resistivity <= 0 || + !Number.isFinite(porosity) || + porosity <= 0 || + !Number.isFinite(clayVolume) || + clayVolume < 0 || + clayVolume > 1 || + !Number.isFinite(depth) + ) { + continue; + } + + const x = clayVolume / porosity; + const y = 1 / (resistivity * Math.pow(porosity, m)); + if (Number.isFinite(x) && Number.isFinite(y)) { + points.push({ index, x, y, depth }); + } + } + + if (points.length < 2) { + return { points, slope: null, intercept: null, r2: null }; + } + + const meanX = points.reduce((sum, point) => sum + point.x, 0) / points.length; + const meanY = points.reduce((sum, point) => sum + point.y, 0) / points.length; + let covariance = 0; + let varianceX = 0; + let totalVarianceY = 0; + let residualSumSquares = 0; + for (const point of points) { + covariance += (point.x - meanX) * (point.y - meanY); + varianceX += Math.pow(point.x - meanX, 2); + totalVarianceY += Math.pow(point.y - meanY, 2); + } + if (varianceX <= 0) { + return { points, slope: null, intercept: null, r2: null }; + } + + const slope = covariance / varianceX; + const intercept = meanY - slope * meanX; + for (const point of points) { + residualSumSquares += Math.pow(point.y - (slope * point.x + intercept), 2); + } + + return { + points, + slope, + intercept, + r2: totalVarianceY > 0 ? 1 - residualSumSquares / totalVarianceY : null + }; +} diff --git a/quick_pp/lithology/sand_silt_clay.py b/quick_pp/lithology/sand_silt_clay.py index ce67936b..34afb308 100644 --- a/quick_pp/lithology/sand_silt_clay.py +++ b/quick_pp/lithology/sand_silt_clay.py @@ -94,19 +94,20 @@ def estimate_lithology(self, nphi, rhob): C = self.dry_clay_point = (dryclay_NPHI, C[1]) logger.debug(f"Updated dry clay point to: ({dryclay_NPHI:.3f}, {C[1]:.3f})") - # Redefine drysilt point by finding intersection between silt line and rock line - A = self.dry_sand_point - if not all(B) or B[0] is None: + # Redefine the dry silt point at its configured RHOB value. + if B[0] is None: rad = math.radians(float(self.silt_line_angle)) p_silt = (D[0] + math.cos(rad), D[1] + math.sin(rad)) - silt_x, silt_y = line_intersection((A, C), (D, p_silt)) - if np.isfinite(silt_x) and np.isfinite(silt_y): - B = self.dry_silt_point = (float(silt_x), float(silt_y)) - else: - drysilt_NPHI = 1 - 1.68 * ( - math.tan(float(self.silt_line_angle - 90) * math.pi / 180) + target_rhob = B[1] if B[1] is not None else 2.68 + silt_x, silt_y = line_intersection( + (D, p_silt), ((0.0, target_rhob), (1.0, target_rhob)) + ) + if not np.isfinite(silt_x) or not np.isfinite(silt_y): + raise ValueError( + "Cannot calculate dry silt point: silt line does not intersect " + f"RHOB={target_rhob:.3f} g/cc" ) - B = self.dry_silt_point = (drysilt_NPHI, B[1] if B[1] is not None else 2.68) + B = self.dry_silt_point = (float(silt_x), float(target_rhob)) logger.debug(f"Updated dry silt point to: ({B[0]:.3f}, {B[1]:.3f})") # Calculate lithology fraction @@ -142,7 +143,13 @@ def lithology_fraction_kuttan_modified(self, nphi, rhob): D = self.fluid_point rock_len = length_a_b(A, C) - res_len = length_a_b(A, B) + reservoir_intersection = line_intersection((A, C), (D, B)) + if not all(np.isfinite(coord) for coord in reservoir_intersection): + raise ValueError( + "Cannot calculate reservoir length: fluid-silt line does not " + "intersect the sand-clay line" + ) + res_len = length_a_b(A, reservoir_intersection) res_ratio = res_len / rock_len var_pt = line_intersection((A, C), (D, (nphi_arr, rhob_arr))) diff --git a/quick_pp/plotter/report_plots.py b/quick_pp/plotter/report_plots.py index 044ea966..4b580437 100644 --- a/quick_pp/plotter/report_plots.py +++ b/quick_pp/plotter/report_plots.py @@ -611,18 +611,20 @@ def generate_nd_crossplot( else: rad = math.radians(float(silt_line_angle)) p_silt = (D[0] + math.cos(rad), D[1] + math.sin(rad)) - silt_inter = line_intersection((A, C), (D, p_silt)) - if ( - silt_inter is not None - and np.isfinite(silt_inter[0]) - and np.isfinite(silt_inter[1]) - ): - B = (float(silt_inter[0]), float(silt_inter[1])) - else: - drysilt_NPHI = 1.0 - 1.68 * math.tan( - float(silt_line_angle - 90) * math.pi / 180.0 + target_rhob = ( + float(dry_silt_point[1]) + if dry_silt_point and dry_silt_point[1] is not None + else 2.68 + ) + silt_inter = line_intersection( + (D, p_silt), ((0.0, target_rhob), (1.0, target_rhob)) + ) + if not np.isfinite(silt_inter[0]) or not np.isfinite(silt_inter[1]): + raise ValueError( + "Cannot calculate dry silt point: silt line does not intersect " + f"RHOB={target_rhob:.3f} g/cc" ) - B = (drysilt_NPHI, 2.68) + B = (float(silt_inter[0]), target_rhob) # Plot SSC ternary model lines ax1.plot( diff --git a/tests/test_backend_workspace_api.py b/tests/test_backend_workspace_api.py index 0a3df7d1..cfea9425 100644 --- a/tests/test_backend_workspace_api.py +++ b/tests/test_backend_workspace_api.py @@ -218,6 +218,20 @@ def test_end_to_end_workspace_compute_workflow(client_and_project): assert len(sat_body["data"]["SWT_ARCHIE"]) == 10 assert len(sat_body["data"]["SWT_WAXMAN"]) == 10 + r_sat_crossplot = client.post( + f"/quick_pp/workspace/projects/{pid}/wells/Well-A/saturation", + json={ + "method": "waxman_smits", + "qv_method": "crossplot", + "cec_clay": 0.2, + "rho_dry_clay": 2.71, + "water_salinity": 35000.0, + "save": False, + }, + ) + assert r_sat_crossplot.status_code == 200 + assert len(r_sat_crossplot.json()["data"]["SWT_WAXMAN"]) == 10 + # 6. Rock Typing across project (including empty well) & Perm Transform r_rt_winland = client.post( f"/quick_pp/workspace/projects/{pid}/rock_typing/compute", diff --git a/tests/test_sand_silt_clay.py b/tests/test_sand_silt_clay.py new file mode 100644 index 00000000..ecb5fde9 --- /dev/null +++ b/tests/test_sand_silt_clay.py @@ -0,0 +1,79 @@ +import math + +import numpy as np + +from quick_pp.lithology.sand_silt_clay import SandSiltClay +from quick_pp.utils import length_a_b, line_intersection + + +def test_missing_dry_silt_nphi_is_calculated_at_configured_rhob(): + model = SandSiltClay( + dry_silt_point=(None, 2.68), + dry_clay_point=(0.33, 2.70), + wet_clay_point=(0.45, 1.80), + ) + + model.estimate_lithology(np.array([0.1, 0.2]), np.array([2.4, 2.5])) + + expected_nphi = model.fluid_point[0] + ( + (2.68 - model.fluid_point[1]) / math.tan(math.radians(model.silt_line_angle)) + ) + assert model.dry_silt_point[1] == 2.68 + assert np.isclose(model.dry_silt_point[0], expected_nphi) + + +def test_missing_dry_silt_nphi_respects_custom_rhob(): + model = SandSiltClay( + dry_silt_point=(None, 2.60), + dry_clay_point=(0.33, 2.70), + wet_clay_point=(0.45, 1.80), + ) + + model.estimate_lithology(np.array([0.1, 0.2]), np.array([2.4, 2.5])) + + assert model.dry_silt_point[1] == 2.60 + + +def test_complete_dry_silt_point_with_zero_nphi_is_preserved(): + model = SandSiltClay( + dry_silt_point=(0.0, 2.68), + dry_clay_point=(0.33, 2.70), + wet_clay_point=(0.45, 1.80), + ) + + model.estimate_lithology(np.array([0.1, 0.2]), np.array([2.4, 2.5])) + + assert model.dry_silt_point == (0.0, 2.68) + + +def test_reservoir_length_uses_fluid_silt_intersection_with_rock_line(monkeypatch): + model = SandSiltClay( + dry_sand_point=(-0.02, 2.65), + dry_silt_point=(0.25, 2.68), + dry_clay_point=(0.33, 2.70), + fluid_point=(1.0, 1.0), + ) + captured = {} + + def capture_lithology_chart(proj_len, rock_len, res_ratio): + captured["rock_len"] = rock_len + captured["res_ratio"] = res_ratio + return np.zeros(2), np.zeros(2), np.zeros(2) + + monkeypatch.setattr(model, "lithology_chart", capture_lithology_chart) + model.lithology_fraction_kuttan_modified( + np.array([0.1, 0.2]), np.array([2.4, 2.5]) + ) + + intersection = line_intersection( + (model.dry_sand_point, model.dry_clay_point), + (model.fluid_point, model.dry_silt_point), + ) + expected_res_len = length_a_b(model.dry_sand_point, intersection) + expected_rock_len = length_a_b(model.dry_sand_point, model.dry_clay_point) + assert np.isclose(captured["rock_len"], expected_rock_len) + assert np.isclose(captured["res_ratio"], expected_res_len / expected_rock_len) + assert not np.isclose( + captured["res_ratio"], + length_a_b(model.dry_sand_point, model.dry_silt_point) / expected_rock_len, + ) From 3ec13e3fd399cd6d83780b51c265ae9eb3db903f Mon Sep 17 00:00:00 2001 From: imranfadhil Date: Wed, 4 Nov 2026 15:46:36 +0800 Subject: [PATCH 05/30] add mica in the multi mineral module --- docs/api/lithology.md | 1 - .../modules/InspectorLithoPoro.svelte | 2 + .../frontend/src/lib/state/wellData.svelte.ts | 11 +- .../src/lib/utils/petrophysicsColors.ts | 28 ++++ quick_pp/config.py | 6 + quick_pp/lithology/multi_mineral.py | 128 ++++++++++++++---- quick_pp/plotter/well_log.py | 2 +- quick_pp/plotter/well_log_config.py | 38 ++++++ tests/test_multi_mineral.py | 46 +++++++ 9 files changed, 233 insertions(+), 29 deletions(-) diff --git a/docs/api/lithology.md b/docs/api/lithology.md index 856b2358..fc8ccb7b 100644 --- a/docs/api/lithology.md +++ b/docs/api/lithology.md @@ -25,4 +25,3 @@ Deterministic and optimization-based mineral volume models for clastics, carbona ## Thin Beds ::: quick_pp.lithology.thin_beds - diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorLithoPoro.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorLithoPoro.svelte index 3a577078..09a4148a 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorLithoPoro.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorLithoPoro.svelte @@ -30,6 +30,8 @@ 'SMECTITE', 'CHLORITE', 'GLAUCONITE', + 'MUSCOVITE', + 'BIOTITE', 'KFELD', 'ALBITE', 'SIDERITE', diff --git a/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts b/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts index 9060a873..f6b6702f 100644 --- a/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts +++ b/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts @@ -1171,12 +1171,15 @@ class WellDataState { return compared > 0; }; - const hasCarbonateMinerals = + const hasMultiMineralCurves = hasPositiveCurve('VCALC') || hasPositiveCurve('VDOLO') || hasPositiveCurve('VANHY') || - hasPositiveCurve('VHALI'); - if (hasCarbonateMinerals) { + hasPositiveCurve('VHALI') || + hasPositiveCurve('VGLAUC') || + hasPositiveCurve('VMUSC') || + hasPositiveCurve('VBIOT'); + if (hasMultiMineralCurves) { if (isDuplicateArray(numericCurves['VSAND'], numericCurves['VCALC'])) { numericCurves['VSAND'] = new Array(numericCurves['VSAND'].length).fill(0); origCopy['VSAND'] = [...numericCurves['VSAND']]; @@ -1202,6 +1205,8 @@ class WellDataState { if (hasPositiveCurve('VSMEC')) detectedMinerals.push('SMECTITE'); if (hasPositiveCurve('VCHLO')) detectedMinerals.push('CHLORITE'); if (hasPositiveCurve('VGLAUC')) detectedMinerals.push('GLAUCONITE'); + if (hasPositiveCurve('VMUSC')) detectedMinerals.push('MUSCOVITE'); + if (hasPositiveCurve('VBIOT')) detectedMinerals.push('BIOTITE'); if (hasPositiveCurve('VKFELD')) detectedMinerals.push('KFELD'); if (hasPositiveCurve('VALBI')) detectedMinerals.push('ALBITE'); if (hasPositiveCurve('VSIDE')) detectedMinerals.push('SIDERITE'); diff --git a/quick_pp/app/frontend/src/lib/utils/petrophysicsColors.ts b/quick_pp/app/frontend/src/lib/utils/petrophysicsColors.ts index 480e278b..e07f800b 100644 --- a/quick_pp/app/frontend/src/lib/utils/petrophysicsColors.ts +++ b/quick_pp/app/frontend/src/lib/utils/petrophysicsColors.ts @@ -43,6 +43,10 @@ export const PETRO_COLORS = { chloStroke: '#14532D', glaucFill: '#047857', glaucStroke: '#064E3B', + muscFill: '#C4B5FD', + muscStroke: '#7C3AED', + biotFill: '#92400E', + biotStroke: '#78350F', kfeldFill: '#F472B6', kfeldStroke: '#BE185D', albiFill: '#E0E7FF', @@ -285,6 +289,26 @@ export const LITHOLOGY_TRACK_SPECS: LithologyTrackSpec[] = [ nphiEndpoint: 0.28, rhobEndpoint: 2.85 }, + { + mnemonic: 'VMUSC', + mineralName: 'MUSCOVITE', + shortLabel: 'Muscovite', + fillRgba: 'rgba(196, 181, 253, 0.62)', + fillHex: PETRO_COLORS.muscFill, + strokeHex: PETRO_COLORS.muscStroke, + nphiEndpoint: 0.02, + rhobEndpoint: 2.83 + }, + { + mnemonic: 'VBIOT', + mineralName: 'BIOTITE', + shortLabel: 'Biotite', + fillRgba: 'rgba(146, 64, 14, 0.62)', + fillHex: PETRO_COLORS.biotFill, + strokeHex: PETRO_COLORS.biotStroke, + nphiEndpoint: 0.04, + rhobEndpoint: 3.09 + }, { mnemonic: 'VKFELD', mineralName: 'KFELD', @@ -364,6 +388,8 @@ export const MINERAL_TO_CURVE_MNEMONIC: Record = { SMECTITE: 'VSMEC', CHLORITE: 'VCHLO', GLAUCONITE: 'VGLAUC', + MUSCOVITE: 'VMUSC', + BIOTITE: 'VBIOT', KFELD: 'VKFELD', ALBITE: 'VALBI', SIDERITE: 'VSIDE', @@ -389,6 +415,8 @@ export const ALL_LITHOLOGY_CURVES = [ 'VSMEC', 'VCHLO', 'VGLAUC', + 'VMUSC', + 'VBIOT', 'VKFELD', 'VALBI', 'VSIDE', diff --git a/quick_pp/config.py b/quick_pp/config.py index 4e15dd4e..7a1819e5 100644 --- a/quick_pp/config.py +++ b/quick_pp/config.py @@ -119,6 +119,8 @@ class Config: "VSMEC": {"name": "Smectite Volume", "unit": "v/v", "min": 0, "max": 1}, "VCHLO": {"name": "Chlorite Volume", "unit": "v/v", "min": 0, "max": 1}, "VGLAUC": {"name": "Glauconite Volume", "unit": "v/v", "min": 0, "max": 1}, + "VMUSC": {"name": "Muscovite Volume", "unit": "v/v", "min": 0, "max": 1}, + "VBIOT": {"name": "Biotite Volume", "unit": "v/v", "min": 0, "max": 1}, "VKFELD": {"name": "K-Feldspar Volume", "unit": "v/v", "min": 0, "max": 1}, "VALBI": {"name": "Albite Volume", "unit": "v/v", "min": 0, "max": 1}, "VSIDE": {"name": "Siderite Volume", "unit": "v/v", "min": 0, "max": 1}, @@ -465,6 +467,8 @@ class Config: "SMECTITE": {"GR": 80.0, "NPHI": 0.45, "RHOB": 2.15, "DTC": 140.0, "PEF": 2.0, "POTA": 0.5, "THOR": 15.0, "URAN": 2.0}, "CHLORITE": {"GR": 15.0, "NPHI": 0.32, "RHOB": 2.85, "DTC": 105.0, "PEF": 6.3, "POTA": 0.0, "THOR": 3.0, "URAN": 1.0}, "GLAUCONITE": {"GR": 220.0, "NPHI": 0.28, "RHOB": 2.85, "DTC": 95.0, "PEF": 5.8, "POTA": 5.0, "THOR": 6.5, "URAN": 4.0}, + "MUSCOVITE": {"GR": 180.0, "NPHI": 0.02, "RHOB": 2.83, "DTC": 68.0, "PEF": 3.6, "POTA": 9.8, "THOR": 1.0, "URAN": 1.0}, + "BIOTITE": {"GR": 180.0, "NPHI": 0.04, "RHOB": 3.09, "DTC": 70.0, "PEF": 8.0, "POTA": 8.5, "THOR": 5.0, "URAN": 1.0}, "KFELD": {"GR": 220.0, "NPHI": -0.02, "RHOB": 2.56, "DTC": 68.0, "PEF": 2.86, "POTA": 12.0, "THOR": 1.0, "URAN": 1.0}, "ALBITE": {"GR": 5.0, "NPHI": -0.01, "RHOB": 2.62, "DTC": 59.0, "PEF": 1.7, "POTA": 0.1, "THOR": 0.5, "URAN": 0.5}, "SIDERITE": {"GR": 0.0, "NPHI": 0.04, "RHOB": 3.96, "DTC": 43.5, "PEF": 14.7, "POTA": 0.0, "THOR": 0.0, "URAN": 0.0}, @@ -489,6 +493,8 @@ class Config: "SMECTITE": "VSMEC", "CHLORITE": "VCHLO", "GLAUCONITE": "VGLAUC", + "MUSCOVITE": "VMUSC", + "BIOTITE": "VBIOT", "KFELD": "VKFELD", "ALBITE": "VALBI", "SIDERITE": "VSIDE", diff --git a/quick_pp/lithology/multi_mineral.py b/quick_pp/lithology/multi_mineral.py index 269d0d36..06bfafae 100644 --- a/quick_pp/lithology/multi_mineral.py +++ b/quick_pp/lithology/multi_mineral.py @@ -18,7 +18,6 @@ "ILLITE", "SMECTITE", "CHLORITE", - "GLAUCONITE", ) DEFAULT_LOG_RANGES = { "GR": 100.0, @@ -33,7 +32,6 @@ } - def _project_bounded_simplex_batch( V: np.ndarray, lower: np.ndarray, @@ -422,9 +420,27 @@ def __init__( # Default fluid properties if none specified if fluid_properties is None: fluid_properties = { - "OIL": {"density": 0.8, "nphi": 0.0, "pef": 0.12, "dtc": 200.0, "u": 0.10}, - "GAS": {"density": 0.2, "nphi": 0.0, "pef": 0.05, "dtc": 400.0, "u": 0.01}, - "WATER": {"density": 1.0, "nphi": 1.0, "pef": 0.36, "dtc": 190.0, "u": 0.36}, + "OIL": { + "density": 0.8, + "nphi": 0.0, + "pef": 0.12, + "dtc": 200.0, + "u": 0.10, + }, + "GAS": { + "density": 0.2, + "nphi": 0.0, + "pef": 0.05, + "dtc": 400.0, + "u": 0.01, + }, + "WATER": { + "density": 1.0, + "nphi": 1.0, + "pef": 0.36, + "dtc": 190.0, + "u": 0.36, + }, } self.fluid_properties = fluid_properties self.fluids = ["OIL", "GAS", "WATER"] @@ -435,7 +451,11 @@ def __init__( default_mineral_bounds.update(mineral_bounds) # Define bounds for fluid volumes (0 to 1 for each fluid, overridden by fluid_bounds) - default_fluid_bounds = {"OIL": (0.0, 1.0), "GAS": (0.0, 1.0), "WATER": (0.0, 1.0)} + default_fluid_bounds = { + "OIL": (0.0, 1.0), + "GAS": (0.0, 1.0), + "WATER": (0.0, 1.0), + } if fluid_bounds is not None: default_fluid_bounds.update(fluid_bounds) @@ -1148,7 +1168,9 @@ def estimate_lithology( method: Optional[str] = None, n_jobs: Optional[int] = None, logs: Optional[Dict[str, np.ndarray]] = None, - bounds: Optional[Union[Dict[str, Tuple[float, float]], Tuple[Tuple[float, float], ...]]] = None, + bounds: Optional[ + Union[Dict[str, Tuple[float, float]], Tuple[Tuple[float, float], ...]] + ] = None, bad_hole_mask: Optional[np.ndarray] = None, cali: Optional[np.ndarray] = None, bs: Optional[Union[float, np.ndarray]] = None, @@ -1196,7 +1218,10 @@ def estimate_lithology( pd.DataFrame: A DataFrame containing estimated mineral/fluid volumes, constructed porosity, residual errors, and reconstructed logs. """ - def _to_float_array(arr: Optional[Union[float, np.ndarray]], length: int) -> np.ndarray: + + def _to_float_array( + arr: Optional[Union[float, np.ndarray]], length: int + ) -> np.ndarray: if arr is None: return np.full(length, np.nan, dtype=float) try: @@ -1215,7 +1240,9 @@ def _to_float_array(arr: Optional[Union[float, np.ndarray]], length: int) -> np. candidate_arrays.extend(logs.values()) candidate_arrays.extend(extra_logs.values()) - valid_lens = [len(a) for a in candidate_arrays if a is not None and hasattr(a, "__len__")] + valid_lens = [ + len(a) for a in candidate_arrays if a is not None and hasattr(a, "__len__") + ] if not valid_lens: raise ValueError("No input log arrays provided to estimate_lithology().") n_samples = max(valid_lens) @@ -1233,7 +1260,11 @@ def _to_float_array(arr: Optional[Union[float, np.ndarray]], length: int) -> np. if dtc is not None: raw_inputs["DTC"] = _to_float_array(dtc, n_samples) - rt_arr = _to_float_array(rt, n_samples) if rt is not None else np.full(n_samples, np.nan, dtype=float) + rt_arr = ( + _to_float_array(rt, n_samples) + if rt is not None + else np.full(n_samples, np.nan, dtype=float) + ) if logs is not None: for k, v in logs.items(): @@ -1274,7 +1305,9 @@ def _to_float_array(arr: Optional[Union[float, np.ndarray]], length: int) -> np. try: # 3. Handle PEF linearization via U = PEF * RHOB - do_pef_lin = self.linearize_pef if linearize_pef is None else bool(linearize_pef) + do_pef_lin = ( + self.linearize_pef if linearize_pef is None else bool(linearize_pef) + ) use_u_channel = False solve_inputs = dict(raw_inputs) @@ -1286,7 +1319,13 @@ def _to_float_array(arr: Optional[Union[float, np.ndarray]], length: int) -> np. use_u_channel = True # 4. Identify linear solve log names (ordered: GR, NPHI, RHOB, U/PEF, DTC, then extra channels) - canonical_order = ["GR", "NPHI", "RHOB", "U" if use_u_channel else "PEF", "DTC"] + canonical_order = [ + "GR", + "NPHI", + "RHOB", + "U" if use_u_channel else "PEF", + "DTC", + ] linear_log_names = [k for k in canonical_order if k in solve_inputs] for k in solve_inputs.keys(): if k not in linear_log_names: @@ -1299,7 +1338,9 @@ def _to_float_array(arr: Optional[Union[float, np.ndarray]], length: int) -> np. n_vars = n_minerals + n_fluids # Degrees of Freedom (DoF) check - n_equations = len(linear_log_names) + 1 # log response rows + 1 closure constraint + n_equations = ( + len(linear_log_names) + 1 + ) # log response rows + 1 closure constraint if n_equations < n_vars: logger.warning( f"MultiMineral model is under-determined: {len(linear_log_names)} log curves " @@ -1334,10 +1375,10 @@ def _to_float_array(arr: Optional[Union[float, np.ndarray]], length: int) -> np. if cali is not None and bs is not None: cali_arr = _to_float_array(cali, n_samples) bs_arr = _to_float_array(bs, n_samples) - is_bad |= (cali_arr > (bs_arr + 1.5)) + is_bad |= cali_arr > (bs_arr + 1.5) if drho is not None: drho_arr = _to_float_array(drho, n_samples) - is_bad |= (np.abs(drho_arr) > 0.05) + is_bad |= np.abs(drho_arr) > 0.05 # Build weight matrix W (n_samples, n_logs) custom_weights = log_weights or {} @@ -1461,7 +1502,9 @@ def _solve_group( delayed(_solve_group)(pi) for pi in range(len(patterns)) ) else: - group_results = [_solve_group(pi) for pi in range(len(patterns))] + group_results = [ + _solve_group(pi) for pi in range(len(patterns)) + ] for g_rows, V_sub, ok_sub in group_results: V_all[g_rows] = V_sub @@ -1480,6 +1523,7 @@ def _solve_group( # Reserve SLSQP for non-linear conductivity or explicit SLSQP solver if use_nonlinear: + def _run_slsqp_depth(i: int) -> Tuple[int, np.ndarray, bool]: log_values = { l_name: float(raw_inputs[l_name][i]) @@ -1525,7 +1569,9 @@ def _run_slsqp_depth(i: int) -> Tuple[int, np.ndarray, bool]: if use_u_channel: u_recon = recon_dict.get("U", np.full(n_samples, np.nan, dtype=float)) rho_recon = recon_dict.get("RHOB", rhob_arr) - safe_rho = np.where(np.isfinite(rho_recon) & (rho_recon > 0.5), rho_recon, 2.65) + safe_rho = np.where( + np.isfinite(rho_recon) & (rho_recon > 0.5), rho_recon, 2.65 + ) pef_reconstructed = np.where( valid_rows & np.isfinite(pef_arr), u_recon / safe_rho, @@ -1533,7 +1579,9 @@ def _run_slsqp_depth(i: int) -> Tuple[int, np.ndarray, bool]: ) else: pef_reconstructed = ( - np.where(valid_rows & np.isfinite(pef_arr), recon_dict["PEF"], np.nan) + np.where( + valid_rows & np.isfinite(pef_arr), recon_dict["PEF"], np.nan + ) if "PEF" in recon_dict else np.full(n_samples, np.nan, dtype=float) ) @@ -1562,15 +1610,45 @@ def _run_slsqp_depth(i: int) -> Tuple[int, np.ndarray, bool]: # Compute average absolute error across all measured logs all_diffs = [] if np.any(np.isfinite(gr_arr)): - all_diffs.append(np.where(valid_rows & np.isfinite(gr_arr), np.abs(gr_arr - gr_reconstructed), np.nan)) + all_diffs.append( + np.where( + valid_rows & np.isfinite(gr_arr), + np.abs(gr_arr - gr_reconstructed), + np.nan, + ) + ) if np.any(np.isfinite(nphi_arr)): - all_diffs.append(np.where(valid_rows & np.isfinite(nphi_arr), np.abs(nphi_arr - nphi_reconstructed), np.nan)) + all_diffs.append( + np.where( + valid_rows & np.isfinite(nphi_arr), + np.abs(nphi_arr - nphi_reconstructed), + np.nan, + ) + ) if np.any(np.isfinite(rhob_arr)): - all_diffs.append(np.where(valid_rows & np.isfinite(rhob_arr), np.abs(rhob_arr - rhob_reconstructed), np.nan)) + all_diffs.append( + np.where( + valid_rows & np.isfinite(rhob_arr), + np.abs(rhob_arr - rhob_reconstructed), + np.nan, + ) + ) if np.any(np.isfinite(pef_arr)): - all_diffs.append(np.where(valid_rows & np.isfinite(pef_arr), np.abs(pef_arr - pef_reconstructed), np.nan)) + all_diffs.append( + np.where( + valid_rows & np.isfinite(pef_arr), + np.abs(pef_arr - pef_reconstructed), + np.nan, + ) + ) if np.any(np.isfinite(dtc_arr)): - all_diffs.append(np.where(valid_rows & np.isfinite(dtc_arr), np.abs(dtc_arr - dtc_reconstructed), np.nan)) + all_diffs.append( + np.where( + valid_rows & np.isfinite(dtc_arr), + np.abs(dtc_arr - dtc_reconstructed), + np.nan, + ) + ) for l_name in linear_log_names: if l_name not in ("GR", "NPHI", "RHOB", "U", "PEF", "DTC"): @@ -1628,7 +1706,9 @@ def _run_slsqp_depth(i: int) -> Tuple[int, np.ndarray, bool]: for l_name in linear_log_names: if l_name not in ("GR", "NPHI", "RHOB", "U", "PEF", "DTC"): col_name = f"{l_name}_RECONSTRUCTED" - meas_val = raw_inputs.get(l_name, np.full(n_samples, np.nan, dtype=float)) + meas_val = raw_inputs.get( + l_name, np.full(n_samples, np.nan, dtype=float) + ) output_data[col_name] = np.where( valid_rows & np.isfinite(meas_val), recon_dict[l_name], diff --git a/quick_pp/plotter/well_log.py b/quick_pp/plotter/well_log.py index 8e910837..f4309c38 100644 --- a/quick_pp/plotter/well_log.py +++ b/quick_pp/plotter/well_log.py @@ -307,7 +307,7 @@ def fix_missing_volumetrics(df): volumetrics = [ "VCLAY", "VSILT", "VSAND", "VCALC", "VDOLO", "VGAS", "VOIL", "VHC", "VFELD", "VKAOL", "VANHY", "VGYPS", "VHALI", "VPYRI", "VCOAL", - "VILLI", "VSMEC", "VCHLO", "VGLAUC", "VKFELD", "VALBI", "VSIDE", "VANKE", "VKERO", + "VILLI", "VSMEC", "VCHLO", "VGLAUC", "VMUSC", "VBIOT", "VKFELD", "VALBI", "VSIDE", "VANKE", "VKERO", ] for col in volumetrics: if col in df.columns: diff --git a/quick_pp/plotter/well_log_config.py b/quick_pp/plotter/well_log_config.py index f17bbe28..fbf9ab09 100644 --- a/quick_pp/plotter/well_log_config.py +++ b/quick_pp/plotter/well_log_config.py @@ -54,6 +54,8 @@ "VSMEC": "#86EFAC", "VCHLO": "#15803D", "VGLAUC": "#047857", + "VMUSC": "#C4B5FD", + "VBIOT": "#92400E", "VKFELD": "#F472B6", "VALBI": "#E0E7FF", "VSIDE": "#78350F", @@ -512,6 +514,42 @@ "orientation": "h", }, }, + "VMUSC": { + "track": 8, + "secondary_y": False, + "hide_xaxis": True, + "style": { + "line_width": 0.5, + "line_color": "black", + "fill": "tonextx", + "fillpattern_bgcolor": COLOR_DICT["VMUSC"], + "fillpattern_fgcolor": "#000000", + "fillpattern_fillmode": "replace", + "fillpattern_shape": "o", + "fillpattern_size": 2, + "fillpattern_solidity": 0.2, + "stackgroup": "litho", + "orientation": "h", + }, + }, + "VBIOT": { + "track": 8, + "secondary_y": False, + "hide_xaxis": True, + "style": { + "line_width": 0.5, + "line_color": "black", + "fill": "tonextx", + "fillpattern_bgcolor": COLOR_DICT["VBIOT"], + "fillpattern_fgcolor": "#000000", + "fillpattern_fillmode": "replace", + "fillpattern_shape": "x", + "fillpattern_size": 2, + "fillpattern_solidity": 0.2, + "stackgroup": "litho", + "orientation": "h", + }, + }, "VKFELD": { "track": 8, "secondary_y": False, diff --git a/tests/test_multi_mineral.py b/tests/test_multi_mineral.py index 5dc7ad98..3042b32c 100644 --- a/tests/test_multi_mineral.py +++ b/tests/test_multi_mineral.py @@ -6,6 +6,7 @@ import numpy as np from quick_pp.lithology.multi_mineral import ( + CLAY_MINERAL_NAMES, MultiMineral, Optim, dual_water_conductivity, @@ -193,6 +194,51 @@ def test_complex_lithology_minerals_and_spectral_gr(): assert res_df["VILLI"].iloc[2] < 0.05 +def test_mica_minerals_have_endpoints_and_volume_curves(): + minerals = ["QUARTZ", "MUSCOVITE", "GLAUCONITE", "BIOTITE"] + fluid_props = { + "WATER": { + "density": 1.0, + "nphi": 1.0, + "pef": 0.36, + "dtc": 190.0, + "u": 0.36, + } + } + mm = MultiMineral(minerals=minerals, fluid_properties=fluid_props) + mm.fluids = ["WATER"] + mm.bounds = mm.mineral_bounds + ((0.0, 1.0),) + + log_names = ["GR", "NPHI", "RHOB", "PEF", "DTC", "POTA", "THOR", "URAN"] + response_matrix = mm._build_response_matrix(log_names) + expected_volumes = np.array( + [ + [0.45, 0.35, 0.0, 0.0, 0.20], + [0.45, 0.0, 0.35, 0.0, 0.20], + [0.45, 0.0, 0.0, 0.35, 0.20], + ] + ) + synthetic_logs = expected_volumes @ response_matrix.T + result = mm.estimate_lithology( + gr=synthetic_logs[:, 0], + nphi=synthetic_logs[:, 1], + rhob=synthetic_logs[:, 2], + pef=synthetic_logs[:, 3], + dtc=synthetic_logs[:, 4], + pota=synthetic_logs[:, 5], + thor=synthetic_logs[:, 6], + uran=synthetic_logs[:, 7], + ) + + assert {"VMUSC", "VGLAUC", "VBIOT"}.issubset(result.columns) + np.testing.assert_allclose( + result[["VMUSC", "VGLAUC", "VBIOT"]].to_numpy(), + expected_volumes[:, 1:4], + atol=1e-4, + ) + assert "GLAUCONITE" not in CLAY_MINERAL_NAMES + + def test_custom_bounds_and_pef_linearization(): """Verify custom bounds clamp accessory minerals and linearize_pef computes exact U.""" # Constrain GLAUCONITE to maximum 20% From bf6fc6724f4916c59e1232b09bc37336ea696f22 Mon Sep 17 00:00:00 2001 From: imranfadhil Date: Wed, 4 Nov 2026 17:17:44 +0800 Subject: [PATCH 06/30] revisit dry silt rhob constraint at 2.68 g/cc --- quick_pp/app/backend/services/workspace.py | 16 +++---- .../modules/InspectorLithoPoro.svelte | 4 +- .../frontend/src/lib/state/wellData.svelte.ts | 20 ++++++--- .../src/lib/state/workbench.svelte.ts | 42 +++++++------------ quick_pp/uncertainty.py | 9 +++- tests/test_backend_workspace_api.py | 15 ++++++- 6 files changed, 57 insertions(+), 49 deletions(-) diff --git a/quick_pp/app/backend/services/workspace.py b/quick_pp/app/backend/services/workspace.py index dc4e2b2e..7253d2eb 100644 --- a/quick_pp/app/backend/services/workspace.py +++ b/quick_pp/app/backend/services/workspace.py @@ -120,6 +120,8 @@ from quick_pp.upscaling import expand_blocked_logs, upscale_logs from quick_pp.utils import nd_triangle_coords +DRY_SILT_RHOB = float(Config.SSC_ENDPOINTS["DRY_SILT_POINT"][1]) + router = APIRouter( prefix="/workspace/projects/{project_id}", tags=["Workspace Compute"], @@ -2269,11 +2271,8 @@ def workspace_lithology( "No valid NPHI and RHOB pairs found in the selected interval" ) - silt_pt = ( - req.dry_silt_point - if req.dry_silt_point and req.dry_silt_point[1] is not None - else (None, 2.68) - ) + # The workspace silt endpoint is derived at the configured dry-silt RHOB. + silt_pt = (None, DRY_SILT_RHOB) ssc_model = SandSiltClay( dry_sand_point=req.dry_sand_point, dry_silt_point=silt_pt, @@ -3008,11 +3007,8 @@ def workspace_porosity( "No valid NPHI and RHOB pairs found in the selected interval" ) - silt_pt = ( - req.dry_silt_point - if req.dry_silt_point and req.dry_silt_point[1] is not None - else (None, 2.68) - ) + # Match workspace lithology: derive the silt endpoint at configured RHOB. + silt_pt = (None, DRY_SILT_RHOB) ssc_model = SandSiltClay( dry_sand_point=req.dry_sand_point, dry_silt_point=silt_pt, diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorLithoPoro.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorLithoPoro.svelte index 09a4148a..c858b15d 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorLithoPoro.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorLithoPoro.svelte @@ -176,10 +176,8 @@ }); $effect(() => { - // Keep drySiltNphi and drySiltRhob synchronized with silt line angle & rock line + // Keep the dry silt point on the silt line at the fixed 2.68 g/cc RHOB. const [siltNphi, siltRhob] = computeSiltIntersection( - [workbench.lithoParams.drySandNphi, workbench.lithoParams.drySandRhob], - [workbench.lithoParams.dryClayNphi, workbench.lithoParams.dryClayRhob], [workbench.lithoParams.fluidNphi, workbench.lithoParams.fluidRhob], workbench.lithoParams.siltLineAngle ); diff --git a/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts b/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts index f6b6702f..de198d9f 100644 --- a/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts +++ b/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts @@ -813,7 +813,21 @@ class WellDataState { const D: [number, number] = [lp.fluidNphi, lp.fluidRhob]; const rockLen = Math.max(1e-6, Math.hypot(A[0] - C[0], A[1] - C[1])); - const resLen = Math.max(1e-6, Math.hypot(A[0] - B[0], A[1] - B[1])); + const xdiff0 = A[0] - C[0]; + const ydiff0 = A[1] - C[1]; + const d0 = A[0] * C[1] - A[1] * C[0]; + const xdiff1 = D[0] - B[0]; + const ydiff1 = D[1] - B[1]; + const d1 = D[0] * B[1] - D[1] * B[0]; + const resDiv = xdiff0 * ydiff1 - xdiff1 * ydiff0; + if (Math.abs(resDiv) < 1e-12) { + throw new Error( + 'Cannot calculate live VSH preview: fluid-silt line does not intersect the sand-clay line' + ); + } + const resIntersectionX = (d0 * xdiff1 - d1 * xdiff0) / resDiv; + const resIntersectionY = (d0 * ydiff1 - d1 * ydiff0) / resDiv; + const resLen = Math.hypot(A[0] - resIntersectionX, A[1] - resIntersectionY); const resRatio = Math.max(0.05, Math.min(0.95, resLen / rockLen)); const nonResLen = Math.max(1e-6, rockLen * (1 - resRatio)); const siltClayRatio = 0.25; @@ -836,10 +850,6 @@ class WellDataState { logIndex: number; }> = []; - const xdiff0 = A[0] - C[0]; - const ydiff0 = A[1] - C[1]; - const d0 = A[0] * C[1] - A[1] * C[0]; - for (const idx of indices) { const d = dept[idx]; const gr = grArr[idx]; diff --git a/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts b/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts index a9e61c8c..4d0f0b14 100644 --- a/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts +++ b/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts @@ -505,36 +505,24 @@ export interface MultiWellVolumetricsState { zoneConfigs: Record; } -/** - * Calculates the intersection point between: - * 1. The silt line emanating from the water/fluid point (fluidNphi, fluidRhob) at siltLineAngle (in degrees). - * 2. The rock line connecting the dry sand point (sandNphi, sandRhob) and dry clay point (clayNphi, clayRhob). - */ +const DRY_SILT_RHOB = 2.68; + +/** Calculates the silt-line intersection with the configured dry-silt RHOB. */ export function computeSiltIntersection( - sand: [number, number], - clay: [number, number], fluid: [number, number], - siltLineAngleDeg: number + siltLineAngleDeg: number, + targetRhob: number = DRY_SILT_RHOB ): [number, number] { const rad = (siltLineAngleDeg * Math.PI) / 180; - const pSilt: [number, number] = [fluid[0] + Math.cos(rad), fluid[1] + Math.sin(rad)]; - - const xdiff0 = sand[0] - clay[0]; - const ydiff0 = sand[1] - clay[1]; - const d0 = sand[0] * clay[1] - sand[1] * clay[0]; - - const xdiff1 = fluid[0] - pSilt[0]; - const ydiff1 = fluid[1] - pSilt[1]; - const d1 = fluid[0] * pSilt[1] - fluid[1] * pSilt[0]; - - const div = xdiff0 * ydiff1 - xdiff1 * ydiff0; - if (Math.abs(div) < 1e-12) { - return [(sand[0] + clay[0]) / 2, (sand[1] + clay[1]) / 2]; + const sinAngle = Math.sin(rad); + if (Math.abs(sinAngle) < 1e-12) { + throw new Error( + 'Cannot calculate dry silt point: silt line is parallel to the RHOB target' + ); } - const varX = (d0 * xdiff1 - d1 * xdiff0) / div; - const varY = (d0 * ydiff1 - d1 * ydiff0) / div; - return [varX, varY]; + const distance = (targetRhob - fluid[1]) / sinAngle; + return [fluid[0] + distance * Math.cos(rad), targetRhob]; } class WorkbenchState { @@ -686,8 +674,8 @@ class WorkbenchState { denCorrMismatchThreshold: 0.15, drySandNphi: -0.02, drySandRhob: 2.65, - drySiltNphi: 0.078, - drySiltRhob: 2.664, + drySiltNphi: 0.069, + drySiltRhob: DRY_SILT_RHOB, dryClayNphi: 0.33, dryClayRhob: 2.7, fluidNphi: 1.0, @@ -1063,8 +1051,6 @@ class WorkbenchState { updateSiltEndpointFromAngle() { const [siltNphi, siltRhob] = computeSiltIntersection( - [this.lithoParams.drySandNphi, this.lithoParams.drySandRhob], - [this.lithoParams.dryClayNphi, this.lithoParams.dryClayRhob], [this.lithoParams.fluidNphi, this.lithoParams.fluidRhob], this.lithoParams.siltLineAngle ); diff --git a/quick_pp/uncertainty.py b/quick_pp/uncertainty.py index 04de63c3..14d84435 100644 --- a/quick_pp/uncertainty.py +++ b/quick_pp/uncertainty.py @@ -339,7 +339,13 @@ def _vectorized_ssc_neu_den( D = fluid_point rock_len = float(length_a_b(A, C)) - res_len = float(length_a_b(A, B)) + reservoir_intersection = line_intersection((A, C), (D, B)) + if not all(np.isfinite(coord) for coord in reservoir_intersection): + raise ValueError( + "Cannot calculate reservoir length: fluid-silt line does not " + "intersect the sand-clay line" + ) + res_len = float(length_a_b(A, reservoir_intersection)) if rock_len <= 1e-9: rock_len = 1.0 res_ratio = np.clip(res_len / rock_len, 1e-6, 1.0 - 1e-6) @@ -857,4 +863,3 @@ def calc_stochastic_reservoir_summary( "summary_df": summary_df, "volumetrics": volumetrics_by_zone, } - diff --git a/tests/test_backend_workspace_api.py b/tests/test_backend_workspace_api.py index cfea9425..0fccca47 100644 --- a/tests/test_backend_workspace_api.py +++ b/tests/test_backend_workspace_api.py @@ -177,13 +177,26 @@ def test_end_to_end_workspace_compute_workflow(client_and_project): # 2. Lithology SSC (save=True, using HC corrected logs) r_lith = client.post( f"/quick_pp/workspace/projects/{pid}/wells/Well-A/lithology", - json={"model": "ssc", "use_hc_corrected": True, "save": True}, + json={ + "model": "ssc", + "use_hc_corrected": True, + "dry_silt_point": [0.151, 2.74], + "silt_line_angle": 116.0, + "save": True, + }, ) assert r_lith.status_code == 200 lith_body = r_lith.json() assert lith_body["saved_rows"] == 10 assert "VSAND" in lith_body["data"] assert "VCLAY" in lith_body["data"] + assert lith_body["crossplot"]["dry_silt_point"][1] == 2.68 + expected_silt_nphi = 1.0 + ( + (2.68 - 1.0) / np.tan(np.deg2rad(116.0)) + ) + assert np.isclose( + lith_body["crossplot"]["dry_silt_point"][0], expected_silt_nphi + ) # 3. Porosity (save=True) r_poro = client.post( From 76313cd85aaaa0677b1ac6f1244b0d1fd0665565 Mon Sep 17 00:00:00 2001 From: imranfadhil Date: Wed, 4 Nov 2026 17:27:46 +0800 Subject: [PATCH 07/30] improvise the BQv crossplot --- .../modules/InspectorSaturation.svelte | 93 +++++++-- .../workbench/CrossplotCanvas.svelte | 180 ++++++++++++------ .../src/lib/state/workbench.svelte.ts | 6 + .../app/frontend/src/lib/utils/saturation.ts | 34 ++++ 4 files changed, 247 insertions(+), 66 deletions(-) diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte index 2387faca..36502f6e 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte @@ -5,7 +5,12 @@ import SavedParamsIndicator from '$lib/components/workbench/SavedParamsIndicator.svelte'; import { wellData } from '$lib/state/wellData.svelte'; import { workbench } from '$lib/state/workbench.svelte'; - import { fillMissingCurve, fitBqvCrossplot } from '$lib/utils/saturation'; + import { + fillMissingCurve, + fitBqvCrossplot, + fitBqvCrossplotLine, + getBqvFitIndices + } from '$lib/utils/saturation'; // Default reference depth is the bottom of the active filtered interval (or well max depth) let defaultRefDepth = $derived.by(() => { @@ -82,7 +87,7 @@ : refDepth; return estimateTempAndRwAtDepth(temperatureDepth); }); - let bqvFit = $derived.by(() => { + let bqvAutoFit = $derived.by(() => { const rawRt = wellData.curves['RT'] ?? []; const rawPhit = wellData.curves['PHIT'] ?? []; const rawVclay = wellData.curves['VCLAY'] ?? wellData.curves['VSHALE'] ?? []; @@ -95,10 +100,19 @@ useTs ? fillMissingCurve(phitSand, rawPhit) : rawPhit, useTs ? fillMissingCurve(wellData.curves['VSH_DIS'], rawVclay) : rawVclay, wellData.curves['DEPT'] ?? wellData.curves['DEPTH'] ?? [], - wellData.visibleIndices, + getBqvFitIndices(wellData.visibleIndices, workbench.brushedDepthIndices), workbench.saturationParams.m ); }); + let bqvFit = $derived.by(() => + workbench.saturationParams.bqvFitMode === 'manual' + ? fitBqvCrossplotLine( + bqvAutoFit.points, + workbench.saturationParams.bqvManualSlope, + workbench.saturationParams.bqvManualIntercept + ) + : bqvAutoFit + ); let crossplotCalibration = $derived.by(() => { const fit = bqvFit; if (fit.slope === null || fit.slope <= 0) return null; @@ -241,6 +255,14 @@ sp.bqvAppliedRhoClay = sp.rhoDryClay; sp.qvMethod = 'crossplot'; } + + function useManualBqvFit() { + const sp = workbench.saturationParams; + if (sp.bqvFitMode === 'manual') return; + if (bqvAutoFit.slope !== null) sp.bqvManualSlope = bqvAutoFit.slope; + if (bqvAutoFit.intercept !== null) sp.bqvManualIntercept = bqvAutoFit.intercept; + sp.bqvFitMode = 'manual'; + }
@@ -546,12 +568,57 @@
+
+ Fit interval and line +
+ + +
+
+ {#if workbench.saturationParams.bqvFitMode === 'manual'} + + + {/if}
- {#if bqvFit.slope !== null && crossplotCalibration} - Current filtered fit slope: {bqvFit.slope.toFixed(4)} (BQv/a), + intercept {bqvFit.intercept?.toFixed(4)}, a × slope = {(bqvFit.slope * workbench.saturationParams.a).toFixed( 4 @@ -560,10 +627,13 @@ R² = {bqvFit.r2 === null ? '—' : bqvFit.r2.toFixed(3)}, - n = {bqvFit.points.length}. At {refDepth.toFixed( - 1 - )} m, B = {crossplotCalibration.b.toFixed(3)} and implied CEC = - {crossplotCalibration.cec.toFixed(4)} meq/g. + n = {bqvFit.points.length}. + {#if crossplotCalibration} + At {refDepth.toFixed(1)} m, B = {crossplotCalibration.b.toFixed(3)} and + implied CEC = {crossplotCalibration.cec.toFixed(4)} meq/g. + {:else} + A positive slope and valid reference-depth inputs are required for CEC. + {/if} {:else} Select an interval with at least two valid crossplot samples and a positive fitted slope. @@ -571,8 +641,9 @@
- Fit uses the current depth/zone filters. Use a water-bearing interval; - the crossplot slope is an effective estimate. + Lasso water-bearing and clean-shale samples on the BQv plot; depth/zone filters + also constrain the interval. The intercept sets the plotted line only and does + not override the configured Rw.
+ {#if effectiveMode === 'bqv'} +
+
+ Fit interval: + + {bqvPlotSummary.hasSelection ? 'Lasso selection' : 'All visible samples'} — + {bqvPlotSummary.fitCount} valid of {bqvPlotSummary.visibleCount} + + {#if bqvPlotSummary.minDepth !== null && bqvPlotSummary.maxDepth !== null} + + ({fmtDepth(bqvPlotSummary.minDepth)}–{fmtDepth(bqvPlotSummary.maxDepth)}) + + {:else if bqvPlotSummary.hasSelection} + No valid BQv points in this selection + {/if} + {#if bqvPlotSummary.hasSelection} + + {/if} +
+
+ {bqvPlotSummary.mode === 'manual' ? 'Manual' : 'Autofit'} + Slope: {fmtNum(bqvPlotSummary.fit.slope, 4)} + Intercept: {fmtNum(bqvPlotSummary.fit.intercept, 4)} + R²: {fmtNum(bqvPlotSummary.fit.r2, 3)} + a×slope: {fmtNum(bqvPlotSummary.effectiveBqv, 4)} +
+
+ {/if} + {#if isScalCrossplotActive && scalQcSummary.samples.length > 0}
{/if} - {#if brushedSummary} + {#if brushedSummary && effectiveMode !== 'bqv'}
diff --git a/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts b/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts index 4d0f0b14..f05578ef 100644 --- a/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts +++ b/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts @@ -154,6 +154,9 @@ export interface SaturationModelParams { qvMethod: 'cec' | 'qvn' | 'crossplot'; cecClay: number; rhoDryClay: number; + bqvFitMode: 'auto' | 'manual'; + bqvManualSlope: number; + bqvManualIntercept: number; bqvAppliedSlope: number | null; bqvAppliedRefDepth: number | null; bqvAppliedRhoClay: number | null; @@ -737,6 +740,9 @@ class WorkbenchState { qvMethod: 'cec', cecClay: 0.1, rhoDryClay: 2.71, + bqvFitMode: 'auto', + bqvManualSlope: 0.1, + bqvManualIntercept: 0, bqvAppliedSlope: null, bqvAppliedRefDepth: null, bqvAppliedRhoClay: null, diff --git a/quick_pp/app/frontend/src/lib/utils/saturation.ts b/quick_pp/app/frontend/src/lib/utils/saturation.ts index 61ea9c3f..dc82ce5e 100644 --- a/quick_pp/app/frontend/src/lib/utils/saturation.ts +++ b/quick_pp/app/frontend/src/lib/utils/saturation.ts @@ -12,6 +12,15 @@ export interface BqvCrossplotFit { r2: number | null; } +export function getBqvFitIndices( + visibleIndices: number[], + brushedIndices: ReadonlySet +): number[] { + return brushedIndices.size > 0 + ? visibleIndices.filter((index) => brushedIndices.has(index)) + : visibleIndices; +} + export function fillMissingCurve(primary: number[] | undefined, fallback: number[]): number[] { if (!primary) return fallback; return fallback.map((value, index) => @@ -19,6 +28,31 @@ export function fillMissingCurve(primary: number[] | undefined, fallback: number ); } +export function fitBqvCrossplotLine( + points: BqvCrossplotPoint[], + slope: number, + intercept: number +): BqvCrossplotFit { + if (points.length < 2 || !Number.isFinite(slope) || !Number.isFinite(intercept)) { + return { points, slope: null, intercept: null, r2: null }; + } + + const meanY = points.reduce((sum, point) => sum + point.y, 0) / points.length; + let totalVarianceY = 0; + let residualSumSquares = 0; + for (const point of points) { + totalVarianceY += Math.pow(point.y - meanY, 2); + residualSumSquares += Math.pow(point.y - (slope * point.x + intercept), 2); + } + + return { + points, + slope, + intercept, + r2: totalVarianceY > 0 ? 1 - residualSumSquares / totalVarianceY : null + }; +} + export function fitBqvCrossplot( rt: number[], phit: number[], From fb8513bef794d9e7bf02583065a4bdaa8d6fc090 Mon Sep 17 00:00:00 2001 From: imranfadhil Date: Wed, 4 Nov 2026 18:24:56 +0800 Subject: [PATCH 08/30] improve BQv autofit with anchor on calculated y-intercept --- quick_pp/app/backend/services/workspace.py | 7 ++ .../modules/InspectorSaturation.svelte | 64 ++++++------- .../workbench/CrossplotCanvas.svelte | 93 ++++++++++++++++--- .../src/lib/state/workbench.svelte.ts | 2 + .../app/frontend/src/lib/utils/saturation.ts | 93 +++++++++++++++++++ tests/test_backend_workspace_api.py | 28 ++++++ 6 files changed, 245 insertions(+), 42 deletions(-) diff --git a/quick_pp/app/backend/services/workspace.py b/quick_pp/app/backend/services/workspace.py index 7253d2eb..22a33e4d 100644 --- a/quick_pp/app/backend/services/workspace.py +++ b/quick_pp/app/backend/services/workspace.py @@ -2691,6 +2691,13 @@ def workspace_lithology( if extra_c in out_df.columns: out_df.loc[active_badhole, extra_c] = np.nan + if model == "ssc": + out_df["VSHALE"] = out_df["VCLAY"] + out_df["VSILT"] + else: + out_df["VSHALE"] = out_df["VCLAY"] + if "VSHALE" not in save_cols: + save_cols.append("VSHALE") + saved_rows = 0 if save_cols: valid_save_mask = out_df[save_cols].notna().any(axis=1) | active_badhole diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte index 36502f6e..226c63e0 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte @@ -7,8 +7,10 @@ import { workbench } from '$lib/state/workbench.svelte'; import { fillMissingCurve, + estimateBqvReferenceRw, fitBqvCrossplot, fitBqvCrossplotLine, + fitBqvCrossplotWithFixedIntercept, getBqvFitIndices } from '$lib/utils/saturation'; @@ -32,11 +34,9 @@ return Number(wellData.depthRange.max.toFixed(1)); }); - let refDepth = $state(0); - - $effect(() => { - refDepth = defaultRefDepth; - }); + let refDepth = $derived( + workbench.saturationParams.bqvReferenceDepth ?? defaultRefDepth + ); function estimateTempAndRwAtDepth(depthM: number) { const sp = workbench.saturationParams; @@ -67,25 +67,14 @@ const tvd = wellData.curves['TVDSS'] ?? wellData.curves['TVD'] ?? wellData.curves['DEPTH'] ?? md; const fallbackTvd = wellData.curves['DEPTH'] ?? md; - let closestIndex = -1; - let closestDistance = Infinity; - for (const index of wellData.visibleIndices) { - const measuredDepth = md[index]; - if ( - Number.isFinite(measuredDepth) && - Math.abs(measuredDepth - refDepth) < closestDistance - ) { - closestIndex = index; - closestDistance = Math.abs(measuredDepth - refDepth); - } - } - const temperatureDepth = - closestIndex >= 0 - ? Number.isFinite(tvd[closestIndex]) - ? tvd[closestIndex] - : (fallbackTvd[closestIndex] ?? refDepth) - : refDepth; - return estimateTempAndRwAtDepth(temperatureDepth); + return estimateBqvReferenceRw( + workbench.saturationParams, + md, + tvd, + fallbackTvd, + wellData.visibleIndices, + refDepth + ); }); let bqvAutoFit = $derived.by(() => { const rawRt = wellData.curves['RT'] ?? []; @@ -95,7 +84,7 @@ const useTs = workbench.tsParams.useInSaturation && Boolean(phitSand?.some((value) => Number.isFinite(value))); - return fitBqvCrossplot( + const fit = fitBqvCrossplot( useTs ? fillMissingCurve(wellData.curves['RSAND_TS'], rawRt) : rawRt, useTs ? fillMissingCurve(phitSand, rawPhit) : rawPhit, useTs ? fillMissingCurve(wellData.curves['VSH_DIS'], rawVclay) : rawVclay, @@ -103,6 +92,12 @@ getBqvFitIndices(wellData.visibleIndices, workbench.brushedDepthIndices), workbench.saturationParams.m ); + const sp = workbench.saturationParams; + const intercept = + bqvReferenceRw.rw > 0 && sp.a > 0 + ? 1 / (sp.a * bqvReferenceRw.rw) + : Number.NaN; + return fitBqvCrossplotWithFixedIntercept(fit.points, intercept); }); let bqvFit = $derived.by(() => workbench.saturationParams.bqvFitMode === 'manual' @@ -117,8 +112,8 @@ const fit = bqvFit; if (fit.slope === null || fit.slope <= 0) return null; const sp = workbench.saturationParams; - const rw = sp.rwMode === 'pickett' ? sp.rwPickett : bqvReferenceRw.rwExact; - const tempC = bqvReferenceRw.tempCExact; + const rw = sp.rwMode === 'pickett' ? sp.rwPickett : bqvReferenceRw.rw; + const tempC = bqvReferenceRw.tempC; const b = (-1.28 + 0.225 * tempC - 0.0004059 * tempC ** 2) / (1 + (0.045 * tempC - 0.27) * Math.pow(rw, 1.23)); @@ -464,7 +459,13 @@ type="number" step="1" min="0" - bind:value={refDepth} + value={refDepth} + oninput={(event) => { + const value = Number(event.currentTarget.value); + workbench.saturationParams.bqvReferenceDepth = Number.isFinite(value) + ? value + : null; + }} title="Reference depth for Rw calculation (defaults to bottom of filtered interval)" class="mono-num h-5 w-16 rounded-2xs border border-[var(--border-hairline)] bg-[var(--bg-surface)] px-1 py-0 text-right text-[10px] font-semibold text-[var(--text-primary)] focus:border-[var(--border-focus)] focus:ring-1 focus:ring-[var(--border-focus)] focus:outline-none" /> @@ -476,7 +477,7 @@
diff --git a/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts b/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts index f05578ef..c5a66060 100644 --- a/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts +++ b/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts @@ -157,6 +157,7 @@ export interface SaturationModelParams { bqvFitMode: 'auto' | 'manual'; bqvManualSlope: number; bqvManualIntercept: number; + bqvReferenceDepth: number | null; bqvAppliedSlope: number | null; bqvAppliedRefDepth: number | null; bqvAppliedRhoClay: number | null; @@ -743,6 +744,7 @@ class WorkbenchState { bqvFitMode: 'auto', bqvManualSlope: 0.1, bqvManualIntercept: 0, + bqvReferenceDepth: null, bqvAppliedSlope: null, bqvAppliedRefDepth: null, bqvAppliedRhoClay: null, diff --git a/quick_pp/app/frontend/src/lib/utils/saturation.ts b/quick_pp/app/frontend/src/lib/utils/saturation.ts index dc82ce5e..76343a94 100644 --- a/quick_pp/app/frontend/src/lib/utils/saturation.ts +++ b/quick_pp/app/frontend/src/lib/utils/saturation.ts @@ -12,6 +12,15 @@ export interface BqvCrossplotFit { r2: number | null; } +export interface BqvRwSettings { + rwMode: 'salinity_temp' | 'pickett'; + rwPickett: number; + measSystem: 'metric' | 'imperial'; + surfaceTemp: number; + tempGradient: number; + waterSalinity: number; +} + export function getBqvFitIndices( visibleIndices: number[], brushedIndices: ReadonlySet @@ -28,6 +37,52 @@ export function fillMissingCurve(primary: number[] | undefined, fallback: number ); } +export function estimateBqvReferenceRw( + settings: BqvRwSettings, + measuredDepths: number[], + tvdDepths: number[], + fallbackDepths: number[], + visibleIndices: number[], + referenceDepth: number +): { rw: number; tempC: number } { + let closestIndex = -1; + let closestDistance = Infinity; + for (const index of visibleIndices) { + const measuredDepth = measuredDepths[index]; + if ( + Number.isFinite(measuredDepth) && + Math.abs(measuredDepth - referenceDepth) < closestDistance + ) { + closestIndex = index; + closestDistance = Math.abs(measuredDepth - referenceDepth); + } + } + + const temperatureDepth = + closestIndex >= 0 + ? Number.isFinite(tvdDepths[closestIndex]) + ? tvdDepths[closestIndex] + : (fallbackDepths[closestIndex] ?? referenceDepth) + : referenceDepth; + let tempC: number; + if (settings.measSystem === 'imperial') { + const tvdKft = (temperatureDepth * 3.28084) / 1000; + const tempF = settings.surfaceTemp + settings.tempGradient * tvdKft; + tempC = Math.max(5, Math.min(250, ((tempF - 32) * 5) / 9)); + } else { + tempC = Math.max( + 5, + Math.min(250, settings.surfaceTemp + settings.tempGradient * (temperatureDepth / 1000)) + ); + } + + const rw = + settings.rwMode === 'pickett' + ? settings.rwPickett + : Math.pow(400000 / (Math.max(100, settings.waterSalinity) * (tempC * 9 / 5 + 32)), 0.88); + return { rw, tempC }; +} + export function fitBqvCrossplotLine( points: BqvCrossplotPoint[], slope: number, @@ -53,6 +108,44 @@ export function fitBqvCrossplotLine( }; } +export function fitBqvCrossplotWithFixedIntercept( + points: BqvCrossplotPoint[], + intercept: number +): BqvCrossplotFit { + if (!Number.isFinite(intercept)) { + return { points, slope: null, intercept: null, r2: null }; + } + if (points.length < 2) { + return { points, slope: null, intercept, r2: null }; + } + + let numerator = 0; + let denominator = 0; + for (const point of points) { + numerator += point.x * (point.y - intercept); + denominator += point.x * point.x; + } + if (denominator <= 0) { + return { points, slope: null, intercept, r2: null }; + } + + const slope = numerator / denominator; + const meanY = points.reduce((sum, point) => sum + point.y, 0) / points.length; + let totalVarianceY = 0; + let residualSumSquares = 0; + for (const point of points) { + totalVarianceY += Math.pow(point.y - meanY, 2); + residualSumSquares += Math.pow(point.y - (slope * point.x + intercept), 2); + } + + return { + points, + slope, + intercept, + r2: totalVarianceY > 0 ? 1 - residualSumSquares / totalVarianceY : null + }; +} + export function fitBqvCrossplot( rt: number[], phit: number[], diff --git a/tests/test_backend_workspace_api.py b/tests/test_backend_workspace_api.py index 0fccca47..591df423 100644 --- a/tests/test_backend_workspace_api.py +++ b/tests/test_backend_workspace_api.py @@ -190,6 +190,14 @@ def test_end_to_end_workspace_compute_workflow(client_and_project): assert lith_body["saved_rows"] == 10 assert "VSAND" in lith_body["data"] assert "VCLAY" in lith_body["data"] + assert "VSHALE" in lith_body["data"] + for vclay, vsilt, vshale in zip( + lith_body["data"]["VCLAY"], + lith_body["data"]["VSILT"], + lith_body["data"]["VSHALE"], + strict=True, + ): + assert np.isclose(vshale, vclay + vsilt) assert lith_body["crossplot"]["dry_silt_point"][1] == 2.68 expected_silt_nphi = 1.0 + ( (2.68 - 1.0) / np.tan(np.deg2rad(116.0)) @@ -594,6 +602,7 @@ def test_badhole_flagging_and_litho_poro_badhole_treatments(client_and_project): lith_ign = r_lith_ign.json()["data"] assert lith_ign["VCLAY"][2] is None assert lith_ign["VSAND"][2] is None + assert lith_ign["VSHALE"][2] is None assert lith_ign["VCLAY"][1] is not None r_poro_ign = client.post( @@ -619,6 +628,11 @@ def test_badhole_flagging_and_litho_poro_badhole_treatments(client_and_project): 0.5 * (lith_interp["VCLAY"][1] + lith_interp["VCLAY"][3]), atol=1e-4, ) + assert np.isclose( + lith_interp["VSHALE"][2], + lith_interp["VCLAY"][2] + lith_interp["VSILT"][2], + atol=1e-6, + ) r_poro_interp = client.post( f"/quick_pp/workspace/projects/{pid}/wells/Well-A/porosity", @@ -647,6 +661,20 @@ def test_badhole_flagging_and_litho_poro_badhole_treatments(client_and_project): lith_gr = r_lith_gr.json()["data"] assert lith_gr["VSILT"][2] == 0.0 assert lith_gr["VCLAY"][2] is not None and 0.0 <= lith_gr["VCLAY"][2] <= 1.0 + assert np.isclose(lith_gr["VSHALE"][2], lith_gr["VCLAY"][2]) + + r_lith_vsh_gr = client.post( + f"/quick_pp/workspace/projects/{pid}/wells/Well-A/lithology", + json={ + "model": "vsh_gr", + "gr_clean": 30.0, + "gr_clay": 110.0, + "save": False, + }, + ) + assert r_lith_vsh_gr.status_code == 200 + lith_vsh_gr = r_lith_vsh_gr.json()["data"] + assert np.allclose(lith_vsh_gr["VSHALE"], lith_vsh_gr["VCLAY"]) r_poro_gr = client.post( f"/quick_pp/workspace/projects/{pid}/wells/Well-A/porosity", From 7786430c7c1144a2eec7a56f742a29935d92dd47 Mon Sep 17 00:00:00 2001 From: imranfadhil Date: Thu, 5 Nov 2026 10:20:37 +0800 Subject: [PATCH 09/30] improve interval/ lasso selection computation --- .../modules/InspectorLithoPoro.svelte | 55 +++++++++++++++---- .../components/modules/InspectorPerm.svelte | 16 +++++- .../components/modules/InspectorQaqc.svelte | 32 +++++++++-- .../components/modules/InspectorResSum.svelte | 29 ++++++++-- .../modules/InspectorSaturation.svelte | 16 +++++- .../components/modules/InspectorScal.svelte | 30 +++++++++- .../workbench/CrossplotCanvas.svelte | 33 ++++++++--- .../workbench/LogTrackCanvas.svelte | 31 ++++++++--- .../frontend/src/lib/state/wellData.svelte.ts | 50 +++++++++++++---- .../src/lib/state/workbench.svelte.ts | 5 ++ 10 files changed, 238 insertions(+), 59 deletions(-) diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorLithoPoro.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorLithoPoro.svelte index c858b15d..30f684f3 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorLithoPoro.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorLithoPoro.svelte @@ -233,6 +233,12 @@ async function executeLithoPoro(persist: boolean = false) { if (!workbench.projectId || !workbench.wellId) return; + const selectionIndices = wellData.getBrushedCalculationIndices(); + if (selectionIndices && selectionIndices.size === 0) { + wellData.lastError = 'The selection contains no rows in the active depth/zone filter.'; + return; + } + const selectionMode = selectionIndices !== null; const runId = ++lithoPoroRunId; wellData.isCalculating = true; wellData.lastError = null; @@ -248,7 +254,7 @@ min_depth: workbench.depthFilter?.min ?? null, max_depth: workbench.depthFilter?.max ?? null, zones: workbench.selectedZones.length > 0 ? workbench.selectedZones : null, - save: persist + save: persist && !selectionMode }; const coalArgs = { @@ -430,17 +436,21 @@ // Apply all computed curves from Steps 1–4 in a single atomic reactive update if (Object.keys(batchedCurves).length > 0) { - wellData.mergeComputedCurves(batchedCurves, batchedStats); + wellData.mergeComputedCurves(batchedCurves, batchedStats, selectionIndices); wellData.markModuleComputed('litho-poro', batchedCurves); } if (persist) { - wellData.lastSavedMessage = 'Litho & Poro Saved ✓'; + if (selectionMode) { + await wellData.saveModuleComputed('litho-poro', 'Litho & Poro Saved ✓'); + } else { + wellData.lastSavedMessage = 'Litho & Poro Saved ✓'; + } } } catch (e: any) { if (runId !== lithoPoroRunId) return; if (Object.keys(batchedCurves).length > 0) { - wellData.mergeComputedCurves(batchedCurves, batchedStats); + wellData.mergeComputedCurves(batchedCurves, batchedStats, selectionIndices); wellData.markModuleComputed('litho-poro', batchedCurves); } wellData.lastError = e?.message || 'Lithology/Porosity error'; @@ -453,6 +463,12 @@ async function executeThomasStieber(persist: boolean = false, chained: boolean = false) { if (!workbench.projectId || !workbench.wellId) return; + const selectionIndices = wellData.getBrushedCalculationIndices(); + if (selectionIndices && selectionIndices.size === 0) { + wellData.lastError = 'The selection contains no rows in the active depth/zone filter.'; + return; + } + const selectionMode = selectionIndices !== null; if (!chained) { wellData.isCalculating = true; wellData.lastError = null; @@ -477,11 +493,11 @@ min_depth: workbench.depthFilter?.min ?? null, max_depth: workbench.depthFilter?.max ?? null, zones: workbench.selectedZones.length > 0 ? workbench.selectedZones : null, - save: persist + save: persist && !selectionMode } ); if (res.data) { - wellData.mergeComputedCurves(res.data, res.stats); + wellData.mergeComputedCurves(res.data, res.stats, selectionIndices); wellData.markModuleComputed('litho-poro', res.data); } workbench.tsParams.enabled = true; @@ -489,7 +505,11 @@ tsSummary = res.summary; } if (persist && !chained) { - wellData.lastSavedMessage = 'Thomas-Stieber Saved ✓'; + if (selectionMode) { + await wellData.saveModuleComputed('litho-poro', 'Thomas-Stieber Saved ✓'); + } else { + wellData.lastSavedMessage = 'Thomas-Stieber Saved ✓'; + } } } catch (e: any) { wellData.lastError = e?.message || 'Thomas-Stieber estimation failed'; @@ -514,6 +534,12 @@ async function executePretrainedMlInference(persist: boolean = false) { if (!workbench.projectId || !workbench.wellId) return; + const selectionIndices = wellData.getBrushedCalculationIndices(); + if (selectionIndices && selectionIndices.size === 0) { + wellData.lastError = 'The selection contains no rows in the active depth/zone filter.'; + return; + } + const selectionMode = selectionIndices !== null; wellData.isCalculating = true; wellData.lastError = null; try { @@ -526,14 +552,14 @@ min_depth: workbench.depthFilter?.min ?? null, max_depth: workbench.depthFilter?.max ?? null, zones: workbench.selectedZones.length > 0 ? workbench.selectedZones : null, - save: persist + save: persist && !selectionMode } ); if (res.data) { - wellData.mergeComputedCurves(res.data, res.stats); + wellData.mergeComputedCurves(res.data, res.stats, selectionIndices); wellData.markModuleComputed('litho-poro', res.data); } else if (res.computed_curves) { - wellData.mergeComputedCurves(res.computed_curves, res.stats); + wellData.mergeComputedCurves(res.computed_curves, res.stats, selectionIndices); wellData.markModuleComputed('litho-poro', res.computed_curves); } mlSummary = { @@ -546,7 +572,14 @@ perm_median_p90_p10_factor: res.interval_width_summary?.perm_median_p90_p10_factor ?? 1 }; if (persist) { - wellData.lastSavedMessage = 'Pre-Trained Conformal Bounds Applied ✓'; + if (selectionMode) { + await wellData.saveModuleComputed( + 'litho-poro', + 'Pre-Trained Conformal Bounds Applied ✓' + ); + } else { + wellData.lastSavedMessage = 'Pre-Trained Conformal Bounds Applied ✓'; + } } } catch (e: any) { wellData.lastError = e?.message || 'Pre-trained ML inference failed'; diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorPerm.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorPerm.svelte index f0899777..0e8ef9e4 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorPerm.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorPerm.svelte @@ -20,6 +20,12 @@ async function executePerm(persist: boolean = false) { if (!workbench.projectId || !workbench.wellId) return; + const selectionIndices = wellData.getBrushedCalculationIndices(); + if (selectionIndices && selectionIndices.size === 0) { + wellData.lastError = 'The selection contains no rows in the active depth/zone filter.'; + return; + } + const selectionMode = selectionIndices !== null; wellData.isCalculating = true; wellData.lastError = null; const deptArr = wellData.curves['DEPT'] ?? wellData.curves['DEPTH'] ?? []; @@ -58,18 +64,22 @@ min_depth: workbench.depthFilter?.min ?? null, max_depth: workbench.depthFilter?.max ?? null, zones: workbench.selectedZones.length > 0 ? workbench.selectedZones : null, - save: persist + save: persist && !selectionMode } as any } ); if (error || !data) { throw new Error(String((error as any)?.detail ?? 'Permeability calculation failed')); } - wellData.mergeComputedCurves(data.data, data.stats); + wellData.mergeComputedCurves(data.data, data.stats, selectionIndices); wellData.markModuleComputed('perm', data.data); wellData.permCoreMetrics = data.core_metrics; if (persist) { - wellData.lastSavedMessage = 'Permeability Saved ✓'; + if (selectionMode) { + await wellData.saveModuleComputed('perm', 'Permeability Saved ✓'); + } else { + wellData.lastSavedMessage = 'Permeability Saved ✓'; + } } } catch (e: any) { wellData.lastError = e?.message || 'Permeability error'; diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorQaqc.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorQaqc.svelte index cc2380a8..6d586c62 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorQaqc.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorQaqc.svelte @@ -673,6 +673,12 @@ async function runBadholeFlagging(persist: boolean = false) { if (!workbench.projectId || !workbench.wellId) return; + const selectionIndices = wellData.getBrushedCalculationIndices(); + if (selectionIndices && selectionIndices.size === 0) { + wellData.lastError = 'The selection contains no rows in the active depth/zone filter.'; + return; + } + const selectionMode = selectionIndices !== null; wellData.isCalculating = true; wellData.lastError = null; const bp = workbench.badholeParams; @@ -698,18 +704,22 @@ min_depth: workbench.depthFilter?.min ?? null, max_depth: workbench.depthFilter?.max ?? null, zones: workbench.selectedZones.length > 0 ? workbench.selectedZones : null, - save: persist + save: persist && !selectionMode } ); if (res.data) { - wellData.mergeComputedCurves(res.data, res.stats); + wellData.mergeComputedCurves(res.data, res.stats, selectionIndices); wellData.markModuleComputed('qaqc-badhole', res.data); } if (res.badhole_summary) { badholeSummary = res.badhole_summary; } if (persist) { - wellData.lastSavedMessage = 'Badhole Flags Saved ✓'; + if (selectionMode) { + await wellData.saveModuleComputed('qaqc-badhole', 'Badhole Flags Saved ✓'); + } else { + wellData.lastSavedMessage = 'Badhole Flags Saved ✓'; + } } } catch (e: any) { wellData.lastError = e?.message || 'Badhole flagging error'; @@ -739,6 +749,12 @@ async function runEnvCorrections(persist: boolean = false) { if (!workbench.projectId || !workbench.wellId) return; + const selectionIndices = wellData.getBrushedCalculationIndices(); + if (selectionIndices && selectionIndices.size === 0) { + wellData.lastError = 'The selection contains no rows in the active depth/zone filter.'; + return; + } + const selectionMode = selectionIndices !== null; wellData.isCalculating = true; wellData.lastError = null; try { @@ -753,15 +769,19 @@ min_depth: workbench.depthFilter?.min ?? null, max_depth: workbench.depthFilter?.max ?? null, zones: workbench.selectedZones.length > 0 ? workbench.selectedZones : null, - save: persist + save: persist && !selectionMode } ); if (res.data) { - wellData.mergeComputedCurves(res.data, res.stats); + wellData.mergeComputedCurves(res.data, res.stats, selectionIndices); wellData.markModuleComputed('qaqc-env', res.data); } if (persist) { - wellData.lastSavedMessage = 'Env Corrections Saved ✓'; + if (selectionMode) { + await wellData.saveModuleComputed('qaqc-env', 'Env Corrections Saved ✓'); + } else { + wellData.lastSavedMessage = 'Env Corrections Saved ✓'; + } } } catch (e: any) { wellData.lastError = e?.message || 'Environmental corrections error'; diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorResSum.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorResSum.svelte index c1e404e1..efd93621 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorResSum.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorResSum.svelte @@ -45,6 +45,12 @@ async function executeResSum(persist: boolean = false) { if (!workbench.projectId || !workbench.wellId) return; + const selectionIndices = wellData.getBrushedCalculationIndices(); + if (selectionIndices && selectionIndices.size === 0) { + wellData.lastError = 'The selection contains no rows in the active depth/zone filter.'; + return; + } + const selectionMode = selectionIndices !== null; wellData.isCalculating = true; wellData.lastError = null; try { @@ -66,20 +72,28 @@ min_depth: workbench.depthFilter?.min ?? null, max_depth: workbench.depthFilter?.max ?? null, zones: workbench.selectedZones.length > 0 ? workbench.selectedZones : null, - save: persist + save: persist && !selectionMode } ); if (data.flags?.data) { - wellData.mergeComputedCurves(data.flags.data); + wellData.mergeComputedCurves(data.flags.data, undefined, selectionIndices); wellData.markModuleComputed('ressum', data.flags.data); } if (data.upscaling?.step_log?.data) { - wellData.mergeComputedCurves(data.upscaling.step_log.data); + wellData.mergeComputedCurves( + data.upscaling.step_log.data, + undefined, + selectionIndices + ); wellData.markModuleComputed('ressum', data.upscaling.step_log.data); } if (data.uncertainty?.cpi?.data) { - wellData.mergeComputedCurves(data.uncertainty.cpi.data); + wellData.mergeComputedCurves( + data.uncertainty.cpi.data, + undefined, + selectionIndices + ); wellData.markModuleComputed('ressum', data.uncertainty.cpi.data); } wellData.zonalSummary = data.summary || []; @@ -113,7 +127,11 @@ } if (persist) { - wellData.lastSavedMessage = 'Pay Flags Saved ✓'; + if (selectionMode) { + await wellData.saveModuleComputed('ressum', 'Pay Flags Saved ✓'); + } else { + wellData.lastSavedMessage = 'Pay Flags Saved ✓'; + } } } catch (e: any) { wellData.lastError = e?.message || 'Reservoir summary error'; @@ -559,4 +577,3 @@
- diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte index 226c63e0..a2dc1af1 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorSaturation.svelte @@ -158,6 +158,12 @@ 'Apply the current BQv crossplot fit before calculating Waxman-Smits saturation.'; return; } + const selectionIndices = wellData.getBrushedCalculationIndices(); + if (selectionIndices && selectionIndices.size === 0) { + wellData.lastError = 'The selection contains no rows in the active depth/zone filter.'; + return; + } + const selectionMode = selectionIndices !== null; wellData.isCalculating = true; wellData.lastError = null; const sp = workbench.saturationParams; @@ -208,14 +214,14 @@ min_depth: workbench.depthFilter?.min ?? null, max_depth: workbench.depthFilter?.max ?? null, zones: workbench.selectedZones.length > 0 ? workbench.selectedZones : null, - save: persist + save: persist && !selectionMode } as any } ); if (error || !data) { throw new Error(String((error as any)?.detail ?? 'Saturation calculation failed')); } - wellData.mergeComputedCurves(data.data, data.stats); + wellData.mergeComputedCurves(data.data, data.stats, selectionIndices); wellData.markModuleComputed('saturation', data.data); // If using Salinity & Temp Gradient mode, sync the median computed Rw to rwPickett for the Pickett Plot line if (sp.rwMode === 'salinity_temp') { @@ -226,7 +232,11 @@ } } if (persist) { - wellData.lastSavedMessage = 'Saturation Saved ✓'; + if (selectionMode) { + await wellData.saveModuleComputed('saturation', 'Saturation Saved ✓'); + } else { + wellData.lastSavedMessage = 'Saturation Saved ✓'; + } } } catch (e: any) { wellData.lastError = e?.message || 'Saturation error'; diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorScal.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorScal.svelte index 9f70f471..5ee7247d 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorScal.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorScal.svelte @@ -45,6 +45,11 @@ } async function runCoreCorrections() { + const selectionIndices = wellData.getBrushedCalculationIndices(); + if (selectionIndices && selectionIndices.size === 0) { + wellData.lastError = 'The selection contains no rows in the active depth/zone filter.'; + return; + } wellData.isCalculating = true; wellData.lastError = null; const sp = workbench.scalParams; @@ -63,6 +68,21 @@ wellData.originalCurves['CPERM'] ?? wellData.curves['CPERM'] ?? []; + const isDepthInSelection = (depth: number) => { + if (!selectionIndices) return true; + let closestIndex = -1; + let closestDelta = Infinity; + for (const idx of selectionIndices) { + const selectedDepth = dept[idx]; + if (!Number.isFinite(selectedDepth)) continue; + const delta = Math.abs(selectedDepth - depth); + if (delta < closestDelta) { + closestIndex = idx; + closestDelta = delta; + } + } + return closestIndex >= 0 && closestDelta <= 0.5; + }; const records: Array<{ DEPTH: number; CPORE: number; CPERM: number }> = []; const validSampleIndices: number[] = []; @@ -73,7 +93,10 @@ const origS = wellData.originalCoreSamples[idx]; const dCur = Number(s.depth ?? s.DEPTH ?? origS?.depth ?? idx + 1); const dRaw = Number(s.raw_depth ?? origS?.raw_depth ?? dCur); - if (!wellData.isCorePlugInActiveFilter(dRaw, dCur)) { + if ( + !wellData.isCorePlugInActiveFilter(dRaw, dCur) || + !isDepthInSelection(dCur) + ) { return; } // Always read from ambient/uncorrected baseline so repeated Compute runs never double-correct @@ -109,6 +132,7 @@ }); } else if (dept.length > 0 && (cporeBaseCurve.length > 0 || cpermBaseCurve.length > 0)) { for (const i of wellData.visibleIndices) { + if (selectionIndices && !selectionIndices.has(i)) continue; const dRaw = dept[i]; const pRaw = cporeBaseCurve[i]; const kRaw = cpermBaseCurve[i]; @@ -127,7 +151,7 @@ validCurveIndices.push(i); } } - } else { + } else if (!selectionIndices) { // Fallback synthetic plugs when well has no core samples loaded [ { depth: 2010, porosity: 0.18, perm: 45 }, @@ -280,7 +304,7 @@ CPERM_AIR: newCpermAir, CPORE_ORI: newCporeAmb, CPERM_ORI: newCpermAir - }); + }, undefined, selectionIndices); wellData.markModuleComputed('scal', [ 'CPORE', 'CPERM', diff --git a/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte b/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte index e139de06..6a508772 100644 --- a/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte +++ b/quick_pp/app/frontend/src/lib/components/workbench/CrossplotCanvas.svelte @@ -5567,20 +5567,37 @@ {#if brushedSummary && effectiveMode !== 'bqv'}
Lasso: {brushedSummary.count} pts ({fmtDepth( brushedSummary.min )}–{fmtDepth(brushedSummary.max)}) - +
+ {#if workbench.scope === 'single-well'} + + {/if} + +
{/if}
diff --git a/quick_pp/app/frontend/src/lib/components/workbench/LogTrackCanvas.svelte b/quick_pp/app/frontend/src/lib/components/workbench/LogTrackCanvas.svelte index 04d1e56b..54ba6042 100644 --- a/quick_pp/app/frontend/src/lib/components/workbench/LogTrackCanvas.svelte +++ b/quick_pp/app/frontend/src/lib/components/workbench/LogTrackCanvas.svelte @@ -4039,13 +4039,30 @@
{#if workbench.brushedDepthIndices.size > 0} - +
+ {#if workbench.scope === 'single-well'} + + {/if} + +
{/if}
diff --git a/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts b/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts index de198d9f..2a51c5a9 100644 --- a/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts +++ b/quick_pp/app/frontend/src/lib/state/wellData.svelte.ts @@ -1432,6 +1432,7 @@ class WellDataState { this.pendingParamSnapshots = {}; moduleParams.reset(); workbench.brushedDepthIndices = new Set(); + workbench.useBrushedCalculationFilter = false; workbench.tsParams.enabled = false; // Restore persisted SCAL, Core Overburden/Klinkenberg & Pc scaling parameters from well config @@ -1623,14 +1624,19 @@ class WellDataState { */ mergeComputedCurves( computedData: Record, - newStats?: Record + newStats?: Record, + targetIndices?: ReadonlySet | null ) { const baseDept = this.curves['DEPT'] ?? this.curves['DEPTH'] ?? []; const incomingDept = (computedData['DEPTH'] ?? computedData['DEPT'] ?? []) as (number | null)[]; + const selectedIndices = targetIndices ?? null; + if (selectedIndices && selectedIndices.size === 0) { + throw new Error('Select at least one visible row before calculating on the selection.'); + } const updated = { ...this.curves }; - if (incomingDept.length === baseDept.length || baseDept.length === 0) { + if (!selectedIndices && (incomingDept.length === baseDept.length || baseDept.length === 0)) { for (const [col, vals] of Object.entries(computedData)) { if (col === 'WELL_NAME' || col === 'ZONES') continue; updated[col] = vals.map((v) => @@ -1639,7 +1645,7 @@ class WellDataState { } if (updated['DEPTH']) updated['DEPT'] = updated['DEPTH']; } else { - // Depth-indexed merge for filtered interval calculations + // Depth-indexed merge for filtered interval and selected-row calculations const depthToIdx = new Map(); baseDept.forEach((d, idx) => { if (Number.isFinite(d)) depthToIdx.set(Number(d.toFixed(4)), idx); @@ -1650,15 +1656,26 @@ class WellDataState { const targetArr = updated[col] ? [...updated[col]] : new Array(baseDept.length).fill(Number.NaN); - incomingDept.forEach((d, i) => { - if (d === null || d === undefined) return; - const targetIdx = depthToIdx.get(Number(Number(d).toFixed(4))); - if (targetIdx !== undefined) { + const positionalRows = vals.length === baseDept.length; + const rowCount = incomingDept.length || (positionalRows ? vals.length : 0); + for (let i = 0; i < rowCount; i++) { + const d = incomingDept[i]; + if ((d === null || d === undefined) && !positionalRows) continue; + const targetIdx = + d !== null && d !== undefined + ? depthToIdx.get(Number(Number(d).toFixed(4))) + : positionalRows && i < baseDept.length + ? i + : undefined; + if ( + targetIdx !== undefined && + (!selectedIndices || selectedIndices.has(targetIdx)) + ) { const v = vals[i]; targetArr[targetIdx] = typeof v === 'number' && Number.isFinite(v) ? v : Number.NaN; } - }); + } updated[col] = targetArr; } } @@ -1672,16 +1689,25 @@ class WellDataState { const calcSt = computeSummaryStats(updated[col], finalDept); mergedStats[col] = { ...calcSt, - ...(newStats?.[col] || {}), - top: newStats?.[col]?.top ?? calcSt.top, - bottom: newStats?.[col]?.bottom ?? calcSt.bottom, - std: newStats?.[col]?.std ?? calcSt.std + ...(selectedIndices ? {} : newStats?.[col] || {}), + top: selectedIndices ? calcSt.top : (newStats?.[col]?.top ?? calcSt.top), + bottom: selectedIndices ? calcSt.bottom : (newStats?.[col]?.bottom ?? calcSt.bottom), + std: selectedIndices ? calcSt.std : (newStats?.[col]?.std ?? calcSt.std) }; } } this.stats = mergedStats; } + getBrushedCalculationIndices(): Set | null { + if (workbench.scope !== 'single-well' || !workbench.useBrushedCalculationFilter) { + return null; + } + return new Set( + this.visibleIndices.filter((idx) => workbench.brushedDepthIndices.has(idx)) + ); + } + /** * Ordered single-well calculation modules for cascading upstream saves. */ diff --git a/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts b/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts index c5a66060..47ca606a 100644 --- a/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts +++ b/quick_pp/app/frontend/src/lib/state/workbench.svelte.ts @@ -543,6 +543,7 @@ class WorkbenchState { // Synchronized cursor & crossplot lasso brushing cursorDepth = $state(null); brushedDepthIndices = $state>(new Set()); + useBrushedCalculationFilter = $state(false); targetScrollDepth = $state(null); // Right pane view mode @@ -1046,10 +1047,14 @@ class WorkbenchState { this.depthFilter = null; this.selectedZones = []; this.brushedDepthIndices = new Set(); + this.useBrushedCalculationFilter = false; } setBrushedIndices(indices: number[]) { this.brushedDepthIndices = new Set(indices); + if (this.brushedDepthIndices.size === 0) { + this.useBrushedCalculationFilter = false; + } } scrollToDepth(depth: number) { From 2f934ad197cb72f4365c57021603a3d1d8d83842 Mon Sep 17 00:00:00 2001 From: imranfadhil Date: Thu, 5 Nov 2026 10:44:57 +0800 Subject: [PATCH 10/30] add log based stress estimation in the standalone core data prep --- docs/workflows/single_well.md | 4 +- quick_pp/app/backend/services/scal.py | 82 ++++- .../components/modules/InspectorScal.svelte | 325 +++++++++++++++++- .../frontend/src/lib/state/wellData.svelte.ts | 33 ++ .../src/lib/state/workbench.svelte.ts | 18 + quick_pp/rock_physics/geomechanics.py | 145 +++++++- tests/test_geomechanics.py | 109 ++++++ 7 files changed, 695 insertions(+), 21 deletions(-) create mode 100644 tests/test_geomechanics.py diff --git a/docs/workflows/single_well.md b/docs/workflows/single_well.md index ebfc6a5f..0db335ce 100644 --- a/docs/workflows/single_well.md +++ b/docs/workflows/single_well.md @@ -330,6 +330,8 @@ flowchart TD 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. + * **Klinkenberg Gas Slippage Correction:** Corrects air permeability ($k_{\text{air}}$) to equivalent liquid permeability ($k_{\infty}$): @@ -343,4 +345,4 @@ flowchart TD $$P_{c,\text{res}} = P_{c,\text{lab}} \cdot \frac{(\sigma \cos\theta)_{\text{res}}}{(\sigma \cos\theta)_{\text{lab}}}$$ * **Input Data:** Core plugs table (`DEPTH`, `CPORE`, `CPERM`), Overburden stress parameters, Lab IFT and contact angle -* **Output Data:** `CPOR_SHIFTED`, `CPERM_SHIFTED`, Stress-corrected core properties, Scaled $P_c$ curves +* **Output Data:** `CPOR_SHIFTED`, `CPERM_SHIFTED`, `SV_EST`, `PP_EST`, `NU_DYN`, `NCS_EST`, Stress-corrected core properties, Scaled $P_c$ curves diff --git a/quick_pp/app/backend/services/scal.py b/quick_pp/app/backend/services/scal.py index 50fc8f2c..b093ee88 100644 --- a/quick_pp/app/backend/services/scal.py +++ b/quick_pp/app/backend/services/scal.py @@ -21,6 +21,7 @@ let_relperm, pc_lab_to_reservoir, ) +from quick_pp.rock_physics.geomechanics import estimate_log_stress_profile router = APIRouter(prefix="/scal", tags=["SCAL"]) @@ -136,6 +137,28 @@ class CoreCorrectionsInput(BaseModel): data: List[Dict[str, Any]] = Field(..., description="Core/log records") +class StressProfileInput(BaseModel): + md: List[Optional[float]] = Field(..., description="Measured depth aligned with the log arrays") + tvd: List[Optional[float]] = Field( + ..., description="Positive-down true vertical depth aligned with the log arrays" + ) + rhob: List[Optional[float]] = Field(..., description="Bulk density [g/cm³]") + dtc: Optional[List[Optional[float]]] = Field( + default=None, description="Compressional sonic slowness" + ) + dts: Optional[List[Optional[float]]] = Field( + default=None, description="Shear sonic slowness; same units as DTC" + ) + depth_unit: str = Field("m", description="'m' or 'ft', matching TVD") + pore_pressure_gradient: float = Field( + 1.42, ge=0.0, description="Pore-pressure gradient [psi per selected depth unit]" + ) + biot_coefficient: float = Field(1.0, ge=0.0, le=1.0) + poisson_ratio: float = Field( + 0.25, ge=0.0, lt=0.5, description="Fallback Poisson's ratio when sonic data are invalid" + ) + + class PcLabToReservoirInput(BaseModel): pc_lab: List[float] = Field(..., description="Laboratory capillary pressure (psi)") ift_lab: float = Field(72.0, gt=0.0, description="Laboratory interfacial tension (dynes/cm)") @@ -289,6 +312,64 @@ async def generate_swof_endpoint(inputs: SWOFTableInput): ) from e +@router.post( + "/stress_profile", + summary="Estimate a Log-Based Effective Confining Stress Profile", + operation_id="estimate_scal_stress_profile", +) +async def estimate_stress_profile_endpoint(inputs: StressProfileInput): + """Estimate vertical, pore, and equivalent effective confining stress from logs.""" + try: + if not (len(inputs.md) == len(inputs.tvd) == len(inputs.rhob)): + raise ValueError("md, tvd, and rhob must have matching lengths.") + if (inputs.dtc is None) != (inputs.dts is None): + raise ValueError("Provide both DTC and DTS for dynamic Poisson's ratio.") + if inputs.dtc is not None and ( + len(inputs.dtc) != len(inputs.md) or len(inputs.dts or []) != len(inputs.md) + ): + raise ValueError("DTC and DTS must match the lengths of the other log arrays.") + + def to_array(values): + if values is None: + return None + return np.asarray( + [np.nan if value is None else value for value in values], dtype=float + ) + + result = estimate_log_stress_profile( + md=to_array(inputs.md), + tvd=to_array(inputs.tvd), + rhob=to_array(inputs.rhob), + dtc=to_array(inputs.dtc), + dts=to_array(inputs.dts), + depth_unit=inputs.depth_unit.strip().lower(), + pore_pressure_gradient=inputs.pore_pressure_gradient, + biot_coefficient=inputs.biot_coefficient, + poisson_ratio=inputs.poisson_ratio, + ) + rows = [ + { + "DEPTH": float(md) if np.isfinite(md) else None, + "SV_EST": float(sv) if np.isfinite(sv) else None, + "PP_EST": float(pp) if np.isfinite(pp) else None, + "NU_DYN": float(nu) if np.isfinite(nu) else None, + "NCS_EST": float(ncs) if np.isfinite(ncs) else None, + } + for md, sv, pp, nu, ncs in zip( + result["md"], + result["sv_psi"], + result["pp_psi"], + result["nu"], + result["ncs_equivalent_psi"], + ) + ] + return {"data": rows} + except Exception as e: + raise HTTPException( + status_code=400, detail=f"Error estimating log-based stress profile: {e}" + ) from e + + @router.post( "/core_corrections", summary="Apply Overburden, Klinkenberg, and Clay-Bound Water Corrections to Core Data", @@ -366,4 +447,3 @@ async def convert_pc_lab_to_reservoir_endpoint(inputs: PcLabToReservoirInput): raise HTTPException( status_code=400, detail=f"Error converting capillary pressure: {e}" ) from e - diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorScal.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorScal.svelte index 5ee7247d..9a179e49 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorScal.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorScal.svelte @@ -9,7 +9,40 @@ import { workbench } from '$lib/state/workbench.svelte'; import { fmtNum } from '$lib/utils/formatters'; + type StressProfileRow = { + DEPTH: number | null; + SV_EST: number | null; + PP_EST: number | null; + NU_DYN: number | null; + NCS_EST: number | null; + }; + let scalPendingSave = $state(false); + let stressProfile = $state(null); + const stressProfileNcsRange = $derived.by(() => { + if (!stressProfile) return null; + let min = Infinity; + let max = -Infinity; + for (const row of stressProfile) { + if (typeof row.NCS_EST !== 'number' || !Number.isFinite(row.NCS_EST)) continue; + min = Math.min(min, row.NCS_EST); + max = Math.max(max, row.NCS_EST); + } + return Number.isFinite(min) && Number.isFinite(max) ? { min, max } : null; + }); + + const stressDepthCurves = $derived( + Object.keys(wellData.curves).filter((curve) => ['TVD', 'DEPT', 'DEPTH'].includes(curve)) + ); + const stressRhobCurves = $derived( + Object.keys(wellData.curves).filter((curve) => /RHOB|DEN/i.test(curve)) + ); + const stressDtcCurves = $derived( + Object.keys(wellData.curves).filter((curve) => /^(DTC|DTCO|DT|AC)$/i.test(curve)) + ); + const stressDtsCurves = $derived( + Object.keys(wellData.curves).filter((curve) => /^(DTS|DTSM|DTSS)$/i.test(curve)) + ); const canSaveScal = $derived( Boolean(workbench.projectId && workbench.wellId) && @@ -44,6 +77,121 @@ scalPendingSave = true; } + function setStressDepthUnit(unit: 'm' | 'ft') { + const sp = workbench.scalParams; + if (sp.stress_depth_unit === unit) return; + sp.stress_pore_pressure_gradient = + unit === 'ft' + ? sp.stress_pore_pressure_gradient * 0.3048 + : sp.stress_pore_pressure_gradient / 0.3048; + sp.stress_depth_unit = unit; + scalPendingSave = true; + } + + async function estimateStressProfile(): Promise { + const sp = workbench.scalParams; + const md = wellData.curves['DEPT'] ?? wellData.curves['DEPTH'] ?? []; + const tvd = wellData.curves[sp.stress_tvd_curve] ?? md; + const rhob = wellData.curves[sp.stress_rhob_curve]; + if (md.length < 2 || tvd.length !== md.length || !rhob || rhob.length !== md.length) { + throw new Error('Select aligned MD/TVD and RHOB curves with at least two rows.'); + } + + const dtcSelected = sp.stress_dtc_curve ? wellData.curves[sp.stress_dtc_curve] : undefined; + const dtsSelected = sp.stress_dts_curve ? wellData.curves[sp.stress_dts_curve] : undefined; + const hasSonicPair = Boolean(dtcSelected && dtsSelected); + const dtc = hasSonicPair ? dtcSelected : undefined; + const dts = hasSonicPair ? dtsSelected : undefined; + if ((dtc && dtc.length !== md.length) || (dts && dts.length !== md.length)) { + throw new Error('Selected sonic curves must align with the well depth grid.'); + } + + const nullable = (values: number[]) => + values.map((value) => (Number.isFinite(value) ? value : null)); + const result = await postJson<{ data: StressProfileRow[] }>('/quick_pp/scal/stress_profile', { + md: nullable(md), + tvd: nullable(tvd), + rhob: nullable(rhob), + dtc: dtc ? nullable(dtc) : null, + dts: dts ? nullable(dts) : null, + depth_unit: sp.stress_depth_unit, + pore_pressure_gradient: sp.stress_pore_pressure_gradient, + biot_coefficient: sp.stress_biot_coefficient, + poisson_ratio: sp.stress_poisson_ratio + }); + const rows = result.data ?? []; + const uniqueStressDepths = new Set(); + for (const row of rows) { + if ( + typeof row.DEPTH === 'number' && + Number.isFinite(row.DEPTH) && + typeof row.NCS_EST === 'number' && + Number.isFinite(row.NCS_EST) + ) { + uniqueStressDepths.add(row.DEPTH); + } + } + if (uniqueStressDepths.size < 2) { + throw new Error('At least two valid depth/density samples are required for a stress profile.'); + } + + stressProfile = rows; + wellData.mergeComputedCurves({ + DEPTH: md, + SV_EST: rows.map((row) => row.SV_EST), + PP_EST: rows.map((row) => row.PP_EST), + NU_DYN: rows.map((row) => row.NU_DYN), + NCS_EST: rows.map((row) => row.NCS_EST) + }); + wellData.markModuleComputed('scal', ['SV_EST', 'PP_EST', 'NU_DYN', 'NCS_EST']); + scalPendingSave = true; + return rows; + } + + function makeStressInterpolator(rows: StressProfileRow[]) { + const samples = rows + .filter( + (row): row is StressProfileRow & { DEPTH: number; NCS_EST: number } => + typeof row.DEPTH === 'number' && + Number.isFinite(row.DEPTH) && + typeof row.NCS_EST === 'number' && + Number.isFinite(row.NCS_EST) + ) + .sort((a, b) => a.DEPTH - b.DEPTH); + return (depth: number): number | null => { + if ( + samples.length < 2 || + depth < samples[0].DEPTH || + depth > samples[samples.length - 1].DEPTH + ) { + return null; + } + for (let i = 1; i < samples.length; i++) { + const upper = samples[i]; + if (depth > upper.DEPTH) continue; + const lower = samples[i - 1]; + const span = upper.DEPTH - lower.DEPTH; + if (span <= 0) continue; + const fraction = (depth - lower.DEPTH) / span; + return lower.NCS_EST + fraction * (upper.NCS_EST - lower.NCS_EST); + } + return null; + }; + } + + async function estimateStressProfileFromButton() { + wellData.isCalculating = true; + wellData.lastError = null; + try { + await estimateStressProfile(); + appStatus.success('Log-based stress profile estimated and added to the well curves'); + } catch (e: any) { + wellData.lastError = e?.message || 'Failed to estimate log-based stress profile'; + } finally { + wellData.isCalculating = false; + } + } + async function runCoreCorrections() { const selectionIndices = wellData.getBrushedCalculationIndices(); if (selectionIndices && selectionIndices.size === 0) { @@ -54,6 +202,18 @@ wellData.lastError = null; const sp = workbench.scalParams; try { + const stressRows = sp.use_log_stress_profile ? await estimateStressProfile() : null; + const interpolateStress = stressRows ? makeStressInterpolator(stressRows) : null; + const stressForRecord = (depth: number) => { + if (!interpolateStress) return {}; + const value = interpolateStress(depth); + if (value === null) { + throw new Error( + `Core depth ${depth} is outside the estimated stress profile coverage.` + ); + } + return { NCS_EST: value }; + }; const hasCoreSamples = wellData.coreSamples.length > 0; const dept = wellData.curves['DEPT'] ?? wellData.curves['DEPTH'] ?? []; const cporeBaseCurve = @@ -84,7 +244,12 @@ return closestIndex >= 0 && closestDelta <= 0.5; }; - const records: Array<{ DEPTH: number; CPORE: number; CPERM: number }> = []; + const records: Array<{ + DEPTH: number; + CPORE: number; + CPERM: number; + NCS_EST?: number; + }> = []; const validSampleIndices: number[] = []; const validCurveIndices: number[] = []; @@ -125,7 +290,8 @@ records.push({ DEPTH: dCur, CPORE: pRaw > 1 ? pRaw / 100 : pRaw, - CPERM: kRaw + CPERM: kRaw, + ...stressForRecord(dCur) }); validSampleIndices.push(idx); } @@ -146,12 +312,13 @@ records.push({ DEPTH: dRaw, CPORE: pRaw > 1 ? pRaw / 100 : pRaw, - CPERM: kRaw + CPERM: kRaw, + ...stressForRecord(dRaw) }); validCurveIndices.push(i); } } - } else if (!selectionIndices) { + } else if (!selectionIndices && !stressRows) { // Fallback synthetic plugs when well has no core samples loaded [ { depth: 2010, porosity: 0.18, perm: 45 }, @@ -188,7 +355,7 @@ const res = await postJson<{ data: Array>; }>('/quick_pp/scal/core_corrections', { - net_confining_stress: sp.net_confining_stress, + net_confining_stress: stressRows ? 'NCS_EST' : sp.net_confining_stress, mean_pore_pressure: sp.mean_pore_pressure, compaction_coeff: compactionCoeff, perm_compaction_coeff: permCompactionCoeff, @@ -218,7 +385,10 @@ : wellData.hasActiveFilter ? ' [Active Interval]' : ''; - const lineageTag = `NOB=${Math.round(sp.net_confining_stress)}psi, Pm=${Math.round(sp.mean_pore_pressure)}psi (${sp.core_lithology})${zoneSuffix}`; + const stressLabel = stressRows + ? 'log-derived equivalent NCS' + : `${Math.round(sp.net_confining_stress)}psi NCS`; + const lineageTag = `NOB=${stressLabel}, Pm=${Math.round(sp.mean_pore_pressure)}psi (${sp.core_lithology})${zoneSuffix}`; // 1. Update discrete core samples in-memory (preserving porosity_amb & perm_air baseline) if (hasCoreSamples && validSampleIndices.length > 0) { @@ -653,15 +823,140 @@ - +
+ + {#if workbench.scalParams.use_log_stress_profile} +
+ + + + +
+
+ + + + +
+

+ Use positive-down TVD from the surface; DEPT is only an MD-as-TVD approximation. + This assumes an onshore/surface datum, integrates RHOB to depth, and uses the selected + pore-pressure gradient. DTC/DTS provide dynamic ν when both are valid; NCS is the + mean effective stress under a uniaxial-strain assumption. +

+ + {#if stressProfile && stressProfileNcsRange} +
+ Profile ready: {stressProfile.length} rows • NCS {fmtNum( + stressProfileNcsRange.min, + 0 + )}–{fmtNum(stressProfileNcsRange.max, 0)} psi +
+ {/if} + {:else} + + {/if} +
= 0) & (density > 0) + if not np.any(valid): + raise ValueError("At least one finite, non-negative TVD and positive RHOB sample is required.") + + valid_depth = depth[valid] + valid_density = density[valid] + unique_depth, inverse = np.unique(valid_depth, return_inverse=True) + density_sum = np.bincount(inverse, weights=valid_density) + density_count = np.bincount(inverse) + unique_density = density_sum / density_count + + integration_depth = unique_depth + integration_density = unique_density + if unique_depth[0] > 0: + integration_depth = np.insert(integration_depth, 0, 0.0) + integration_density = np.insert(integration_density, 0, unique_density[0]) + max_depth = np.nanmax(depth[np.isfinite(depth) & (depth >= 0)]) + if max_depth > integration_depth[-1]: + integration_depth = np.append(integration_depth, max_depth) + integration_density = np.append(integration_density, unique_density[-1]) + + cumulative_density_depth = np.concatenate( + ( + [0.0], + np.cumsum( + np.diff(integration_depth) + * (integration_density[:-1] + integration_density[1:]) + / 2.0 + ), + ) + ) + integrated = np.interp( + np.maximum(depth, 0.0), integration_depth, cumulative_density_depth + ) + pressure = np.full(depth.shape, np.nan, dtype=float) + valid_depth_rows = np.isfinite(depth) & (depth >= 0) + pressure[valid_depth_rows] = 0.00980665 * integrated[valid_depth_rows] + return pressure + + +def estimate_log_stress_profile( + md, + tvd, + rhob, + pore_pressure_gradient=0.433, + biot_coefficient=1.0, + poisson_ratio=0.25, + dtc=None, + dts=None, + depth_unit="ft", +): + """Estimate equivalent effective confining stress from well logs. + + Vertical stress is integrated from RHOB, pore pressure is estimated from a + constant gradient, and horizontal effective stress follows a uniaxial-strain + approximation using static or DTC/DTS-derived Poisson's ratio. + + Args: + md (array-like): Measured-depth coordinates aligned with the log arrays. + tvd (array-like): Positive-down true vertical depth aligned with the logs. + rhob (array-like): Bulk density [g/cm³]. + pore_pressure_gradient (float): Formation pore-pressure gradient [psi/ft] + when `depth_unit` is 'ft', otherwise [psi/m]. + biot_coefficient (float): Biot coefficient, from 0 to 1. + poisson_ratio (float): Fallback Poisson's ratio when sonic values are absent or invalid. + dtc (array-like, optional): Compressional sonic slowness, in any consistent unit. + dts (array-like, optional): Shear sonic slowness in the same unit as `dtc`. + depth_unit (str): 'ft' or 'm'. + + Returns: + dict[str, np.ndarray]: MD, vertical stress, pore pressure, dynamic Poisson's + ratio, and equivalent effective confining stress, all stresses in psi. + """ + md_arr = np.asarray(md, dtype=float) + tvd_arr = np.asarray(tvd, dtype=float) + rhob_arr = np.asarray(rhob, dtype=float) + if md_arr.ndim != 1 or tvd_arr.shape != md_arr.shape or rhob_arr.shape != md_arr.shape: + raise ValueError("md, tvd, and rhob must be one-dimensional arrays with matching shapes.") + if depth_unit not in {"ft", "m"}: + raise ValueError("depth_unit must be 'ft' or 'm'.") + if not np.isfinite(pore_pressure_gradient) or pore_pressure_gradient < 0: + raise ValueError("pore_pressure_gradient must be finite and non-negative.") + if not np.isfinite(biot_coefficient) or not 0 <= biot_coefficient <= 1: + raise ValueError("biot_coefficient must be between 0 and 1.") + if not np.isfinite(poisson_ratio) or not 0 <= poisson_ratio < 0.5: + raise ValueError("poisson_ratio must be in [0, 0.5).") + if (dtc is None) != (dts is None): + raise ValueError("dtc and dts must be provided together.") + + tvd_m = tvd_arr * 0.3048 if depth_unit == "ft" else tvd_arr + overburden_mpa = _integrate_overburden_mpa(rhob_arr, tvd_m) + vertical_psi = overburden_mpa * 145.0377377 + pore_pressure_psi = pore_pressure_gradient * tvd_arr + pore_pressure_psi[~np.isfinite(tvd_arr) | (tvd_arr < 0)] = np.nan + + nu = np.full(md_arr.shape, poisson_ratio, dtype=float) + if dtc is not None and dts is not None: + dtc_arr = np.asarray(dtc, dtype=float) + dts_arr = np.asarray(dts, dtype=float) + if dtc_arr.shape != md_arr.shape or dts_arr.shape != md_arr.shape: + raise ValueError("dtc and dts must match the shape of md.") + valid_sonic = ( + np.isfinite(dtc_arr) + & np.isfinite(dts_arr) + & (dtc_arr > 0) + & (dts_arr > 0) + ) + vp_vs = np.zeros(md_arr.shape, dtype=float) + vp_vs[valid_sonic] = dts_arr[valid_sonic] / dtc_arr[valid_sonic] + valid_sonic &= vp_vs > 1.0 + nu_dynamic = np.zeros(md_arr.shape, dtype=float) + nu_dynamic[valid_sonic] = 0.5 * ( + (vp_vs[valid_sonic] ** 2 - 2.0) / (vp_vs[valid_sonic] ** 2 - 1.0) + ) + valid_sonic &= (nu_dynamic >= 0.0) & (nu_dynamic < 0.5) + nu[valid_sonic] = nu_dynamic[valid_sonic] + + effective_vertical_psi = vertical_psi - biot_coefficient * pore_pressure_psi + effective_horizontal_psi = nu / (1.0 - nu) * effective_vertical_psi + equivalent_confining_psi = ( + effective_vertical_psi + 2.0 * effective_horizontal_psi + ) / 3.0 + return { + "md": md_arr, + "sv_psi": vertical_psi, + "pp_psi": pore_pressure_psi, + "nu": nu, + "ncs_equivalent_psi": equivalent_confining_psi, + } + + def estimate_normal_compaction_trend_dt(dtc, vshale, depth, vsh_threshold=0.6): """Estimate normal compaction trend from sonic transit time accounting shale intervals only. @@ -231,15 +367,16 @@ def estimate_pore_pressure_res(s, p_hyd, res, res_shale=None, x=1.2): s (np.ndarray or float): Overburden stress [MPa]. p_hyd (np.ndarray or float): Hydrostatic pressure [MPa]. res (np.ndarray or float): Formation resistivity [ohm.m]. - res_shale (np.ndarray or float, optional): Normal compaction trend for resistivity [ohm.m]. Defaults to None. + res_shale (np.ndarray or float): Normal compaction trend for resistivity [ohm.m]. x (float, optional): Exponent for the empirical relation. Defaults to 1.2. Returns: np.ndarray or float: Estimated pore pressure [MPa]. """ if res_shale is None: - logger.debug("Shale resistivity not provided, estimating from water trend") - res_shale = estimate_rt_water_trend(res) + raise ValueError( + "res_shale is required; provide a calibrated normal compaction resistivity trend." + ) logger.debug(f"Estimating pore pressure from resistivity with exponent x={x}") pp = s - (s - p_hyd) * (res_shale / res) ** x diff --git a/tests/test_geomechanics.py b/tests/test_geomechanics.py new file mode 100644 index 00000000..e94515bd --- /dev/null +++ b/tests/test_geomechanics.py @@ -0,0 +1,109 @@ +import numpy as np +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from quick_pp.app.backend.router import api_router +from quick_pp.rock_physics.geomechanics import ( + _integrate_overburden_mpa, + estimate_log_stress_profile, + estimate_pore_pressure_res, +) + + +def test_overburden_pressure_integrates_density_over_tvd_in_original_order(): + pressure = _integrate_overburden_mpa( + rhob=[2.0, 2.0, 2.0], + tvd_m=[1000.0, 0.0, 500.0], + ) + + expected = np.array([19.6133, 0.0, 9.80665]) + np.testing.assert_allclose(pressure, expected, rtol=1e-5) + + +def test_log_stress_profile_uses_sonic_poisson_ratio_and_equivalent_stress(): + result = estimate_log_stress_profile( + md=[0.0, 1000.0], + tvd=[0.0, 1000.0], + rhob=[2.0, 2.0], + pore_pressure_gradient=0.433, + biot_coefficient=1.0, + dtc=[80.0, 80.0], + dts=[140.0, 140.0], + depth_unit="ft", + ) + + assert result["sv_psi"][0] == pytest.approx(0.0) + assert result["pp_psi"][1] == pytest.approx(433.0) + assert result["nu"][1] == pytest.approx(0.257, abs=0.001) + assert result["ncs_equivalent_psi"][1] < result["sv_psi"][1] + + +def test_log_stress_profile_rejects_mismatched_sonic_logs(): + with pytest.raises(ValueError, match="match the shape"): + estimate_log_stress_profile( + md=[0.0, 1000.0], + tvd=[0.0, 1000.0], + rhob=[2.0, 2.0], + dtc=[80.0], + dts=[140.0, 140.0], + depth_unit="ft", + ) + + +def test_resistivity_pore_pressure_requires_explicit_shale_trend(): + with pytest.raises(ValueError, match="res_shale is required"): + estimate_pore_pressure_res( + s=np.array([20.0]), + p_hyd=np.array([10.0]), + res=np.array([5.0]), + ) + + +def test_stress_profile_endpoint_returns_depth_aligned_curves(): + app = FastAPI() + app.include_router(api_router) + client = TestClient(app) + response = client.post( + "/quick_pp/scal/stress_profile", + json={ + "md": [100.0, 200.0], + "tvd": [100.0, 200.0], + "rhob": [2.0, 2.1], + "dtc": [80.0, 80.0], + "dts": [140.0, 140.0], + "depth_unit": "m", + "pore_pressure_gradient": 1.42, + }, + ) + + assert response.status_code == 200 + rows = response.json()["data"] + assert [row["DEPTH"] for row in rows] == [100.0, 200.0] + assert rows[-1]["SV_EST"] > rows[0]["SV_EST"] + assert rows[-1]["NCS_EST"] > 0 + assert rows[-1]["NU_DYN"] == pytest.approx(0.257, abs=0.001) + + +def test_core_corrections_accept_depth_varying_stress_column(): + app = FastAPI() + app.include_router(api_router) + client = TestClient(app) + response = client.post( + "/quick_pp/scal/core_corrections", + json={ + "net_confining_stress": "NCS_EST", + "mean_pore_pressure": None, + "ambient_stress": 0.0, + "compaction_coeff": 0.0001, + "perm_compaction_coeff": 0.0, + "data": [ + {"DEPTH": 100.0, "CPORE": 0.2, "CPERM": 100.0, "NCS_EST": 500.0}, + {"DEPTH": 200.0, "CPORE": 0.2, "CPERM": 100.0, "NCS_EST": 1500.0}, + ], + }, + ) + + assert response.status_code == 200 + corrected = response.json()["data"] + assert corrected[0]["CPORE"] > corrected[1]["CPORE"] From 67e6d0011c26a1bc69b15f76a1d98b94e7d55018 Mon Sep 17 00:00:00 2001 From: imranfadhil Date: Thu, 5 Nov 2026 14:13:22 +0800 Subject: [PATCH 11/30] close accordians in the left pane by default --- .../components/modules/InspectorScal.svelte | 122 +- .../components/modules/MultiWellFpt.svelte | 564 ++++- .../modules/MultiWellInventory.svelte | 353 ++- .../modules/MultiWellPermTransform.svelte | 96 +- .../modules/MultiWellRockTyping.svelte | 322 ++- .../MultiWellRtClassifierTrainer.svelte | 236 +- .../components/modules/MultiWellSwirr.svelte | 2089 +++++++++-------- 7 files changed, 2330 insertions(+), 1452 deletions(-) diff --git a/quick_pp/app/frontend/src/lib/components/modules/InspectorScal.svelte b/quick_pp/app/frontend/src/lib/components/modules/InspectorScal.svelte index 9a179e49..304a23d7 100644 --- a/quick_pp/app/frontend/src/lib/components/modules/InspectorScal.svelte +++ b/quick_pp/app/frontend/src/lib/components/modules/InspectorScal.svelte @@ -108,17 +108,20 @@ const nullable = (values: number[]) => values.map((value) => (Number.isFinite(value) ? value : null)); - const result = await postJson<{ data: StressProfileRow[] }>('/quick_pp/scal/stress_profile', { - md: nullable(md), - tvd: nullable(tvd), - rhob: nullable(rhob), - dtc: dtc ? nullable(dtc) : null, - dts: dts ? nullable(dts) : null, - depth_unit: sp.stress_depth_unit, - pore_pressure_gradient: sp.stress_pore_pressure_gradient, - biot_coefficient: sp.stress_biot_coefficient, - poisson_ratio: sp.stress_poisson_ratio - }); + const result = await postJson<{ data: StressProfileRow[] }>( + '/quick_pp/scal/stress_profile', + { + md: nullable(md), + tvd: nullable(tvd), + rhob: nullable(rhob), + dtc: dtc ? nullable(dtc) : null, + dts: dts ? nullable(dts) : null, + depth_unit: sp.stress_depth_unit, + pore_pressure_gradient: sp.stress_pore_pressure_gradient, + biot_coefficient: sp.stress_biot_coefficient, + poisson_ratio: sp.stress_poisson_ratio + } + ); const rows = result.data ?? []; const uniqueStressDepths = new Set(); for (const row of rows) { @@ -132,7 +135,9 @@ } } if (uniqueStressDepths.size < 2) { - throw new Error('At least two valid depth/density samples are required for a stress profile.'); + throw new Error( + 'At least two valid depth/density samples are required for a stress profile.' + ); } stressProfile = rows; @@ -296,7 +301,10 @@ validSampleIndices.push(idx); } }); - } else if (dept.length > 0 && (cporeBaseCurve.length > 0 || cpermBaseCurve.length > 0)) { + } else if ( + dept.length > 0 && + (cporeBaseCurve.length > 0 || cpermBaseCurve.length > 0) + ) { for (const i of wellData.visibleIndices) { if (selectionIndices && !selectionIndices.has(i)) continue; const dRaw = dept[i]; @@ -438,7 +446,9 @@ if (hasCoreSamples && validSampleIndices.length > 0) { validSampleIndices.forEach((sampleIdx, i) => { - const sd = Number(wellData.coreSamples[sampleIdx]?.depth ?? records[i].DEPTH); + const sd = Number( + wellData.coreSamples[sampleIdx]?.depth ?? records[i].DEPTH + ); if (!Number.isFinite(sd)) return; let lo = 0; let hi = dept.length - 1; @@ -466,15 +476,19 @@ }); } - wellData.mergeComputedCurves({ - DEPTH: dept, - CPORE: newCpore, - CPERM: newCperm, - CPORE_AMB: newCporeAmb, - CPERM_AIR: newCpermAir, - CPORE_ORI: newCporeAmb, - CPERM_ORI: newCpermAir - }, undefined, selectionIndices); + wellData.mergeComputedCurves( + { + DEPTH: dept, + CPORE: newCpore, + CPERM: newCperm, + CPORE_AMB: newCporeAmb, + CPERM_AIR: newCpermAir, + CPORE_ORI: newCporeAmb, + CPERM_ORI: newCpermAir + }, + undefined, + selectionIndices + ); wellData.markModuleComputed('scal', [ 'CPORE', 'CPERM', @@ -486,7 +500,8 @@ } scalPendingSave = true; - wellData.lastSavedMessage = 'Core Overburden & Klinkenberg Previewed (Click Save to Persist)'; + wellData.lastSavedMessage = + 'Core Overburden & Klinkenberg Previewed (Click Save to Persist)'; appStatus.info( wellData.hasActiveFilter ? `Previewed Core Overburden & Klinkenberg on ${records.length} active-zone plugs — click Save to persist` @@ -510,7 +525,8 @@ if (!wellData.isCorePlugInActiveFilter(dRaw, dCur)) { return s; } - const ambPhi = s.porosity_amb ?? origS?.porosity_amb ?? origS?.porosity ?? s.porosity; + const ambPhi = + s.porosity_amb ?? origS?.porosity_amb ?? origS?.porosity ?? s.porosity; const airK = s.perm_air ?? origS?.perm_air ?? origS?.permeability ?? s.permeability; return { ...s, @@ -782,7 +798,7 @@ badge={wellData.coreShiftDirty ? `Shift ${wellData.coreShiftDelta >= 0 ? '+' : ''}${fmtNum(wellData.coreShiftDelta, 2)}m` : `${totalCorePlugCount} PLUGS`} - defaultOpen={true} + defaultOpen={false} >
@@ -794,21 +810,17 @@ : workbench.scalParams.core_corrected ? `${totalCorePlugCount} PLUGS • RES` : `${totalCorePlugCount} PLUGS`} - defaultOpen={true} + defaultOpen={false} >
- {#each [ - ['sandstone', 'Consolidated Sand', '4.5e-6 (1/psi) — well-consolidated sandstone'], - ['friable_sandstone', 'Friable Sand', '8.0e-6 (1/psi) — friable / poorly cemented sandstone'], - ['carbonate', 'Carbonate', '2.5e-6 (1/psi) — stiff / well-cemented limestone or dolomite'] - ] as [l, lbl, tip]} + {#each [['sandstone', 'Consolidated Sand', '4.5e-6 (1/psi) — well-consolidated sandstone'], ['friable_sandstone', 'Friable Sand', '8.0e-6 (1/psi) — friable / poorly cemented sandstone'], ['carbonate', 'Carbonate', '2.5e-6 (1/psi) — stiff / well-cemented limestone or dolomite']] as [l, lbl, tip]} {/each}
-
+
Compaction Coeff (cφ / ck): - {workbench.scalParams.compaction_coeff.toExponential(1)} / {workbench.scalParams.perm_compaction_coeff.toExponential(1)} psi⁻¹ + {workbench.scalParams.compaction_coeff.toExponential(1)} / {workbench.scalParams.perm_compaction_coeff.toExponential( + 1 + )} psi⁻¹
-
-