quick-pp 0.2.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- quick_pp/__init__.py +0 -0
- quick_pp/api/__init__.py +0 -0
- quick_pp/api/exceptions.py +61 -0
- quick_pp/api/fastapi_mlflow/__init__.py +1 -0
- quick_pp/api/fastapi_mlflow/_mlflow_types.py +59 -0
- quick_pp/api/fastapi_mlflow/applications.py +72 -0
- quick_pp/api/fastapi_mlflow/exceptions.py +22 -0
- quick_pp/api/fastapi_mlflow/predictors.py +96 -0
- quick_pp/api/main.py +90 -0
- quick_pp/api/mlflow_model_deployment.py +99 -0
- quick_pp/api/qpp_assistant.py +160 -0
- quick_pp/api/router.py +18 -0
- quick_pp/api/schemas/lithology_hc_correction.py +39 -0
- quick_pp/api/schemas/lithology_ssc.py +37 -0
- quick_pp/api/schemas/lithology_vsh_gr.py +25 -0
- quick_pp/api/schemas/permeability_choo.py +25 -0
- quick_pp/api/schemas/permeability_others.py +24 -0
- quick_pp/api/schemas/porosity.py +22 -0
- quick_pp/api/schemas/ressum.py +29 -0
- quick_pp/api/schemas/saturation_archie.py +25 -0
- quick_pp/api/schemas/saturation_b.py +24 -0
- quick_pp/api/schemas/saturation_qv.py +26 -0
- quick_pp/api/schemas/saturation_rw.py +24 -0
- quick_pp/api/schemas/saturation_temp_grad.py +24 -0
- quick_pp/api/schemas/saturation_waxman_smits.py +28 -0
- quick_pp/api/services/las_handler.py +136 -0
- quick_pp/api/services/lithology.py +278 -0
- quick_pp/api/services/permeability.py +252 -0
- quick_pp/api/services/porosity.py +151 -0
- quick_pp/api/services/reservoir_summary.py +78 -0
- quick_pp/api/services/saturation.py +359 -0
- quick_pp/api/static/favicon.ico +0 -0
- quick_pp/api/static/logo.png +0 -0
- quick_pp/cli.py +118 -0
- quick_pp/config.py +94 -0
- quick_pp/core_calibration.py +394 -0
- quick_pp/fluid_type.py +128 -0
- quick_pp/geomechanics.py +195 -0
- quick_pp/las_handler.py +327 -0
- quick_pp/lithology/__init__.py +80 -0
- quick_pp/lithology/carbonate.py +166 -0
- quick_pp/lithology/multi_mineral.py +151 -0
- quick_pp/lithology/sand_shale.py +79 -0
- quick_pp/lithology/sand_silt_clay.py +131 -0
- quick_pp/logger.py +19 -0
- quick_pp/modelling/__init__.py +0 -0
- quick_pp/modelling/config.py +72 -0
- quick_pp/modelling/mock_data/mock_data.parquet +0 -0
- quick_pp/modelling/predict_pipeline.py +126 -0
- quick_pp/modelling/train_pipeline.py +220 -0
- quick_pp/modelling/utils.py +111 -0
- quick_pp/objects.py +177 -0
- quick_pp/permeability.py +151 -0
- quick_pp/plotter/__init__.py +0 -0
- quick_pp/plotter/plotter.py +315 -0
- quick_pp/plotter/well_log.py +187 -0
- quick_pp/plotter/well_log_config.py +409 -0
- quick_pp/porosity.py +341 -0
- quick_pp/qaqc.py +436 -0
- quick_pp/ressum.py +326 -0
- quick_pp/rock_type.py +499 -0
- quick_pp/saturation.py +455 -0
- quick_pp/utils.py +328 -0
- quick_pp-0.2.3.dist-info/METADATA +103 -0
- quick_pp-0.2.3.dist-info/RECORD +69 -0
- quick_pp-0.2.3.dist-info/WHEEL +4 -0
- quick_pp-0.2.3.dist-info/entry_points.txt +2 -0
- quick_pp-0.2.3.dist-info/licenses/AUTHORS.rst +13 -0
- quick_pp-0.2.3.dist-info/licenses/LICENSE +22 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
from fastapi import APIRouter, HTTPException
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from typing import List, Dict
|
|
4
|
+
|
|
5
|
+
from quick_pp.api.schemas.ressum import InputData
|
|
6
|
+
from quick_pp.ressum import calc_reservoir_summary
|
|
7
|
+
|
|
8
|
+
router = APIRouter(prefix="/ressum", tags=["Reservoir Summary"])
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@router.post(
|
|
12
|
+
"",
|
|
13
|
+
summary="Calculate Reservoir Summary",
|
|
14
|
+
description=(
|
|
15
|
+
"""
|
|
16
|
+
Calculate reservoir summary statistics for respective zones based on input petrophysical data.
|
|
17
|
+
This includes calculating average porosity, average water saturation, average permeability,
|
|
18
|
+
and other relevant metrics for the specified zones.
|
|
19
|
+
|
|
20
|
+
Input model: InputData (see quick_pp.api.schemas.ressum.InputData)
|
|
21
|
+
|
|
22
|
+
Request body must be a JSON object with the following fields:
|
|
23
|
+
- data: list of objects, each with keys:
|
|
24
|
+
- depth: float (required)
|
|
25
|
+
- vcld: float (volume of clay, required)
|
|
26
|
+
- phit: float (total porosity, required)
|
|
27
|
+
- swt: float (water saturation, required)
|
|
28
|
+
- perm: float (permeability, required)
|
|
29
|
+
- zones: string or int (zone identifier, required)
|
|
30
|
+
- cut_offs: dict with cutoff parameters for filtering, e.g.:
|
|
31
|
+
- min_phit: float (optional, minimum porosity)
|
|
32
|
+
- max_swt: float (optional, maximum water saturation)
|
|
33
|
+
- min_perm: float (optional, minimum permeability)
|
|
34
|
+
- ... (other cutoffs as needed)
|
|
35
|
+
|
|
36
|
+
Example:
|
|
37
|
+
{
|
|
38
|
+
"data": [
|
|
39
|
+
{"depth": 1000.0, "vcld": 0.25, "phit": 0.18, "swt": 0.35, "perm": 120.0, "zones": "A"},
|
|
40
|
+
{"depth": 1001.0, "vcld": 0.22, "phit": 0.20, "swt": 0.30, "perm": 150.0, "zones": "A"},
|
|
41
|
+
{"depth": 1020.0, "vcld": 0.30, "phit": 0.15, "swt": 0.40, "perm": 90.0, "zones": "B"}
|
|
42
|
+
],
|
|
43
|
+
"cut_offs": {
|
|
44
|
+
"min_phit": 0.12,
|
|
45
|
+
"max_swt": 0.45
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
"""
|
|
49
|
+
),
|
|
50
|
+
operation_id="calculate_reservoir_summary",
|
|
51
|
+
response_model=List[Dict],
|
|
52
|
+
)
|
|
53
|
+
async def calculate_reservoir_summary_(inputs: InputData):
|
|
54
|
+
"""
|
|
55
|
+
Calculates reservoir summary statistics based on input petrophysical data.
|
|
56
|
+
Args:
|
|
57
|
+
inputs (InputData): Input data model containing petrophysical measurements and cutoff parameters.
|
|
58
|
+
Returns:
|
|
59
|
+
List[dict]: A list of dictionaries, each representing a row of the computed reservoir summary.
|
|
60
|
+
Raises:
|
|
61
|
+
HTTPException: If input data is invalid or calculation fails.
|
|
62
|
+
"""
|
|
63
|
+
try:
|
|
64
|
+
input_dict = inputs.model_dump()
|
|
65
|
+
input_df = pd.DataFrame.from_records(input_dict['data'])
|
|
66
|
+
ressum_df = calc_reservoir_summary(
|
|
67
|
+
depth=input_df['depth'],
|
|
68
|
+
vshale=input_df['vcld'],
|
|
69
|
+
phit=input_df['phit'],
|
|
70
|
+
swt=input_df['swt'],
|
|
71
|
+
perm=input_df['perm'],
|
|
72
|
+
zones=input_df['zones'],
|
|
73
|
+
cutoffs=input_dict['cut_offs']
|
|
74
|
+
)
|
|
75
|
+
ressum_df.dropna(inplace=True)
|
|
76
|
+
return ressum_df.to_dict(orient='records')
|
|
77
|
+
except Exception as e:
|
|
78
|
+
raise HTTPException(status_code=400, detail=f"Error calculating reservoir summary: {e}")
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
from fastapi import APIRouter, HTTPException
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from typing import List, Dict, Any, Optional
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from quick_pp.api.schemas.saturation_waxman_smits import InputData as WaxmanSmitsInput
|
|
7
|
+
from quick_pp.api.schemas.saturation_archie import InputData as ArchieInput
|
|
8
|
+
from quick_pp.api.schemas.saturation_temp_grad import InputData as TempGradInput
|
|
9
|
+
from quick_pp.api.schemas.saturation_rw import InputData as RwInput
|
|
10
|
+
from quick_pp.api.schemas.saturation_b import InputData as BInput
|
|
11
|
+
from quick_pp.api.schemas.saturation_qv import InputData as QvInput
|
|
12
|
+
|
|
13
|
+
from quick_pp.saturation import (
|
|
14
|
+
waxman_smits_saturation, archie_saturation, estimate_rw_temperature_salinity, estimate_temperature_gradient,
|
|
15
|
+
estimate_b_waxman_smits, estimate_qv
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
router = APIRouter(prefix="/saturation", tags=["Saturation"])
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _safe_float(val):
|
|
22
|
+
"""
|
|
23
|
+
Safely convert a value to float for API output.
|
|
24
|
+
If the value is complex, returns the real part as float.
|
|
25
|
+
If conversion fails, returns 0.0 to maintain API contract.
|
|
26
|
+
"""
|
|
27
|
+
try:
|
|
28
|
+
if isinstance(val, complex):
|
|
29
|
+
return float(val.real)
|
|
30
|
+
return float(val)
|
|
31
|
+
except Exception:
|
|
32
|
+
return 0.0 # fallback to 0.0 for API contract
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _parse_and_respond(
|
|
36
|
+
inputs: Any,
|
|
37
|
+
func,
|
|
38
|
+
func_args: List[str],
|
|
39
|
+
result_key: str,
|
|
40
|
+
extra_args: Optional[Dict[str, Any]] = None,
|
|
41
|
+
dtypes: Optional[Dict[str, Any]] = None
|
|
42
|
+
) -> List[Dict[str, float]]:
|
|
43
|
+
"""
|
|
44
|
+
Helper to parse input, call calculation, and format response for batch endpoints.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
inputs: Pydantic model instance containing the request data.
|
|
48
|
+
func: The calculation function to call (e.g., estimate_b_waxman_smits).
|
|
49
|
+
func_args: List of column names to extract from the input DataFrame as function arguments.
|
|
50
|
+
result_key: The key to use in the output dictionary for the result.
|
|
51
|
+
extra_args: Optional dictionary of extra arguments to pass to the calculation function.
|
|
52
|
+
dtypes: Optional dictionary mapping column names to numpy dtypes for type enforcement.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
List[Dict[str, float]]: List of dictionaries with the result for each input record.
|
|
56
|
+
|
|
57
|
+
Technical Details:
|
|
58
|
+
- Converts input Pydantic model to dict and then to a pandas DataFrame.
|
|
59
|
+
- Applies type conversions as specified in dtypes.
|
|
60
|
+
- Extracts columns as numpy arrays for vectorized calculation.
|
|
61
|
+
- Handles both scalar and array results, always returning a list of dicts.
|
|
62
|
+
- Uses _safe_float to ensure all outputs are valid floats.
|
|
63
|
+
- Raises HTTPException with status 400 on any error.
|
|
64
|
+
"""
|
|
65
|
+
try:
|
|
66
|
+
input_dict = inputs.model_dump()
|
|
67
|
+
input_df = pd.DataFrame.from_records(input_dict['data'])
|
|
68
|
+
if dtypes:
|
|
69
|
+
for col, dtype in dtypes.items():
|
|
70
|
+
if col in input_df:
|
|
71
|
+
input_df[col] = input_df[col].astype(dtype)
|
|
72
|
+
args = [np.asarray(input_df[col]) for col in func_args if col in input_df]
|
|
73
|
+
if extra_args:
|
|
74
|
+
args.extend(extra_args.values())
|
|
75
|
+
result = func(*args)
|
|
76
|
+
# Ensure result is always iterable
|
|
77
|
+
if np.isscalar(result):
|
|
78
|
+
result_list = [_safe_float(result)]
|
|
79
|
+
else:
|
|
80
|
+
result_list = [_safe_float(val) for val in np.asarray(result).flatten()]
|
|
81
|
+
return [{result_key: val} for val in result_list]
|
|
82
|
+
except Exception as e:
|
|
83
|
+
raise HTTPException(status_code=400, detail=f"Error processing request: {e}")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@router.post(
|
|
87
|
+
"/temp_grad",
|
|
88
|
+
summary="Estimate Temperature Gradient",
|
|
89
|
+
description=(
|
|
90
|
+
"Estimate the temperature gradient based on depth data and specified measurement system (metric or imperial).\n"
|
|
91
|
+
"Input model: TempGradInput (see quick_pp.api.schemas.saturation_temp_grad.InputData).\n"
|
|
92
|
+
"Request body must be a JSON object with the following fields:\n"
|
|
93
|
+
"- meas_system: string (required, 'metric' or 'imperial')\n"
|
|
94
|
+
"- data: list of objects, each with key 'tvdss' (float, required)\n"
|
|
95
|
+
"Example:\n"
|
|
96
|
+
"{\n 'meas_system': 'metric',\n 'data': [ {'tvdss': 1500.0}, {'tvdss': 2000.0} ]\n}"
|
|
97
|
+
),
|
|
98
|
+
operation_id="estimate_temperature_gradient",
|
|
99
|
+
)
|
|
100
|
+
async def estimate_temperature_gradient_(inputs: TempGradInput) -> List[Dict[str, float]]:
|
|
101
|
+
"""
|
|
102
|
+
Estimate the temperature gradient for each input record.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
inputs (TempGradInput): Input data containing a list of records with 'tvdss' (true vertical depth subsea)
|
|
106
|
+
and the measurement system ('meas_system').
|
|
107
|
+
Returns:
|
|
108
|
+
List[Dict[str, float]]: List of dictionaries with the estimated temperature gradient under the key 'TEMP_GRAD'.
|
|
109
|
+
Technical Details:
|
|
110
|
+
- Converts input data to a pandas DataFrame and enforces float type for 'tvdss'.
|
|
111
|
+
- Calls estimate_temperature_gradient with the TVDSS array and measurement system.
|
|
112
|
+
- Handles both scalar and array results, always returning a list of dicts.
|
|
113
|
+
- Uses _safe_float to ensure all outputs are valid floats.
|
|
114
|
+
- Raises HTTPException with status 400 on any error.
|
|
115
|
+
"""
|
|
116
|
+
input_dict = inputs.model_dump()
|
|
117
|
+
meas_system = input_dict['meas_system']
|
|
118
|
+
try:
|
|
119
|
+
input_df = pd.DataFrame.from_records(input_dict['data'])
|
|
120
|
+
input_df['tvdss'] = input_df['tvdss'].astype(np.float64)
|
|
121
|
+
temp_grad = estimate_temperature_gradient(np.asarray(input_df['tvdss']), meas_system)
|
|
122
|
+
if np.isscalar(temp_grad):
|
|
123
|
+
result_list = [_safe_float(temp_grad)]
|
|
124
|
+
else:
|
|
125
|
+
result_list = [_safe_float(val) for val in np.asarray(temp_grad).flatten()]
|
|
126
|
+
return [{"TEMP_GRAD": val} for val in result_list]
|
|
127
|
+
except Exception as e:
|
|
128
|
+
raise HTTPException(status_code=400, detail=f"Error processing request: {e}")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@router.post(
|
|
132
|
+
"/rw",
|
|
133
|
+
summary="Estimate Formation Water Resistivity (Rw)",
|
|
134
|
+
description=(
|
|
135
|
+
"Estimate formation water resistivity (Rw) based on temperature gradient and water salinity.\n"
|
|
136
|
+
"Input model: RwInput (see quick_pp.api.schemas.saturation_rw.InputData).\n"
|
|
137
|
+
"Request body must be a JSON object with the following fields:\n"
|
|
138
|
+
"- water_salinity: float (required)\n"
|
|
139
|
+
"- data: list of objects, each with key 'temp_grad' (float, required)\n"
|
|
140
|
+
"Example:\n"
|
|
141
|
+
"{\n 'water_salinity': 35000.0,\n 'data': [ {'temp_grad': 0.025}, {'temp_grad': 0.030} ]\n}"
|
|
142
|
+
),
|
|
143
|
+
operation_id="estimate_formation_water_resistivity",
|
|
144
|
+
)
|
|
145
|
+
async def estimate_rw(inputs: RwInput) -> List[Dict[str, float]]:
|
|
146
|
+
"""
|
|
147
|
+
Estimate formation water resistivity (Rw) for each input record.
|
|
148
|
+
|
|
149
|
+
Args:
|
|
150
|
+
inputs (RwInput): Input data containing water salinity and a list of temperature gradient records.
|
|
151
|
+
Returns:
|
|
152
|
+
List[Dict[str, float]]: List of dictionaries with the estimated Rw values under the key 'RW'.
|
|
153
|
+
Technical Details:
|
|
154
|
+
- Converts input data to a pandas DataFrame and enforces float type for 'temp_grad'.
|
|
155
|
+
- Calls estimate_rw_temperature_salinity with the temperature gradient array and water salinity.
|
|
156
|
+
- Handles both scalar and array results, always returning a list of dicts.
|
|
157
|
+
- Uses _safe_float to ensure all outputs are valid floats.
|
|
158
|
+
- Raises HTTPException with status 400 on any error.
|
|
159
|
+
"""
|
|
160
|
+
input_dict = inputs.model_dump()
|
|
161
|
+
water_salinity = input_dict['water_salinity']
|
|
162
|
+
try:
|
|
163
|
+
input_df = pd.DataFrame.from_records(input_dict['data'])
|
|
164
|
+
input_df['temp_grad'] = input_df['temp_grad'].astype(np.float64)
|
|
165
|
+
rw = estimate_rw_temperature_salinity(np.asarray(input_df['temp_grad']), water_salinity)
|
|
166
|
+
if np.isscalar(rw):
|
|
167
|
+
result_list = [_safe_float(rw)]
|
|
168
|
+
else:
|
|
169
|
+
result_list = [_safe_float(val) for val in np.asarray(rw).flatten()]
|
|
170
|
+
return [{"RW": val} for val in result_list]
|
|
171
|
+
except Exception as e:
|
|
172
|
+
raise HTTPException(status_code=400, detail=f"Error processing request: {e}")
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@router.post(
|
|
176
|
+
"/b_waxman_smits",
|
|
177
|
+
summary="Estimate B Parameter using Waxman-Smits Model",
|
|
178
|
+
description=(
|
|
179
|
+
"Estimate the B parameter using the Waxman-Smits model based on temperature gradient and "
|
|
180
|
+
"formation water resistivity.\n"
|
|
181
|
+
"Input model: BInput (see quick_pp.api.schemas.saturation_b.InputData).\n"
|
|
182
|
+
"Request body must be a JSON object with the following fields:\n"
|
|
183
|
+
"- data: list of objects, each with keys 'temp_grad' (float, required) and 'rw' (float, required)\n"
|
|
184
|
+
"Example:\n"
|
|
185
|
+
"{\n 'data': [ {'temp_grad': 0.025, 'rw': 0.12},\n {'temp_grad': 0.030, 'rw': 0.10} ]\n}"
|
|
186
|
+
),
|
|
187
|
+
operation_id="estimate_b_parameter_waxman_smits",
|
|
188
|
+
)
|
|
189
|
+
async def estimate_b_waxman_smits_(inputs: BInput) -> List[Dict[str, float]]:
|
|
190
|
+
"""
|
|
191
|
+
Estimate the B parameter using the Waxman-Smits model for each input record.
|
|
192
|
+
|
|
193
|
+
Args:
|
|
194
|
+
inputs (BInput): Input data model containing a list of records with 'temp_grad' (temperature gradient)
|
|
195
|
+
and 'rw' (formation water resistivity).
|
|
196
|
+
Returns:
|
|
197
|
+
List[Dict[str, float]]: List of dictionaries with the estimated B parameter under the key 'B'.
|
|
198
|
+
Technical Details:
|
|
199
|
+
- Uses _parse_and_respond helper to handle input parsing, type enforcement, and output formatting.
|
|
200
|
+
- Calls estimate_b_waxman_smits with temperature gradient and resistivity arrays.
|
|
201
|
+
- Handles both scalar and array results, always returning a list of dicts.
|
|
202
|
+
- Uses _safe_float to ensure all outputs are valid floats.
|
|
203
|
+
- Raises HTTPException with status 400 on any error.
|
|
204
|
+
"""
|
|
205
|
+
return _parse_and_respond(
|
|
206
|
+
inputs,
|
|
207
|
+
estimate_b_waxman_smits,
|
|
208
|
+
['temp_grad', 'rw'],
|
|
209
|
+
'B',
|
|
210
|
+
dtypes={"temp_grad": np.float64, "rw": np.float64}
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@router.post(
|
|
215
|
+
"/estimate_qv",
|
|
216
|
+
summary="Estimate Cation Exchange Capacity per Unit Pore Volume (Qv)",
|
|
217
|
+
description=(
|
|
218
|
+
"Estimate Qv based on volume of clay (vcld), total porosity (phit), and specific clay properties.\n"
|
|
219
|
+
"Input model: QvInput (see quick_pp.api.schemas.saturation_qv.InputData).\n"
|
|
220
|
+
"Request body must be a JSON object with the following fields:\n"
|
|
221
|
+
"- rho_clay: float (required)\n"
|
|
222
|
+
"- cec_clay: float (required)\n"
|
|
223
|
+
"- data: list of objects, each with keys 'vcld' (float, required) and 'phit' (float, required)\n"
|
|
224
|
+
"Example (truncated): { 'rho_clay': 2.58, 'cec_clay': 0.9, 'data': [ {'vcld': 0.35, 'phit': 0.22}, ... ] }"
|
|
225
|
+
),
|
|
226
|
+
operation_id="estimate_cation_exchange_capacity",
|
|
227
|
+
)
|
|
228
|
+
async def estimate_qv_(inputs: QvInput) -> List[Dict[str, float]]:
|
|
229
|
+
"""
|
|
230
|
+
Estimate the cation exchange capacity per unit pore volume (Qv) for each input record.
|
|
231
|
+
|
|
232
|
+
Args:
|
|
233
|
+
inputs (QvInput): Input data containing well log measurements (vcld, phit) and
|
|
234
|
+
clay properties (rho_clay, cec_clay).
|
|
235
|
+
Returns:
|
|
236
|
+
List[Dict[str, float]]: List of dictionaries with the estimated Qv values under the key 'QV'.
|
|
237
|
+
Technical Details:
|
|
238
|
+
- Converts input data to a pandas DataFrame and enforces float type for 'vcld' and 'phit'.
|
|
239
|
+
- Calls estimate_qv with vcld, phit, rho_clay, and cec_clay.
|
|
240
|
+
- Handles both scalar and array results, always returning a list of dicts.
|
|
241
|
+
- Uses _safe_float to ensure all outputs are valid floats.
|
|
242
|
+
- Raises HTTPException with status 400 on any error.
|
|
243
|
+
"""
|
|
244
|
+
input_dict = inputs.model_dump()
|
|
245
|
+
try:
|
|
246
|
+
input_df = pd.DataFrame.from_records(input_dict['data'])
|
|
247
|
+
input_df['vcld'] = input_df['vcld'].astype(np.float64)
|
|
248
|
+
input_df['phit'] = input_df['phit'].astype(np.float64)
|
|
249
|
+
qv = estimate_qv(
|
|
250
|
+
np.asarray(input_df['vcld']), np.asarray(input_df['phit']),
|
|
251
|
+
input_dict['rho_clay'], input_dict['cec_clay']
|
|
252
|
+
)
|
|
253
|
+
if np.isscalar(qv):
|
|
254
|
+
result_list = [_safe_float(qv)]
|
|
255
|
+
else:
|
|
256
|
+
result_list = [_safe_float(val) for val in np.asarray(qv).flatten()]
|
|
257
|
+
return [{"QV": val} for val in result_list]
|
|
258
|
+
except Exception as e:
|
|
259
|
+
raise HTTPException(status_code=400, detail=f"Error processing request: {e}")
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
@router.post(
|
|
263
|
+
"/waxman_smits",
|
|
264
|
+
summary="Estimate Water Saturation using Waxman-Smits Model",
|
|
265
|
+
description=(
|
|
266
|
+
"Estimate total water saturation (SWT) using the Waxman-Smits model based on input data.\n"
|
|
267
|
+
"Input model: WaxmanSmitsInput (see quick_pp.api.schemas.saturation_waxman_smits.InputData).\n"
|
|
268
|
+
"Request body must be a JSON object with the following field:\n"
|
|
269
|
+
"- data: list of objects, each with keys 'rt', 'rw', 'phit', 'qv', 'b' (all float, required), "
|
|
270
|
+
"and 'm' (int, required)\n"
|
|
271
|
+
"Example:\n"
|
|
272
|
+
"{\n 'data': [\n {'rt': 12.0, 'rw': 0.12, 'phit': 0.22, 'qv': 0.05, 'b': 0.8, 'm': 2},\n"
|
|
273
|
+
" {'rt': 10.0, 'rw': 0.10, 'phit': 0.18, 'qv': 0.04, 'b': 0.7, 'm': 2}\n ]\n}"
|
|
274
|
+
),
|
|
275
|
+
operation_id="estimate_waxman_smits_water_saturation",
|
|
276
|
+
)
|
|
277
|
+
async def estimate_swt_waxman_smits(inputs: WaxmanSmitsInput) -> List[Dict[str, float]]:
|
|
278
|
+
"""
|
|
279
|
+
Estimate water saturation (SWT) using the Waxman-Smits model for each input record.
|
|
280
|
+
|
|
281
|
+
Args:
|
|
282
|
+
inputs (WaxmanSmitsInput): Input data for multiple samples, including rt, rw, phit, qv, b, and m.
|
|
283
|
+
Returns:
|
|
284
|
+
List[Dict[str, float]]: List of dictionaries with the estimated water saturation under the key 'SWT'.
|
|
285
|
+
Technical Details:
|
|
286
|
+
- Converts input data to a pandas DataFrame and enforces correct types for all columns.
|
|
287
|
+
- Passes m as a single integer (first value in the input) to waxman_smits_saturation.
|
|
288
|
+
- Calls waxman_smits_saturation with all required arrays and m.
|
|
289
|
+
- Handles both scalar and array results, always returning a list of dicts.
|
|
290
|
+
- Uses _safe_float to ensure all outputs are valid floats.
|
|
291
|
+
- Raises HTTPException with status 400 on any error.
|
|
292
|
+
"""
|
|
293
|
+
input_dict = inputs.model_dump()
|
|
294
|
+
try:
|
|
295
|
+
input_df = pd.DataFrame.from_records(input_dict['data'])
|
|
296
|
+
input_df['rt'] = input_df['rt'].astype(np.float64)
|
|
297
|
+
input_df['rw'] = input_df['rw'].astype(np.float64)
|
|
298
|
+
input_df['phit'] = input_df['phit'].astype(np.float64)
|
|
299
|
+
input_df['qv'] = input_df['qv'].astype(np.float64)
|
|
300
|
+
input_df['b'] = input_df['b'].astype(np.float64)
|
|
301
|
+
input_df['m'] = input_df['m'].astype(np.int_)
|
|
302
|
+
# Use the first value of m for all records if function expects a scalar
|
|
303
|
+
m_value = int(input_df['m'].iloc[0])
|
|
304
|
+
swt = waxman_smits_saturation(
|
|
305
|
+
np.asarray(input_df['rt']), np.asarray(input_df['rw']), np.asarray(input_df['phit']),
|
|
306
|
+
np.asarray(input_df['qv']), np.asarray(input_df['b']), m_value
|
|
307
|
+
)
|
|
308
|
+
if np.isscalar(swt):
|
|
309
|
+
result_list = [_safe_float(swt)]
|
|
310
|
+
else:
|
|
311
|
+
result_list = [_safe_float(val) for val in np.asarray(swt).flatten()]
|
|
312
|
+
return [{"SWT": val} for val in result_list]
|
|
313
|
+
except Exception as e:
|
|
314
|
+
raise HTTPException(status_code=400, detail=f"Error processing request: {e}")
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
@router.post(
|
|
318
|
+
"/archie",
|
|
319
|
+
summary="Estimate Water Saturation using Archie Model",
|
|
320
|
+
description=(
|
|
321
|
+
"Estimate total water saturation (SWT) using the Archie model based on input data.\n"
|
|
322
|
+
"Input model: ArchieInput (see quick_pp.api.schemas.saturation_archie.InputData).\n"
|
|
323
|
+
"Request body must be a JSON object with the following field:\n"
|
|
324
|
+
"- data: list of objects, each with keys 'rt', 'rw', 'phit' (all float, required)\n"
|
|
325
|
+
"Example (truncated): { 'data': [ {'rt': 12.0, 'rw': 0.12, 'phit': 0.22}, ... ] }"
|
|
326
|
+
),
|
|
327
|
+
operation_id="estimate_archie_water_saturation",
|
|
328
|
+
)
|
|
329
|
+
async def estimate_swt_archie(inputs: ArchieInput) -> List[Dict[str, float]]:
|
|
330
|
+
"""
|
|
331
|
+
Estimate water saturation (SWT) using Archie's equation for each input record.
|
|
332
|
+
|
|
333
|
+
Args:
|
|
334
|
+
inputs (ArchieInput): Input data for multiple samples, including rt, rw, and phit.
|
|
335
|
+
Returns:
|
|
336
|
+
List[Dict[str, float]]: List of dictionaries with the estimated water saturation under the key 'SWT'.
|
|
337
|
+
Technical Details:
|
|
338
|
+
- Converts input data to a pandas DataFrame and enforces float type for all columns.
|
|
339
|
+
- Calls archie_saturation with fixed parameters a=1, m=2, n=2 (typical for clean sandstone).
|
|
340
|
+
- Handles both scalar and array results, always returning a list of dicts.
|
|
341
|
+
- Uses _safe_float to ensure all outputs are valid floats.
|
|
342
|
+
- Raises HTTPException with status 400 on any error.
|
|
343
|
+
"""
|
|
344
|
+
input_dict = inputs.model_dump()
|
|
345
|
+
try:
|
|
346
|
+
input_df = pd.DataFrame.from_records(input_dict['data'])
|
|
347
|
+
input_df['rt'] = input_df['rt'].astype(np.float64)
|
|
348
|
+
input_df['rw'] = input_df['rw'].astype(np.float64)
|
|
349
|
+
input_df['phit'] = input_df['phit'].astype(np.float64)
|
|
350
|
+
swt = archie_saturation(
|
|
351
|
+
np.asarray(input_df['rt']), np.asarray(input_df['rw']), np.asarray(input_df['phit']), 1, 2, 2
|
|
352
|
+
)
|
|
353
|
+
if np.isscalar(swt):
|
|
354
|
+
result_list = [_safe_float(swt)]
|
|
355
|
+
else:
|
|
356
|
+
result_list = [_safe_float(val) for val in np.asarray(swt).flatten()]
|
|
357
|
+
return [{"SWT": val} for val in result_list]
|
|
358
|
+
except Exception as e:
|
|
359
|
+
raise HTTPException(status_code=400, detail=f"Error processing request: {e}")
|
|
Binary file
|
|
Binary file
|
quick_pp/cli.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import click
|
|
2
|
+
from subprocess import Popen
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import socket
|
|
8
|
+
from importlib import metadata, resources
|
|
9
|
+
|
|
10
|
+
from quick_pp.modelling.train_pipeline import train_pipeline
|
|
11
|
+
from quick_pp.modelling.predict_pipeline import predict_pipeline
|
|
12
|
+
from quick_pp.modelling.utils import run_mlflow_server
|
|
13
|
+
|
|
14
|
+
try:
|
|
15
|
+
quick_ppVersion = metadata.version('quick_pp')
|
|
16
|
+
except metadata.PackageNotFoundError:
|
|
17
|
+
quick_ppVersion = "0.0.0"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def is_server_running(host, port):
|
|
21
|
+
try:
|
|
22
|
+
with socket.create_connection((host, port), timeout=2):
|
|
23
|
+
return True
|
|
24
|
+
except Exception:
|
|
25
|
+
return False
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@click.group()
|
|
29
|
+
@click.version_option(
|
|
30
|
+
prog_name="quick_pp",
|
|
31
|
+
version=quick_ppVersion,
|
|
32
|
+
message="%(prog)s version: %(version)s",
|
|
33
|
+
)
|
|
34
|
+
def cli():
|
|
35
|
+
"""A handy CLI tool for quick_pp."""
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@click.command()
|
|
40
|
+
@click.option('--debug', is_flag=True)
|
|
41
|
+
def app(debug):
|
|
42
|
+
"""Run the App consisting of API server and qpp assistant module."""
|
|
43
|
+
if not is_server_running('localhost', 8888):
|
|
44
|
+
reload_ = "--reload" if debug else ""
|
|
45
|
+
cmd = f"uvicorn quick_pp.api.main:app --host 0.0.0.0 --port 8888 {reload_}"
|
|
46
|
+
click.echo(f"App is not running. Starting it now... | {cmd}")
|
|
47
|
+
process = Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, shell=True)
|
|
48
|
+
process.wait()
|
|
49
|
+
click.echo("App started successfully.")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@click.command()
|
|
53
|
+
@click.argument('env', default='local', type=click.Choice(['local', 'remote']))
|
|
54
|
+
def mlflow_server(env):
|
|
55
|
+
run_mlflow_server(env)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@click.command()
|
|
59
|
+
@click.option('--debug', is_flag=True)
|
|
60
|
+
def model_deployment(debug):
|
|
61
|
+
"""Run the MLflow model deployment."""
|
|
62
|
+
if not is_server_running('localhost', 5555):
|
|
63
|
+
reload_ = "--reload" if debug else ""
|
|
64
|
+
cmd = f"uvicorn quick_pp.api.mlflow_model_deployment:app --host 0.0.0.0 --port 5555 {reload_}"
|
|
65
|
+
click.echo(f"Model server is not running. Starting it now... | {cmd}")
|
|
66
|
+
process = Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, shell=True)
|
|
67
|
+
process.wait()
|
|
68
|
+
click.echo("Model server started successfully.")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@click.command()
|
|
72
|
+
@click.argument('model_config', required=True, type=click.STRING)
|
|
73
|
+
@click.argument('data_hash', required=True, type=click.STRING)
|
|
74
|
+
@click.argument('env', default='local', type=click.Choice(['local', 'remote']))
|
|
75
|
+
def train(model_config, data_hash, env):
|
|
76
|
+
"""Train the model with the specified parameters."""
|
|
77
|
+
|
|
78
|
+
# Copy config.py into the root directory if it doesn't exist
|
|
79
|
+
config_file = resources.files('quick_pp.modelling').joinpath('config.py')
|
|
80
|
+
root_config_file = Path(os.getcwd(), 'config.py')
|
|
81
|
+
if os.path.exists(config_file) and not os.path.exists(root_config_file):
|
|
82
|
+
shutil.copyfile(config_file, root_config_file)
|
|
83
|
+
click.echo(f"Copied {config_file} to {root_config_file}")
|
|
84
|
+
|
|
85
|
+
# Copy mock_data.parquet into data/input if it doesn't exist
|
|
86
|
+
mock_file = resources.files('quick_pp.modelling.mock_data').joinpath('mock_data.parquet')
|
|
87
|
+
data_dir = Path(os.getcwd(), 'data', 'input')
|
|
88
|
+
os.makedirs(data_dir, exist_ok=True)
|
|
89
|
+
root_mock_file = Path(data_dir, 'mock_data.parquet')
|
|
90
|
+
if os.path.exists(mock_file) and not os.path.exists(root_mock_file):
|
|
91
|
+
shutil.copyfile(mock_file, root_mock_file)
|
|
92
|
+
click.echo(f"Copied {mock_file} to {root_mock_file}")
|
|
93
|
+
|
|
94
|
+
click.echo(f"Training {model_config} model with data hash {data_hash}")
|
|
95
|
+
train_pipeline(model_config, data_hash, env)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@click.command()
|
|
99
|
+
@click.argument('model_config', required=True, type=click.STRING)
|
|
100
|
+
@click.argument('data_hash', required=True, type=click.STRING)
|
|
101
|
+
@click.argument('output_file_name', required=False, default='test', type=click.STRING)
|
|
102
|
+
@click.argument('env', default='local', type=click.Choice(['local', 'remote']))
|
|
103
|
+
def predict(model_config, data_hash, output_file_name, env):
|
|
104
|
+
"""Run the prediction."""
|
|
105
|
+
click.echo("Running prediction...")
|
|
106
|
+
predict_pipeline(model_config, data_hash, output_file_name, env)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# Add commands to the CLI group
|
|
110
|
+
cli.add_command(app)
|
|
111
|
+
cli.add_command(mlflow_server)
|
|
112
|
+
cli.add_command(model_deployment)
|
|
113
|
+
cli.add_command(train)
|
|
114
|
+
cli.add_command(predict)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
if __name__ == "__main__":
|
|
118
|
+
cli()
|
quick_pp/config.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
class Config(object):
|
|
2
|
+
|
|
3
|
+
RESSUM_CUTOFFS = dict(
|
|
4
|
+
VSHALE=0.4,
|
|
5
|
+
PHIT=0.05,
|
|
6
|
+
SWT=0.95
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
VARS = dict(
|
|
10
|
+
GR=dict(name="Gamma Ray", unit="GAPI", min=0, max=200),
|
|
11
|
+
RT=dict(name="True Resistivity", unit="ohm.m", min=0, max=2000),
|
|
12
|
+
NPHI=dict(name="Neutron Porosity", unit="v/v", min=-.05, max=0.45),
|
|
13
|
+
RHOB=dict(name="Bulk Density", unit="g/cc", min=1.85, max=2.85),
|
|
14
|
+
VSAND=dict(name="Sand Volume", unit="v/v", min=0, max=1),
|
|
15
|
+
VSILT=dict(name="Silt Volume", unit="v/v", min=0, max=1),
|
|
16
|
+
VCLAY=dict(name="Clay Volume", unit="v/v", min=0, max=1),
|
|
17
|
+
VSHALE=dict(name="Shale Volume", unit="v/v", min=0, max=1),
|
|
18
|
+
PHIT=dict(name="Total Porosity", unit="v/v", min=0, max=0.5),
|
|
19
|
+
PHIE=dict(name="Effective Porosity", unit="v/v", min=0, max=0.5),
|
|
20
|
+
SWT=dict(vname="Total Water Saturation", unit="v/v", min=0, max=1),
|
|
21
|
+
SWE=dict(vname="Effective Water Saturation", unit="v/v", min=0, max=1),
|
|
22
|
+
PERM=dict(name="Permeability", unit="mD", min=0.01, max=100000)
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
SSC_ENDPOINTS = dict(
|
|
26
|
+
FLUID_POINT=(1.0, 1.0),
|
|
27
|
+
DRY_SAND_POINT=(-0.02, 2.65),
|
|
28
|
+
DRY_SILT_POINT=(None, 2.68), # None means it will be calculated
|
|
29
|
+
DRY_CLAY_POINT=(None, 2.71), # None means it will be calculated
|
|
30
|
+
WET_CLAY_POINT=(None, None), # None means it will be calculated
|
|
31
|
+
SILT_LINE_ANGLE=119 # Deg angle from horizontal
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
CARB_NEU_DEN_ENDPOINTS = dict(
|
|
35
|
+
FLUID_POINT=(1.0, 1.0),
|
|
36
|
+
DRY_CALC_POINT=(0.0, 2.71),
|
|
37
|
+
DRY_DOLO_POINT=(0.01, 2.87),
|
|
38
|
+
DRY_CLAY_POINT=(0.24, 2.78),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
CARB_DEN_PEF_ENDPOINTS = dict(
|
|
42
|
+
FLUID_POINT=(1.0, 1.0),
|
|
43
|
+
DRY_CALC_POINT=(5.08, 2.71),
|
|
44
|
+
DRY_DOLO_POINT=(3.14, 2.87),
|
|
45
|
+
DRY_CLAY_POINT=(2.2, 2.78),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
MINERALS_LOG_VALUE = {
|
|
49
|
+
'GR_QUARTZ': 0.0,
|
|
50
|
+
'NPHI_QUARTZ': -0.02,
|
|
51
|
+
'RHOB_QUARTZ': 2.64,
|
|
52
|
+
'DTC_QUARTZ': 52.9,
|
|
53
|
+
'PEF_QUARTZ': 1.8,
|
|
54
|
+
|
|
55
|
+
'GR_CALCITE': 0.0,
|
|
56
|
+
'NPHI_CALCITE': 0.0,
|
|
57
|
+
'RHOB_CALCITE': 2.71,
|
|
58
|
+
'DTC_CALCITE': 49.7,
|
|
59
|
+
'PEF_CALCITE': 5.1,
|
|
60
|
+
|
|
61
|
+
'GR_DOLOMITE': 0.0,
|
|
62
|
+
'NPHI_DOLOMITE': 0.01,
|
|
63
|
+
'RHOB_DOLOMITE': 2.85,
|
|
64
|
+
'DTC_DOLOMITE': 43.5,
|
|
65
|
+
'PEF_DOLOMITE': 3.1,
|
|
66
|
+
|
|
67
|
+
'GR_SILT': 80.0,
|
|
68
|
+
'NPHI_SILT': 0.1,
|
|
69
|
+
'RHOB_SILT': 2.68,
|
|
70
|
+
'DTC_SILT': 100.0,
|
|
71
|
+
'PEF_SILT': 2.0,
|
|
72
|
+
|
|
73
|
+
# Kaolinite
|
|
74
|
+
'GR_SH': 130.0,
|
|
75
|
+
'NPHI_SH': 0.34,
|
|
76
|
+
'RHOB_SH': 2.41,
|
|
77
|
+
'DTC_SH': 143.0,
|
|
78
|
+
'PEF_SH': 1.8,
|
|
79
|
+
|
|
80
|
+
'GR_MUD': 0.0,
|
|
81
|
+
'NPHI_MUD': 1.0,
|
|
82
|
+
'RHOB_MUD': 1.3,
|
|
83
|
+
'DTC_MUD': 180.0,
|
|
84
|
+
'PEF_MUD': 0.0
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
@staticmethod
|
|
88
|
+
def vars_units(data):
|
|
89
|
+
"""Return list of units for variables exist in data.columns.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
list: List of units for variables exist in data.columns.
|
|
93
|
+
"""
|
|
94
|
+
return {k: v['unit'] for k, v in Config.VARS.items() if k in data.columns and 'unit' in v.keys()}
|