predict.py
7.4 KB · 214 lines · python Raw
1 """
2 Inference Script for MHD Hybrid Nanofluid Thermal Management Model
3
4 Provides easy-to-use interface for:
5 1. Single-point prediction
6 2. Batch prediction
7 3. Parameter sweep analysis
8 4. PSO optimization
9 """
10
11 import torch
12 import numpy as np
13 import json
14 import os
15
16 from model import ThermalSurrogateModel, DataNormalizer, get_model_config
17 from pso_optimizer import PSOOptimizer
18
19
20 class ThermalPredictor:
21 """High-level prediction interface for the thermal management model."""
22
23 def __init__(self, model_dir='/app/outputs'):
24 """Load model, normalizer, and config."""
25 self.config = get_model_config()
26
27 # Load model
28 self.model = ThermalSurrogateModel(
29 input_dim=self.config['input_dim'],
30 hidden_dims=self.config['hidden_dims'],
31 output_dim=self.config['output_dim'],
32 dropout=0.0
33 )
34 self.model.load_state_dict(torch.load(
35 os.path.join(model_dir, 'model.pt'),
36 weights_only=True
37 ))
38 self.model.eval()
39
40 # Load normalizer
41 self.normalizer = DataNormalizer.load(
42 os.path.join(model_dir, 'normalizer.json')
43 )
44
45 self.output_names = self.config['output_features']
46 self.input_names = self.config['input_features']
47
48 def predict(self, Ha, phi, u_in):
49 """
50 Predict thermal performance for given parameters.
51
52 Args:
53 Ha: Hartmann number (0-60)
54 phi: Nanoparticle volume fraction (0.01-0.05)
55 u_in: Inlet flow velocity (0.05-0.30 m/s)
56
57 Returns:
58 dict with predictions for all output variables
59 """
60 X = np.array([[Ha, phi, u_in]], dtype=np.float32)
61 X_norm = self.normalizer.transform_input(X)
62
63 with torch.no_grad():
64 pred_norm = self.model(torch.tensor(X_norm, dtype=torch.float32)).cpu().numpy()
65
66 pred = self.normalizer.inverse_transform_output(pred_norm)[0]
67
68 result = {}
69 for i, name in enumerate(self.output_names):
70 result[name] = float(pred[i])
71
72 # Add derived metrics
73 result['thermal_runaway_risk'] = 'High' if result['T_max'] > 55 else \
74 'Moderate' if result['T_max'] > 45 else \
75 'Low' if result['T_max'] > 38 else 'Very Low'
76 result['within_safe_range'] = result['T_max'] <= 40.0
77
78 return result
79
80 def batch_predict(self, params_list):
81 """
82 Predict for multiple parameter sets.
83
84 Args:
85 params_list: list of (Ha, phi, u_in) tuples
86
87 Returns:
88 list of result dicts
89 """
90 return [self.predict(*p) for p in params_list]
91
92 def parameter_sweep(self, param_name, values, fixed_params):
93 """
94 Sweep one parameter while holding others fixed.
95
96 Args:
97 param_name: 'Ha', 'phi', or 'u_in'
98 values: array of values to sweep
99 fixed_params: dict with fixed values for other params
100 """
101 results = []
102 for val in values:
103 params = fixed_params.copy()
104 params[param_name] = val
105 pred = self.predict(params['Ha'], params['phi'], params['u_in'])
106 pred[param_name] = val
107 results.append(pred)
108 return results
109
110 def optimize(self, alpha=0.55, n_particles=50, max_iter=200):
111 """
112 Run PSO optimization.
113
114 Args:
115 alpha: Weight for T_max (1-alpha for S_gen)
116
117 Returns:
118 optimal_params, optimal_performance
119 """
120 pso = PSOOptimizer(
121 model=self.model,
122 normalizer=self.normalizer,
123 n_particles=n_particles,
124 max_iter=max_iter,
125 alpha=alpha
126 )
127 best_pos, best_pred, convergence = pso.optimize(verbose=False)
128
129 params = {
130 'Ha': float(best_pos[0]),
131 'phi': float(best_pos[1]),
132 'u_in': float(best_pos[2]),
133 }
134
135 performance = {}
136 for i, name in enumerate(self.output_names):
137 performance[name] = float(best_pred[i])
138
139 return params, performance, convergence
140
141
142 def demo():
143 """Run demonstration of the prediction pipeline."""
144 print("=" * 65)
145 print(" MHD Hybrid Nanofluid EV Battery Thermal Management Model")
146 print(" Neural Network Surrogate with PSO Optimization")
147 print("=" * 65)
148
149 predictor = ThermalPredictor()
150
151 # 1. Single prediction at paper's PSO optimal
152 print("\n1. PREDICTION AT PAPER'S PSO OPTIMAL POINT")
153 print("-" * 50)
154 result = predictor.predict(Ha=32.4, phi=0.038, u_in=0.187)
155 print(f" Input: Ha=32.4, φ=0.038, u₀=0.187 m/s")
156 print(f" T_max: {result['T_max']:.2f}°C (Paper: 40.8°C)")
157 print(f" Nusselt (Nu): {result['Nu']:.2f} (Paper: 18.7)")
158 print(f" Entropy (S_gen):{result['S_gen']:.4f}")
159 print(f" Cell-to-Cell ΔT:{result['delta_T']:.2f}°C")
160 print(f" k_ratio: {result['k_ratio']:.3f}")
161 print(f" BL Suppression: {result['BL_suppression']:.2f}%")
162 print(f" Runaway Risk: {result['thermal_runaway_risk']}")
163
164 # 2. Conventional cooling comparison
165 print("\n2. CONVENTIONAL COOLING (No MHD, Low Nanoparticle)")
166 print("-" * 50)
167 result_conv = predictor.predict(Ha=0, phi=0.01, u_in=0.15)
168 print(f" Input: Ha=0, φ=0.01, u₀=0.15 m/s")
169 print(f" T_max: {result_conv['T_max']:.2f}°C (Paper: ~61.3°C)")
170 print(f" Nusselt (Nu): {result_conv['Nu']:.2f} (Paper: ~12.4)")
171 print(f" Runaway Risk: {result_conv['thermal_runaway_risk']}")
172
173 # 3. Improvement calculation
174 print("\n3. IMPROVEMENT: OPTIMIZED vs CONVENTIONAL")
175 print("-" * 50)
176 T_reduction = (result_conv['T_max'] - result['T_max']) / result_conv['T_max'] * 100
177 Nu_improvement = (result['Nu'] - result_conv['Nu']) / result_conv['Nu'] * 100
178 print(f" Temperature Reduction: {T_reduction:.1f}% (Paper: 33.4%)")
179 print(f" Nu Improvement: {Nu_improvement:.1f}% (Paper: 50.8%)")
180
181 # 4. Parameter sweep: effect of Hartmann number
182 print("\n4. PARAMETER SWEEP: EFFECT OF HARTMANN NUMBER")
183 print("-" * 50)
184 print(f" {'Ha':>5} | {'T_max (°C)':>12} | {'Nu':>8} | {'BL Supp %':>10} | {'S_gen':>8}")
185 print(f" {'':->5}-+-{'':-<12}-+-{'':-<8}-+-{'':-<10}-+-{'':-<8}")
186
187 Ha_sweep = predictor.parameter_sweep(
188 'Ha',
189 np.arange(0, 61, 10),
190 fixed_params={'Ha': 0, 'phi': 0.03, 'u_in': 0.187}
191 )
192 for r in Ha_sweep:
193 print(f" {r['Ha']:5.0f} | {r['T_max']:12.2f} | {r['Nu']:8.2f} | "
194 f"{r['BL_suppression']:10.2f} | {r['S_gen']:8.4f}")
195
196 # 5. Run PSO optimization
197 print("\n5. PSO OPTIMIZATION (Finding optimal parameters)")
198 print("-" * 50)
199 optimal_params, optimal_perf, _ = predictor.optimize(alpha=0.55)
200 print(f" Optimal Ha: {optimal_params['Ha']:.2f}")
201 print(f" Optimal φ: {optimal_params['phi']:.4f}")
202 print(f" Optimal u₀: {optimal_params['u_in']:.4f} m/s")
203 print(f" → T_max: {optimal_perf['T_max']:.2f}°C")
204 print(f" → Nu: {optimal_perf['Nu']:.2f}")
205 print(f" → S_gen: {optimal_perf['S_gen']:.4f}")
206
207 print("\n" + "=" * 65)
208 print(" Pipeline complete! Model ready for deployment.")
209 print("=" * 65)
210
211
212 if __name__ == "__main__":
213 demo()
214