-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidity.py
More file actions
1509 lines (1228 loc) · 60.7 KB
/
validity.py
File metadata and controls
1509 lines (1228 loc) · 60.7 KB
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pandas as pd
import numpy as np
from scipy.interpolate import interp1d
from scipy.stats import pearsonr, gaussian_kde, ttest_1samp, chi2, normaltest, shapiro, t
import matplotlib.pyplot as plt
from pathlib import Path
def get_thermistor_positions():
"""
Get thermistor positions dictionary.
Returns:
- Dictionary mapping thermistor_id to position in meters from x=0
"""
return {
0: 0.003, # 3mm
1: 0.008, # 8mm
2: 0.013, # 13mm
3: 0.018, # 18mm
4: 0.023, # 23mm
5: 0.028, # 28mm
6: 0.033, # 33mm
7: 0.038 # 38mm
}
def interpolate_temperature_at_position(T_brass_all, x_grid, x_pos, t_eval):
"""
Interpolate brass temperature at a specific position for all time points.
Parameters:
- T_brass_all: Array of brass temperatures at grid points, shape (N_nodes, len(t_eval))
- x_grid: Spatial grid positions along the brass rod
- x_pos: Position along rod to interpolate to (in meters)
- t_eval: Time points where solution is evaluated
Returns:
- T_at_pos: Temperature at x_pos for all time points (in Kelvin)
"""
T_at_pos = np.zeros(len(t_eval))
for i in range(len(t_eval)):
T_brass_interp = interp1d(x_grid, T_brass_all[:, i], kind='linear',
fill_value='extrapolate', bounds_error=False)
T_at_pos[i] = T_brass_interp(x_pos)
return T_at_pos
def calculate_residual(T_model_C, t_model, thermistor_data, t_exp):
"""
Calculate residual between model and experimental data.
Parameters:
- T_model_C: Model temperature in Celsius at model time points
- t_model: Model time points
- thermistor_data: Experimental thermistor data
- t_exp: Experimental time points
Returns:
- residual: Model - Experimental (in Celsius)
"""
T_model_interp_func = interp1d(t_model, T_model_C, kind='linear',
fill_value='extrapolate', bounds_error=False)
T_model_at_exp_times = T_model_interp_func(t_exp)
return T_model_at_exp_times - thermistor_data
def plot_thermistor_comparison(ax, t_eval, T_model_C, timestamp, thermistor_data,
x_pos_mm, thermistor_id, model_color, exp_color):
"""
Plot temperature comparison for a single thermistor.
Parameters:
- ax: Matplotlib axis to plot on
- t_eval: Model time points
- T_model_C: Model temperature in Celsius
- timestamp: Experimental time points
- thermistor_data: Experimental thermistor data
- x_pos_mm: Position in mm
- thermistor_id: Thermistor ID number
- model_color: Color for model line
- exp_color: Color for experimental line
"""
ax.plot(t_eval, T_model_C, model_color, linewidth=2,
label=f'T_brass (Model, x={x_pos_mm:.1f}mm)')
ax.plot(timestamp, thermistor_data, exp_color, linewidth=2,
label=f'Thermistor {thermistor_id} (Experimental)', alpha=0.7)
ax.set_xlabel('Time (s)', fontsize=12)
ax.set_ylabel('Temperature (°C)', fontsize=12)
ax.set_title(f'Brass Temperature at x={x_pos_mm:.1f}mm (Thermistor {thermistor_id}) vs Time',
fontsize=14, fontweight='bold')
ax.grid(True, alpha=0.3)
ax.legend(loc='best', fontsize=11)
def plot_residual(ax, timestamp, residual, thermistor_id, residual_color):
"""
Plot residual for a single thermistor.
Parameters:
- ax: Matplotlib axis to plot on
- timestamp: Time points
- residual: Residual values (Model - Experimental)
- thermistor_id: Thermistor ID number
- residual_color: Color for residual line
"""
ax.plot(timestamp, residual, residual_color, linewidth=2,
label=f'Residual (Model - Thermistor {thermistor_id})')
ax.set_xlabel('Time (s)', fontsize=12)
ax.set_ylabel('Residual (°C)', fontsize=12)
ax.set_title(f'Residual: Numerical Model - Thermistor {thermistor_id} Data',
fontsize=14, fontweight='bold')
ax.grid(True, alpha=0.3)
ax.axhline(y=0, color='k', linestyle='--', linewidth=0.8, alpha=0.5)
ax.legend(loc='best', fontsize=11)
def calculate_rmse_and_correlation(T_model, T_exp):
"""
Calculate RMSE and Pearson correlation coefficient between model and experimental data.
Parameters:
- T_model: Model temperature array
- T_exp: Experimental temperature array
Returns:
- rmse: Root Mean Square Error in °C
- correlation: Pearson correlation coefficient
"""
# Remove any NaN or inf values
valid_mask = np.isfinite(T_model) & np.isfinite(T_exp)
if np.sum(valid_mask) == 0:
return np.nan, np.nan
T_model_valid = T_model[valid_mask]
T_exp_valid = T_exp[valid_mask]
# Calculate RMSE
rmse = np.sqrt(np.mean((T_model_valid - T_exp_valid)**2))
# Calculate Pearson correlation
if len(T_model_valid) > 1 and np.std(T_model_valid) > 0 and np.std(T_exp_valid) > 0:
correlation, _ = pearsonr(T_model_valid, T_exp_valid)
else:
correlation = np.nan
return rmse, correlation
def save_temperature_data_to_csv(sol_dict, timestamp, thermistor_data_dict, x_grid, save_path=None):
"""
Save temperature comparison data (model vs experimental) for all thermistors to CSV.
Only saves the middle 90% of the dataset (excludes first 5% and last 5%).
Parameters:
- sol_dict: Dictionary mapping thermistor_id to solution object from solve_ivp
- timestamp: Original time data
- thermistor_data_dict: Dictionary mapping thermistor_id to {'data': array, 'x_pos': float}
x_pos is in meters (e.g., 0.003 for 3mm)
- x_grid: Spatial grid positions along the brass rod
- save_path: Path to save the CSV file (if None, uses default path)
"""
# Extract middle 90% of dataset (remove first 5% and last 5%)
n_total = len(timestamp)
start_idx = int(0.05 * n_total) # Start at 5%
end_idx = int(0.95 * n_total) # End at 95%
# Filter data to middle 90% for saving
timestamp_plot = timestamp[start_idx:end_idx]
# Process each thermistor's solution
thermistor_results = {}
for therm_id, therm_info in thermistor_data_dict.items():
sol = sol_dict[therm_id]
x_pos = therm_info['x_pos']
# Use actual solution points to avoid interpolation artifacts
t_eval = sol.t
T_solution = sol.y
T_brass_all = T_solution[2:, :]
# Interpolate model temperature at this thermistor's position
T_brass_K = interpolate_temperature_at_position(T_brass_all, x_grid, x_pos, t_eval)
T_brass_C = T_brass_K - 273.15
# Filter experimental data to middle 90% for comparison
thermistor_data_middle90 = therm_info['data'][start_idx:end_idx]
# Interpolate model to experimental time points in middle 90%
T_model_interp_func = interp1d(t_eval, T_brass_C, kind='linear',
fill_value='extrapolate', bounds_error=False)
T_model_middle90 = T_model_interp_func(timestamp_plot)
thermistor_results[therm_id] = {
'T_model_C': T_model_middle90, # Filtered to middle 90%
'T_exp_C': thermistor_data_middle90, # Experimental data (middle 90%)
'x_pos_mm': x_pos * 1000
}
# Create DataFrame with time and all thermistor data
data_dict = {'Time (s)': timestamp_plot}
# Add columns for each thermistor (sorted by ID)
for therm_id in sorted(thermistor_results.keys()):
result = thermistor_results[therm_id]
data_dict[f'T_model_{therm_id}_x{result["x_pos_mm"]:.1f}mm (°C)'] = result['T_model_C']
data_dict[f'T_exp_{therm_id}_x{result["x_pos_mm"]:.1f}mm (°C)'] = result['T_exp_C']
df = pd.DataFrame(data_dict)
# Save to CSV
if save_path is None:
save_path = Path('data/comparison/temperature_comparison_data.csv')
else:
save_path = Path(save_path)
save_path.parent.mkdir(parents=True, exist_ok=True)
df.to_csv(save_path, index=False)
print(f"Temperature comparison data saved to: {save_path}")
print(f" Saved {len(df)} time points with data for {len(thermistor_results)} thermistors")
return save_path
def plot_temperatures_vs_time(sol_dict, timestamp, thermistor_data_dict, x_grid, voltage_func, params,
t_span, rtol, atol, N_nodes, save_path=None):
"""
Plot T_brass at thermistor positions and thermistor temperatures as a function of time.
Each thermistor uses its own T0 for numerical integration.
Only plots the middle 90% of the dataset (excludes first 5% and last 5%).
Parameters:
- sol_dict: Dictionary mapping thermistor_id to solution object from solve_ivp
- timestamp: Original time data for reference
- thermistor_data_dict: Dictionary mapping thermistor_id to {'data': array, 'x_pos': float}
x_pos is in meters (e.g., 0.003 for 3mm)
- x_grid: Spatial grid positions along the brass rod
- voltage_func: Function V(t) returning voltage at time t
- params: Dictionary containing physical parameters
- t_span: Time span tuple (t0, tf)
- rtol: Relative tolerance for ODE solver
- atol: Absolute tolerance for ODE solver
- N_nodes: Number of nodes in spatial discretization
- save_path: Path to save the plot (if None, plot is displayed)
"""
# Extract middle 90% of dataset (remove first 5% and last 5%)
n_total = len(timestamp)
start_idx = int(0.05 * n_total) # Start at 5%
end_idx = int(0.95 * n_total) # End at 95%
# Filter data to middle 90% for plotting
timestamp_plot = timestamp[start_idx:end_idx]
# Process each thermistor's solution
thermistor_results = {}
for therm_id, therm_info in thermistor_data_dict.items():
sol = sol_dict[therm_id]
x_pos = therm_info['x_pos']
# Use actual solution points to avoid interpolation artifacts
t_eval = sol.t
T_solution = sol.y
# Extract temperatures
Tc = T_solution[0, :]
Th = T_solution[1, :]
T_brass_all = T_solution[2:, :]
# Interpolate model temperature at this thermistor's position
T_brass_K = interpolate_temperature_at_position(T_brass_all, x_grid, x_pos, t_eval)
T_brass_C = T_brass_K - 273.15
# Filter experimental data to middle 90% for comparison
thermistor_data_middle90 = therm_info['data'][start_idx:end_idx]
# Filter model data to middle 90% for plotting
# Interpolate model to experimental time points in middle 90%
T_model_interp_func = interp1d(t_eval, T_brass_C, kind='linear',
fill_value='extrapolate', bounds_error=False)
T_model_middle90 = T_model_interp_func(timestamp_plot)
thermistor_results[therm_id] = {
'T_model_C': T_model_middle90, # Filtered to middle 90%
'T_exp_C': thermistor_data_middle90, # Experimental data (middle 90%)
'x_pos_mm': x_pos * 1000,
't_eval': timestamp_plot, # Use filtered timestamp for plotting
'Tc': Tc,
'Th': Th
}
# Define colors for each thermistor
model_colors = ['g', 'orange', 'brown', 'red', 'purple', 'pink', 'olive', 'cyan']
exp_colors = ['b', 'purple', 'pink', 'coral', 'indigo', 'magenta', 'darkgreen', 'teal']
# Create subplots: 1 plot per thermistor (temperature comparison only)
n_thermistors = len(thermistor_data_dict)
fig, axes = plt.subplots(n_thermistors, 1, figsize=(10, 3*n_thermistors))
# Handle case where there's only one thermistor (axes becomes 1D instead of array)
if n_thermistors == 1:
axes = [axes]
# Plot each thermistor (using middle 90% data)
for i, (therm_id, therm_info) in enumerate(sorted(thermistor_data_dict.items())):
result = thermistor_results[therm_id]
# Plot temperature comparison (middle 90% only)
plot_thermistor_comparison(
axes[i], result['t_eval'], result['T_model_C'], timestamp_plot,
result['T_exp_C'], result['x_pos_mm'], therm_id,
model_colors[i % len(model_colors)], exp_colors[i % len(exp_colors)]
)
plt.tight_layout()
# Save plot if save_path is provided
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Plot saved to: {save_path}")
plt.close()
else:
plt.show(block=True)
def plot_residual_distributions(sol_dict, timestamp, thermistor_data_dict, x_grid, save_path=None):
"""
Plot residual distributions (histograms with kernel density estimation) for all thermistors.
Uses KDE instead of assuming a Gaussian distribution.
Parameters:
- sol_dict: Dictionary mapping thermistor_id to solution object from solve_ivp
- timestamp: Original time data for reference
- thermistor_data_dict: Dictionary mapping thermistor_id to {'data': array, 'x_pos': float}
x_pos is in meters (e.g., 0.003 for 3mm)
- x_grid: Spatial grid positions along the brass rod
- save_path: Path to save the plot (if None, plot is displayed)
"""
# Extract middle 90% of dataset (remove first 5% and last 5%)
n_total = len(timestamp)
start_idx = int(0.05 * n_total) # Start at 5%
end_idx = int(0.95 * n_total) # End at 95%
# Filter data to middle 90% for analysis
timestamp_plot = timestamp[start_idx:end_idx]
# Calculate residuals for each thermistor
n_thermistors = len(thermistor_data_dict)
# Create subplots: arrange in a grid (2 columns, or as needed)
n_cols = 2
n_rows = (n_thermistors + n_cols - 1) // n_cols # Ceiling division
fig, axes = plt.subplots(n_rows, n_cols, figsize=(12, 4*n_rows))
# Handle different subplot arrangements
if n_thermistors == 1:
axes = np.array([axes])
elif n_rows == 1:
axes = axes if isinstance(axes, np.ndarray) else np.array([axes])
axes = axes.flatten()
else:
axes = axes.flatten()
# Process each thermistor
for idx, (therm_id, therm_info) in enumerate(sorted(thermistor_data_dict.items())):
sol = sol_dict[therm_id]
x_pos = therm_info['x_pos']
# Use actual solution points to avoid interpolation artifacts
t_eval = sol.t
T_solution = sol.y
T_brass_all = T_solution[2:, :]
# Interpolate model temperature at this thermistor's position
T_brass_K = interpolate_temperature_at_position(T_brass_all, x_grid, x_pos, t_eval)
T_brass_C = T_brass_K - 273.15
# Filter experimental data to middle 90% for comparison
thermistor_data_middle90 = therm_info['data'][start_idx:end_idx]
# Interpolate model to experimental time points in middle 90%
T_model_interp_func = interp1d(t_eval, T_brass_C, kind='linear',
fill_value='extrapolate', bounds_error=False)
T_model_middle90 = T_model_interp_func(timestamp_plot)
# Calculate residuals (Model - Experimental)
residuals = T_model_middle90 - thermistor_data_middle90
# Remove NaN and inf values
valid_mask = np.isfinite(residuals)
residuals_clean = residuals[valid_mask]
if len(residuals_clean) == 0:
print(f" Warning: No valid residuals for thermistor {therm_id}")
continue
# Calculate statistics for display
mu = np.mean(residuals_clean)
std = np.std(residuals_clean)
median = np.median(residuals_clean)
# Create histogram
ax = axes[idx]
n_bins = min(50, int(np.sqrt(len(residuals_clean)))) # Adaptive number of bins
counts, bins, patches = ax.hist(residuals_clean, bins=n_bins, density=True,
color='purple', alpha=0.7, edgecolor='black', linewidth=0.5)
# Fit kernel density estimation (non-parametric, doesn't assume Gaussian)
try:
kde = gaussian_kde(residuals_clean)
x_fit = np.linspace(residuals_clean.min(), residuals_clean.max(), 200)
y_fit = kde(x_fit)
ax.plot(x_fit, y_fit, 'k-', linewidth=2,
label=f'KDE (μ={mu:.2f}, σ={std:.2f}, med={median:.2f})')
except Exception as e:
# Fallback if KDE fails (e.g., too few points or constant values)
print(f" Warning: KDE fitting failed for thermistor {therm_id}: {e}")
# Plot simple statistics line
ax.axvline(mu, color='k', linestyle='--', linewidth=1.5,
label=f'Mean={mu:.2f}, σ={std:.2f}')
# Formatting
ax.set_xlabel('Error (°C)', fontsize=11)
ax.set_ylabel('Density', fontsize=11)
ax.set_title(f'Residual Distribution (Thermistor {therm_id} at {x_pos*1000:.0f}mm)',
fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3)
ax.legend(loc='best', fontsize=10)
# Hide unused subplots
for idx in range(n_thermistors, len(axes)):
axes[idx].set_visible(False)
plt.tight_layout()
# Save plot if save_path is provided
if save_path:
save_path = Path(save_path)
save_path.parent.mkdir(parents=True, exist_ok=True)
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Residual distributions plot saved to: {save_path}")
plt.close()
else:
plt.show(block=True)
def plot_mean_residual_distribution(sol_dict, timestamp, thermistor_data_dict, x_grid, save_path=None):
"""
Plot mean residual distribution combining all thermistors into one plot.
Parameters:
- sol_dict: Dictionary mapping thermistor_id to solution object from solve_ivp
- timestamp: Original time data for reference
- thermistor_data_dict: Dictionary mapping thermistor_id to {'data': array, 'x_pos': float}
x_pos is in meters (e.g., 0.003 for 3mm)
- x_grid: Spatial grid positions along the brass rod
- save_path: Path to save the plot (if None, plot is displayed)
"""
# Extract middle 90% of dataset (remove first 5% and last 5%)
n_total = len(timestamp)
start_idx = int(0.05 * n_total) # Start at 5%
end_idx = int(0.95 * n_total) # End at 95%
# Filter data to middle 90% for analysis
timestamp_plot = timestamp[start_idx:end_idx]
# Collect all residuals from all thermistors
all_residuals = []
for therm_id, therm_info in sorted(thermistor_data_dict.items()):
sol = sol_dict[therm_id]
x_pos = therm_info['x_pos']
# Use actual solution points to avoid interpolation artifacts
t_eval = sol.t
T_solution = sol.y
T_brass_all = T_solution[2:, :]
# Interpolate model temperature at this thermistor's position
T_brass_K = interpolate_temperature_at_position(T_brass_all, x_grid, x_pos, t_eval)
T_brass_C = T_brass_K - 273.15
# Filter experimental data to middle 90% for comparison
thermistor_data_middle90 = therm_info['data'][start_idx:end_idx]
# Interpolate model to experimental time points in middle 90%
T_model_interp_func = interp1d(t_eval, T_brass_C, kind='linear',
fill_value='extrapolate', bounds_error=False)
T_model_middle90 = T_model_interp_func(timestamp_plot)
# Calculate residuals (Model - Experimental)
residuals = T_model_middle90 - thermistor_data_middle90
# Remove NaN and inf values
valid_mask = np.isfinite(residuals)
residuals_clean = residuals[valid_mask]
# Add to combined list
all_residuals.extend(residuals_clean.tolist())
all_residuals = np.array(all_residuals)
if len(all_residuals) == 0:
print(" Warning: No valid residuals found!")
return
# Calculate statistics for display
mu = np.mean(all_residuals)
std = np.std(all_residuals)
median = np.median(all_residuals)
# Create figure
fig, ax = plt.subplots(figsize=(10, 6))
# Create histogram
n_bins = min(50, int(np.sqrt(len(all_residuals)))) # Adaptive number of bins
counts, bins, patches = ax.hist(all_residuals, bins=n_bins, density=True,
color='purple', alpha=0.7, edgecolor='black', linewidth=0.5)
# Fit kernel density estimation (non-parametric, doesn't assume Gaussian)
try:
kde = gaussian_kde(all_residuals)
x_fit = np.linspace(all_residuals.min(), all_residuals.max(), 200)
y_fit = kde(x_fit)
ax.plot(x_fit, y_fit, 'k-', linewidth=2,
label=f'KDE (μ={mu:.2f}, σ={std:.2f}, med={median:.2f})')
except Exception as e:
# Fallback if KDE fails (e.g., too few points or constant values)
print(f" Warning: KDE fitting failed: {e}")
# Plot simple statistics line
ax.axvline(mu, color='k', linestyle='--', linewidth=1.5,
label=f'Mean={mu:.2f}, σ={std:.2f}')
# Formatting
ax.set_xlabel('Error (°C)', fontsize=12)
ax.set_ylabel('Density', fontsize=12)
ax.set_title('Mean Residual Distribution (All Thermistors Combined)',
fontsize=14, fontweight='bold')
ax.grid(True, alpha=0.3)
ax.legend(loc='best', fontsize=11)
plt.tight_layout()
# Save plot if save_path is provided
if save_path:
save_path = Path(save_path)
save_path.parent.mkdir(parents=True, exist_ok=True)
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Mean residual distribution plot saved to: {save_path}")
plt.close()
else:
plt.show(block=True)
def plot_rmse_and_correlation_vs_position(sol_dict, timestamp, thermistor_data_dict, x_grid, save_path=None):
"""
Plot RMSE and Pearson Correlation vs position for all thermistors in one image.
Parameters:
- sol_dict: Dictionary mapping thermistor_id to solution object from solve_ivp
- timestamp: Original time data for reference
- thermistor_data_dict: Dictionary mapping thermistor_id to {'data': array, 'x_pos': float}
x_pos is in meters (e.g., 0.003 for 3mm)
- x_grid: Spatial grid positions along the brass rod
- save_path: Path to save the plot (if None, plot is displayed)
"""
# Extract middle 90% of dataset (remove first 5% and last 5%)
n_total = len(timestamp)
start_idx = int(0.05 * n_total) # Start at 5%
end_idx = int(0.95 * n_total) # End at 95%
# Filter data to middle 90% for analysis
timestamp_plot = timestamp[start_idx:end_idx]
# Calculate RMSE and correlation for each thermistor
positions = []
rmse_values = []
correlation_values = []
for therm_id, therm_info in sorted(thermistor_data_dict.items()):
sol = sol_dict[therm_id]
x_pos = therm_info['x_pos']
# Use actual solution points to avoid interpolation artifacts
t_eval = sol.t
T_solution = sol.y
T_brass_all = T_solution[2:, :]
# Interpolate model temperature at this thermistor's position
T_brass_K = interpolate_temperature_at_position(T_brass_all, x_grid, x_pos, t_eval)
T_brass_C = T_brass_K - 273.15
# Filter experimental data to middle 90% for comparison
thermistor_data_middle90 = therm_info['data'][start_idx:end_idx]
# Interpolate model to experimental time points in middle 90%
T_model_interp_func = interp1d(t_eval, T_brass_C, kind='linear',
fill_value='extrapolate', bounds_error=False)
T_model_middle90 = T_model_interp_func(timestamp_plot)
# Calculate RMSE and correlation
rmse, correlation = calculate_rmse_and_correlation(T_model_middle90, thermistor_data_middle90)
positions.append(x_pos * 1000) # Convert to mm
rmse_values.append(rmse)
correlation_values.append(correlation)
print(f" Thermistor {therm_id} (x={x_pos*1000:.1f}mm): RMSE={rmse:.4f} °C, r={correlation:.6f}")
# Create figure with dual y-axes
fig, ax1 = plt.subplots(figsize=(10, 6))
# Plot RMSE on left y-axis (red dots only, no line)
color_rmse = 'red'
ax1.set_xlabel('Position along rod (mm)', fontsize=12)
ax1.set_ylabel('RMSE (°C)', fontsize=12, color=color_rmse)
line1 = ax1.plot(positions, rmse_values, 'o', color=color_rmse,
markersize=8, label='RMSE', alpha=0.8)
ax1.tick_params(axis='y', labelcolor=color_rmse)
ax1.grid(True, alpha=0.3)
# Plot Pearson Correlation on right y-axis (blue line with squares)
ax2 = ax1.twinx()
color_corr = 'blue'
ax2.set_ylabel('Pearson Correlation (r)', fontsize=12, color=color_corr)
line2 = ax2.plot(positions, correlation_values, 's-', color=color_corr, linewidth=2,
markersize=8, label='Pearson Correlation', alpha=0.8)
ax2.tick_params(axis='y', labelcolor=color_corr)
# Set title
ax1.set_title('Model Performance vs. Sensor Position', fontsize=14, fontweight='bold')
# Add legend - position it in upper left to avoid overlapping with curves
lines = line1 + line2
labels = [l.get_label() for l in lines]
ax1.legend(lines, labels, loc='upper left', fontsize=11)
plt.tight_layout()
# Save plot if save_path is provided
if save_path:
save_path = Path(save_path)
save_path.parent.mkdir(parents=True, exist_ok=True)
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"RMSE and Correlation plot saved to: {save_path}")
plt.close()
else:
plt.show(block=True)
def plot_temperatures_from_csv(csv_path, save_path=None):
"""
Plot temperature comparisons from CSV data.
Parameters:
- csv_path: Path to temperature_comparison_data.csv
- save_path: Path to save the plot (if None, plot is displayed)
"""
df = pd.read_csv(csv_path)
time = df['Time (s)'].values
# Get all thermistor IDs from column names
model_cols = [col for col in df.columns if col.startswith('T_model_')]
n_thermistors = len(model_cols)
# Define colors for each thermistor
model_colors = ['g', 'orange', 'brown', 'red', 'purple', 'pink', 'olive', 'cyan']
exp_colors = ['b', 'purple', 'pink', 'coral', 'indigo', 'magenta', 'darkgreen', 'teal']
# Create subplots: 1 plot per thermistor
fig, axes = plt.subplots(n_thermistors, 1, figsize=(10, 3*n_thermistors))
# Handle case where there's only one thermistor
if n_thermistors == 1:
axes = [axes]
# Plot each thermistor
for i in range(n_thermistors):
model_col = f'T_model_{i}_x'
exp_col = f'T_exp_{i}_x'
# Find the actual column names (they have position info)
model_col_name = [col for col in model_cols if col.startswith(model_col)][0]
exp_col_name = model_col_name.replace('T_model_', 'T_exp_')
# Extract position from column name (e.g., "T_model_0_x3.0mm (°C)" -> 3.0)
x_pos_mm = float(model_col_name.split('_x')[1].split('mm')[0])
T_model = df[model_col_name].values
T_exp = df[exp_col_name].values
# Plot
axes[i].plot(time, T_model, model_colors[i % len(model_colors)], linewidth=2,
label=f'T_brass (Model, x={x_pos_mm:.1f}mm)')
axes[i].plot(time, T_exp, exp_colors[i % len(exp_colors)], linewidth=2,
label=f'Thermistor {i} (Experimental)', alpha=0.7)
axes[i].set_xlabel('Time (s)', fontsize=12)
axes[i].set_ylabel('Temperature (°C)', fontsize=12)
axes[i].set_title(f'Brass Temperature at x={x_pos_mm:.1f}mm (Thermistor {i}) vs Time',
fontsize=14, fontweight='bold')
axes[i].grid(True, alpha=0.3)
axes[i].legend(loc='best', fontsize=11)
plt.tight_layout()
# Save plot if save_path is provided
if save_path:
save_path = Path(save_path)
save_path.parent.mkdir(parents=True, exist_ok=True)
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Plot saved to: {save_path}")
plt.close()
else:
plt.show(block=True)
def plot_residuals_from_csv(csv_path, save_path=None):
"""
Plot residual distributions from CSV data.
Parameters:
- csv_path: Path to temperature_comparison_data.csv
- save_path: Path to save the plot (if None, plot is displayed)
"""
df = pd.read_csv(csv_path)
# Get all thermistor IDs from column names
model_cols = [col for col in df.columns if col.startswith('T_model_')]
n_thermistors = len(model_cols)
# Create subplots: arrange in a grid (2 columns)
n_cols = 2
n_rows = (n_thermistors + n_cols - 1) // n_cols
fig, axes = plt.subplots(n_rows, n_cols, figsize=(12, 4*n_rows))
# Handle different subplot arrangements
if n_thermistors == 1:
axes = np.array([axes])
elif n_rows == 1:
axes = axes if isinstance(axes, np.ndarray) else np.array([axes])
axes = axes.flatten()
else:
axes = axes.flatten()
# Process each thermistor
for i in range(n_thermistors):
model_col_name = model_cols[i]
exp_col_name = model_col_name.replace('T_model_', 'T_exp_')
# Extract position from column name
x_pos_mm = float(model_col_name.split('_x')[1].split('mm')[0])
T_model = df[model_col_name].values
T_exp = df[exp_col_name].values
# Calculate residuals
residuals = T_model - T_exp
# Remove NaN and inf values
valid_mask = np.isfinite(residuals)
residuals_clean = residuals[valid_mask]
if len(residuals_clean) == 0:
print(f" Warning: No valid residuals for thermistor {i}")
continue
# Calculate statistics
mu = np.mean(residuals_clean)
std = np.std(residuals_clean)
median = np.median(residuals_clean)
# Create histogram
ax = axes[i]
n_bins = min(50, int(np.sqrt(len(residuals_clean))))
counts, bins, patches = ax.hist(residuals_clean, bins=n_bins, density=True,
color='purple', alpha=0.7, edgecolor='black', linewidth=0.5)
# Fit kernel density estimation
try:
kde = gaussian_kde(residuals_clean)
x_fit = np.linspace(residuals_clean.min(), residuals_clean.max(), 200)
y_fit = kde(x_fit)
ax.plot(x_fit, y_fit, 'k-', linewidth=2,
label=f'KDE (μ={mu:.2f}, σ={std:.2f}, med={median:.2f})')
except Exception as e:
print(f" Warning: KDE fitting failed for thermistor {i}: {e}")
ax.axvline(mu, color='k', linestyle='--', linewidth=1.5,
label=f'Mean={mu:.2f}, σ={std:.2f}')
# Formatting
ax.set_xlabel('Error (°C)', fontsize=11)
ax.set_ylabel('Density', fontsize=11)
ax.set_title(f'Residual Distribution (Thermistor {i} at {x_pos_mm:.0f}mm)',
fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3)
ax.legend(loc='best', fontsize=10)
# Hide unused subplots
for idx in range(n_thermistors, len(axes)):
axes[idx].set_visible(False)
plt.tight_layout()
# Save plot if save_path is provided
if save_path:
save_path = Path(save_path)
save_path.parent.mkdir(parents=True, exist_ok=True)
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Residual distributions plot saved to: {save_path}")
plt.close()
else:
plt.show(block=True)
def plot_rmse_correlation_from_csv(csv_path, save_path=None):
"""
Plot RMSE and correlation vs position from CSV data.
Parameters:
- csv_path: Path to temperature_comparison_data.csv
- save_path: Path to save the plot (if None, plot is displayed)
"""
df = pd.read_csv(csv_path)
# Get all thermistor IDs from column names
model_cols = [col for col in df.columns if col.startswith('T_model_')]
positions = []
rmse_values = []
correlation_values = []
mse_values = []
for model_col_name in sorted(model_cols):
exp_col_name = model_col_name.replace('T_model_', 'T_exp_')
# Extract thermistor ID and position from column name
# e.g., "T_model_0_x3.0mm (°C)" -> therm_id=0, x_pos=3.0
parts = model_col_name.split('_')
therm_id = int(parts[2])
# Extract position: "x3.0mm (°C)" -> "3.0"
# parts[3] is "x3.0mm" but if there's a space, it might be "x3.0mm (°C)"
pos_str = parts[3].split()[0] # Take first part before any space
x_pos_mm = float(pos_str.replace('x', '').replace('mm', ''))
T_model = df[model_col_name].values
T_exp = df[exp_col_name].values
# Calculate RMSE and correlation
rmse, correlation = calculate_rmse_and_correlation(T_model, T_exp)
# Calculate MSE
valid_mask = np.isfinite(T_model) & np.isfinite(T_exp)
if np.sum(valid_mask) > 0:
T_model_valid = T_model[valid_mask]
T_exp_valid = T_exp[valid_mask]
mse = np.mean((T_model_valid - T_exp_valid)**2)
else:
mse = np.nan
positions.append(x_pos_mm)
rmse_values.append(rmse)
correlation_values.append(correlation)
mse_values.append(mse)
print(f" Thermistor {therm_id} (x={x_pos_mm:.1f}mm): RMSE={rmse:.4f} °C, r={correlation:.6f}, MSE={mse:.6f} °C²")
# Calculate mean residuals and standard deviations for the 4th plot
mean_residuals = []
std_residuals = []
for model_col_name in sorted(model_cols):
exp_col_name = model_col_name.replace('T_model_', 'T_exp_')
T_model = df[model_col_name].values
T_exp = df[exp_col_name].values
# Calculate residuals
residuals = T_model - T_exp
# Remove NaN and inf values
valid_mask = np.isfinite(residuals)
residuals_clean = residuals[valid_mask]
if len(residuals_clean) > 0:
mean_residual = np.mean(residuals_clean)
std_residual = np.std(residuals_clean)
else:
mean_residual = np.nan
std_residual = np.nan
mean_residuals.append(mean_residual)
std_residuals.append(std_residual)
# Create figure with 4 subplots
fig, axes = plt.subplots(4, 1, figsize=(10, 16))
# Plot 1: RMSE
ax1 = axes[0]
ax1.plot(positions, rmse_values, 'o-', color='red', linewidth=2,
markersize=8, label='RMSE', alpha=0.8)
ax1.set_xlabel('Position along rod (mm)', fontsize=12)
ax1.set_ylabel('RMSE (°C)', fontsize=12, color='red')
ax1.set_title('Root Mean Square Error vs. Sensor Position', fontsize=13, fontweight='bold')
ax1.tick_params(axis='y', labelcolor='red')
ax1.grid(True, alpha=0.3)
ax1.legend(loc='best', fontsize=11)
# Plot 2: Pearson Correlation
ax2 = axes[1]
ax2.plot(positions, correlation_values, 's-', color='blue', linewidth=2,
markersize=8, label='Pearson Correlation', alpha=0.8)
ax2.set_xlabel('Position along rod (mm)', fontsize=12)
ax2.set_ylabel('Pearson Correlation (r)', fontsize=12, color='blue')
ax2.set_title('Pearson Correlation vs. Sensor Position', fontsize=13, fontweight='bold')
ax2.tick_params(axis='y', labelcolor='blue')
ax2.grid(True, alpha=0.3)
ax2.legend(loc='best', fontsize=11)
# Plot 3: MSE
ax3 = axes[2]
ax3.plot(positions, mse_values, '^-', color='green', linewidth=2,
markersize=8, label='MSE', alpha=0.8)
ax3.set_xlabel('Position along rod (mm)', fontsize=12)
ax3.set_ylabel('MSE (°C²)', fontsize=12, color='green')
ax3.set_title('Mean Squared Error vs. Sensor Position', fontsize=13, fontweight='bold')
ax3.tick_params(axis='y', labelcolor='green')
ax3.grid(True, alpha=0.3)
ax3.legend(loc='best', fontsize=11)
# Plot 4: Mean Residual
ax4 = axes[3]
ax4.errorbar(positions, mean_residuals, yerr=std_residuals,
fmt='o-', color='purple', linewidth=2, markersize=8,
capsize=5, capthick=2, alpha=0.8, label='Mean Residual ± 1σ')
ax4.axhline(y=0, color='k', linestyle='--', linewidth=1, alpha=0.5, label='Zero Error')
ax4.set_xlabel('Position along rod (mm)', fontsize=12)
ax4.set_ylabel('Mean Residual (°C)', fontsize=12)
ax4.set_title('Mean Residual (Center Position) vs. Distance Along Rod',
fontsize=13, fontweight='bold')
ax4.grid(True, alpha=0.3)
ax4.legend(loc='best', fontsize=11)
# Overall title
fig.suptitle('Model Performance Metrics vs. Sensor Position', fontsize=16, fontweight='bold', y=0.995)
plt.tight_layout(rect=[0, 0, 1, 0.99]) # Leave space for suptitle
# Save plot if save_path is provided
if save_path:
save_path = Path(save_path)
save_path.parent.mkdir(parents=True, exist_ok=True)
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"RMSE and Correlation plot saved to: {save_path}")
plt.close()
else:
plt.show(block=True)
def plot_metrics_bar_chart_normalized(csv_path, save_path=None):
"""
Plot RMSE, MSE, and Mean Residual as unnormalized bar charts (in degrees Celsius).
Parameters:
- csv_path: Path to temperature_comparison_data.csv
- save_path: Path to save the plot (if None, plot is displayed)
"""
df = pd.read_csv(csv_path)
# Get all thermistor IDs from column names
model_cols = [col for col in df.columns if col.startswith('T_model_')]
positions = []
rmse_values = []
mse_values = []
mean_residuals = []
std_residuals = []
for model_col_name in sorted(model_cols):
exp_col_name = model_col_name.replace('T_model_', 'T_exp_')
# Extract thermistor ID and position from column name
parts = model_col_name.split('_')
therm_id = int(parts[2])
pos_str = parts[3].split()[0]
x_pos_mm = float(pos_str.replace('x', '').replace('mm', ''))
T_model = df[model_col_name].values
T_exp = df[exp_col_name].values
# Calculate RMSE
rmse, _ = calculate_rmse_and_correlation(T_model, T_exp)
# Calculate MSE
valid_mask = np.isfinite(T_model) & np.isfinite(T_exp)
if np.sum(valid_mask) > 0:
T_model_valid = T_model[valid_mask]
T_exp_valid = T_exp[valid_mask]
mse = np.mean((T_model_valid - T_exp_valid)**2)
else:
mse = np.nan
# Calculate residuals