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
quick_pp/rock_type.py
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from scipy.cluster.hierarchy import ward, dendrogram
|
|
4
|
+
from scipy.spatial.distance import pdist
|
|
5
|
+
import matplotlib.pyplot as plt
|
|
6
|
+
import matplotlib.ticker as ticker
|
|
7
|
+
from sklearn.model_selection import train_test_split, RandomizedSearchCV
|
|
8
|
+
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
|
|
9
|
+
from sklearn.metrics import (classification_report, auc, ConfusionMatrixDisplay, confusion_matrix,
|
|
10
|
+
r2_score, mean_absolute_error)
|
|
11
|
+
|
|
12
|
+
from quick_pp.utils import min_max_line
|
|
13
|
+
from quick_pp.lithology import shale_volume_steiber
|
|
14
|
+
from quick_pp.logger import logger
|
|
15
|
+
|
|
16
|
+
plt.style.use('seaborn-v0_8-paper')
|
|
17
|
+
plt.rcParams.update(
|
|
18
|
+
{
|
|
19
|
+
'axes.labelsize': 10,
|
|
20
|
+
'xtick.labelsize': 10,
|
|
21
|
+
'legend.fontsize': 'small'
|
|
22
|
+
}
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def calc_rqi(pore, perm):
|
|
27
|
+
"""Calculate RQI (Rock Quality Index) from Kozeny-Carman equation, based on Amaefule et al. (1993)
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
perm (float): Permeability in mD
|
|
31
|
+
pore (float): Total porosity in fraction
|
|
32
|
+
|
|
33
|
+
Returns:
|
|
34
|
+
float: RQI
|
|
35
|
+
"""
|
|
36
|
+
return 0.0314 * (perm / pore)**0.5
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def calc_fzi(pore, perm):
|
|
40
|
+
"""Calculate FZI (Flow Zone Indicator) from Kozeny-Carman equation, based on Amaefule et al. (1993)
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
perm (float): Permeability in mD
|
|
44
|
+
pore (float): Total porosity in fraction
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
float: FZI
|
|
48
|
+
"""
|
|
49
|
+
return calc_rqi(pore, perm) / (pore / (1 - pore))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def calc_fzi_perm(fzi, pore):
|
|
53
|
+
"""Calculate permeability from FZI and porosity, based on Amaefule et al. (1993)
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
fzi (float): Flow Zone Indicator
|
|
57
|
+
pore (float): Total porosity in fraction
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
float: Permeability in mD
|
|
61
|
+
"""
|
|
62
|
+
return pore * ((pore * fzi) / (.0314 * (1 - pore)))**2
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def calc_r35(pore, perm):
|
|
66
|
+
"""Calculate Winland R35 from Kozeny-Carman equation, based on Winland (1979)
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
perm (float): Permeability in mD
|
|
70
|
+
pore (float): Total porosity in fraction
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
float: R35
|
|
74
|
+
"""
|
|
75
|
+
return 10**(.732 + .588 * np.log10(perm) - .864 * np.log10(pore * 100))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def calc_r35_perm(r35, pore):
|
|
79
|
+
"""Calculate permeability from Winland R35 and porosity, based on Winland (1979)
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
r35 (float): Winland R35
|
|
83
|
+
pore (float): Total porosity in fraction
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
float: Permeability in mD
|
|
87
|
+
"""
|
|
88
|
+
return 10**((np.log10(r35) - .732 + .864 * np.log10(pore * 100)) / .588)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def plot_fzi(cpore, cperm, cut_offs=None, rock_type=None, title='Flow Zone Indicator (FZI)'):
|
|
92
|
+
"""Plot the FZI cross plot.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
perm (float): Permeability in mD
|
|
96
|
+
pore (float): Total porosity in fraction
|
|
97
|
+
"""
|
|
98
|
+
# Plot the FZI cross plot
|
|
99
|
+
_, ax = plt.subplots(figsize=(10, 8))
|
|
100
|
+
plt.title(title)
|
|
101
|
+
plt.scatter(cpore, cperm, marker='.', c=rock_type, cmap='viridis')
|
|
102
|
+
cut_offs = cut_offs if cut_offs is not None else np.arange(0.5, 5)
|
|
103
|
+
phit_points = np.geomspace(0.001, 1, 20)
|
|
104
|
+
prt_num = len(cut_offs)
|
|
105
|
+
ax.annotate(f'PRT {prt_num + 1}', xy=(.3, .7), xytext=(1, 1),
|
|
106
|
+
textcoords='offset points', fontsize=10, fontweight='bold')
|
|
107
|
+
for i, fzi in enumerate(cut_offs):
|
|
108
|
+
perm_points = phit_points * ((phit_points * fzi) / (.0314 * (1 - phit_points)))**2
|
|
109
|
+
ax.plot(phit_points, perm_points, linestyle='dashed', label=f'FZI={round(fzi, 3)}')
|
|
110
|
+
prt_num = len(cut_offs) - i
|
|
111
|
+
ax.annotate(f'PRT {prt_num}', xy=(.3, perm_points[-4]), xytext=(1, 1),
|
|
112
|
+
textcoords='offset points', fontsize=10, fontweight='bold')
|
|
113
|
+
|
|
114
|
+
plt.xlabel('Porosity (frac)')
|
|
115
|
+
plt.xlim(-.05, .5)
|
|
116
|
+
plt.ylabel('Permeability (mD)')
|
|
117
|
+
plt.ylim(1e-3, 1e4)
|
|
118
|
+
plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
|
|
119
|
+
|
|
120
|
+
plt.yscale('log')
|
|
121
|
+
ax.yaxis.set_major_formatter(ticker.FuncFormatter(
|
|
122
|
+
lambda x, pos: ('{{:.{:1d}f}}'.format(int(np.maximum(-np.log10(x), 0)))).format(x)))
|
|
123
|
+
|
|
124
|
+
plt.minorticks_on()
|
|
125
|
+
plt.grid(True, which='major', linestyle='--', linewidth='0.5', color='gray')
|
|
126
|
+
plt.grid(True, which='minor', linestyle=':', linewidth='0.3', color='gray')
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def plot_rfn(cpore, cperm, rock_type=None, title='Lucia RFN'):
|
|
130
|
+
"""Plot the Rock Fabric Number (RFN) lines on porosity and permeability cross plot. The permeability (mD) is
|
|
131
|
+
calculated based on Lucia-Jenkins, 2003.
|
|
132
|
+
```
|
|
133
|
+
perm = 10**(9.7892 - 12.0838 * log(RFN) + (8.6711 - 8.2965 * log(RFN)) * log(phi))
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
cpore (float): Critical porosity in v/v
|
|
138
|
+
cperm (float): Critical permeability in mD
|
|
139
|
+
"""
|
|
140
|
+
# Plot the RFN cross plot
|
|
141
|
+
_, ax = plt.subplots(figsize=(10, 8))
|
|
142
|
+
plt.title(title)
|
|
143
|
+
plt.scatter(cpore, cperm, marker='.', c=rock_type, cmap='viridis')
|
|
144
|
+
pore_points = np.linspace(0, .6, 20)
|
|
145
|
+
for rfn in np.arange(.5, 4.5, .5):
|
|
146
|
+
perm_points = 10**(9.7892 - 12.0838 * np.log10(rfn) + (8.6711 - 8.2965 * np.log10(rfn)) * np.log10(pore_points))
|
|
147
|
+
plt.plot(pore_points, perm_points, linestyle='dashed', label=f'RFN={rfn}')
|
|
148
|
+
|
|
149
|
+
plt.xlabel('Porosity (frac)')
|
|
150
|
+
plt.xlim(-.05, .5)
|
|
151
|
+
plt.ylabel('Permeability (mD)')
|
|
152
|
+
plt.ylim(1e-3, 1e4)
|
|
153
|
+
plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
|
|
154
|
+
|
|
155
|
+
plt.yscale('log')
|
|
156
|
+
ax.yaxis.set_major_formatter(ticker.FuncFormatter(
|
|
157
|
+
lambda x, pos: ('{{:.{:1d}f}}'.format(int(np.maximum(-np.log10(x), 0)))).format(x)))
|
|
158
|
+
|
|
159
|
+
plt.minorticks_on()
|
|
160
|
+
plt.grid(True, which='major', linestyle='--', linewidth='0.5', color='gray')
|
|
161
|
+
plt.grid(True, which='minor', linestyle=':', linewidth='0.3', color='gray')
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def plot_winland(cpore, cperm, cut_offs=None, rock_type=None, title='Winland R35'):
|
|
165
|
+
"""Plot the Winland R35 lines on porosity and permeability cross plot. The permeability (mD) is calculated based on
|
|
166
|
+
Winland, 1972.
|
|
167
|
+
```
|
|
168
|
+
perm = 10**((log(r35) - 0.732 + 0.864 * log(phi)) / 0.588)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
cpore (float): Critical porosity in v/v
|
|
173
|
+
cperm (float): Critical permeability in mD
|
|
174
|
+
"""
|
|
175
|
+
# Plot the Winland R35 cross plot
|
|
176
|
+
_, ax = plt.subplots(figsize=(10, 8))
|
|
177
|
+
plt.title(title)
|
|
178
|
+
plt.scatter(cpore, cperm, marker='.', c=rock_type, cmap='viridis')
|
|
179
|
+
cut_offs = cut_offs if cut_offs is not None else [.05, .1, .5, 2, 10, 100]
|
|
180
|
+
pore_points = np.linspace(0.001, .6, 20)
|
|
181
|
+
for r35 in cut_offs:
|
|
182
|
+
perm_points = calc_r35_perm(r35, pore_points)
|
|
183
|
+
plt.plot(pore_points, perm_points, linestyle='dashed', label=f'R35={r35}')
|
|
184
|
+
|
|
185
|
+
plt.xlabel('Porosity (frac)')
|
|
186
|
+
plt.xlim(-.05, .5)
|
|
187
|
+
plt.ylabel('Permeability (mD)')
|
|
188
|
+
plt.ylim(1e-3, 1e4)
|
|
189
|
+
plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
|
|
190
|
+
|
|
191
|
+
plt.yscale('log')
|
|
192
|
+
ax.yaxis.set_major_formatter(ticker.FuncFormatter(
|
|
193
|
+
lambda x, pos: ('{{:.{:1d}f}}'.format(int(np.maximum(-np.log10(x), 0)))).format(x)))
|
|
194
|
+
|
|
195
|
+
plt.minorticks_on()
|
|
196
|
+
plt.grid(True, which='major', linestyle='--', linewidth='0.5', color='gray')
|
|
197
|
+
plt.grid(True, which='minor', linestyle=':', linewidth='0.3', color='gray')
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def plot_ward_dendogram(X, p=10, title="Ward's Dendogram"):
|
|
201
|
+
# Calculate the pairwise distance matrix
|
|
202
|
+
input_df = X.dropna().sort_values().reset_index(drop=True).values.reshape(-1, 1)
|
|
203
|
+
distance_matrix = pdist(input_df)
|
|
204
|
+
|
|
205
|
+
# Perform Ward's linkage
|
|
206
|
+
linkage_matrix = ward(distance_matrix)
|
|
207
|
+
|
|
208
|
+
# Plot the dendrogram
|
|
209
|
+
fig_width = min(10, p * 0.5)
|
|
210
|
+
plt.figure(figsize=(fig_width, 10))
|
|
211
|
+
dendrogram(linkage_matrix, truncate_mode='lastp', p=p)
|
|
212
|
+
plt.title('Ward\'s Dendrogram')
|
|
213
|
+
plt.xlabel('Sample Index')
|
|
214
|
+
plt.ylabel('Distance')
|
|
215
|
+
plt.show()
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def plot_cumulative_probability(cpore, cperm, cutoffs=[], title="Cumulative Probability Plot"):
|
|
219
|
+
"""Plot cumulative probability to identify possible flow units.
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
cpore (float): Core porosity in fraction.
|
|
223
|
+
cperm (float): Core permeability in mD.
|
|
224
|
+
title (str, optional): Title of the plot. Defaults to "Cumulative Probability Plot".
|
|
225
|
+
"""
|
|
226
|
+
fzi = calc_fzi(cpore, cperm)
|
|
227
|
+
fzi = fzi[~np.isnan(fzi)]
|
|
228
|
+
sorted_fzi = sorted(fzi)
|
|
229
|
+
log_fzi = np.log10(sorted_fzi)
|
|
230
|
+
zi = np.cumsum(sorted_fzi) / np.sum(sorted_fzi)
|
|
231
|
+
|
|
232
|
+
# Generate cumulative probability plot
|
|
233
|
+
plt.figure(figsize=(8, 4))
|
|
234
|
+
plt.title(title)
|
|
235
|
+
plt.scatter(log_fzi, zi, marker='.')
|
|
236
|
+
plt.xlabel('log(FZI)')
|
|
237
|
+
plt.ylabel('Cumulative Probability')
|
|
238
|
+
plt.minorticks_on()
|
|
239
|
+
plt.grid(True, which='major', linestyle='--', linewidth='0.5', color='gray')
|
|
240
|
+
plt.grid(True, which='minor', linestyle=':', linewidth='0.3', color='gray')
|
|
241
|
+
plt.xticks(np.arange(min(log_fzi[log_fzi != -np.inf]), max(log_fzi[log_fzi != np.inf]), .2))
|
|
242
|
+
for i, c in enumerate(cutoffs):
|
|
243
|
+
plt.axvline(x=c, color='r', linestyle='dashed', label=cutoffs[i])
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def plot_lorenz_heterogeneity(cpore, cperm, title="Lorenz's Plot"):
|
|
247
|
+
"""Plot Lorenz's plot to estimate heteroginity.
|
|
248
|
+
|
|
249
|
+
Args:
|
|
250
|
+
cpore (float): Core porosity in fraction.
|
|
251
|
+
cperm (float): Core permeability in mD.
|
|
252
|
+
title (str, optional): Title of the plot. Defaults to "Lorenz's Plot".
|
|
253
|
+
"""
|
|
254
|
+
sorted_perm, sorted_phit = zip(*sorted(zip(cperm, cpore), reverse=True))
|
|
255
|
+
perm_cdf = np.cumsum(sorted_perm) / np.sum(sorted_perm)
|
|
256
|
+
phit_cdf = np.cumsum(sorted_phit) / np.sum(sorted_phit)
|
|
257
|
+
lorenz_coeff = (auc(phit_cdf, perm_cdf) - 0.5) / 0.5
|
|
258
|
+
# Generate Lorenz's plot
|
|
259
|
+
plt.figure(figsize=(10, 8))
|
|
260
|
+
plt.title(title)
|
|
261
|
+
plt.text(.4, .1, f'Lorenz Coefficient: {lorenz_coeff:.2f}', fontsize=10, transform=plt.gca().transAxes)
|
|
262
|
+
plt.scatter(phit_cdf, perm_cdf, marker='.')
|
|
263
|
+
plt.plot([0, 1], [0, 1], linestyle='dashed', color='gray')
|
|
264
|
+
plt.xlabel('CDF of Porosity')
|
|
265
|
+
plt.ylabel('CDF of Permeability')
|
|
266
|
+
plt.xlim(0, 1)
|
|
267
|
+
plt.ylim(0, 1)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def plot_modified_lorenz(cpore, cperm, title="Modified Lorenz's Plot"):
|
|
271
|
+
"""Plot Lorenz's plot to identify possible flow units.
|
|
272
|
+
|
|
273
|
+
Args:
|
|
274
|
+
cpore (float): Core porosity in fraction.
|
|
275
|
+
cperm (float): Core permeability in mD.
|
|
276
|
+
title (str, optional): Title of the plot. Defaults to "Lorenz's Plot".
|
|
277
|
+
"""
|
|
278
|
+
fzi = calc_fzi(cpore, cperm)
|
|
279
|
+
sorted_fzi, sorted_perm, sorted_pore = zip(*sorted(zip(fzi, cperm, cpore), reverse=False))
|
|
280
|
+
perm_cdf = np.cumsum(sorted_perm) / np.sum(sorted_perm)
|
|
281
|
+
pore_cdf = np.cumsum(sorted_pore) / np.sum(sorted_pore)
|
|
282
|
+
# Generate Lorenz's plot
|
|
283
|
+
plt.figure(figsize=(10, 8))
|
|
284
|
+
plt.title(title)
|
|
285
|
+
plt.scatter(pore_cdf, perm_cdf, marker='.')
|
|
286
|
+
plt.xlabel('CDF of Porosity')
|
|
287
|
+
plt.ylabel('CDF of Permeability')
|
|
288
|
+
plt.minorticks_on()
|
|
289
|
+
plt.grid(True, which='major', linestyle='--', linewidth='0.5', color='gray')
|
|
290
|
+
plt.grid(True, which='minor', linestyle=':', linewidth='0.3', color='gray')
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def estimate_pore_throat(pc, ift, theta):
|
|
294
|
+
"""Estimate pore throat size from capillary pressure curve based on Washburn 1921.
|
|
295
|
+
|
|
296
|
+
Args:
|
|
297
|
+
pc (float): Capillary pressure in psi.
|
|
298
|
+
ift (float): Interfacial tension in mN/m.
|
|
299
|
+
theta (float): Contact angle in degree.
|
|
300
|
+
|
|
301
|
+
Returns:
|
|
302
|
+
float: Pore throat size in micrometer.
|
|
303
|
+
"""
|
|
304
|
+
return 2 * 0.145 * ift * abs(np.cos(np.radians(theta))) / pc
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def estimate_vsh_gr(gr, min_gr=None, max_gr=None, alpha=0.1):
|
|
308
|
+
"""Estimate volume of shale from gamma ray. If min_gr and max_gr are not provided,
|
|
309
|
+
it will be automatically estimated.
|
|
310
|
+
|
|
311
|
+
Args:
|
|
312
|
+
gr (float): Gamma ray from well log.
|
|
313
|
+
min_gr (float, optional): Minimum gamma ray value. Defaults to None.
|
|
314
|
+
max_gr (float, optional): Maximum gamma ray value. Defaults to None.
|
|
315
|
+
alpha (float, optional): Alpha value for min-max normalization. Defaults to 0.1.
|
|
316
|
+
|
|
317
|
+
Returns:
|
|
318
|
+
float: VSH_GR.
|
|
319
|
+
"""
|
|
320
|
+
# Normalize gamma ray
|
|
321
|
+
if not max_gr or (not min_gr and min_gr != 0):
|
|
322
|
+
# Remove high outliers and forward fill missing values
|
|
323
|
+
gr = np.where(gr <= np.nanmean(gr) + 1.5 * np.nanstd(gr), gr, np.nan)
|
|
324
|
+
mask = np.isnan(gr)
|
|
325
|
+
idx = np.where(~mask, np.arange(len(mask)), 0)
|
|
326
|
+
np.maximum.accumulate(idx, axis=0, out=idx)
|
|
327
|
+
gr = gr[idx]
|
|
328
|
+
|
|
329
|
+
_, max_gr = min_max_line(gr, alpha)
|
|
330
|
+
gri = np.where(gr < max_gr, gr / max_gr, 1)
|
|
331
|
+
else:
|
|
332
|
+
gri = (gr - min_gr) / (max_gr - min_gr)
|
|
333
|
+
gri = np.where(gri < 1, gri, 1)
|
|
334
|
+
return shale_volume_steiber(gri).flatten()
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def estimate_vsh_dn(phin, phid, phin_sh=0.35, phid_sh=0.05):
|
|
338
|
+
"""Estimate volume of shale from neutron porosity and density porosity.
|
|
339
|
+
|
|
340
|
+
Args:
|
|
341
|
+
phin (float): Neutron porosity in fraction.
|
|
342
|
+
phid (float): Density porosity in fraction.
|
|
343
|
+
phin_sh (float, optional): Neutron porosity for shale. Defaults to 0.35.
|
|
344
|
+
phid_sh (float, optional): Density porosity for shale. Defaults to 0.05.
|
|
345
|
+
|
|
346
|
+
Returns:
|
|
347
|
+
float: Volume of shale.
|
|
348
|
+
"""
|
|
349
|
+
return (phin - phid) / (phin_sh - phid_sh)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def rock_typing(curve, cut_offs=[.1, .2, .3, .4], higher_is_better=True):
|
|
353
|
+
"""Rock typing based on cutoffs.
|
|
354
|
+
|
|
355
|
+
Args:
|
|
356
|
+
curve (float): Curve to be used for rock typing.
|
|
357
|
+
cut_offs (list, optional): 3 cutoffs to group the curve into 4 rock types. Defaults to [.1, .2, .3, .4].
|
|
358
|
+
higher_is_better (bool, optional): Whether higher value of curve is better quality or not. Defaults to True.
|
|
359
|
+
|
|
360
|
+
Returns:
|
|
361
|
+
float: Rock type.
|
|
362
|
+
"""
|
|
363
|
+
# Set number of rock types
|
|
364
|
+
rock_type = np.arange(1, len(cut_offs) + 2)
|
|
365
|
+
rock_type = rock_type[::-1] if higher_is_better else rock_type
|
|
366
|
+
# Rock typing based on cutoffs
|
|
367
|
+
conditions = [curve < cut_off for cut_off in cut_offs] + [curve >= cut_offs[-1]]
|
|
368
|
+
choices = rock_type[-len(conditions):]
|
|
369
|
+
return np.where(np.isnan(curve), np.nan, np.select(conditions, choices))
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def train_classification_model(data, input_features: list, target_feature: str, stratifier=None):
|
|
373
|
+
"""Train a classification Random Forest model to predict a binary feature.
|
|
374
|
+
|
|
375
|
+
Args:
|
|
376
|
+
data (DataFrame): Dataframe containing input and target features.
|
|
377
|
+
input_features (list): List of input features.
|
|
378
|
+
target_feature (str): The target feature.
|
|
379
|
+
stratifier (array, optional): Stratifier for train-test split. Defaults to None.
|
|
380
|
+
|
|
381
|
+
Returns:
|
|
382
|
+
RandomForestClassifier: Trained model.
|
|
383
|
+
"""
|
|
384
|
+
random_seed = 123
|
|
385
|
+
X = data[input_features]
|
|
386
|
+
y = data[target_feature]
|
|
387
|
+
y = y.astype(int)
|
|
388
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
389
|
+
X, y, test_size=0.2, random_state=random_seed, stratify=stratifier)
|
|
390
|
+
|
|
391
|
+
# Hyperparameter tuning
|
|
392
|
+
param_dist = {
|
|
393
|
+
'n_estimators': [150, 200],
|
|
394
|
+
'max_depth': [30, None],
|
|
395
|
+
'max_features': [.5, 'sqrt'],
|
|
396
|
+
'min_samples_split': [2, .5],
|
|
397
|
+
'min_samples_leaf': [1, .2],
|
|
398
|
+
'criterion': ['gini', 'entropy']
|
|
399
|
+
}
|
|
400
|
+
model = RandomizedSearchCV(RandomForestClassifier(), param_dist, cv=7, scoring='f1_weighted',
|
|
401
|
+
random_state=random_seed)
|
|
402
|
+
model.fit(X_train, y_train)
|
|
403
|
+
|
|
404
|
+
# Feature importance
|
|
405
|
+
best_model = model.best_estimator_
|
|
406
|
+
importances = best_model.feature_importances_
|
|
407
|
+
std = np.std([tree.feature_importances_ for tree in best_model.estimators_], axis=0)
|
|
408
|
+
rf_importances = pd.Series(importances, index=input_features)
|
|
409
|
+
|
|
410
|
+
fig, ax = plt.subplots()
|
|
411
|
+
rf_importances.plot.bar(yerr=std, ax=ax)
|
|
412
|
+
ax.set_title("Feature importances using MDI")
|
|
413
|
+
ax.set_ylabel("Mean decrease in impurity")
|
|
414
|
+
fig.tight_layout()
|
|
415
|
+
|
|
416
|
+
# Model evaluation
|
|
417
|
+
y_pred_train = model.predict(X_train)
|
|
418
|
+
y_pred = model.predict(X_test)
|
|
419
|
+
logger.info(f'Score for {target_feature} model')
|
|
420
|
+
logger.info('Best parameters found: %s', model.best_params_)
|
|
421
|
+
logger.info('### Train Set ###')
|
|
422
|
+
logger.info('Classification Report:\n%s', classification_report(y_train, y_pred_train))
|
|
423
|
+
cm = confusion_matrix(y_train, y_pred_train, labels=model.classes_)
|
|
424
|
+
ConfusionMatrixDisplay(cm, display_labels=model.classes_).plot()
|
|
425
|
+
|
|
426
|
+
logger.info('\n### Test Set ###')
|
|
427
|
+
logger.info('Classification Report:\n%s', classification_report(y_test, y_pred))
|
|
428
|
+
cm = confusion_matrix(y_test, y_pred, labels=model.classes_)
|
|
429
|
+
ConfusionMatrixDisplay(cm, display_labels=model.classes_).plot()
|
|
430
|
+
|
|
431
|
+
return model
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def train_regression_model(data, input_features: list, target_feature: list, stratifier=None):
|
|
435
|
+
"""Train a regression Random Forest model to predict a continuous feature.
|
|
436
|
+
|
|
437
|
+
Args:
|
|
438
|
+
data (DataFrame): Dataframe containing input, target and stratifier features.
|
|
439
|
+
input_features (list): List of input features.
|
|
440
|
+
target_feature (str): The target feature.
|
|
441
|
+
stratifier (array, optional): Stratifier for train-test split. Defaults to None.
|
|
442
|
+
|
|
443
|
+
Returns:
|
|
444
|
+
RandomForestRegressor: Trained model.
|
|
445
|
+
"""
|
|
446
|
+
random_seed = 123
|
|
447
|
+
X = data[input_features]
|
|
448
|
+
y = data[target_feature]
|
|
449
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
450
|
+
X, y, test_size=0.2, random_state=random_seed, stratify=stratifier)
|
|
451
|
+
|
|
452
|
+
# Hyperparameter tuning
|
|
453
|
+
param_dist = {
|
|
454
|
+
'n_estimators': [150, 200],
|
|
455
|
+
'max_depth': [30, None],
|
|
456
|
+
'max_features': [.5, 'sqrt'],
|
|
457
|
+
'min_samples_split': [2, .5],
|
|
458
|
+
'min_samples_leaf': [1, .2],
|
|
459
|
+
'criterion': ['squared_error', 'absolute_error']
|
|
460
|
+
}
|
|
461
|
+
model = RandomizedSearchCV(RandomForestRegressor(), param_dist, cv=5, scoring='r2',
|
|
462
|
+
random_state=random_seed)
|
|
463
|
+
model.fit(X_train, y_train)
|
|
464
|
+
|
|
465
|
+
# Feature importance
|
|
466
|
+
best_model = model.best_estimator_
|
|
467
|
+
importances = best_model.feature_importances_
|
|
468
|
+
std = np.std([tree.feature_importances_ for tree in best_model.estimators_], axis=0)
|
|
469
|
+
rf_importances = pd.Series(importances, index=input_features)
|
|
470
|
+
|
|
471
|
+
fig, ax = plt.subplots()
|
|
472
|
+
rf_importances.plot.bar(yerr=std, ax=ax)
|
|
473
|
+
ax.set_title("Feature importances using MDI")
|
|
474
|
+
ax.set_ylabel("Mean decrease in impurity")
|
|
475
|
+
fig.tight_layout()
|
|
476
|
+
|
|
477
|
+
# Model evaluation
|
|
478
|
+
y_pred_train = model.predict(X_train)
|
|
479
|
+
y_pred = model.predict(X_test)
|
|
480
|
+
logger.info(f'Score for {target_feature} model')
|
|
481
|
+
logger.info('Best parameters found: %s', model.best_params_)
|
|
482
|
+
logger.info('### Train Set ###')
|
|
483
|
+
logger.info('R2 Score: %s', r2_score(y_train, y_pred_train))
|
|
484
|
+
logger.info('Mean Absolute Error: %s', mean_absolute_error(y_train, y_pred_train))
|
|
485
|
+
logger.info('\n### Test Set ###')
|
|
486
|
+
logger.info('R2 Score: %s', r2_score(y_test, y_pred))
|
|
487
|
+
logger.info('Mean Absolute Error: %s', mean_absolute_error(y_test, y_pred))
|
|
488
|
+
|
|
489
|
+
# Plot the true vs predicted values
|
|
490
|
+
plt.figure(figsize=(10, 8))
|
|
491
|
+
plt.plot(y_train, y_pred_train, '.', label='Actual', markersize=8)
|
|
492
|
+
plt.plot(y_test, y_pred, '.', label='Predicted', markersize=6)
|
|
493
|
+
plt.xlabel('True')
|
|
494
|
+
plt.ylabel('Predicted')
|
|
495
|
+
plt.title(f'{target_feature} Prediction')
|
|
496
|
+
plt.legend(bbox_to_anchor=(1, 1), loc="upper left")
|
|
497
|
+
plt.show()
|
|
498
|
+
|
|
499
|
+
return model
|