quick-pp 0.2.1__tar.gz → 0.2.2__tar.gz

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 (64) hide show
  1. {quick_pp-0.2.1 → quick_pp-0.2.2}/HISTORY.rst +6 -0
  2. {quick_pp-0.2.1 → quick_pp-0.2.2}/PKG-INFO +15 -7
  3. quick_pp-0.2.2/docs/_build/html/_static/file.png +0 -0
  4. quick_pp-0.2.2/docs/_build/html/_static/minus.png +0 -0
  5. quick_pp-0.2.2/docs/_build/html/_static/plus.png +0 -0
  6. {quick_pp-0.2.1 → quick_pp-0.2.2}/docs/source/quick_pp.lithology.rst +0 -1
  7. quick_pp-0.2.2/docs/source/quick_pp.modelling.rst +23 -0
  8. quick_pp-0.2.2/docs/source/quick_pp.plotter.rst +16 -0
  9. {quick_pp-0.2.1 → quick_pp-0.2.2}/docs/source/quick_pp.rst +12 -4
  10. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/__init__.py +3 -1
  11. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/core_calibration.py +5 -4
  12. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/las_handler.py +5 -2
  13. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/lithology/carbonate.py +2 -2
  14. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/lithology/sand_shale.py +2 -2
  15. quick_pp-0.2.2/quick_pp/logger.py +22 -0
  16. quick_pp-0.2.2/quick_pp/modelling/__init__.py +0 -0
  17. quick_pp-0.2.2/quick_pp/modelling/config.py +64 -0
  18. quick_pp-0.2.2/quick_pp/modelling/predict_pipeline.py +120 -0
  19. quick_pp-0.2.2/quick_pp/modelling/train_pipeline.py +177 -0
  20. quick_pp-0.2.2/quick_pp/modelling/utils.py +107 -0
  21. quick_pp-0.2.2/quick_pp/plotter/__init__.py +0 -0
  22. quick_pp-0.2.2/quick_pp/plotter/plotter.py +302 -0
  23. quick_pp-0.2.2/quick_pp/plotter/well_log.py +185 -0
  24. quick_pp-0.2.2/quick_pp/plotter/well_log_config.py +409 -0
  25. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/qaqc.py +5 -4
  26. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/rock_type.py +15 -15
  27. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/utils.py +3 -2
  28. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp.egg-info/PKG-INFO +15 -7
  29. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp.egg-info/SOURCES.txt +15 -0
  30. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp.egg-info/requires.txt +6 -4
  31. {quick_pp-0.2.1 → quick_pp-0.2.2}/setup.py +5 -4
  32. {quick_pp-0.2.1 → quick_pp-0.2.2}/AUTHORS.rst +0 -0
  33. {quick_pp-0.2.1 → quick_pp-0.2.2}/CONTRIBUTING.rst +0 -0
  34. {quick_pp-0.2.1 → quick_pp-0.2.2}/LICENSE +0 -0
  35. {quick_pp-0.2.1 → quick_pp-0.2.2}/MANIFEST.in +0 -0
  36. {quick_pp-0.2.1 → quick_pp-0.2.2}/README.rst +0 -0
  37. {quick_pp-0.2.1 → quick_pp-0.2.2}/docs/Makefile +0 -0
  38. {quick_pp-0.2.1 → quick_pp-0.2.2}/docs/make.bat +0 -0
  39. {quick_pp-0.2.1 → quick_pp-0.2.2}/docs/source/authors.rst +0 -0
  40. {quick_pp-0.2.1 → quick_pp-0.2.2}/docs/source/conf.py +0 -0
  41. {quick_pp-0.2.1 → quick_pp-0.2.2}/docs/source/contributing.rst +0 -0
  42. {quick_pp-0.2.1 → quick_pp-0.2.2}/docs/source/history.rst +0 -0
  43. {quick_pp-0.2.1 → quick_pp-0.2.2}/docs/source/index.rst +0 -0
  44. {quick_pp-0.2.1 → quick_pp-0.2.2}/docs/source/installation.rst +0 -0
  45. {quick_pp-0.2.1 → quick_pp-0.2.2}/docs/source/usage.rst +0 -0
  46. {quick_pp-0.2.1 → quick_pp-0.2.2}/docs/static/quick_pp_demo.gif +0 -0
  47. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/config.py +0 -0
  48. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/fluid_type.py +0 -0
  49. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/geomechanics.py +0 -0
  50. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/lithology/__init__.py +0 -0
  51. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/lithology/multi_mineral.py +0 -0
  52. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/lithology/sand_silt_clay.py +0 -0
  53. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/objects.py +0 -0
  54. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/permeability.py +0 -0
  55. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/porosity.py +0 -0
  56. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/ressum.py +0 -0
  57. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp/saturation.py +0 -0
  58. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp.egg-info/dependency_links.txt +0 -0
  59. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp.egg-info/entry_points.txt +0 -0
  60. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp.egg-info/not-zip-safe +0 -0
  61. {quick_pp-0.2.1 → quick_pp-0.2.2}/quick_pp.egg-info/top_level.txt +0 -0
  62. {quick_pp-0.2.1 → quick_pp-0.2.2}/setup.cfg +0 -0
  63. {quick_pp-0.2.1 → quick_pp-0.2.2}/tests/__init__.py +0 -0
  64. {quick_pp-0.2.1 → quick_pp-0.2.2}/tests/test_quick_pp.py +0 -0
@@ -63,3 +63,9 @@ History
63
63
  * Add ML modelling module.
64
64
  * Add cli using click.
65
65
  * Refactor the well log plotter module.
66
+
67
+ 0.2.2 (2025-05-23)
68
+ -------------------
69
+ * Add qpp_assistant module based on chainlit.
70
+ * Updated the requirements to use Python 3.11.
71
+ * Updated the readme and documentation.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quick_pp
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: Python package to assist in providing quick-look/ preliminary petrophysical estimation.
5
5
  Home-page: https://github.com/imranfadhil/quick_pp
6
6
  Author: Imran Fadhil
@@ -11,24 +11,26 @@ Classifier: Development Status :: 2 - Pre-Alpha
11
11
  Classifier: Intended Audience :: Developers
12
12
  Classifier: License :: OSI Approved :: MIT License
13
13
  Classifier: Natural Language :: English
14
- Classifier: Programming Language :: Python :: 3.10
15
- Requires-Python: >=3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Requires-Python: >=3.11
16
16
  License-File: LICENSE
17
17
  License-File: AUTHORS.rst
18
18
  Requires-Dist: Click>=7.0
19
+ Requires-Dist: numpy==1.26.2
20
+ Requires-Dist: scikit-learn==1.6.1
21
+ Requires-Dist: matplotlib==3.8.0
22
+ Requires-Dist: SALib==1.5.1
23
+ Requires-Dist: langchain_ollama==0.3.3
24
+ Requires-Dist: chainlit==2.5.5
19
25
  Requires-Dist: ruptures
20
26
  Requires-Dist: welly
21
27
  Requires-Dist: pandas
22
- Requires-Dist: numpy
23
28
  Requires-Dist: statsmodels
24
- Requires-Dist: scikit-learn==1.6.1
25
29
  Requires-Dist: mlflow
26
30
  Requires-Dist: fastapi
27
31
  Requires-Dist: fastapi_mcp
28
32
  Requires-Dist: psycopg2-binary
29
33
  Requires-Dist: ptitprince
30
- Requires-Dist: matplotlib==3.8.0
31
- Requires-Dist: SALib==1.5.1
32
34
  Requires-Dist: orjson
33
35
  Dynamic: author
34
36
  Dynamic: author-email
@@ -135,3 +137,9 @@ History
135
137
  * Add ML modelling module.
136
138
  * Add cli using click.
137
139
  * Refactor the well log plotter module.
140
+
141
+ 0.2.2 (2025-05-23)
142
+ -------------------
143
+ * Add qpp_assistant module based on chainlit.
144
+ * Updated the requirements to use Python 3.11.
145
+ * Updated the readme and documentation.
@@ -21,7 +21,6 @@ Carbonate module
21
21
  .. automethod:: quick_pp.lithology.carbonate.Carbonate.lithology_fraction_neu_den
22
22
  .. automethod:: quick_pp.lithology.carbonate.Carbonate.lithology_fraction_pef
23
23
  .. automethod:: quick_pp.lithology.carbonate.Carbonate.clay_correction
24
- .. automethod:: quick_pp.lithology.carbonate.Carbonate.estimate_vcld_from_gr
25
24
 
26
25
  Multi Mineral module
27
26
  -----------------------------------------
@@ -0,0 +1,23 @@
1
+ Predict Pipeline module
2
+ --------------------------------------------
3
+
4
+ .. automodule:: quick_pp.modelling.predict_pipeline
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
8
+
9
+ Train Pipeline module
10
+ ------------------------------------------
11
+
12
+ .. automodule:: quick_pp.modelling.train_pipeline
13
+ :members:
14
+ :undoc-members:
15
+ :show-inheritance:
16
+
17
+ Utils module
18
+ --------------------------------
19
+
20
+ .. automodule:: quick_pp.modelling.utils
21
+ :members:
22
+ :undoc-members:
23
+ :show-inheritance:
@@ -0,0 +1,16 @@
1
+ Plotter module
2
+ --------------------------------
3
+
4
+ .. automodule:: quick_pp.plotter.plotter
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
8
+
9
+ Well Log module
10
+ ----------------------------------
11
+
12
+ .. automodule:: quick_pp.plotter.well_log
13
+ :members:
14
+ :undoc-members:
15
+ :show-inheritance:
16
+
@@ -100,7 +100,15 @@ Utilities module
100
100
  Plotter module
101
101
  ------------------------
102
102
 
103
- .. automodule:: quick_pp.plotter
104
- :members:
105
- :undoc-members:
106
- :show-inheritance:
103
+ .. toctree::
104
+ :maxdepth: 4
105
+
106
+ quick_pp.plotter
107
+
108
+ Machine Learning Modelling module
109
+ ----------------------------------
110
+
111
+ .. toctree::
112
+ :maxdepth: 4
113
+
114
+ quick_pp.modelling
@@ -1,3 +1,5 @@
1
+ from .logger import logger
2
+
1
3
  __author__ = """Imran Fadhil"""
2
4
  __email__ = 'imranfadhil@gmail.com'
3
- __version__ = '0.2.1'
5
+ __version__ = '0.2.2'
@@ -4,6 +4,7 @@ import numpy as np
4
4
  import plotly.graph_objects as go
5
5
 
6
6
  from quick_pp.utils import power_law_func, inv_power_law_func
7
+ from quick_pp.logger import logger
7
8
 
8
9
 
9
10
  plt.style.use('seaborn-v0_8-paper')
@@ -140,7 +141,7 @@ def j_xplot(sw, j, a=None, b=None, core_group=None, label=None, log_log=False, a
140
141
  ax.set_xlabel('Sw (frac)')
141
142
  ax.set_xlim(0.01, 1)
142
143
  ax.set_ylabel('J')
143
- ax.set_ylim(ylim) if ylim else ax.set_ylim(0.01, ax.get_lines()[-1].get_ydata().max())
144
+ ax.set_ylim(ylim) if ylim else ax.set_ylim(0.01, max(ax.get_lines()[-1].get_ydata()))
144
145
  if log_log:
145
146
  ax.set_yscale('log')
146
147
  ax.set_ylim(0.01, 100)
@@ -167,7 +168,7 @@ def fit_j_curve(sw, j):
167
168
  b = [round(c, 3) for c in popt][1]
168
169
  return a, b
169
170
  except Exception as e:
170
- print(e)
171
+ logger.error(e)
171
172
  return 1, 1
172
173
 
173
174
 
@@ -218,7 +219,7 @@ def fit_skelt_harrison_curve(sw, h):
218
219
  d = [round(c, 3) for c in popt][3]
219
220
  return a, b, c, d
220
221
  except Exception as e:
221
- print(e)
222
+ logger.error(e)
222
223
  return 1, 1, 1, 1
223
224
 
224
225
 
@@ -252,7 +253,7 @@ def fit_poroperm_curve(poro, perm):
252
253
  b = [round(c, 3) for c in popt][1]
253
254
  return a, b
254
255
  except Exception as e:
255
- print(e)
256
+ logger.error(e)
256
257
  return 1, 1
257
258
 
258
259
 
@@ -5,6 +5,9 @@ import numpy as np
5
5
  import pandas as pd
6
6
  import mmap
7
7
  import welly
8
+ import welly.las
9
+
10
+ from quick_pp.logger import logger
8
11
 
9
12
 
10
13
  def read_las_files(las_files):
@@ -27,7 +30,7 @@ def read_las_files(las_files):
27
30
  try:
28
31
  df, well_header = read_las_file_welly(f)
29
32
  except Exception as e:
30
- print(f"[read_las_files] Exception for {f.name} | {e} ")
33
+ logger.error(f"[read_las_files] Exception for {f.name} | {e} ")
31
34
  df, well_header, _ = read_las_file_mmap(f)
32
35
  merged_data = pd.concat([merged_data, df], ignore_index=True)
33
36
  header_data = pd.concat([header_data, well_header], ignore_index=True)
@@ -284,7 +287,7 @@ def check_index_consistent(welly_object):
284
287
  else:
285
288
  return False
286
289
  except Exception as e:
287
- print(f"[las_handler] `check_index_consistent` Error | {e}")
290
+ logger.error(f"[las_handler] `check_index_consistent` Error | {e}")
288
291
  return False
289
292
 
290
293
 
@@ -7,8 +7,8 @@ from quick_pp.config import Config
7
7
  class Carbonate:
8
8
  """Carbonate model based on neutron density or density pef cross plots."""
9
9
 
10
- def __init__(self, dry_calc_point: tuple = None, dry_dolo_point: tuple = None, dry_clay_point: tuple = None,
11
- fluid_point: tuple = None, **kwargs):
10
+ def __init__(self, dry_calc_point: tuple = (float, float), dry_dolo_point: tuple = (float, float),
11
+ dry_clay_point: tuple = (float, float), fluid_point: tuple = (float, float), **kwargs):
12
12
  # Initialize the endpoints
13
13
  self.dry_calc_point = dry_calc_point or Config.CARB_NEU_DEN_ENDPOINTS["DRY_CALC_POINT"]
14
14
  self.dry_dolo_point = dry_dolo_point or Config.CARB_NEU_DEN_ENDPOINTS["DRY_DOLO_POINT"]
@@ -7,8 +7,8 @@ from quick_pp.config import Config
7
7
  class SandShale:
8
8
  """This binary model only consider a combination of sand-shale components. """
9
9
 
10
- def __init__(self, dry_sand_point: tuple = None, dry_clay_point: tuple = None,
11
- fluid_point: tuple = None, wet_clay_point: tuple = None, silt_line_angle: float = None, **kwargs):
10
+ def __init__(self, dry_sand_point: tuple = (float, float), dry_clay_point: tuple = (float, float),
11
+ fluid_point: tuple = (float, float), wet_clay_point: tuple = (float, float), silt_line_angle: float = 0, **kwargs):
12
12
  # Initialize the endpoints
13
13
  self.dry_sand_point = dry_sand_point or Config.SSC_ENDPOINTS["DRY_SAND_POINT"]
14
14
  self.dry_clay_point = dry_clay_point or Config.SSC_ENDPOINTS["DRY_CLAY_POINT"]
@@ -0,0 +1,22 @@
1
+ import logging
2
+ import sys
3
+
4
+ # Set up a package-wide logger for quick_pp
5
+ logger = logging.getLogger("quick_pp")
6
+ logger.setLevel(logging.INFO)
7
+
8
+ # Create handler (console)
9
+ console_handler = logging.StreamHandler(sys.stdout)
10
+ console_handler.setLevel(logging.INFO)
11
+
12
+ # Create formatter and add to handler
13
+ formatter = logging.Formatter('[%(asctime)s] %(levelname)s | %(name)s | %(message)s')
14
+ console_handler.setFormatter(formatter)
15
+
16
+ # Add handler to logger if not already added
17
+ if not logger.hasHandlers():
18
+ logger.addHandler(console_handler)
19
+
20
+ # Optionally, silence overly verbose loggers from dependencies
21
+ logging.getLogger("matplotlib").setLevel(logging.WARNING)
22
+ logging.getLogger("mlflow").setLevel(logging.WARNING)
File without changes
@@ -0,0 +1,64 @@
1
+ from collections import OrderedDict
2
+ from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
3
+
4
+ MLFLOW_CONFIG = dict(
5
+ local=dict(
6
+ tracking_host='localhost',
7
+ tracking_port=5015,
8
+ backend_store_uri='sqlite:///./mlruns/mlflow.db',
9
+ artifact_location='./mlruns/',
10
+ ),
11
+ remote=dict(
12
+ tracking_host='<your-mlflow-server>',
13
+ tracking_port=5000,
14
+ backend_store_uri='postgresql://<username>:<password>@<hostname>:<port>/<database>?sslmode=require',
15
+ artifact_location='wasbs://<your-blob-storage-account-name>.blob.core.windows.net/<your-container-name>/',
16
+ # artifact_location='s3://<your-s3-bucket-name>/<your-folder-name>/',
17
+ ),
18
+ )
19
+
20
+ RAW_FEATURES = ['GR', 'RT', 'NPHI', 'RHOB']
21
+ MODELLING_CONFIG = dict(
22
+ clastic=OrderedDict(
23
+ OIL=dict(
24
+ alg=RandomForestClassifier,
25
+ targets=['OIL_FLAG'],
26
+ features=RAW_FEATURES,
27
+ description='Oil flag classification',
28
+ ),
29
+ GAS=dict(
30
+ alg=RandomForestClassifier,
31
+ targets=['GAS_FLAG'],
32
+ features=RAW_FEATURES + ['OIL_FLAG'],
33
+ description='Gas flag classification',
34
+ ),
35
+ CLASTIC=dict(
36
+ alg=RandomForestRegressor,
37
+ targets=['PHIT', 'SWT', 'LOG_PERM', 'VSAND', 'VSILT', 'VCLW'],
38
+ features=RAW_FEATURES,
39
+ description=('Clastic properties prediction consisting of total porosity, total water saturation, '
40
+ 'log permeability, sand volume, silt volume, and clay volume'),
41
+ ),
42
+ ),
43
+ carbonate=OrderedDict(
44
+ OIL=dict(
45
+ alg=RandomForestClassifier,
46
+ targets=['OIL_FLAG'],
47
+ features=RAW_FEATURES,
48
+ description='Oil flag classification',
49
+ ),
50
+ GAS=dict(
51
+ alg=RandomForestClassifier,
52
+ targets=['GAS_FLAG'],
53
+ features=RAW_FEATURES + ['OIL_FLAG'],
54
+ description='Gas flag classification',
55
+ ),
56
+ CARBONATE=dict(
57
+ alg=RandomForestRegressor,
58
+ targets=['PHIT', 'SWT', 'LOG_PERM', 'VCALC', 'VCLW', 'VDOLO'],
59
+ features=RAW_FEATURES,
60
+ description=('Carbonate properties prediction consisting of total porosity, total water saturation, '
61
+ 'log permeability, calcite volume, clay volume, and dolomite volume'),
62
+ ),
63
+ )
64
+ )
@@ -0,0 +1,120 @@
1
+ import pandas as pd
2
+ import os
3
+ from pathlib import Path
4
+ from mlflow.pyfunc import load_model
5
+ import mlflow.tracking as mlflow_tracking
6
+
7
+ # # Uncomment below 2 lines to run >> if __name__ == "__main__"
8
+ # import sys
9
+ # sys.path.append(os.getcwd())
10
+
11
+ from quick_pp.modelling.config import MODELLING_CONFIG, RAW_FEATURES
12
+ from quick_pp.modelling.utils import get_latest_registered_models, unique_id, run_mlflow_server
13
+
14
+
15
+ def load_data(hash: str) -> pd.DataFrame:
16
+ """Load data from the specified directory using a hash to identify the file.
17
+
18
+ Args:
19
+ hash (str): Hash to identify the file.
20
+
21
+ Raises:
22
+ FileNotFoundError: If no file is found with the specified hash.
23
+
24
+ Returns:
25
+ pd.DataFrame: Loaded DataFrame.
26
+ """
27
+ data_dir = Path("data/input/")
28
+ matching_files = list(data_dir.glob(f"*{hash}*.parquet"))
29
+ if not matching_files:
30
+ raise FileNotFoundError(f"No file found in {data_dir} containing hash '{hash}'")
31
+ path = matching_files[0]
32
+ return pd.read_parquet(path)
33
+
34
+
35
+ def postprocess_data(df: pd.DataFrame) -> pd.DataFrame:
36
+ """Postprocess the DataFrame by inverting LOG_PERM to PERM if needed.
37
+
38
+ Args:
39
+ df (pd.DataFrame): DataFrame to postprocess.
40
+
41
+ Returns:
42
+ pd.DataFrame: Postprocessed DataFrame.
43
+ """
44
+ # Invert LOG_PERM to PERM if exists
45
+ if 'LOG_PERM' in df.columns and 'PERM' not in df.columns:
46
+ df['PERM'] = 10 ** df['LOG_PERM']
47
+ return df
48
+
49
+
50
+ def save_predictions(pred_df: pd.DataFrame, output_file_name: str):
51
+ """Save the predictions DataFrame to a Parquet file.
52
+
53
+ Args:
54
+ pred_df (pd.DataFrame): DataFrame containing predictions.
55
+ output_file_name (str): Base name for the output file.
56
+ """
57
+ hash = unique_id(pred_df)
58
+ output_dir = Path("data/output/")
59
+ os.makedirs(output_dir, exist_ok=True)
60
+ output_path = Path(f"{output_dir}/{output_file_name}_{hash}.parquet")
61
+ pred_df.to_parquet(output_path, index=False)
62
+ print(f"Predictions saved to {output_path}")
63
+
64
+
65
+ def predict_pipeline(model_config: str, data_hash: str, output_file_name: str, env: str = 'local'):
66
+ """
67
+ Run the prediction pipeline: load the latest models, make predictions on input data, postprocess, and save results.
68
+
69
+ Args:
70
+ model_config (str): Model configuration key.
71
+ data_hash (str): Hash to identify the input data file.
72
+ output_file_name (str): Base name for the output predictions file.
73
+ env (str, optional): Environment for MLflow server. Defaults to 'local'.
74
+ """
75
+ # Run MLflow server
76
+ run_mlflow_server(env)
77
+
78
+ # Get the information of the latest registered models
79
+ client = mlflow_tracking.MlflowClient()
80
+ latest_rms = get_latest_registered_models(client, model_config, data_hash)
81
+
82
+ # Load the data
83
+ data = load_data(data_hash)
84
+
85
+ pred_df = data[['DEPTH'] + RAW_FEATURES].copy()
86
+ for model_key, model_values in MODELLING_CONFIG[model_config].items():
87
+ targets = model_values['targets']
88
+ features = model_values['features']
89
+ reg_model_name = f'{model_config}_{model_key}_{data_hash}'
90
+ print(f"Predicting with model: {model_key} | {reg_model_name}")
91
+
92
+ # Load the model
93
+ model = load_model(latest_rms[reg_model_name]['model_uri'])
94
+
95
+ # Run predictions and concat to pred_df
96
+ preds = model.predict(data[features])
97
+ temp_df = pd.DataFrame(preds, columns=targets)
98
+ pred_df = pd.concat([pred_df, temp_df], axis=1)
99
+
100
+ # Postprocess the predictions and save
101
+ pred_df = postprocess_data(pred_df)
102
+ save_predictions(pred_df, output_file_name)
103
+
104
+
105
+ if __name__ == "__main__":
106
+ import argparse
107
+
108
+ parser = argparse.ArgumentParser(description="Prediction pipeline")
109
+ parser.add_argument("--model-config", type=str, required=True, help="Path to model config")
110
+ parser.add_argument("--data", type=str, required=True, help="Path to input data parquet file")
111
+ parser.add_argument("--output", type=str, default='test', help="Path to save predictions parquet file")
112
+ args = parser.parse_args()
113
+
114
+ # Set up MLflow
115
+ os.makedirs('data/output', exist_ok=True)
116
+
117
+ print(args.model_config)
118
+ print(args.data)
119
+
120
+ predict_pipeline(args.model_config, args.data, args.output)
@@ -0,0 +1,177 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+ from pathlib import Path
4
+ from sklearn.model_selection import train_test_split
5
+ from sklearn.metrics import r2_score, mean_absolute_error, f1_score, accuracy_score
6
+ import mlflow
7
+ import mlflow.sklearn as mlflow_sklearn
8
+ from mlflow.models.signature import infer_signature
9
+
10
+ # # Uncomment below 3 lines to run >> if __name__ == "__main__"
11
+ # import os
12
+ # import sys
13
+ # sys.path.append(os.getcwd())
14
+
15
+ from quick_pp.modelling.config import MODELLING_CONFIG
16
+ from quick_pp.modelling.utils import run_mlflow_server
17
+
18
+
19
+ def load_data(hash: str):
20
+ """Load data from the specified directory using a hash to identify the file.
21
+
22
+ Args:
23
+ hash (str): Hash to identify the file.
24
+
25
+ Raises:
26
+ FileNotFoundError: If no file is found with the specified hash.
27
+
28
+ Returns:
29
+ pd.DataFrame: Loaded DataFrame.
30
+ """
31
+ data_dir = Path("data/input/")
32
+ matching_files = list(data_dir.glob(f"*{hash}*.parquet"))
33
+ if not matching_files:
34
+ raise FileNotFoundError(f"No file found in {data_dir} containing hash '{hash}'")
35
+ path = matching_files[0]
36
+ return pd.read_parquet(path)
37
+
38
+
39
+ def preprocess_data(
40
+ df: pd.DataFrame, target_column: list[str], features: list[str]) -> tuple[pd.DataFrame, pd.DataFrame]:
41
+ """Preprocess the DataFrame by adding a log-perm column if needed and dropping rows with NaN values.
42
+
43
+ Args:
44
+ df (pd.DataFrame): DataFrame to preprocess.
45
+ target_column (list[str]): Target column(s) for the model.
46
+ features (list[str]): Feature columns for the model.
47
+
48
+ Returns:
49
+ tuple[pd.DataFrame, pd.DataFrame]: Tuple containing the features DataFrame and target DataFrame.
50
+ """
51
+ # Add log perm if not already present
52
+ if 'LOG_PERM' not in df.columns and 'PERM' in df.columns and (
53
+ 'LOG_PERM' in target_column or 'LOG_PERM' in features):
54
+ df['LOG_PERM'] = np.log10(df['PERM'].clip(lower=1e-3))
55
+
56
+ # Drop rows with NaN in target or features
57
+ return_df = df.dropna(subset=target_column + features)
58
+ X = return_df[features]
59
+ y = return_df[target_column]
60
+ return X, y
61
+
62
+
63
+ def split_data(X, y, test_size=0.2, random_state=42) -> list:
64
+ """Split the data into training and testing sets.
65
+
66
+ Args:
67
+ X (pd.DataFrame): Feature DataFrame.
68
+ y (pd.DataFrame): Target DataFrame.
69
+ test_size (float, optional): Proportion of the dataset to include in the test split. Defaults to 0.2.
70
+ random_state (int, optional): Random seed for reproducibility. Defaults to 42.
71
+
72
+ Returns:
73
+ list: List containing the training and testing sets for features and target.
74
+ """
75
+ return train_test_split(X, y, test_size=test_size, random_state=random_state)
76
+
77
+
78
+ def train_model(alg, X_train: pd.DataFrame, y_train: pd.DataFrame):
79
+ """Train the model using the specified algorithm.
80
+
81
+ Args:
82
+ alg (_type_): Algorithm to use for training.
83
+ X_train (pd.DataFrame): Feature DataFrame.
84
+ y_train (pd.DataFrame): Target DataFrame.
85
+
86
+ Returns:
87
+ _type_: _description_
88
+ """
89
+ model = alg(random_state=42)
90
+ model.fit(X_train, y_train)
91
+ return model
92
+
93
+
94
+ def evaluate_model(model, X_test: pd.DataFrame, y_test: pd.DataFrame) -> dict:
95
+ """Evaluate the model using the test data.
96
+
97
+ Args:
98
+ model (_type_): Trained model to evaluate.
99
+ X_test (pd.DataFrame): Feature DataFrame for testing.
100
+ y_test (pd.DataFrame): Target DataFrame for testing.
101
+
102
+ Returns:
103
+ dict: Dictionary containing evaluation metrics.
104
+ """
105
+ y_pred = model.predict(X_test)
106
+
107
+ # Check model type
108
+ if hasattr(model, "predict_proba"):
109
+ return dict(
110
+ f1_score=f1_score(y_test, y_pred),
111
+ accuracy=accuracy_score(y_test, y_pred),
112
+ )
113
+ else:
114
+ return dict(
115
+ r2_score=r2_score(y_test, y_pred),
116
+ mean_absolute_error=mean_absolute_error(y_test, y_pred),
117
+ )
118
+
119
+
120
+ # 6. Train pipeline
121
+ def train_pipeline(model_config: str, data_hash: str, env: str = 'local'):
122
+ """This function automates the process of training, evaluating, and logging multiple models as defined in
123
+ a configuration, leveraging MLflow for experiment tracking and model management.
124
+
125
+ Args:
126
+ model_config (str): Key for the model configuration in the MODELLING_CONFIG dictionary.
127
+ data_hash (str): Hash to identify the data file in the 'data/input/' directory.
128
+ env (str, optional): MLflow environment to use. Defaults to 'local'.
129
+
130
+ Raises:
131
+ TypeError: If the targets or features are not lists of strings.
132
+ """
133
+ # Run MLflow server
134
+ run_mlflow_server(env)
135
+
136
+ for model_key, model_values in MODELLING_CONFIG[model_config].items():
137
+ alg = model_values['alg']
138
+ targets = model_values['targets']
139
+ features = model_values['features']
140
+
141
+ if not (isinstance(targets, list) and all(isinstance(t, str) for t in targets)):
142
+ raise TypeError(f"Targets must be a list of strings, got {targets}")
143
+ if not (isinstance(features, list) and all(isinstance(f, str) for f in features)):
144
+ raise TypeError(f"Features must be a list of strings, got {features}")
145
+
146
+ df = load_data(data_hash)
147
+ X, y = preprocess_data(df, targets, features)
148
+ X_train, X_test, y_train, y_test = split_data(X, y)
149
+ mlflow.set_experiment(model_config)
150
+ with mlflow.start_run(run_name=model_key, description=str(model_values['description'])):
151
+ # Train model
152
+ model = train_model(alg, X_train, y_train)
153
+
154
+ # Log metrics
155
+ metrics_dict = evaluate_model(model, X_test, y_test)
156
+ for metric_name, metric_value in metrics_dict.items():
157
+ mlflow.log_metric(metric_name, float(metric_value))
158
+
159
+ # Log model
160
+ reg_model_name = f'{model_config}_{model_key}_{data_hash}'
161
+ signature = infer_signature(X_train, y_train)
162
+ mlflow_sklearn.log_model(
163
+ model, "model", signature=signature, input_example=X_test.sample(5),
164
+ registered_model_name=reg_model_name)
165
+
166
+
167
+ if __name__ == "__main__":
168
+ import os
169
+
170
+ # Set up MLflow
171
+ os.makedirs('./mlruns', exist_ok=True)
172
+ os.makedirs('data/input', exist_ok=True)
173
+
174
+ # Example usage
175
+ data_hash = "x2x2" # Update with your hash for your data in the 'data/input/' folder
176
+ model_config = "carbonate" # Update with your model config
177
+ train_pipeline(model_config, data_hash)