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.
Files changed (69) hide show
  1. quick_pp/__init__.py +0 -0
  2. quick_pp/api/__init__.py +0 -0
  3. quick_pp/api/exceptions.py +61 -0
  4. quick_pp/api/fastapi_mlflow/__init__.py +1 -0
  5. quick_pp/api/fastapi_mlflow/_mlflow_types.py +59 -0
  6. quick_pp/api/fastapi_mlflow/applications.py +72 -0
  7. quick_pp/api/fastapi_mlflow/exceptions.py +22 -0
  8. quick_pp/api/fastapi_mlflow/predictors.py +96 -0
  9. quick_pp/api/main.py +90 -0
  10. quick_pp/api/mlflow_model_deployment.py +99 -0
  11. quick_pp/api/qpp_assistant.py +160 -0
  12. quick_pp/api/router.py +18 -0
  13. quick_pp/api/schemas/lithology_hc_correction.py +39 -0
  14. quick_pp/api/schemas/lithology_ssc.py +37 -0
  15. quick_pp/api/schemas/lithology_vsh_gr.py +25 -0
  16. quick_pp/api/schemas/permeability_choo.py +25 -0
  17. quick_pp/api/schemas/permeability_others.py +24 -0
  18. quick_pp/api/schemas/porosity.py +22 -0
  19. quick_pp/api/schemas/ressum.py +29 -0
  20. quick_pp/api/schemas/saturation_archie.py +25 -0
  21. quick_pp/api/schemas/saturation_b.py +24 -0
  22. quick_pp/api/schemas/saturation_qv.py +26 -0
  23. quick_pp/api/schemas/saturation_rw.py +24 -0
  24. quick_pp/api/schemas/saturation_temp_grad.py +24 -0
  25. quick_pp/api/schemas/saturation_waxman_smits.py +28 -0
  26. quick_pp/api/services/las_handler.py +136 -0
  27. quick_pp/api/services/lithology.py +278 -0
  28. quick_pp/api/services/permeability.py +252 -0
  29. quick_pp/api/services/porosity.py +151 -0
  30. quick_pp/api/services/reservoir_summary.py +78 -0
  31. quick_pp/api/services/saturation.py +359 -0
  32. quick_pp/api/static/favicon.ico +0 -0
  33. quick_pp/api/static/logo.png +0 -0
  34. quick_pp/cli.py +118 -0
  35. quick_pp/config.py +94 -0
  36. quick_pp/core_calibration.py +394 -0
  37. quick_pp/fluid_type.py +128 -0
  38. quick_pp/geomechanics.py +195 -0
  39. quick_pp/las_handler.py +327 -0
  40. quick_pp/lithology/__init__.py +80 -0
  41. quick_pp/lithology/carbonate.py +166 -0
  42. quick_pp/lithology/multi_mineral.py +151 -0
  43. quick_pp/lithology/sand_shale.py +79 -0
  44. quick_pp/lithology/sand_silt_clay.py +131 -0
  45. quick_pp/logger.py +19 -0
  46. quick_pp/modelling/__init__.py +0 -0
  47. quick_pp/modelling/config.py +72 -0
  48. quick_pp/modelling/mock_data/mock_data.parquet +0 -0
  49. quick_pp/modelling/predict_pipeline.py +126 -0
  50. quick_pp/modelling/train_pipeline.py +220 -0
  51. quick_pp/modelling/utils.py +111 -0
  52. quick_pp/objects.py +177 -0
  53. quick_pp/permeability.py +151 -0
  54. quick_pp/plotter/__init__.py +0 -0
  55. quick_pp/plotter/plotter.py +315 -0
  56. quick_pp/plotter/well_log.py +187 -0
  57. quick_pp/plotter/well_log_config.py +409 -0
  58. quick_pp/porosity.py +341 -0
  59. quick_pp/qaqc.py +436 -0
  60. quick_pp/ressum.py +326 -0
  61. quick_pp/rock_type.py +499 -0
  62. quick_pp/saturation.py +455 -0
  63. quick_pp/utils.py +328 -0
  64. quick_pp-0.2.3.dist-info/METADATA +103 -0
  65. quick_pp-0.2.3.dist-info/RECORD +69 -0
  66. quick_pp-0.2.3.dist-info/WHEEL +4 -0
  67. quick_pp-0.2.3.dist-info/entry_points.txt +2 -0
  68. quick_pp-0.2.3.dist-info/licenses/AUTHORS.rst +13 -0
  69. quick_pp-0.2.3.dist-info/licenses/LICENSE +22 -0
quick_pp/qaqc.py ADDED
@@ -0,0 +1,436 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+
5
+ from quick_pp.utils import length_a_b, line_intersection
6
+ from quick_pp.rock_type import estimate_vsh_gr
7
+ from quick_pp.config import Config
8
+ from quick_pp.ressum import calc_reservoir_summary, flag_interval
9
+ from quick_pp.logger import logger
10
+
11
+ plt.style.use('seaborn-v0_8-paper')
12
+
13
+
14
+ def mask_outside_threshold(data, fill=False):
15
+ """ Replace values outside of min and max with null or the min/ max value.
16
+
17
+ Args:
18
+ data (pd.DataFrame): Data to be transformed
19
+
20
+ Returns:
21
+ (pd.DataFrame): masked dataframe
22
+ """
23
+ data = data.copy()
24
+ for model_, vars_ in Config.VARS.items():
25
+ for var_ in vars_:
26
+ var = var_['var']
27
+ if (('min' in var_.keys()) or ('max' in var_.keys())):
28
+ if var in data.columns:
29
+ if not fill:
30
+ data.loc[:, var] = np.where(data[var] < var_['min'], np.nan, data[var])
31
+ data.loc[:, var] = np.where(data[var] > var_['max'], np.nan, data[var])
32
+ else:
33
+ data.loc[:, var] = np.where(data[var] < var_['min'], var_['min'], data[var])
34
+ data.loc[:, var] = np.where(data[var] > var_['max'], var_['max'], data[var])
35
+ return data
36
+
37
+
38
+ def badhole_flagging(data, thold=4):
39
+ """Generate BADHOLE flag using ruptures package. Modified based on https://hallau.world/post/bitsize-from-caliper/
40
+
41
+ Args:
42
+ df (pd.DataFrame): Dataframe used to generate the BADHOLE_FLAG
43
+ thold (int, optional): Threshold in difference between CALI and BS to flag as badhole. Defaults to 4.
44
+
45
+ Returns:
46
+ pd.DataFrame: Pandas dataframe with BADHOLE_FLAG
47
+ """
48
+ import ruptures as rpt
49
+ import scipy.stats
50
+ from scipy.signal import find_peaks
51
+ df = data.copy()
52
+ if 'CALI' not in df.columns:
53
+ df['BADHOLE'] = 0
54
+ return df
55
+
56
+ def reject_outliers(data, m=3):
57
+ data = np.where((data > 8.5) & (data < 21.5), data, np.nan)
58
+ d = np.abs(data - np.nanmedian(data))
59
+ mdev = np.nanmedian(d)
60
+ s = d / mdev if mdev else 0.0
61
+ data = np.where(s < m, data, np.nanmedian(data))
62
+ return data
63
+
64
+ bit_sizes = {
65
+ # 6.0: 6.0,
66
+ 8.5: 8.5,
67
+ 12.25: 12.25,
68
+ 17.5: 17.5
69
+ }
70
+
71
+ model = "rbf"
72
+ return_df = pd.DataFrame()
73
+
74
+ df['BS'] = np.nan if 'BS' not in df.columns else df['BS']
75
+
76
+ for well, well_data in df.groupby('WELL_NAME'):
77
+ # Determine the breakpoints for different bit size
78
+ well_data.sort_values(by='DEPTH', inplace=True)
79
+ well_data['BIN'] = 0
80
+ well_data['ESTIMATED_BITSIZE'] = 8.5
81
+ if not well_data[well_data["CALI"].notna()].empty:
82
+ logger.info(f"[feature_transformer `badhole_flag`] Processing {well}.")
83
+
84
+ signal_data = well_data['CALI']
85
+ signal_data = reject_outliers(signal_data)
86
+ try:
87
+ # Identifying number of clusters/breakpoints from Kernel Density Estimation
88
+ # gaussian_kde couldn't handle constant value
89
+ if (len(np.unique(signal_data)) > 1) & (len(signal_data[~np.isnan(signal_data)]) > 1):
90
+ kde = scipy.stats.gaussian_kde(signal_data[~np.isnan(signal_data)])
91
+ evaluated = kde.evaluate(np.linspace(signal_data.min(), signal_data.max(), 100))
92
+ peaks, _ = find_peaks(evaluated, height=0.1)
93
+ else:
94
+ peaks = []
95
+
96
+ jump = 60
97
+ algo = rpt.BottomUp(model=model, jump=jump).fit(signal_data)
98
+ my_bkps = algo.predict(n_bkps=len(peaks))
99
+
100
+ # Determine the bit sizes based on break points
101
+ indices = [0] + my_bkps
102
+ bins = list(zip(indices, indices[1:]))
103
+ ii = pd.IntervalIndex.from_tuples(bins, closed='left')
104
+ well_data['BIN'] = pd.cut(well_data.reset_index().index, bins=ii)
105
+ bits_percentiles = well_data.groupby('BIN')['CALI'].describe(percentiles=[.01])
106
+
107
+ estimated_bits = []
108
+ for i in bits_percentiles['1%'].values:
109
+ bit_ = bit_sizes[min(bit_sizes.keys(), key=lambda k: abs(k - i))]
110
+ estimated_bits.append(bit_)
111
+
112
+ bits_diff_1 = np.array(estimated_bits[1:] + [estimated_bits[-1]])
113
+ bits_diff_neg1 = np.array([estimated_bits[0]] + estimated_bits[:-1])
114
+ estimated_bits = np.array(estimated_bits)
115
+ estimated_bits = np.where(bits_diff_1 == bits_diff_neg1, bits_diff_1, estimated_bits)
116
+
117
+ categories = dict(zip(well_data.BIN.unique(), estimated_bits))
118
+ well_data['ESTIMATED_BITSIZE'] = well_data.apply(lambda x: categories.get(x.BIN), axis=1)
119
+ except Exception as e:
120
+ logger.error(f"[feature_transformer `badhole_flag`] Error {e}.")
121
+ continue
122
+
123
+ return_df = pd.concat([return_df, well_data])
124
+
125
+ if not return_df.empty:
126
+ bitsize = np.where(return_df.BS.notna(), return_df.BS, return_df.ESTIMATED_BITSIZE)
127
+ return_df['BS'] = bitsize
128
+ absdiff = np.where(return_df.CALI.notna(), abs(return_df.CALI - bitsize), 0)
129
+ return_df['BADHOLE'] = np.where(absdiff < thold, 0, 1)
130
+
131
+ # Drop BIN and ESTIMATED_BITSIZE
132
+ return_df.drop(['BIN', 'ESTIMATED_BITSIZE'], axis=1, inplace=True)
133
+
134
+ return return_df
135
+ else:
136
+ return df
137
+
138
+
139
+ def neu_den_xplot_hc_correction(
140
+ nphi, rhob, vsh_gr=None,
141
+ dry_min1_point: tuple = (),
142
+ dry_clay_point: tuple = (),
143
+ fluid_point: tuple = (1.0, 1.0),
144
+ corr_angle: float = 50, buffer=0.0):
145
+ """Estimate correction for neutron porosity and bulk density based on correction angle.
146
+
147
+ Args:
148
+ nphi (float): Neutron porosity log in fraction.
149
+ rhob (float): Bulk density log in g/cc.
150
+ vsh_gr (float, optional): Vshale from gamma ray log. Defaults to None.
151
+ dry_min1_point (tuple, optional): Neutron porosity and bulk density of mineral 1 point. Defaults to None.
152
+ dry_clay_point (tuple, optional): Neutron porosity and bulk density of dry clay point. Defaults to None.
153
+ fluid_point (tuple, optional): Neutron porosity and bulk density of fluid point. Defaults to (1.0, 1.0).
154
+ corr_angle (float, optional): Correction angle (degree) from east horizontal line. Defaults to 50.
155
+ buffer (float, optional): Buffer to be included in correction. Defaults to 0.0.
156
+
157
+ Returns:
158
+ (float, float): Corrected neutron porosity and bulk density.
159
+ """
160
+ corr_angle = 90 - corr_angle
161
+ A = dry_min1_point
162
+ C = dry_clay_point
163
+ D = fluid_point
164
+ rocklithofrac = length_a_b(A, C)
165
+
166
+ frac_vsh_gr = vsh_gr if vsh_gr is not None else np.zeros(len(nphi))
167
+ nphi_corrected = np.empty(0)
168
+ rhob_corrected = np.empty(0)
169
+ hc_flag = np.empty(0)
170
+ for i, point in enumerate(list(zip(nphi, rhob, frac_vsh_gr))):
171
+ var_pt = line_intersection((A, C), (D, (point[0], point[1])))
172
+ projlithofrac = length_a_b(var_pt, C) + buffer
173
+ if (projlithofrac > rocklithofrac) and (point[0] < .4):
174
+ # Iteration until vsh_dn = vsh_gr
175
+ vsh_dn = 1 - (projlithofrac / rocklithofrac)
176
+ nphi_corr = point[0]
177
+ rhob_corr = point[1]
178
+ shi = 0
179
+ count = 0
180
+ while vsh_dn <= point[2] and not np.isnan(point[2]) and count < 100:
181
+ nphi_corr = point[0] + shi * np.sin(np.radians(corr_angle))
182
+ rhob_corr = point[1] + shi * np.cos(np.radians(corr_angle))
183
+ shi += 0.01
184
+ count += 1
185
+ # Recalculate vsh_dn
186
+ var_pt = line_intersection((A, C), (D, (nphi_corr, rhob_corr)))
187
+ projlithofrac = length_a_b(var_pt, C)
188
+ vsh_dn = 1 - (projlithofrac / rocklithofrac)
189
+
190
+ nphi_corrected = np.append(nphi_corrected, nphi_corr)
191
+ rhob_corrected = np.append(rhob_corrected, rhob_corr)
192
+ hc_flag = np.append(hc_flag, 1)
193
+ else:
194
+ nphi_corrected = np.append(nphi_corrected, point[0])
195
+ rhob_corrected = np.append(rhob_corrected, point[1])
196
+ hc_flag = np.append(hc_flag, 0)
197
+
198
+ return nphi_corrected, rhob_corrected, hc_flag
199
+
200
+
201
+ def den_correction(nphi, gr, vsh_gr=None, phin_sh=.35, phid_sh=.05, rho_ma=2.68, rho_fluid=1.0, alpha=0.05):
202
+ """Correct bulk density based on nphi and gamma ray.
203
+
204
+ Args:
205
+ nphi (float): Neutron porosity log in fraction.
206
+ gr (float): Gamma ray log in GAPI.
207
+ phin_sh (float, optional): Neutron porosity of shale. Defaults to .35.
208
+ phid_sh (float, optional): Density porosity of shale. Defaults to .05.
209
+ rho_ma (float, optional): Matrix density. Defaults to 2.68.
210
+ rho_fluid (float, optional): Fluid density. Defaults to 1.0.
211
+ alpha (float, optional): Alpha value for gamma ray normalization. Defaults
212
+
213
+ Returns:
214
+ float: Corrected bulk density.
215
+ """
216
+ # Estimate vsh_gr
217
+ vsh_gr = vsh_gr if vsh_gr is not None else estimate_vsh_gr(gr, alpha=alpha)
218
+ # Estimate phid assuming vsh_gr = vsh_dn = (phin - phid) / (phin_sh - phid_sh)
219
+ phid = nphi - (phin_sh - phid_sh) * vsh_gr
220
+ return rho_ma - (rho_ma - rho_fluid) * phid
221
+
222
+
223
+ def quick_qc(well_data, return_fig=False):
224
+ """Quick QC for well data.
225
+
226
+ Args:
227
+ well_data (pd.DataFrame): Well data, meant to process one well at a time.
228
+
229
+ Returns:
230
+ pd.DataFrame: Well data with QC flags.
231
+ pd.DataFrame: Reservoir summary.
232
+ plt.Figure: Distribution plot.
233
+ plt.Figure: Depth plot.
234
+ """
235
+ return_df = well_data.copy()
236
+ return_df['ZONES'] = "ALL"
237
+ return_df['QC_FLAG'] = 0
238
+ return_df['PERM'].where(return_df['PERM'] > 0, np.nan, inplace=True)
239
+
240
+ cutoffs = dict(VSHALE=0.4, PHIT=0.01, SWT=0.9)
241
+ _, return_df['RES_FLAG'], _ = flag_interval(return_df['VCLW'], return_df['PHIT'], return_df['SWT'], cutoffs)
242
+ return_df['ALL_FLAG'] = 1
243
+
244
+ # Check average swt in non-reservoir zone
245
+ return_df['QC_FLAG'] = np.where((return_df['RES_FLAG'] == 0) & (return_df['SWT'] < 0.8), 3, return_df['QC_FLAG'])
246
+
247
+ # Summarize
248
+ summary_df = calc_reservoir_summary(
249
+ return_df.DEPTH, return_df.VCLW, return_df.PHIT, return_df.SWT, return_df.PERM, return_df.ZONES
250
+ )
251
+ summary_df.columns = [col.upper() for col in summary_df.columns]
252
+ for group in ['all', 'reservoir']:
253
+ index = return_df['ALL_FLAG'] == 1 if group == 'all' else return_df['RES_FLAG'] == 1
254
+ data = return_df[index]
255
+
256
+ # Calculate average and standard deviation
257
+ temp_df = data.groupby('ZONES').agg({
258
+ 'GR': ['mean', 'std'],
259
+ 'RT': ['mean', 'std'],
260
+ 'NPHI': ['mean', 'std'],
261
+ 'RHOB': ['mean', 'std'],
262
+ })
263
+ # Rename columns
264
+ cols_rename = [f'{stat}_{col}' for col, stat in temp_df.columns]
265
+ cols_rename = [col.replace('mean', 'AV').replace('std', 'STD') for col in cols_rename]
266
+ temp_df.columns = cols_rename
267
+
268
+ summary_df.loc[summary_df.FLAG == group, ['AV_GR', 'AV_RT', 'AV_NPHI', 'AV_RHOB']] = temp_df[
269
+ ['AV_GR', 'AV_RT', 'AV_NPHI', 'AV_RHOB']].values
270
+
271
+ summary_df.loc[summary_df.FLAG == group, ['STD_GR', 'STD_RT', 'STD_NPHI', 'STD_RHOB']] = temp_df[
272
+ ['STD_GR', 'STD_RT', 'STD_NPHI', 'STD_RHOB']].values
273
+
274
+ summary_df.loc[summary_df.FLAG == group, 'QC_FLAG_COUNT'] = data.where(
275
+ data['QC_FLAG'] == 1, 0).groupby('ZONES')['QC_FLAG'].sum().values
276
+
277
+ summary_df.loc[summary_df.FLAG == group, 'QC_FLAG_mode'] = data.groupby(
278
+ 'ZONES')['QC_FLAG'].agg(lambda x: x.mode()).values
279
+
280
+ if return_fig:
281
+ # Distribution plot
282
+ dist_fig, axs = plt.subplots(8, 1, figsize=(5, 15))
283
+ for group, data in return_df.groupby('RES_FLAG'):
284
+ label = 'RES' if group == 1 else 'NON-RES'
285
+ axs[0].hist(data['VSHALE'], bins=100, alpha=0.7, label=label)
286
+ axs[1].hist(summary_df[f'AV_VSHALE_{label}'], bins=25, alpha=0.7, label=f'AV_{label}')
287
+ axs[2].hist(data['PHIT'], bins=100, alpha=0.7, label=label)
288
+ axs[3].hist(summary_df[f'AV_PHIT_{label}'], bins=25, alpha=0.7, label=f'AV_{label}')
289
+ axs[4].hist(data['SWT'], bins=100, alpha=0.7, label=label)
290
+ axs[5].hist(summary_df[f'AV_SWT_{label}'], bins=25, alpha=0.7, label=f'AV_{label}')
291
+ axs[6].hist(data['PERM'], bins=100, alpha=0.7, label=label)
292
+ axs[7].hist(summary_df[f'AV_PERM_GM_{label}'], bins=25, alpha=0.7, label=f'AV_{label}')
293
+ axs[0].set_title('VSHALE Distribution')
294
+ axs[0].legend()
295
+
296
+ axs[1].set_title('AV_VSHALE Distribution')
297
+ axs[1].legend()
298
+
299
+ axs[2].set_title('PHIT Distribution')
300
+ axs[2].legend()
301
+
302
+ axs[3].set_title('AV_PHIT Distribution')
303
+ axs[3].legend()
304
+
305
+ axs[4].set_title('SWT Distribution')
306
+ axs[4].set_yscale('log')
307
+ axs[4].legend()
308
+
309
+ axs[5].set_title('AV_SWT Distribution')
310
+ axs[5].set_yscale('log')
311
+ axs[5].legend()
312
+
313
+ axs[6].set_title('PERM Distribution')
314
+ axs[6].set_yscale('log')
315
+ axs[6].legend()
316
+
317
+ axs[7].set_title('AV_PERM_GM Distribution')
318
+ axs[7].set_yscale('log')
319
+ axs[7].legend()
320
+
321
+ dist_fig.tight_layout()
322
+
323
+ # Depth plot
324
+ depth_fig, axs = plt.subplots(4, 1, figsize=(20, 5), sharex=True)
325
+ axs[0].plot(return_df['DEPTH'], return_df['VSHALE'], label='VSHALE')
326
+ # Compare vsh_gr and vsh_dn
327
+ if 'VSH_GR' in return_df.columns:
328
+ return_df['QC_FLAG'] = np.where(
329
+ abs(return_df['VSH_GR'] - return_df['VSHALE']) > 0.1, 1, return_df['QC_FLAG'])
330
+ axs[0].plot(return_df['DEPTH'], return_df['VSH_GR'], label='VSH_GR')
331
+ axs[0].set_frame_on(False)
332
+ axs[0].set_title('VSHALE')
333
+ axs[0].legend()
334
+
335
+ axs[1].plot(return_df['DEPTH'], return_df['PHIT'], label='PHIT')
336
+ # Compare phit_dn and phit_d
337
+ if 'PHID' in return_df.columns:
338
+ return_df['QC_FLAG'] = np.where(abs(return_df['PHIT'] - return_df['PHID']) > 0.1, 2, return_df['QC_FLAG'])
339
+ axs[1].plot(return_df['DEPTH'], return_df['PHID'], label='PHID')
340
+ axs[1].set_frame_on(False)
341
+ axs[1].set_title('PHIT')
342
+ axs[1].legend()
343
+
344
+ axs[2].plot(return_df['DEPTH'], return_df['SWT'], label='SWT')
345
+ axs[2].plot(return_df['DEPTH'], return_df['RES_FLAG'], label='RES_FLAG')
346
+ axs[2].set_frame_on(False)
347
+ axs[2].set_title('SWT')
348
+ axs[2].legend()
349
+
350
+ axs[3].plot(return_df['DEPTH'], return_df['QC_FLAG'], label='QC_FLAG')
351
+ axs[3].set_frame_on(False)
352
+ axs[3].set_title('QC_FLAG')
353
+ axs[3].legend()
354
+
355
+ depth_fig.tight_layout()
356
+
357
+ return return_df, summary_df, dist_fig, depth_fig
358
+
359
+ else:
360
+ return return_df, summary_df, None, None
361
+
362
+
363
+ def quick_compare(field_data, level='WELL', return_fig=False):
364
+ """Quick comparison of field data.
365
+
366
+ Args:
367
+ field_data (pd.DataFrame): Field data.
368
+ level (str, optional): Level of comparison, either 'WELL' or 'ZONE'. Defaults to 'WELL'.
369
+ return_fig (bool, optional): Whether to return figure. Defaults to False.
370
+
371
+ Returns:
372
+ pd.DataFrame: Comparison dataframe.
373
+ plt.Figure: Comparison figure.
374
+ """
375
+ assert level in ['WELL', 'ZONE'], "Level must be either 'WELL' or 'ZONE'"
376
+ field_data['ZONES'] = "ALL" if level == 'WELL' else field_data['ZONES']
377
+ compare_df = pd.DataFrame()
378
+ for well, well_data in field_data.groupby('WELL_NAME'):
379
+ logger.info(f"Processing {well}")
380
+ _, summary_df, _, _ = quick_qc(well_data, return_fig=False)
381
+ summary_df.insert(0, 'WELL_NAME', well)
382
+ compare_df = pd.concat([compare_df, summary_df])
383
+ logger.info("Finished processing all wells.")
384
+
385
+ if return_fig:
386
+ # Box plot
387
+ curves = ['AV_GR', 'AV_RT', 'AV_NPHI', 'AV_RHOB',
388
+ 'AV_VSHALE', 'AV_PHIT', 'AV_SWT', 'PERM_GM']
389
+ no_curves = len(curves)
390
+ plot_df = compare_df[compare_df.FLAG == 'all']
391
+ idx_percentiles = [int(x * (len(plot_df) - 1)) for x in [0, 0.1, 0.25, 0.5, 0.75, 0.9, 1]]
392
+ fig, axes = plt.subplots(no_curves, 3, figsize=(7, 2.5 * no_curves),
393
+ gridspec_kw={'width_ratios': [1, 3, 5]})
394
+ for i, curve in enumerate(curves):
395
+ # Box plot
396
+ axes[i, 0].set_title(curve)
397
+ axes[i, 0].boxplot(plot_df[curve], labels=[''])
398
+
399
+ # Distribution plot
400
+ axes[i, 1].hist(plot_df[curve], bins=25, alpha=0.7, orientation='horizontal')
401
+
402
+ # Summary table
403
+ df = plot_df[['WELL_NAME', curve]].sort_values(by=curve, ascending=True).reset_index(drop=True)
404
+ df = df.loc[idx_percentiles, :].round(2)
405
+ df['PERCENTILES'] = ['0%', '10%', '25%', '50%', '75%', '90%', '100%']
406
+ df = df[['PERCENTILES', curve, 'WELL_NAME']]
407
+ axes[i, 2].table(cellText=df.values, colLabels=df.columns, loc='center', cellLoc='center',
408
+ colColours=['#f2f2f2'] * 3)
409
+ axes[i, 2].axis('off')
410
+
411
+ plt.tight_layout()
412
+ return compare_df.reset_index(drop=True), fig
413
+
414
+ else:
415
+ return compare_df.reset_index(drop=True), None
416
+
417
+
418
+ def extract_quick_stats(compare_df, flag='all'):
419
+ """Extract quick stats from average comparison dataframe.
420
+
421
+ Args:
422
+ compare_df (pd.DataFrame): Comparison dataframe
423
+
424
+ Returns:
425
+ pd.DataFrame: Quick stats dataframe
426
+ """
427
+ compare_df = compare_df[compare_df.FLAG == flag].copy()
428
+ # Extract quick stats
429
+ reqs = ['PHIT', 'SWT']
430
+ stats_df = pd.DataFrame()
431
+ for col in compare_df.columns:
432
+ if any([req in col for req in reqs]) or col in ['NET', 'NTG']:
433
+ stats = compare_df[col].describe(percentiles=[0.1, 0.5, 0.9])
434
+ stats_df[col] = stats
435
+
436
+ return round(stats_df, 3)