File size: 11,814 Bytes
095fc22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d595eb5
095fc22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
"""
Leachate Prediction Inference Script
Two-Stage Model: Volume → Chemistry Prediction
"""

import pickle
import json
import pandas as pd
import numpy as np
from pathlib import Path
from typing import Dict, Union, Optional


class LeachatePredictionModel:
    """
    Two-stage prediction model for leachate volume and chemistry.
    
    Stage 1: Predicts leachate volume
    Stage 2: Predicts chemical composition (if volume exceeds threshold)
    """
    
    def __init__(self, model_dir: str = 'model'):
        """
        Initialize the model by loading saved artifacts.
        
        Args:
            model_dir: Directory containing saved model files
        """
        self.model_dir = Path(model_dir)
        self._load_models()
        self._load_config()
        
    def _load_models(self):
        """Load trained models and scalers."""
        print("Loading models...")
        
        # Load Stage 1
        with open(self.model_dir / 'stage1_volume_model.pkl', 'rb') as f:
            self.stage1 = pickle.load(f)
        
        # Load Stage 2
        with open(self.model_dir / 'stage2_chemistry_models.pkl', 'rb') as f:
            self.stage2 = pickle.load(f)
            
        print(f"✓ Stage 1 model loaded")
        print(f"✓ Stage 2 loaded ({len(self.stage2['models'])} chemistry models)")
        
    def _load_config(self):
        """Load model configuration."""
        with open(self.model_dir / 'model_config.json', 'r') as f:
            self.config = json.load(f)
        print(f"✓ Configuration loaded (version {self.config['model_version']})")
        
    def predict_volume(self, input_data: Union[pd.DataFrame, Dict]) -> Dict:
        """
        Stage 1: Predict leachate volume.
        
        Args:
            input_data: Dictionary or DataFrame with rock properties and event data
            
        Returns:
            Dictionary with volume prediction and metadata
        """
        # Convert dict to DataFrame if needed
        if isinstance(input_data, dict):
            input_data = pd.DataFrame([input_data])
        
        # Ensure all required features are present
        missing_features = set(self.stage1['features']) - set(input_data.columns)
        if missing_features:
            raise ValueError(f"Missing required features: {missing_features}")
        
        # Select and order features
        X = input_data[self.stage1['features']].copy()
        
        # Scale features
        X_scaled = pd.DataFrame(
            self.stage1['scaler'].transform(X),
            columns=self.stage1['features'],
            index=X.index
        )
        
        # Predict
        volume_pred = self.stage1['model'].predict(X_scaled)[0]
        
        # Ensure non-negative volume
        volume_pred = max(0, volume_pred)
        
        return {
            'predicted_volume_ml': round(volume_pred, 2),
            'exceeds_threshold': volume_pred >= self.config['volume_threshold'],
            'threshold_ml': self.config['volume_threshold'],
            'stage1_metrics': self.stage1['metrics']
        }
    
    def predict_chemistry(self, input_data: Union[pd.DataFrame, Dict], 
                         volume: Optional[float] = None) -> Dict:
        """
        Stage 2: Predict chemical composition.
        
        Args:
            input_data: Dictionary or DataFrame with all features including volume
            volume: Optional volume value (if not in input_data)
            
        Returns:
            Dictionary with chemistry predictions
        """
        # Convert dict to DataFrame if needed
        if isinstance(input_data, dict):
            input_data = pd.DataFrame([input_data])
        
        # Add volume if provided separately
        if volume is not None:
            input_data = input_data.copy()
            input_data['Volume_leachate'] = volume
        
        # Check volume threshold
        if 'Volume_leachate' not in input_data.columns:
            raise ValueError("Volume must be provided for chemistry prediction")
        
        volume_value = input_data['Volume_leachate'].iloc[0]
        
        if volume_value < self.config['volume_threshold']:
            return {
                'error': 'Insufficient volume for chemistry prediction',
                'volume_ml': volume_value,
                'threshold_ml': self.config['volume_threshold'],
                'predictions': None
            }
        
        # Ensure all required features are present
        missing_features = set(self.stage2['features']) - set(input_data.columns)
        if missing_features:
            raise ValueError(f"Missing required features: {missing_features}")
        
        # Select and order features
        X = input_data[self.stage2['features']].copy()
        
        # Predict each chemistry parameter
        predictions = {}
        
        for target_full, model_data in self.stage2['models'].items():
            target_name = target_full.replace('_leachate', '')
            
            # Scale features
            X_scaled = pd.DataFrame(
                model_data['scaler'].transform(X),
                columns=self.stage2['features'],
                index=X.index
            )
            
            # Predict
            pred_value = model_data['model'].predict(X_scaled)[0]
            predictions[target_name] = round(pred_value, 4)
        
        return {
            'volume_ml': volume_value,
            'predictions': predictions,
            'chemistry_targets': list(predictions.keys())
        }
    
    def predict(self, input_data: Union[pd.DataFrame, Dict]) -> Dict:
        """
        Full two-stage prediction: Volume → Chemistry.
        
        Args:
            input_data: Dictionary or DataFrame with rock properties and event data
            
        Returns:
            Complete prediction results from both stages
        """
        # Stage 1: Predict volume
        volume_result = self.predict_volume(input_data)
        
        result = {
            'stage1_volume': volume_result,
            'stage2_chemistry': None
        }
        
        # Stage 2: Predict chemistry if volume is sufficient
        if volume_result['exceeds_threshold']:
            # Convert to DataFrame and add predicted volume
            if isinstance(input_data, dict):
                input_data_with_volume = input_data.copy()
            else:
                input_data_with_volume = input_data.copy()
            
            # Add predicted volume for chemistry prediction
            if isinstance(input_data_with_volume, dict):
                input_data_with_volume['Volume_leachate'] = volume_result['predicted_volume_ml']
                input_df = pd.DataFrame([input_data_with_volume])
            else:
                input_df = input_data_with_volume.copy()
                input_df['Volume_leachate'] = volume_result['predicted_volume_ml']
            
            chemistry_result = self.predict_chemistry(input_df)
            result['stage2_chemistry'] = chemistry_result
        else:
            result['stage2_chemistry'] = {
                'message': 'Volume below threshold. Chemistry prediction skipped.',
                'predictions': None
            }
        
        return result
    
    def get_model_info(self) -> Dict:
        """Get model metadata and performance metrics."""
        with open(self.model_dir / 'performance_summary.json', 'r') as f:
            performance = json.load(f)
        
        return {
            'version': self.config['model_version'],
            'training_date': self.config['training_date'],
            'volume_threshold': self.config['volume_threshold'],
            'stage1_features': len(self.config['stage1_features']),
            'stage2_features': len(self.config['stage2_features']),
            'chemistry_models': len(self.stage2['models']),
            'performance': performance
        }


# Example usage functions
def example_single_prediction():
    """Example: Single sample prediction"""
    print("\n" + "="*60)
    print("EXAMPLE: Single Sample Prediction")
    print("="*60)
    
    # Initialize model
    model = LeachatePredictionModel()
    
    # Example input data
    sample_input = {
        # Rock properties (example values - replace with actual features)
        'SiO2_rock': 45.2,
        'Al2O3_rock': 12.3,
        'Fe2O3_rock': 8.5,
        'CaO_rock': 15.4,
        'MgO_rock': 6.2,
        'K2O_rock': 2.1,
        'Na2O_rock': 3.5,
        'TiO2_rock': 1.2,
        'MnO_rock': 0.3,
        'P2O5_rock': 0.5,
        'EC_rock': 120.5,
        'Ph_rock': 7.2,
        
        # Event features
        'Type_event_encoded': 0,  # 0=rain, 1=snow
        'Event_quantity': 25.5,
        'Acid': 0,  # 0=no, 1=yes
        'Temp': 15.3,
        'Timestep': 5,
        
        # Missing indicators (if any)
        # Add any _missing columns needed
    }
    
    # Make prediction
    result = model.predict(sample_input)
    
    # Display results
    print("\nINPUT:")
    print(f"  Event: {'Rain' if sample_input['Type_event_encoded'] == 0 else 'Snow'}")
    print(f"  Temperature: {sample_input['Temp']}°C")
    print(f"  Event Quantity: {sample_input['Event_quantity']} mm")
    
    print("\nSTAGE 1 - VOLUME PREDICTION:")
    vol = result['stage1_volume']
    print(f"  Predicted Volume: {vol['predicted_volume_ml']} mL")
    print(f"  Exceeds Threshold: {vol['exceeds_threshold']}")
    
    print("\nSTAGE 2 - CHEMISTRY PREDICTION:")
    chem = result['stage2_chemistry']
    if chem['predictions']:
        for param, value in chem['predictions'].items():
            print(f"  {param:15s}: {value:10.2f}")
    else:
        print(f"  {chem.get('message', 'No predictions available')}")


def example_batch_prediction():
    """Example: Batch predictions for multiple samples"""
    print("\n" + "="*60)
    print("EXAMPLE: Batch Prediction")
    print("="*60)
    
    # Initialize model
    model = LeachatePredictionModel()
    
    # Load batch data (example - replace with actual data)
    # batch_data = pd.read_csv('new_samples.csv')
    
    # For demonstration, create sample batch
    batch_data = pd.DataFrame({
        'SiO2_rock': [45.2, 48.1, 43.5],
        'Al2O3_rock': [12.3, 13.1, 11.8],
        # ... add all required features
        'Type_event_encoded': [0, 1, 0],
        'Event_quantity': [25.5, 30.2, 22.1],
        'Temp': [15.3, 8.2, 18.5],
        'Timestep': [5, 6, 7],
        'Acid': [0, 0, 1]
    })
    
    # Process each sample
    results = []
    for idx, row in batch_data.iterrows():
        result = model.predict(row.to_dict())
        results.append({
            'sample_id': idx,
            'volume': result['stage1_volume']['predicted_volume_ml'],
            'has_chemistry': result['stage2_chemistry']['predictions'] is not None
        })
    
    results_df = pd.DataFrame(results)
    print("\nBatch Results:")
    print(results_df)
    
    return results_df


if __name__ == "__main__":
    # Initialize model
    print("Initializing Leachate Prediction Model...")
    model = LeachatePredictionModel()
    
    # Display model info
    info = model.get_model_info()
    print("\n" + "="*60)
    print("MODEL INFORMATION")
    print("="*60)
    print(f"Version: {info['version']}")
    print(f"Training Date: {info['training_date']}")
    print(f"Volume Threshold: {info['volume_threshold']} mL")
    print(f"Stage 1 Features: {info['stage1_features']}")
    print(f"Stage 2 Features: {info['stage2_features']}")
    print(f"Chemistry Models: {info['chemistry_models']}")
    print(f"\nStage 1 Performance: R² = {info['performance']['stage1']['test_r2']:.4f}")
    
    # Run examples
    example_single_prediction()
    # example_batch_prediction()