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
@@ -0,0 +1,151 @@
1
+ def choo_permeability(vclw, vsilt, phit, m=2, B=None, A=20e7, C=3):
2
+ """Estimate permeability using Choo's equation.
3
+
4
+ Args:
5
+ vclw (float): Volume of clay in fraction.
6
+ vsilt (float): Volume of silt in fraction.
7
+ phit (float): Total porosity in fraction.
8
+ A (float): Constant based on 0.125 * rg**2 / 10. Defaults to 20e7.
9
+ B (float): Constant derived from cementation and compaction factor, defaults to m * ((2 / C) + 1) + 2.
10
+ C (float): Constant, defaults to 2.
11
+
12
+ Returns:
13
+ float: Choo's permeability in mD.
14
+ """
15
+ B = B or m * ((2 / C) + 1) + 2
16
+ return A * phit**B / 10**(6 * vclw + 3 * vsilt)
17
+
18
+
19
+ def kozeny_carman_permeability(phit, S=0.01):
20
+ """Estimate permeability using Kozeny-Carman's equation.
21
+
22
+ Args:
23
+ phit (float): Total porosity in fraction.
24
+ S (float): Specific surface area of the grains
25
+
26
+ Returns:
27
+ float: Permeability in mD.
28
+ """
29
+ return phit**3 / (5 * S**2 * (1 - phit)**2)
30
+
31
+
32
+ def timur_permeability(phit, Swirr):
33
+ """Estimate permeability based on Timur (1968) emperical equation established on 155 sandstone samples from
34
+ 3 different oil fields in North America.
35
+
36
+ Args:
37
+ phit (float): Porosity in fraction.
38
+ Swirr (float): Irreduceable water saturation in fraction.
39
+
40
+ Returns:
41
+ float: Permeability in mD.
42
+ """
43
+ return 0.136 * phit**4.4 / Swirr**2
44
+
45
+
46
+ def coates_permeability(phie, Swirr, a=1):
47
+ """Estimate permeability based on Coates (1974)
48
+
49
+ Args:
50
+ phie (float): Effective porosity in fraction.
51
+ Swirr (float): Irreduceable water saturation in fraction.
52
+ a (float): Constant. Defaults to 1.
53
+
54
+ Returns:
55
+ float: Coates permeability in mD.
56
+ """
57
+ return (phie**2 / a * (1 - Swirr) / Swirr)**2
58
+
59
+
60
+ def tixier_permeability(phit, Swirr):
61
+ """Estimate permeability based on Tixier (1949)
62
+
63
+ Args:
64
+ phit (float): Porosity in fraction.
65
+ Swirr (float): Irreduceable water saturation in fraction.
66
+
67
+ Returns:
68
+ float: Permeability in mD
69
+ """
70
+ return 62.5 * phit**6 / Swirr**2
71
+
72
+
73
+ def morris_biggs_permeability(phit, C, Swirr):
74
+ """Estimate permeability based on Morris and Biggs (1967)
75
+
76
+ Args:
77
+ phit (float): Total porosity in fraction.
78
+ C (float): A constant which depends on the density of hydrocarbon in the formation.
79
+ 250 for medium oil. 79 for gas.
80
+ Swirr (float): Irreduceable water saturation in fraction.
81
+
82
+ Returns:
83
+ float: Permeability in mD.
84
+ """
85
+ return (C * phit**3 / Swirr)**2
86
+
87
+
88
+ def morris_biggs_modified_permeability(phit, phie, Vbwi):
89
+ """Estimate permeability based on Morris and Biggs (1967)
90
+
91
+ Args:
92
+ phit (float): Total porosity in fraction.
93
+ phie (float): Effective porosity in fraction.
94
+ Vbwi (float): Volume of bound water in fraction.
95
+
96
+ Returns:
97
+ float: Permeability in mD.
98
+ """
99
+ return (1e2 * phie**2 * (phit - Vbwi) / Vbwi)**2
100
+
101
+
102
+ def estimate_krw(swt, swirr):
103
+ """Estimate permeability based on Park Jones (1945)
104
+
105
+ Args:
106
+ swt (float): Total water saturation.
107
+ swirr (float): Irreducible water saturation.
108
+
109
+ Returns:
110
+ float: Water relative permeability.
111
+ """
112
+ return ((swt - swirr) / (1 - swirr))**3
113
+
114
+
115
+ def estimate_kro(swt, swirr):
116
+ """Estimate permeability based on Park Jones (1945)
117
+
118
+ Args:
119
+ swt (float): Total water saturation.
120
+ swirr (float): Irreducible water saturation.
121
+ Returns:
122
+ float: Oil relative permeability.
123
+ """
124
+ return ((0.9 - swt) / (0.9 - swirr))**2
125
+
126
+
127
+ def estimate_wor(krw, kro, A=2):
128
+ """Estimating Water Oil Ratio of surface production. Based on Pirson (1950).
129
+
130
+ Args:
131
+ krw (float): Water relative permeability.
132
+ kro (float): Oil relative permeability.
133
+ A (float): Constant. Defaults to 2.
134
+ Light oil: 1 - 5
135
+ Medium oil: 10 - 50
136
+ Heavy oil: > 50
137
+ Returns:
138
+ float: Water Oil Ratio.
139
+ """
140
+ return (krw / kro) * A
141
+
142
+
143
+ def estimate_wc(wor):
144
+ """Estimating Water Cut of surface production.
145
+
146
+ Args:
147
+ wor (float): Water Oil Ratio.
148
+ Returns:
149
+ float: Water Cut.
150
+ """
151
+ return wor / (1 + wor)
File without changes
@@ -0,0 +1,315 @@
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ from matplotlib.figure import Figure
4
+
5
+ from quick_pp.utils import line_intersection
6
+ from quick_pp.logger import logger
7
+ import quick_pp.plotter.well_log as plotter_wells
8
+ plotly_log = plotter_wells.plotly_log
9
+
10
+ plt.style.use('seaborn-v0_8-paper')
11
+ plt.rcParams.update(
12
+ {
13
+ 'axes.labelsize': 10,
14
+ 'xtick.labelsize': 10,
15
+ 'legend.fontsize': 'small'
16
+ }
17
+ )
18
+
19
+
20
+ def update_fluid_contacts(well_data, well_config: dict):
21
+ logger.debug(f"Updating fluid contacts for well with config: {well_config}")
22
+ """Update fluid flags based on fluid contacts.
23
+
24
+ Args:
25
+ well_data (pandas.DataFrame): Pandas dataframe containing well log data.
26
+ well_config (dict): Dictionary containing well sorting and fluid contacts.
27
+
28
+ Returns:
29
+ pandas.DataFrame: Pandas dataframe containing updated fluid
30
+ """
31
+ owc = well_config.get('OWC', np.nan)
32
+ odt = well_config.get('ODT', np.nan)
33
+ out = well_config.get('OUT', np.nan)
34
+ goc = well_config.get('GOC', np.nan)
35
+ gdt = well_config.get('GDT', np.nan)
36
+ gut = well_config.get('GUT', np.nan)
37
+ gwc = well_config.get('GWC', np.nan)
38
+ wut = well_config.get('WUT', np.nan)
39
+
40
+ well_data = well_data.copy()
41
+ logger.debug(f"well_data columns before update: {well_data.columns.tolist()}")
42
+ well_data['OIL_FLAG'] = np.where(
43
+ ((well_data['DEPTH'] > out) | (well_data['DEPTH'] > goc)) & (
44
+ (well_data['DEPTH'] < odt) | (well_data['DEPTH'] < owc)), 1, 0)
45
+
46
+ well_data['GAS_FLAG'] = np.where(
47
+ ((well_data['DEPTH'] < gdt) | (well_data['DEPTH'] < gwc) | (well_data['DEPTH'] < goc)) & (
48
+ well_data['DEPTH'] > gut), 1, 0)
49
+
50
+ well_data['WATER_FLAG'] = np.where(
51
+ ((well_data['DEPTH'] > wut) | (well_data['DEPTH'] > owc) | (well_data['DEPTH'] > gwc)), 1, 0)
52
+
53
+ well_data['FLUID_FLAG'] = np.where(
54
+ well_data['OIL_FLAG'] == 1, 1, np.where(
55
+ well_data['GAS_FLAG'] == 1, 2, 0))
56
+
57
+ return well_data
58
+
59
+
60
+ def generate_zone_config(zones: list = ['ALL']):
61
+ logger.info(f"Generating zone config for zones: {zones}")
62
+ """Generate zone configuration.
63
+
64
+ Args:
65
+ zones (list, optional): List of zone names. Defaults to ['ALL'].
66
+
67
+ Returns:
68
+ dict: Zone configuration
69
+ """
70
+ zone_config = {}
71
+ for zone in zones:
72
+ zone_config[zone] = {
73
+ 'GUT': 0, 'GDT': 0, 'GOC': 0, 'GWC': 0, 'OUT': 0, 'ODT': 0, 'OWC': 0, 'WUT': 0
74
+ }
75
+ return zone_config
76
+
77
+
78
+ def update_zone_config(zone_config: dict, zone: str, fluid_contacts: dict):
79
+ logger.info(f"Updating zone config for zone: {zone} with contacts: {fluid_contacts}")
80
+ """Update zone configuration with fluid contacts.
81
+
82
+ Args:
83
+ zone_config (dict): Dictionary containing zone configuration.
84
+ zone (str): Zone name for which configuration is to be updated.
85
+ fluid_contacts (dict): Fluid contacts for the specified zone.
86
+
87
+ Returns:
88
+ dict: Updated zone configuration
89
+ """
90
+ if zone in zone_config:
91
+ zone_config[zone].update(fluid_contacts)
92
+ else:
93
+ zone_config[zone] = fluid_contacts
94
+ return zone_config
95
+
96
+
97
+ def generate_well_config(well_names: list = ['X']):
98
+ logger.info(f"Generating well config for wells: {well_names}")
99
+ """Generate well configuration.
100
+
101
+ Args:
102
+ well_names (list, optional): List of well names. Defaults to ['X'].
103
+
104
+ Returns:
105
+ dict: Well configuration
106
+ """
107
+ well_config = {}
108
+ for i, well in enumerate(well_names):
109
+ well_config[well] = {
110
+ 'sorting': i + 1,
111
+ 'zones': {
112
+ 'ALL': {'GUT': 0, 'GDT': 0, 'GOC': 0, 'GWC': 0, 'OUT': 0, 'ODT': 0, 'OWC': 0, 'WUT': 0},
113
+ }
114
+ }
115
+ return well_config
116
+
117
+
118
+ def update_well_config(
119
+ well_config: dict, well_name: str, zone: str = '', fluid_contacts: dict = {}, sorting: int = 0):
120
+ logger.info(f"Updating well config for well: {well_name}, zone: {zone}, sorting: {sorting}")
121
+ """Update well configuration with fluid contacts.
122
+
123
+ Args:
124
+ well_config (dict): Dictionary containing well sorting and fluid contacts.
125
+ well_name (str): Well name for which configuration is to be updated.
126
+ zone (str): Zone name for which configuration is to be updated.
127
+ fluid_contacts (dict): Fluid contacts for the specified zone.
128
+ sorting (int, optional): Sorting of the wells on the stick plot. Defaults to None.
129
+
130
+ Returns:
131
+ dict: Updated well configuration
132
+ """
133
+ if zone in well_config[well_name]['zones']:
134
+ well_config[well_name]['zones'][zone].update(fluid_contacts)
135
+ elif zone:
136
+ well_config[well_name]['zones'][zone] = fluid_contacts
137
+
138
+ if sorting:
139
+ well_config[well_name]['sorting'] = sorting
140
+ return well_config
141
+
142
+
143
+ def assert_well_config_structure(well_config):
144
+ logger.debug("Asserting well config structure.")
145
+ """Assert well configuration structure.
146
+
147
+ Args:
148
+ well_config (dict): Dictionary containing well sorting and fluid contacts.
149
+ """
150
+ required_keys = {'sorting', 'zones'}
151
+ optional_keys = {'GUT', 'GDT', 'GOC', 'GWC', 'OUT', 'ODT', 'OWC', 'WUT'}
152
+ for well, config in well_config.items():
153
+ assert isinstance(config, dict), f"Value for well '{well}' is not a dictionary"
154
+ assert set(config.keys()).intersection(required_keys), f"Well '{well}' does not have the required keys"
155
+
156
+ for zone, fluid_contacts in config['zones'].items():
157
+ assert isinstance(fluid_contacts, dict), f"Value for zone '{zone}' in well '{well}' is not a dictionary"
158
+ assert set(fluid_contacts.keys()).intersection(
159
+ optional_keys), f"zone '{zone}' in well '{well}' has invalid keys"
160
+
161
+
162
+ def stick_plot(data, well_config: dict, zone: str = 'ALL'):
163
+ logger.info(f"Generating stick plot for zone: {zone}")
164
+ """Generate stick plot with water saturation and fluid contacts for specified zone.
165
+
166
+ Example of well_config:
167
+ ```
168
+ well_config = {
169
+ 'X': {
170
+ 'sorting': 0,
171
+ 'zones': {
172
+ 'ALL': {
173
+ 'GUT': 0,
174
+ 'GDT': 0,
175
+ 'GOC': 0,
176
+ 'GWC': 0,
177
+ 'OUT': 0,
178
+ 'ODT': 0,
179
+ 'OWC': 0,
180
+ 'WUT': 0
181
+ },
182
+ }
183
+ }
184
+ }
185
+ ```
186
+
187
+ Args:
188
+ data (pandas.DataFrame): Pandas dataframe containing well log data.
189
+ well_config (dict): Dictionary containing well sorting and fluid contacts.
190
+ """
191
+ assert 'SWT' in data.columns, 'SWT column not found in data.'
192
+ assert_well_config_structure(well_config)
193
+
194
+ # Create BVO and BVOH columns
195
+ data['BVO'] = data['PHIT'] * (1 - data['SWT'])
196
+ data['BVOH'] = data['PHIT'] * (1 - data['SHF']) if 'SHF' in data.columns else 0
197
+
198
+ # Sort well names based on sorting key
199
+ well_names = sorted(data['WELL_NAME'].unique(), key=lambda name: well_config[name]['sorting'])
200
+
201
+ # Create subplots
202
+ fig, axes = plt.subplots(nrows=1, ncols=len(well_names), sharey=True, figsize=(len(well_names) * 2, 15))
203
+
204
+ # Plot each well's data
205
+ for ax, well_name in zip(axes, well_names):
206
+ logger.debug(f"Plotting well: {well_name}")
207
+ well_data = data[(data['WELL_NAME'] == well_name) & (data['ZONES'] == zone)].copy()
208
+ well_data = update_fluid_contacts(well_data, well_config[well_name]['zones'][zone])
209
+ ax.plot(well_data['BVO'], well_data['DEPTH'], label=r'$BVO_{Log}$')
210
+ if 'BVOH' in well_data.columns:
211
+ ax.plot(well_data['BVOH'], well_data['DEPTH'], label=r'$BVO_{SHF}$')
212
+
213
+ # Fill between based on fluid flag
214
+ ax.fill_betweenx(
215
+ well_data['DEPTH'], 0, 1, where=well_data['FLUID_FLAG'] == 1, color='g', alpha=0.3, label='Oil')
216
+ ax.fill_betweenx(
217
+ well_data['DEPTH'], 0, 1, where=well_data['FLUID_FLAG'] == 2, color='r', alpha=0.3, label='Gas')
218
+ ax.fill_betweenx(
219
+ well_data['DEPTH'], 0, 1, where=well_data['FLUID_FLAG'] == 0, color='b', alpha=0.3, label='Water')
220
+
221
+ ax.set_title(f'Well: {well_name}')
222
+ ax.set_xlim(0, .5)
223
+ ax.legend()
224
+
225
+ axes[0].set_ylabel('Depth')
226
+ fig.subplots_adjust(wspace=0.3, hspace=0)
227
+ fig.set_facecolor('aliceblue')
228
+ plt.gca().invert_yaxis()
229
+ plt.show()
230
+
231
+
232
+ def neutron_density_xplot(nphi, rhob,
233
+ dry_min1_point: tuple,
234
+ dry_clay_point: tuple,
235
+ fluid_point: tuple,
236
+ wet_clay_point: tuple = (),
237
+ dry_silt_point: tuple = (), **kwargs):
238
+ logger.info("Generating neutron-density crossplot.")
239
+ """Neutron-Density crossplot with lithology lines based on specified end points.
240
+
241
+ Args:
242
+ nphi (float): Neutron porosity log.
243
+ rhob (float): Bulk density log.
244
+ dry_min1_point (tuple): Neutron porosity and bulk density of mineral 1 point.
245
+ dry_clay_point (tuple): Neutron porosity and bulk density of dry clay point.
246
+ fluid_point (tuple): Neutron porosity and bulk density of fluid point.
247
+ wet_clay_point (tuple): Neutron porosity and bulk density of wet clay point.
248
+ dry_silt_point (tuple): Neutron porosity and bulk density of dry silt point. Default is None.
249
+
250
+ Returns:
251
+ matplotlib.pyplot.Figure: Neutron porosity and bulk density cross plot.
252
+ """
253
+ A = dry_min1_point
254
+ C = dry_clay_point
255
+ D = fluid_point
256
+ E = list(zip(nphi, rhob))
257
+ # Plotting the NPHI-RHOB crossplot
258
+ projected_pt = []
259
+ for i in range(len(nphi)):
260
+ projected_pt.append(line_intersection((A, C), (D, E[i])))
261
+ rockline_from_pt = (A, C)
262
+ min1line_from_pt = (D, A)
263
+ clayline_from_pt = (D, C)
264
+
265
+ fig = Figure(figsize=(5, 5))
266
+ ax = fig.add_subplot(111)
267
+ ax.set_title('NPHI-RHOB Crossplot')
268
+ ax.scatter(nphi, rhob, c=np.arange(0, len(nphi)).tolist(), cmap='rainbow', marker='.')
269
+ ax.plot(*zip(*min1line_from_pt), label='Mineral 1 Line', color='blue')
270
+
271
+ if dry_silt_point:
272
+ B = dry_silt_point
273
+ siltline_from_pt = (D, B)
274
+ ax.plot(*zip(*siltline_from_pt), label='Silt Line', color='green')
275
+ ax.scatter(dry_silt_point[0], dry_silt_point[1], label='Dry Silt Point', color='orange')
276
+
277
+ ax.plot(*zip(*clayline_from_pt), label='Clay Line', color='gray')
278
+ ax.plot(*zip(*rockline_from_pt), label='Rock Line', color='black')
279
+ ax.scatter(*zip(*projected_pt), label='Projected Line', color='purple', marker='.')
280
+ ax.scatter(dry_min1_point[0], dry_min1_point[1],
281
+ label=f'Mineral 1 Point: ({dry_min1_point[0]}, {dry_min1_point[1]})', color='yellow')
282
+ ax.scatter(dry_clay_point[0], dry_clay_point[1],
283
+ label=f'Dry Clay Point: ({dry_clay_point[0]}, {dry_clay_point[1]})', color='black')
284
+
285
+ if wet_clay_point:
286
+ ax.scatter(wet_clay_point[0], wet_clay_point[1], label='Wet Clay Point', color='gray')
287
+
288
+ ax.scatter(fluid_point[0], fluid_point[1],
289
+ label=f'Fluid Point: ({fluid_point[0]}, {fluid_point[1]})', color='blue')
290
+
291
+ ax.set_ylim(3, 0)
292
+ ax.set_ylabel('RHOB')
293
+ ax.set_xlim(-0.15, 1)
294
+ ax.set_xlabel('NPHI')
295
+ ax.legend(loc="upper left", prop={'size': 9})
296
+ ax.minorticks_on()
297
+ ax.grid(True, which='major', linestyle='--', linewidth='0.5', color='gray')
298
+ ax.grid(True, which='minor', linestyle=':', linewidth='0.4', color='gray')
299
+ fig.tight_layout()
300
+
301
+ return fig
302
+
303
+
304
+ def sonic_density_xplot():
305
+ logger.info("Called sonic_density_xplot (not implemented)")
306
+ """ TODO: Implement sonic density crossplot
307
+ """
308
+ pass
309
+
310
+
311
+ def sonic_neutron_xplot():
312
+ logger.info("Called sonic_neutron_xplot (not implemented)")
313
+ """ TODO: Implement sonic neutron crossplot
314
+ """
315
+ pass
@@ -0,0 +1,187 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ from collections import OrderedDict
4
+ import plotly.graph_objects as go
5
+ from plotly.subplots import make_subplots
6
+
7
+ from quick_pp.plotter.well_log_config import COLOR_DICT, TRACE_DEFS, XAXIS_DEFS
8
+
9
+
10
+ # --- Helper to add traces from trace_defs ---
11
+ def add_defined_traces(fig, df, index, no_of_track, trace_defs, **kwargs):
12
+ trace_ix = 0
13
+ for col, trace_def in trace_defs.items():
14
+ # Skip special cases handled separately
15
+ if col in ['COAL_FLAG', 'ZONES']:
16
+ continue
17
+
18
+ style = trace_def.get('style', {})
19
+ trace_args = dict(
20
+ x=df[col],
21
+ y=index,
22
+ name=col,
23
+ **kwargs
24
+ )
25
+ trace_args.update(style)
26
+ fig.add_trace(
27
+ go.Scatter(**trace_args),
28
+ row=1,
29
+ col=trace_def['track'],
30
+ secondary_y=trace_def.get('secondary_y', False)
31
+ )
32
+ # Required for xaxis visibility for overlapping traces
33
+ if not trace_def.get('hide_xaxis', True) and trace_ix >= no_of_track:
34
+ fig.data[trace_ix].update(xaxis=f'x{trace_ix + 1}')
35
+ trace_ix += 1
36
+
37
+ return fig
38
+
39
+
40
+ def plotly_log(well_data, depth_uom="", trace_defs: OrderedDict = OrderedDict(),
41
+ xaxis_defs: dict = {}, column_widths: list = []):
42
+ """
43
+ Generate a multi-track well log plot using Plotly, supporting custom traces, rock/coal flags, and zone markers.
44
+ Parameters
45
+ ----------
46
+ well_data : pandas.DataFrame
47
+ DataFrame containing well log data. Must include a 'DEPTH' column and may include columns referenced in
48
+ `trace_defs`, as well as optional 'ROCK_FLAG', 'COAL_FLAG', and 'ZONES' columns.
49
+ depth_uom : str, optional
50
+ Unit of measurement for depth, displayed on the y-axis label (e.g., 'm', 'ft'). Default is an empty string.
51
+ trace_defs : dict, optional
52
+ Dictionary defining traces to plot. Keys are column names in `well_data`, values are dicts with at least:
53
+ - 'track': int, the subplot column (track) to plot on.
54
+ - 'style': dict, Plotly Scatter style arguments (e.g., line color, dash).
55
+ - 'secondary_y': bool, whether to plot on the secondary y-axis of the track.
56
+ - 'hide_xaxis': bool, whether to hide the x-axis for this trace.
57
+ Default is TRACE_DEFS.
58
+ xaxis_defs : dict, optional
59
+ Dictionary defining x-axis layout options for each trace. Keys are column names, values are dicts of axis layout
60
+ properties (e.g., range, title, tickvals). Default is XAXIS_DEFS.
61
+ Returns
62
+ -------
63
+ fig : plotly.graph_objs._figure.Figure
64
+ Plotly Figure object containing the multi-track well log plot.
65
+ Notes
66
+ -----
67
+ - Handles missing columns in `COLOR_DICT` by filling with NaN.
68
+ - One-hot encodes 'ROCK_FLAG' if present, assigning unique colors for each flag.
69
+ - Adds special traces for 'COAL_FLAG' (tracks 4-8, filled black) and 'ROCK_FLAG_X' (track 7, colored by flag).
70
+ - Adds horizontal zone markers and labels if 'ZONES' column is present.
71
+ - Layout is configured for 8 tracks, with shared y-axis (depth), custom margins, and a unified hover mode.
72
+ - The plot is interactive, with pan/zoom and drawing tools enabled, and a custom color theme.
73
+ Examples
74
+ --------
75
+ >>> fig = plotly_log(well_data, depth_uom='m')
76
+ >>> fig.show()
77
+ """
78
+ trace_defs = trace_defs or TRACE_DEFS
79
+ xaxis_defs = xaxis_defs or XAXIS_DEFS
80
+ no_of_track = max([trace['track'] for trace in trace_defs.values()])
81
+ column_widths = column_widths or [1] * no_of_track
82
+ df = well_data.copy()
83
+ index = df.DEPTH
84
+
85
+ # Ensure all required columns exist (fill with NaN if missing)
86
+ for k in trace_defs.keys():
87
+ if k not in df.columns:
88
+ df[k] = np.nan
89
+
90
+ # One-hot encode ROCK_FLAG if present
91
+ if 'ROCK_FLAG' in df.columns:
92
+ # Add ROCK_FLAG colors
93
+ no_of_rock_flags = df['ROCK_FLAG'].nunique() + 1
94
+ df['ROCK_FLAG'] = df['ROCK_FLAG'].fillna(no_of_rock_flags)
95
+ for i in df['ROCK_FLAG'].unique():
96
+ lightness = 100 - (int(i) / no_of_rock_flags * 100)
97
+ COLOR_DICT[f'ROCK_FLAG_{i}'] = f'hsl(30, 70%, {lightness}%)'
98
+
99
+ df['ROCK_FLAG'] = df['ROCK_FLAG'].astype(int).astype('category')
100
+ df = df.drop(columns=[c for c in df.columns if 'ROCK_FLAG_' in c])
101
+ df = pd.get_dummies(df, columns=['ROCK_FLAG'], prefix='ROCK_FLAG', dtype=int)
102
+
103
+ fig = make_subplots(
104
+ rows=1, cols=no_of_track, shared_yaxes=True, horizontal_spacing=.02,
105
+ column_widths=column_widths, specs=[list([{'secondary_y': True}] * no_of_track)]
106
+ )
107
+ fig = add_defined_traces(fig, df, index, no_of_track, trace_defs)
108
+
109
+ # --- COAL_FLAG traces (special style, always on tracks 4-8, secondary_y=True) ---
110
+ if 'COAL_FLAG' in trace_defs.keys():
111
+ for c in [4, 5, 6, 7, 8]:
112
+ fig.add_trace(
113
+ go.Scatter(x=df['COAL_FLAG'], y=index, name='', line_color=COLOR_DICT['COAL_FLAG'],
114
+ fill='tozerox', fillcolor='rgba(0,0,0,1)', opacity=1),
115
+ row=1, col=c, secondary_y=True)
116
+
117
+ # --- ROCK_FLAG_X traces (special style, always on track 7, secondary_y=False) ---
118
+ if 'ROCK_FLAG_1' in trace_defs.keys():
119
+ rock_flag_columns = [col for col in df.columns if col.startswith('ROCK_FLAG_')]
120
+ # Remove 'ROCK_FLAG_1' if it already exists as a trace in fig.data
121
+ rock_flag_columns.remove('ROCK_FLAG_1') if any(
122
+ trace.name == 'ROCK_FLAG_1' for trace in fig.data) and 'ROCK_FLAG_1' in rock_flag_columns else None
123
+ for feature in rock_flag_columns:
124
+ fig.add_trace(
125
+ go.Scatter(x=df[feature], y=index, line_color=COLOR_DICT[feature], name=feature,
126
+ fill='tozerox', fillcolor=COLOR_DICT.get(feature, '#000000')),
127
+ row=1, col=7, secondary_y=False)
128
+
129
+ # Update xaxis and yaxis layout configurations
130
+ visible_xaxis = [col for col, trace_def in trace_defs.items() if not trace_def.get('hide_xaxis', True)]
131
+ layout_dict = {f'xaxis{x.xaxis[1:]}': v for k, v in xaxis_defs.items() for x in fig.data
132
+ if k in visible_xaxis and x.name == k}
133
+ layout_dict['yaxis'] = {'domain': [0, .84], 'title': f'DEPTH ({depth_uom})'}
134
+
135
+ for i in range(2, no_of_track * 2 + 1):
136
+ layout_dict[f'yaxis{i}'] = {
137
+ 'domain': [0, .84],
138
+ 'visible': False if i % 2 == 0 else True,
139
+ 'showgrid': False
140
+ }
141
+ fig.update_layout(**layout_dict)
142
+ fig.update_xaxes(fixedrange=True)
143
+ fig.update_yaxes(matches='y', constrain='domain', autorange='reversed')
144
+
145
+ # --- Helper for zone markers (ZONES) ---
146
+ def add_zone_markers(fig, df):
147
+ if 'ZONES' in df.columns:
148
+ tops_df = df[['DEPTH', 'ZONES']].dropna().reset_index()
149
+ if not tops_df.empty and sum([1 for c in tops_df.ZONES.unique() if 'SAND_' in c]) < 30:
150
+ zone_tops_idx = [0] + [idx for idx, (i, j) in enumerate(
151
+ zip(tops_df['ZONES'], tops_df['ZONES'][1:]), 1) if i != j]
152
+ zone_tops = tops_df.loc[zone_tops_idx, :]
153
+ for tops in zone_tops.values:
154
+ fig.add_shape(
155
+ dict(type='line', x0=-5, y0=tops[1], x1=150, y1=tops[1]), row=1, col='all',
156
+ line=dict(color='#763F98', dash='dot', width=1.5)
157
+ )
158
+ fig.add_trace(
159
+ go.Scatter(
160
+ name=tops[2], x=[1.1, 1.1], y=[tops[1] - 1, tops[1] - 1],
161
+ text=tops[2], mode='text', textfont=dict(color='#763F98', size=12), textposition='top right'
162
+ ), row=1, col=2)
163
+ add_zone_markers(fig, df)
164
+
165
+ fig.update_layout(
166
+ height=1000,
167
+ autosize=True,
168
+ showlegend=False,
169
+ title={
170
+ 'text': '%s Logs' % df.WELL_NAME.dropna().unique()[0],
171
+ 'y': .99,
172
+ 'xanchor': 'center',
173
+ 'yanchor': 'top',
174
+ 'font_size': 12
175
+ },
176
+ hovermode='y unified',
177
+ dragmode='pan',
178
+ modebar_remove=['lasso', 'select', 'autoscale'],
179
+ modebar_add=['drawline', 'drawcircle', 'drawrect', 'eraseshape'],
180
+ newshape_line_color='cyan', newshape_line_width=3,
181
+ template='none',
182
+ margin=dict(l=70, r=0, t=20, b=10),
183
+ paper_bgcolor="#dadada",
184
+ hoverlabel_bgcolor='#F3F3F3'
185
+ )
186
+
187
+ return fig