quick-pp 0.2.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- quick_pp/__init__.py +0 -0
- quick_pp/api/__init__.py +0 -0
- quick_pp/api/exceptions.py +61 -0
- quick_pp/api/fastapi_mlflow/__init__.py +1 -0
- quick_pp/api/fastapi_mlflow/_mlflow_types.py +59 -0
- quick_pp/api/fastapi_mlflow/applications.py +72 -0
- quick_pp/api/fastapi_mlflow/exceptions.py +22 -0
- quick_pp/api/fastapi_mlflow/predictors.py +96 -0
- quick_pp/api/main.py +90 -0
- quick_pp/api/mlflow_model_deployment.py +99 -0
- quick_pp/api/qpp_assistant.py +160 -0
- quick_pp/api/router.py +18 -0
- quick_pp/api/schemas/lithology_hc_correction.py +39 -0
- quick_pp/api/schemas/lithology_ssc.py +37 -0
- quick_pp/api/schemas/lithology_vsh_gr.py +25 -0
- quick_pp/api/schemas/permeability_choo.py +25 -0
- quick_pp/api/schemas/permeability_others.py +24 -0
- quick_pp/api/schemas/porosity.py +22 -0
- quick_pp/api/schemas/ressum.py +29 -0
- quick_pp/api/schemas/saturation_archie.py +25 -0
- quick_pp/api/schemas/saturation_b.py +24 -0
- quick_pp/api/schemas/saturation_qv.py +26 -0
- quick_pp/api/schemas/saturation_rw.py +24 -0
- quick_pp/api/schemas/saturation_temp_grad.py +24 -0
- quick_pp/api/schemas/saturation_waxman_smits.py +28 -0
- quick_pp/api/services/las_handler.py +136 -0
- quick_pp/api/services/lithology.py +278 -0
- quick_pp/api/services/permeability.py +252 -0
- quick_pp/api/services/porosity.py +151 -0
- quick_pp/api/services/reservoir_summary.py +78 -0
- quick_pp/api/services/saturation.py +359 -0
- quick_pp/api/static/favicon.ico +0 -0
- quick_pp/api/static/logo.png +0 -0
- quick_pp/cli.py +118 -0
- quick_pp/config.py +94 -0
- quick_pp/core_calibration.py +394 -0
- quick_pp/fluid_type.py +128 -0
- quick_pp/geomechanics.py +195 -0
- quick_pp/las_handler.py +327 -0
- quick_pp/lithology/__init__.py +80 -0
- quick_pp/lithology/carbonate.py +166 -0
- quick_pp/lithology/multi_mineral.py +151 -0
- quick_pp/lithology/sand_shale.py +79 -0
- quick_pp/lithology/sand_silt_clay.py +131 -0
- quick_pp/logger.py +19 -0
- quick_pp/modelling/__init__.py +0 -0
- quick_pp/modelling/config.py +72 -0
- quick_pp/modelling/mock_data/mock_data.parquet +0 -0
- quick_pp/modelling/predict_pipeline.py +126 -0
- quick_pp/modelling/train_pipeline.py +220 -0
- quick_pp/modelling/utils.py +111 -0
- quick_pp/objects.py +177 -0
- quick_pp/permeability.py +151 -0
- quick_pp/plotter/__init__.py +0 -0
- quick_pp/plotter/plotter.py +315 -0
- quick_pp/plotter/well_log.py +187 -0
- quick_pp/plotter/well_log_config.py +409 -0
- quick_pp/porosity.py +341 -0
- quick_pp/qaqc.py +436 -0
- quick_pp/ressum.py +326 -0
- quick_pp/rock_type.py +499 -0
- quick_pp/saturation.py +455 -0
- quick_pp/utils.py +328 -0
- quick_pp-0.2.3.dist-info/METADATA +103 -0
- quick_pp-0.2.3.dist-info/RECORD +69 -0
- quick_pp-0.2.3.dist-info/WHEEL +4 -0
- quick_pp-0.2.3.dist-info/entry_points.txt +2 -0
- quick_pp-0.2.3.dist-info/licenses/AUTHORS.rst +13 -0
- quick_pp-0.2.3.dist-info/licenses/LICENSE +22 -0
|
@@ -0,0 +1,126 @@
|
|
|
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
|
+
from quick_pp.logger import logger
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def load_data(hash: str) -> pd.DataFrame:
|
|
17
|
+
"""Load data from the specified directory using a hash to identify the file.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
hash (str): Hash to identify the file.
|
|
21
|
+
|
|
22
|
+
Raises:
|
|
23
|
+
FileNotFoundError: If no file is found with the specified hash.
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
pd.DataFrame: Loaded DataFrame.
|
|
27
|
+
"""
|
|
28
|
+
data_dir = Path("data/input/")
|
|
29
|
+
matching_files = list(data_dir.glob(f"*{hash}*.parquet"))
|
|
30
|
+
if not matching_files:
|
|
31
|
+
logger.error(f"No file found in {data_dir} containing hash '{hash}'")
|
|
32
|
+
raise FileNotFoundError(f"No file found in {data_dir} containing hash '{hash}'")
|
|
33
|
+
path = matching_files[0]
|
|
34
|
+
logger.info(f"Loading data from {path}")
|
|
35
|
+
return pd.read_parquet(path)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def postprocess_data(df: pd.DataFrame) -> pd.DataFrame:
|
|
39
|
+
"""Postprocess the DataFrame by inverting LOG_PERM to PERM if needed.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
df (pd.DataFrame): DataFrame to postprocess.
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
pd.DataFrame: Postprocessed DataFrame.
|
|
46
|
+
"""
|
|
47
|
+
# Invert LOG_PERM to PERM if exists
|
|
48
|
+
if 'LOG_PERM' in df.columns and 'PERM' not in df.columns:
|
|
49
|
+
logger.info("Inverting LOG_PERM to PERM")
|
|
50
|
+
df['PERM'] = 10 ** df['LOG_PERM']
|
|
51
|
+
return df
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def save_predictions(pred_df: pd.DataFrame, output_file_name: str):
|
|
55
|
+
"""Save the predictions DataFrame to a Parquet file.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
pred_df (pd.DataFrame): DataFrame containing predictions.
|
|
59
|
+
output_file_name (str): Base name for the output file.
|
|
60
|
+
"""
|
|
61
|
+
hash = unique_id(pred_df)
|
|
62
|
+
output_dir = Path("data/output/")
|
|
63
|
+
os.makedirs(output_dir, exist_ok=True)
|
|
64
|
+
output_path = Path(f"{output_dir}/{output_file_name}_{hash}.parquet")
|
|
65
|
+
pred_df.to_parquet(output_path, index=False)
|
|
66
|
+
logger.info(f"Predictions saved to {output_path}")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def predict_pipeline(model_config: str, data_hash: str, output_file_name: str, env: str = 'local'):
|
|
70
|
+
"""
|
|
71
|
+
Run the prediction pipeline: load the latest models, make predictions on input data, postprocess, and save results.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
model_config (str): Model configuration key.
|
|
75
|
+
data_hash (str): Hash to identify the input data file.
|
|
76
|
+
output_file_name (str): Base name for the output predictions file.
|
|
77
|
+
env (str, optional): Environment for MLflow server. Defaults to 'local'.
|
|
78
|
+
"""
|
|
79
|
+
logger.info("Starting prediction pipeline")
|
|
80
|
+
# Run MLflow server
|
|
81
|
+
run_mlflow_server(env)
|
|
82
|
+
|
|
83
|
+
# Get the information of the latest registered models
|
|
84
|
+
client = mlflow_tracking.MlflowClient()
|
|
85
|
+
latest_rms = get_latest_registered_models(client, model_config, data_hash)
|
|
86
|
+
|
|
87
|
+
# Load the data
|
|
88
|
+
data = load_data(data_hash)
|
|
89
|
+
|
|
90
|
+
pred_df = data[['DEPTH'] + RAW_FEATURES].copy()
|
|
91
|
+
for model_key, model_values in MODELLING_CONFIG[model_config].items():
|
|
92
|
+
targets = model_values['targets']
|
|
93
|
+
features = model_values['features']
|
|
94
|
+
reg_model_name = f'{model_config}_{model_key}_{data_hash}'
|
|
95
|
+
logger.info(f"Predicting with model: {model_key} | {reg_model_name}")
|
|
96
|
+
|
|
97
|
+
# Load the model
|
|
98
|
+
model = load_model(latest_rms[reg_model_name]['model_uri'])
|
|
99
|
+
|
|
100
|
+
# Run predictions and concat to pred_df
|
|
101
|
+
preds = model.predict(data[features])
|
|
102
|
+
temp_df = pd.DataFrame(preds, columns=targets)
|
|
103
|
+
pred_df = pd.concat([pred_df, temp_df], axis=1)
|
|
104
|
+
|
|
105
|
+
# Postprocess the predictions and save
|
|
106
|
+
pred_df = postprocess_data(pred_df)
|
|
107
|
+
save_predictions(pred_df, output_file_name)
|
|
108
|
+
logger.info("Prediction pipeline completed successfully")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
if __name__ == "__main__":
|
|
112
|
+
import argparse
|
|
113
|
+
|
|
114
|
+
parser = argparse.ArgumentParser(description="Prediction pipeline")
|
|
115
|
+
parser.add_argument("--model-config", type=str, required=True, help="Path to model config")
|
|
116
|
+
parser.add_argument("--data", type=str, required=True, help="Path to input data parquet file")
|
|
117
|
+
parser.add_argument("--output", type=str, default='test', help="Path to save predictions parquet file")
|
|
118
|
+
args = parser.parse_args()
|
|
119
|
+
|
|
120
|
+
# Set up MLflow
|
|
121
|
+
os.makedirs('data/output', exist_ok=True)
|
|
122
|
+
|
|
123
|
+
logger.info(f"Model config: {args.model_config}")
|
|
124
|
+
logger.info(f"Data hash: {args.data}")
|
|
125
|
+
|
|
126
|
+
predict_pipeline(args.model_config, args.data, args.output)
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
import numpy as np
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from sklearn.model_selection import train_test_split
|
|
6
|
+
from sklearn.metrics import r2_score, mean_absolute_error, f1_score, accuracy_score
|
|
7
|
+
import mlflow
|
|
8
|
+
import mlflow.sklearn as mlflow_sklearn
|
|
9
|
+
from mlflow.models.signature import infer_signature
|
|
10
|
+
import importlib.util
|
|
11
|
+
|
|
12
|
+
# # Uncomment below 3 lines to run >> if __name__ == "__main__"
|
|
13
|
+
# import sys
|
|
14
|
+
# sys.path.append(os.getcwd())
|
|
15
|
+
|
|
16
|
+
from quick_pp.modelling.config import MODELLING_CONFIG
|
|
17
|
+
from quick_pp.modelling.utils import run_mlflow_server
|
|
18
|
+
from quick_pp.logger import logger
|
|
19
|
+
|
|
20
|
+
# Check if config.py exists in the root directory and update MODELLING_CONFIG if found
|
|
21
|
+
root_config_path = Path(os.getcwd(), "config.py")
|
|
22
|
+
if root_config_path.exists():
|
|
23
|
+
try:
|
|
24
|
+
spec = importlib.util.spec_from_file_location("root_config", root_config_path)
|
|
25
|
+
root_config = importlib.util.module_from_spec(spec)
|
|
26
|
+
spec.loader.exec_module(root_config)
|
|
27
|
+
if hasattr(root_config, "MODELLING_CONFIG"):
|
|
28
|
+
logger.info("Updating MODELLING_CONFIG from root config.py")
|
|
29
|
+
MODELLING_CONFIG.clear()
|
|
30
|
+
MODELLING_CONFIG.update(root_config.MODELLING_CONFIG)
|
|
31
|
+
else:
|
|
32
|
+
logger.warning("MODELLING_CONFIG not found in root config.py, using default MODELLING_CONFIG")
|
|
33
|
+
except Exception as e:
|
|
34
|
+
logger.warning(f"Could not import MODELLING_CONFIG from root config.py: {e}")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def load_data(hash: str):
|
|
38
|
+
"""Load data from the specified directory using a hash to identify the file.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
hash (str): Hash to identify the file.
|
|
42
|
+
|
|
43
|
+
Raises:
|
|
44
|
+
FileNotFoundError: If no file is found with the specified hash.
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
pd.DataFrame: Loaded DataFrame.
|
|
48
|
+
"""
|
|
49
|
+
data_dir = Path("data/input/")
|
|
50
|
+
matching_files = list(data_dir.glob(f"*{hash}*.parquet"))
|
|
51
|
+
if not matching_files:
|
|
52
|
+
raise FileNotFoundError(f"No file found in {data_dir} containing hash '{hash}'")
|
|
53
|
+
path = matching_files[0]
|
|
54
|
+
return pd.read_parquet(path)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def preprocess_data(
|
|
58
|
+
df: pd.DataFrame, target_column: list[str], features: list[str]) -> tuple[pd.DataFrame, pd.DataFrame]:
|
|
59
|
+
"""Preprocess the DataFrame by adding a log-perm column if needed and dropping rows with NaN values.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
df (pd.DataFrame): DataFrame to preprocess.
|
|
63
|
+
target_column (list[str]): Target column(s) for the model.
|
|
64
|
+
features (list[str]): Feature columns for the model.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
tuple[pd.DataFrame, pd.DataFrame]: Tuple containing the features DataFrame and target DataFrame.
|
|
68
|
+
"""
|
|
69
|
+
# Add log perm if not already present
|
|
70
|
+
if 'LOG_PERM' not in df.columns and 'PERM' in df.columns and (
|
|
71
|
+
'LOG_PERM' in target_column or 'LOG_PERM' in features):
|
|
72
|
+
df['LOG_PERM'] = np.log10(df['PERM'].clip(lower=1e-3))
|
|
73
|
+
|
|
74
|
+
# Drop rows with NaN in target or features
|
|
75
|
+
return_df = df.dropna(subset=target_column + features)
|
|
76
|
+
X = return_df[features]
|
|
77
|
+
y = return_df[target_column]
|
|
78
|
+
return X, y
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def split_data(X, y, test_size=0.2, random_state=42) -> list:
|
|
82
|
+
"""Split the data into training and testing sets.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
X (pd.DataFrame): Feature DataFrame.
|
|
86
|
+
y (pd.DataFrame): Target DataFrame.
|
|
87
|
+
test_size (float, optional): Proportion of the dataset to include in the test split. Defaults to 0.2.
|
|
88
|
+
random_state (int, optional): Random seed for reproducibility. Defaults to 42.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
list: List containing the training and testing sets for features and target.
|
|
92
|
+
"""
|
|
93
|
+
return train_test_split(X, y, test_size=test_size, random_state=random_state)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def train_model(alg, X_train: pd.DataFrame, y_train: pd.DataFrame):
|
|
97
|
+
"""Train the model using the specified algorithm.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
alg (_type_): Algorithm to use for training.
|
|
101
|
+
X_train (pd.DataFrame): Feature DataFrame.
|
|
102
|
+
y_train (pd.DataFrame): Target DataFrame.
|
|
103
|
+
|
|
104
|
+
Returns:
|
|
105
|
+
_type_: _description_
|
|
106
|
+
"""
|
|
107
|
+
logger.info(f"Training model: {getattr(alg, '__name__', str(alg))}")
|
|
108
|
+
model = alg(random_state=42)
|
|
109
|
+
model.fit(X_train, y_train)
|
|
110
|
+
logger.debug("Model training complete")
|
|
111
|
+
return model
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def evaluate_model(model, X_test: pd.DataFrame, y_test: pd.DataFrame) -> dict:
|
|
115
|
+
"""Evaluate the model using the test data.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
model (_type_): Trained model to evaluate.
|
|
119
|
+
X_test (pd.DataFrame): Feature DataFrame for testing.
|
|
120
|
+
y_test (pd.DataFrame): Target DataFrame for testing.
|
|
121
|
+
|
|
122
|
+
Returns:
|
|
123
|
+
dict: Dictionary containing evaluation metrics.
|
|
124
|
+
"""
|
|
125
|
+
logger.info(f"Evaluating model: {type(model).__name__}")
|
|
126
|
+
y_pred = model.predict(X_test)
|
|
127
|
+
|
|
128
|
+
# Check model type
|
|
129
|
+
if hasattr(model, "predict_proba"):
|
|
130
|
+
logger.debug("Classification metrics calculated")
|
|
131
|
+
return dict(
|
|
132
|
+
f1_score=f1_score(y_test, y_pred),
|
|
133
|
+
accuracy=accuracy_score(y_test, y_pred),
|
|
134
|
+
)
|
|
135
|
+
else:
|
|
136
|
+
logger.debug("Regression metrics calculated")
|
|
137
|
+
return dict(
|
|
138
|
+
r2_score=r2_score(y_test, y_pred),
|
|
139
|
+
mean_absolute_error=mean_absolute_error(y_test, y_pred),
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# 6. Train pipeline
|
|
144
|
+
def train_pipeline(model_config: str, data_hash: str, env: str = 'local'):
|
|
145
|
+
"""This function automates the process of training, evaluating, and logging multiple models as defined in
|
|
146
|
+
a configuration, leveraging MLflow for experiment tracking and model management.
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
model_config (str): Key for the model configuration in the MODELLING_CONFIG dictionary.
|
|
150
|
+
data_hash (str): Hash to identify the data file in the 'data/input/' directory.
|
|
151
|
+
env (str, optional): MLflow environment to use. Defaults to 'local'.
|
|
152
|
+
|
|
153
|
+
Raises:
|
|
154
|
+
TypeError: If the targets or features are not lists of strings.
|
|
155
|
+
"""
|
|
156
|
+
logger.info(f"Starting train_pipeline with model_config={model_config}, data_hash={data_hash}, env={env}")
|
|
157
|
+
|
|
158
|
+
# Check if the model_config exists in MODELLING_CONFIG
|
|
159
|
+
if model_config not in MODELLING_CONFIG:
|
|
160
|
+
error_msg = f"Model configuration '{model_config}' not found in MODELLING_CONFIG"
|
|
161
|
+
logger.error(error_msg)
|
|
162
|
+
raise ValueError(error_msg)
|
|
163
|
+
|
|
164
|
+
# Run MLflow server
|
|
165
|
+
run_mlflow_server(env)
|
|
166
|
+
|
|
167
|
+
for model_key, model_values in MODELLING_CONFIG[model_config].items():
|
|
168
|
+
alg = model_values['alg']
|
|
169
|
+
targets = model_values['targets']
|
|
170
|
+
features = model_values['features']
|
|
171
|
+
|
|
172
|
+
logger.info(f"Processing model: {model_key}")
|
|
173
|
+
if not (isinstance(targets, list) and all(isinstance(t, str) for t in targets)):
|
|
174
|
+
logger.error(f"Targets must be a list of strings, got {targets}")
|
|
175
|
+
raise TypeError(f"Targets must be a list of strings, got {targets}")
|
|
176
|
+
if not (isinstance(features, list) and all(isinstance(f, str) for f in features)):
|
|
177
|
+
logger.error(f"Features must be a list of strings, got {features}")
|
|
178
|
+
raise TypeError(f"Features must be a list of strings, got {features}")
|
|
179
|
+
|
|
180
|
+
df = load_data(data_hash)
|
|
181
|
+
# Skip if targets or features are not in the DataFrame
|
|
182
|
+
if not all(col in df.columns for col in targets + features):
|
|
183
|
+
missing_cols = [col for col in targets + features if col not in df.columns]
|
|
184
|
+
logger.warning(f"Skipping model {model_key} due to missing columns: {missing_cols}")
|
|
185
|
+
continue
|
|
186
|
+
X, y = preprocess_data(df, targets, features)
|
|
187
|
+
X_train, X_test, y_train, y_test = split_data(X, y)
|
|
188
|
+
|
|
189
|
+
mlflow_dir = Path('./mlruns')
|
|
190
|
+
os.makedirs(mlflow_dir, exist_ok=True)
|
|
191
|
+
mlflow.set_experiment(model_config)
|
|
192
|
+
with mlflow.start_run(run_name=model_key, description=str(model_values['description'])):
|
|
193
|
+
# Train model
|
|
194
|
+
model = train_model(alg, X_train, y_train)
|
|
195
|
+
|
|
196
|
+
# Log metrics
|
|
197
|
+
metrics_dict = evaluate_model(model, X_test, y_test)
|
|
198
|
+
for metric_name, metric_value in metrics_dict.items():
|
|
199
|
+
mlflow.log_metric(metric_name, float(metric_value))
|
|
200
|
+
logger.info(f"Logged metric: {metric_name}={metric_value}")
|
|
201
|
+
|
|
202
|
+
# Log model
|
|
203
|
+
reg_model_name = f'{model_config}_{model_key}_{data_hash}'
|
|
204
|
+
signature = infer_signature(X_train, y_train)
|
|
205
|
+
mlflow_sklearn.log_model(
|
|
206
|
+
model, "model", signature=signature, input_example=X_test.sample(5),
|
|
207
|
+
registered_model_name=reg_model_name)
|
|
208
|
+
logger.info(f"Model logged and registered as: {reg_model_name}")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
if __name__ == "__main__":
|
|
212
|
+
|
|
213
|
+
# Set up folders
|
|
214
|
+
os.makedirs('./mlruns', exist_ok=True)
|
|
215
|
+
os.makedirs('data/input', exist_ok=True)
|
|
216
|
+
|
|
217
|
+
# Example usage
|
|
218
|
+
data_hash = "x2x2" # Update with your hash for your data in the 'data/input/' folder
|
|
219
|
+
model_config = "carbonate" # Update with your model config
|
|
220
|
+
train_pipeline(model_config, data_hash)
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
from pandas.util import hash_pandas_object
|
|
3
|
+
import os
|
|
4
|
+
import mlflow
|
|
5
|
+
from mlflow.tracking import MlflowClient
|
|
6
|
+
import socket
|
|
7
|
+
from subprocess import Popen
|
|
8
|
+
from hashlib import sha256
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from quick_pp.modelling.config import MLFLOW_CONFIG
|
|
12
|
+
from quick_pp.logger import logger
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def unique_id(df: pd.DataFrame) -> str:
|
|
16
|
+
"""Generate a unique ID for the DataFrame based on its content.
|
|
17
|
+
Args:
|
|
18
|
+
df (pd.DataFrame): DataFrame to hash.
|
|
19
|
+
Returns:
|
|
20
|
+
str: Unique ID for the DataFrame.
|
|
21
|
+
"""
|
|
22
|
+
# Hash the DataFrame content and convert to hex string
|
|
23
|
+
uid = sha256(hash_pandas_object(df, index=True).to_numpy().tobytes()).hexdigest()[:8]
|
|
24
|
+
logger.debug(f"Generated unique_id: {uid}")
|
|
25
|
+
return uid
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def is_mlflow_server_running(host, port):
|
|
29
|
+
"""Check if the MLflow server is running on the specified host and port.
|
|
30
|
+
Args:
|
|
31
|
+
host (str): Hostname or IP address of the MLflow server.
|
|
32
|
+
port (int): Port number of the MLflow server.
|
|
33
|
+
Returns:
|
|
34
|
+
bool: True if the server is running, False otherwise.
|
|
35
|
+
"""
|
|
36
|
+
try:
|
|
37
|
+
with socket.create_connection((host, int(port)), timeout=2):
|
|
38
|
+
logger.debug(f"MLflow server is running at {host}:{port}")
|
|
39
|
+
return True
|
|
40
|
+
except Exception as e:
|
|
41
|
+
logger.debug(f"MLflow server not running at {host}:{port}: {e}")
|
|
42
|
+
return False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def run_mlflow_server(env):
|
|
46
|
+
"""
|
|
47
|
+
Starts an MLflow tracking server if it is not already running for the specified environment,
|
|
48
|
+
and sets the MLflow tracking URI accordingly.
|
|
49
|
+
Args:
|
|
50
|
+
env (str): The environment key to select the MLflow server configuration from MLFLOW_CONFIG.
|
|
51
|
+
Raises:
|
|
52
|
+
KeyError: If the specified environment is not found in MLFLOW_CONFIG.
|
|
53
|
+
Side Effects:
|
|
54
|
+
- Starts an MLflow server process if one is not already running for the given environment.
|
|
55
|
+
- Sets the MLflow tracking URI for the current process.
|
|
56
|
+
- Prints status messages to the console.
|
|
57
|
+
"""
|
|
58
|
+
mlruns_dir = Path(str(MLFLOW_CONFIG[env]['artifact_location']))
|
|
59
|
+
os.makedirs(mlruns_dir, exist_ok=True)
|
|
60
|
+
mlflog_config = MLFLOW_CONFIG[env]
|
|
61
|
+
if not is_mlflow_server_running(mlflog_config['tracking_host'], mlflog_config['tracking_port']):
|
|
62
|
+
cmd_mlflow_server = (
|
|
63
|
+
f"mlflow server --backend-store-uri {mlflog_config['backend_store_uri']} "
|
|
64
|
+
f"--default-artifact-root {mlflog_config['artifact_location']} "
|
|
65
|
+
f"--host {mlflog_config['tracking_host']} "
|
|
66
|
+
f"--port {mlflog_config['tracking_port']}"
|
|
67
|
+
)
|
|
68
|
+
logger.warning(f"MLflow server is not running. Starting it now... | {cmd_mlflow_server}")
|
|
69
|
+
Popen(cmd_mlflow_server, shell=True)
|
|
70
|
+
logger.info("MLflow server started successfully.")
|
|
71
|
+
|
|
72
|
+
mlflow.set_tracking_uri(
|
|
73
|
+
f"http://{MLFLOW_CONFIG[env]['tracking_host']}:{MLFLOW_CONFIG[env]['tracking_port']}")
|
|
74
|
+
logger.info(f"MLflow tracking URI set to: {mlflow.get_tracking_uri()}")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def get_model_info(registered_model):
|
|
78
|
+
"""Extract information of the registered models to load models automatically for predictions.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
registered_model (class): Model that has been loaded and registered
|
|
82
|
+
"""
|
|
83
|
+
model_info = {}
|
|
84
|
+
for model in registered_model:
|
|
85
|
+
model_info['reg_model_name'] = model.name
|
|
86
|
+
model_info['run_id'] = model.run_id
|
|
87
|
+
model_info['version'] = model.version
|
|
88
|
+
model_info['model_uri'] = model.source
|
|
89
|
+
model_info['stage'] = model.current_stage
|
|
90
|
+
logger.debug(f"Extracted model info: {model_info}")
|
|
91
|
+
return model_info
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def get_latest_registered_models(client: MlflowClient, experiment_name: str, data_hash: str) -> dict:
|
|
95
|
+
"""Get the latest registered models from MLflow.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
client (MlflowClient): MLflow client to interact with the tracking server.
|
|
99
|
+
experiment_name (str): Name of the experiment to filter registered models.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
dict: Dictionary containing the latest registered models with their details.
|
|
103
|
+
"""
|
|
104
|
+
latest_rm_models = {}
|
|
105
|
+
filter_str = f"name ILIKE '{experiment_name}%' AND name like '%{data_hash}'"
|
|
106
|
+
logger.info(f"Searching for registered models with filter: {filter_str}")
|
|
107
|
+
for rm in client.search_registered_models(filter_string=filter_str):
|
|
108
|
+
latest_rm_info = get_model_info(rm.latest_versions)
|
|
109
|
+
latest_rm_models[latest_rm_info['reg_model_name']] = latest_rm_info
|
|
110
|
+
logger.info(f"Adding {latest_rm_info['reg_model_name']} to latest_rm_models dictionary")
|
|
111
|
+
return latest_rm_models
|
quick_pp/objects.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
import getpass
|
|
3
|
+
import pandas as pd
|
|
4
|
+
import pickle
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
import quick_pp.las_handler as las
|
|
8
|
+
from quick_pp.config import Config
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Project(object):
|
|
12
|
+
def __init__(self, name="", description="", project_path=""):
|
|
13
|
+
self.name = name
|
|
14
|
+
self.description = description
|
|
15
|
+
self.data = {}
|
|
16
|
+
self.history = []
|
|
17
|
+
self.project_path = project_path or os.path.join("data", "04_project")
|
|
18
|
+
self.data_path = os.path.join(self.project_path, self.name)
|
|
19
|
+
self.output_path = os.path.join(self.data_path, "outputs")
|
|
20
|
+
os.makedirs(self.data_path, exist_ok=True)
|
|
21
|
+
os.makedirs(self.output_path, exist_ok=True)
|
|
22
|
+
|
|
23
|
+
def read_las(self, path: list):
|
|
24
|
+
for file in path:
|
|
25
|
+
well = Well()
|
|
26
|
+
well.read_las(file)
|
|
27
|
+
self.save_well(well)
|
|
28
|
+
self.update_history(action=f"Read LAS file for project {self.name}")
|
|
29
|
+
|
|
30
|
+
def update_data(self, data: pd.DataFrame, group_by: str = "WELL_NAME"):
|
|
31
|
+
for well_name, well_data in data.groupby(group_by):
|
|
32
|
+
well = Well(well_name)
|
|
33
|
+
well.update_data(well_data)
|
|
34
|
+
self.save_well(well)
|
|
35
|
+
self.update_history(action=f"Added data to project {self.name}")
|
|
36
|
+
|
|
37
|
+
def get_all_data(self):
|
|
38
|
+
data = pd.DataFrame()
|
|
39
|
+
for well_path in self.data.values():
|
|
40
|
+
well = Well().load(well_path)
|
|
41
|
+
data = pd.concat([data, well.data])
|
|
42
|
+
return data
|
|
43
|
+
|
|
44
|
+
def get_well_names(self):
|
|
45
|
+
return list(self.data.keys())
|
|
46
|
+
|
|
47
|
+
def get_well_data(self, well_name: str):
|
|
48
|
+
well = Well().load(self.data[well_name])
|
|
49
|
+
return well.data
|
|
50
|
+
|
|
51
|
+
def get_well(self, well_name: str):
|
|
52
|
+
return Well().load(self.data[well_name])
|
|
53
|
+
|
|
54
|
+
def export_all_to_parquet(self):
|
|
55
|
+
path = os.path.join(self.output_path, f"{self.name}.parquet")
|
|
56
|
+
data = self.get_all_data()
|
|
57
|
+
data.to_parquet(path)
|
|
58
|
+
|
|
59
|
+
def export_all_to_las(self):
|
|
60
|
+
data = self.get_all_data()
|
|
61
|
+
for well_name, well_data in data.groupby("WELL_NAME"):
|
|
62
|
+
las.export_to_las(well_data=well_data, well_name=well_name, folder=self.output_path)
|
|
63
|
+
|
|
64
|
+
def save_well(self, well):
|
|
65
|
+
well_path = os.path.join(self.data_path, f"{well.name}.qppw")
|
|
66
|
+
well.save(well_path)
|
|
67
|
+
self.data.update({well.name: well_path})
|
|
68
|
+
self.update_history(action=f"Added well {well.name} to project {self.name}")
|
|
69
|
+
|
|
70
|
+
def save(self, notes=""):
|
|
71
|
+
path = os.path.join(self.project_path, f"{self.name}.qppp")
|
|
72
|
+
with open(path, "wb") as f:
|
|
73
|
+
pickle.dump(self, f)
|
|
74
|
+
self.update_history(action=f"Saved project to {path} | {notes}")
|
|
75
|
+
|
|
76
|
+
def load(self, path: str):
|
|
77
|
+
with open(path, "rb") as f:
|
|
78
|
+
project = pickle.load(f)
|
|
79
|
+
return project
|
|
80
|
+
|
|
81
|
+
def update_history(self, user=getpass.getuser(), time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), action=""):
|
|
82
|
+
self.history.append({"user": user, "time": time, "action": action})
|
|
83
|
+
|
|
84
|
+
def __str__(self):
|
|
85
|
+
return f"Project: {self.name} - {self.description}"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class WellConfig(object):
|
|
89
|
+
litho_model: str = "ssc"
|
|
90
|
+
dry_sand_point: tuple = Config.SSC_ENDPOINTS["DRY_SAND_POINT"]
|
|
91
|
+
dry_silt_point: tuple = Config.SSC_ENDPOINTS["DRY_SILT_POINT"]
|
|
92
|
+
dry_clay_point: tuple = Config.SSC_ENDPOINTS["DRY_CLAY_POINT"]
|
|
93
|
+
wet_clay_point: tuple = Config.SSC_ENDPOINTS["WET_CLAY_POINT"]
|
|
94
|
+
fluid_point: tuple = Config.SSC_ENDPOINTS["FLUID_POINT"]
|
|
95
|
+
dry_calc_point: tuple = Config.CARB_NEU_DEN_ENDPOINTS["DRY_CALC_POINT"]
|
|
96
|
+
dry_dolo_point: tuple = Config.CARB_NEU_DEN_ENDPOINTS["DRY_DOLO_POINT"]
|
|
97
|
+
silt_line_angle: float = Config.SSC_ENDPOINTS["SILT_LINE_ANGLE"]
|
|
98
|
+
sw_water_salinity: int = 6000
|
|
99
|
+
sw_m: float = 2.0
|
|
100
|
+
sw_n: float = 2.0
|
|
101
|
+
hc_corr_angle: int = 50
|
|
102
|
+
hc_buffer: float = 0.0
|
|
103
|
+
ressum_cutoffs: dict = Config.RESSUM_CUTOFFS
|
|
104
|
+
|
|
105
|
+
def update(self, config: dict):
|
|
106
|
+
for key, value in config.items():
|
|
107
|
+
setattr(self, key, value)
|
|
108
|
+
|
|
109
|
+
def __setattr__(self, name, value):
|
|
110
|
+
if hasattr(self, name):
|
|
111
|
+
# Allow modification of existing attributes
|
|
112
|
+
super().__setattr__(name, value)
|
|
113
|
+
else:
|
|
114
|
+
# Prevent adding new attributes
|
|
115
|
+
raise AttributeError(f"Cannot add new attribute '{name}' to instances of {self.__class__.__name__}")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class Well(object):
|
|
119
|
+
header: pd.DataFrame = pd.DataFrame()
|
|
120
|
+
data: pd.DataFrame = pd.DataFrame()
|
|
121
|
+
ressum: pd.DataFrame = pd.DataFrame()
|
|
122
|
+
depth_uom: str = ""
|
|
123
|
+
config: WellConfig = WellConfig()
|
|
124
|
+
history: list = []
|
|
125
|
+
|
|
126
|
+
def __init__(self, name="", description=""):
|
|
127
|
+
self.name = name
|
|
128
|
+
self.description = description
|
|
129
|
+
|
|
130
|
+
def read_las(self, path: str):
|
|
131
|
+
with open(path, "rb") as f:
|
|
132
|
+
data, header = las.read_las_files([f])
|
|
133
|
+
header_df = header.T
|
|
134
|
+
self.name = header_df[header_df['mnemonic'] == 'WELL']['value'].values[0].replace("/", "-")
|
|
135
|
+
self.description = f"Well {self.name}"
|
|
136
|
+
self.depth_uom = header_df[header_df['mnemonic'] == 'STRT']['unit'].values[0]
|
|
137
|
+
self.data = data
|
|
138
|
+
self.header = header
|
|
139
|
+
self.update_history(action=f"Read LAS file {path}")
|
|
140
|
+
|
|
141
|
+
def update_data(self, data: pd.DataFrame):
|
|
142
|
+
self.data = data
|
|
143
|
+
self.update_history(action=f"Updated data for well {self.name}")
|
|
144
|
+
|
|
145
|
+
def update_ressum(self, data: pd.DataFrame):
|
|
146
|
+
self.ressum = data
|
|
147
|
+
self.update_history(action=f"Updated ressum for well {self.name}")
|
|
148
|
+
|
|
149
|
+
def update_config(self, config: dict):
|
|
150
|
+
self.config.update(config)
|
|
151
|
+
self.update_history(action=f"Updated config for well {self.name}")
|
|
152
|
+
|
|
153
|
+
def export_to_parquet(self, folder=os.path.join("data", "04_project", "outputs")):
|
|
154
|
+
os.makedirs(folder, exist_ok=True)
|
|
155
|
+
path = os.path.join(folder, f"{self.name}.parquet")
|
|
156
|
+
self.data.to_parquet(path)
|
|
157
|
+
|
|
158
|
+
def export_to_las(self, folder=os.path.join("data", "04_project", "outputs")):
|
|
159
|
+
os.makedirs(folder, exist_ok=True)
|
|
160
|
+
las.export_to_las(well_data=self.data, well_name=self.name, folder=folder)
|
|
161
|
+
|
|
162
|
+
def save(self, path, notes=""):
|
|
163
|
+
path = path if path.endswith(".qppw") else f"{path}.qppw"
|
|
164
|
+
with open(path, "wb") as f:
|
|
165
|
+
pickle.dump(self, f)
|
|
166
|
+
self.update_history(action=f"Saved well to {path} | {notes}")
|
|
167
|
+
|
|
168
|
+
def load(self, path: str):
|
|
169
|
+
with open(path, "rb") as f:
|
|
170
|
+
well = pickle.load(f)
|
|
171
|
+
return well
|
|
172
|
+
|
|
173
|
+
def update_history(self, user=getpass.getuser(), time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), action=""):
|
|
174
|
+
self.history.append({"user": user, "time": time, "action": action})
|
|
175
|
+
|
|
176
|
+
def __str__(self):
|
|
177
|
+
return f"Well: {self.name} - {self.description}"
|