Update src/visualization.py

#32
by axelrvite - opened
Files changed (1) hide show
  1. src/visualization.py +83 -22
src/visualization.py CHANGED
@@ -1,4 +1,4 @@
1
- #!/usr/bin/env python3
2
  # -*- coding: utf-8 -*-
3
  """
4
  Module de visualisation pour le projet d'IA solaire.
@@ -17,7 +17,9 @@ from matplotlib.colors import LinearSegmentedColormap
17
  import matplotlib.cm as cm
18
  from mpl_toolkits.mplot3d import Axes3D
19
  from pvlib.pvsystem import i_from_v
20
- import tempfile
 
 
21
 
22
 
23
  def iv_curve(voltage, rsh, rs, nNsVth, J0, Jph):
@@ -38,17 +40,13 @@ class SolarCellVisualizer:
38
  pour la prédiction des paramètres des cellules solaires.
39
  """
40
 
41
- def __init__(self, results_dir=None):
42
  """
43
  Initialise le visualiseur.
44
 
45
  Args:
46
  results_dir (str): Répertoire pour sauvegarder les résultats.
47
  """
48
- if results_dir is None:
49
- results_dir = os.path.join(tempfile.gettempdir(), "results") # ✅ Dossier temporaire
50
-
51
- os.makedirs(results_dir, exist_ok=True)
52
  self.results_dir = results_dir
53
 
54
  # Constants
@@ -90,9 +88,11 @@ class SolarCellVisualizer:
90
  ax1.legend(fontsize=12)
91
 
92
  # Tracer l'erreur absolue moyenne
 
 
93
  ax2 = plt.subplot(gs[0, 1])
94
- ax2.plot(history['mae'], 'g-', linewidth=2, label='Entraînement')
95
- ax2.plot(history['val_mae'], 'm-', linewidth=2, label='Validation')
96
  ax2.set_title('Évolution de l\'erreur absolue moyenne', fontsize=14, fontweight='bold')
97
  ax2.set_xlabel('Époque', fontsize=12)
98
  ax2.set_ylabel('MAE', fontsize=12)
@@ -116,7 +116,7 @@ class SolarCellVisualizer:
116
  # Calculer les statistiques
117
  best_epoch = np.argmin(history['val_loss'])
118
  best_val_loss = history['val_loss'][best_epoch]
119
- best_val_mae = history['val_mae'][best_epoch]
120
 
121
  # Créer le tableau
122
  table_data = [
@@ -571,9 +571,8 @@ class SolarCellVisualizer:
571
  else:
572
  plt.close()
573
 
574
- def test_all_data(self,data_processor, model, X_test, y_test):
575
  param_names = ['Rsh', 'Rs', 'n', 'J0', 'Jph']
576
-
577
  y_pred = model.predict(X_test)
578
 
579
  # Inverser la normalisation
@@ -591,9 +590,19 @@ class SolarCellVisualizer:
591
  params_pred = y_pred_orig[i]
592
  params = {}
593
  for i, param in enumerate(param_names):
594
- params[param] = params_pred[i]
 
 
595
  I_model = -iv_curve(v_values, params['Rsh'], params['Rs'], params['n']*self.Vth, params['J0'], params['Jph'])
596
- I_reel = - iv_curve(v_values, params_real[0], params_real[1], params_real[2]*self.Vth, params_real[3], params_real[4])
 
 
 
 
 
 
 
 
597
 
598
  ssd = np.mean(np.square(I_model - I_reel), axis=0)
599
  if not np.isnan(ssd):
@@ -603,8 +612,8 @@ class SolarCellVisualizer:
603
 
604
  for i, param in enumerate(param_names):
605
  real_val = params_real[i]
606
- pred_val = params_pred[i]
607
- logger.info(f"vraies infos {real_val} {pred_val}")
608
 
609
  rel_error[param] += np.abs((real_val - pred_val) / (real_val)) * 100
610
  for i, param in enumerate(param_names):
@@ -613,23 +622,74 @@ class SolarCellVisualizer:
613
  ssd_mean = ssd_mean / nb_good_samples
614
  logger.info(f"SSD moyen pour les échantillons de test: {ssd_mean:.4g}")
615
  return rel_error, ssd_mean
 
616
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
617
 
618
- def plot_comparaison_courbes(self,data_processor, model, X_test, lst_I_real, lst_V, Plot =True):
619
 
 
 
620
  param_names = ['Rsh', 'Rs', 'n', 'J0', 'Jph']
621
-
622
  y_pred = model.predict(X_test)
623
  # Inverser la normalisation
624
  y_pred_orig = data_processor.inverse_transform_params(y_pred)
 
625
  for i in range (len(X_test)):
626
  params = {'Rsh':0, 'Rs':0, 'n':0, 'J0':0, 'Jph':0}
627
  params_pred = y_pred_orig[i]
628
  for j, param in enumerate(param_names):
629
  params[param] = params_pred[j]
630
-
631
  I_model = -iv_curve(lst_V[i], params['Rsh'], params['Rs'], params['n']*self.Vth, params['J0'], params['Jph'])
632
-
633
  if Plot:
634
  plt.plot(lst_V[i], I_model, label='Courbe I-V prédite', color='red')
635
  plt.plot(lst_V[i], lst_I_real[i], label='Courbe I-V réelle', color='blue')
@@ -640,6 +700,7 @@ class SolarCellVisualizer:
640
  plt.legend(fontsize=12)
641
  plt.show()
642
  return params, I_model
 
643
 
644
  def comparaison_courbes(self,data_processor, model, X_test, lst_I_real, lst_V):
645
 
@@ -651,8 +712,8 @@ class SolarCellVisualizer:
651
  for i in range (len(X_test)):
652
  params = {'Rsh':0, 'Rs':0, 'n':0, 'J0':0, 'Jph':0}
653
  params_pred = y_pred_orig[i]
654
- for i, param in enumerate(param_names):
655
- params[param] = params_pred[i]
656
 
657
  I_model = -iv_curve(lst_V, params['Rsh'], params['Rs'], params['n']*self.Vth, params['J0'], params['Jph'])
658
  return params, I_model
 
1
+ #!/usr/bin/env python3
2
  # -*- coding: utf-8 -*-
3
  """
4
  Module de visualisation pour le projet d'IA solaire.
 
17
  import matplotlib.cm as cm
18
  from mpl_toolkits.mplot3d import Axes3D
19
  from pvlib.pvsystem import i_from_v
20
+ from scipy.optimize import curve_fit
21
+ from scipy.interpolate import interp1d
22
+
23
 
24
 
25
  def iv_curve(voltage, rsh, rs, nNsVth, J0, Jph):
 
40
  pour la prédiction des paramètres des cellules solaires.
41
  """
42
 
43
+ def __init__(self, results_dir='../results'):
44
  """
45
  Initialise le visualiseur.
46
 
47
  Args:
48
  results_dir (str): Répertoire pour sauvegarder les résultats.
49
  """
 
 
 
 
50
  self.results_dir = results_dir
51
 
52
  # Constants
 
88
  ax1.legend(fontsize=12)
89
 
90
  # Tracer l'erreur absolue moyenne
91
+ mae_moy = np.mean([history['output_Rsh_mae'],history['output_Rs_mae'],history['output_n_mae'],history['output_J0_mae'],history['output_Jph_mae'] ], axis=0)
92
+ val_mae_moy = np.mean([history['val_output_Rsh_mae'],history['val_output_Rs_mae'],history['val_output_n_mae'],history['val_output_J0_mae'],history['val_output_Jph_mae'] ], axis=0)
93
  ax2 = plt.subplot(gs[0, 1])
94
+ ax2.plot(mae_moy, 'g-', linewidth=2, label='Entraînement')
95
+ ax2.plot(val_mae_moy, 'm-', linewidth=2, label='Validation')
96
  ax2.set_title('Évolution de l\'erreur absolue moyenne', fontsize=14, fontweight='bold')
97
  ax2.set_xlabel('Époque', fontsize=12)
98
  ax2.set_ylabel('MAE', fontsize=12)
 
116
  # Calculer les statistiques
117
  best_epoch = np.argmin(history['val_loss'])
118
  best_val_loss = history['val_loss'][best_epoch]
119
+ best_val_mae = val_mae_moy[best_epoch]
120
 
121
  # Créer le tableau
122
  table_data = [
 
571
  else:
572
  plt.close()
573
 
574
+ def test_all_data(self,data_processor, model, X_test, y_test, Fit = False, Plot = False):
575
  param_names = ['Rsh', 'Rs', 'n', 'J0', 'Jph']
 
576
  y_pred = model.predict(X_test)
577
 
578
  # Inverser la normalisation
 
590
  params_pred = y_pred_orig[i]
591
  params = {}
592
  for i, param in enumerate(param_names):
593
+ params[param] = params_pred[i]
594
+ if Fit:
595
+ params, I_after_fit, ssd = self.fit_after_model(X_orig[:, 1], X_orig[:, 0], params)
596
  I_model = -iv_curve(v_values, params['Rsh'], params['Rs'], params['n']*self.Vth, params['J0'], params['Jph'])
597
+ I_reel = X_orig[:, 1]
598
+ if Plot:
599
+ plt.plot(v_values, I_model, label='Modèle')
600
+ plt.plot(v_values, I_reel, label='Réel')
601
+ plt.title(f'Comparaison des courbes I-V - Échantillon {i}')
602
+ plt.xlabel('Tension (V)')
603
+ plt.ylabel('Courant (I)')
604
+ plt.legend()
605
+ plt.show()
606
 
607
  ssd = np.mean(np.square(I_model - I_reel), axis=0)
608
  if not np.isnan(ssd):
 
612
 
613
  for i, param in enumerate(param_names):
614
  real_val = params_real[i]
615
+ pred_val = params[param]
616
+ #logger.info(f"vraies infos {real_val} {pred_val}")
617
 
618
  rel_error[param] += np.abs((real_val - pred_val) / (real_val)) * 100
619
  for i, param in enumerate(param_names):
 
622
  ssd_mean = ssd_mean / nb_good_samples
623
  logger.info(f"SSD moyen pour les échantillons de test: {ssd_mean:.4g}")
624
  return rel_error, ssd_mean
625
+
626
 
627
+ def fit_after_model(self, I, V, params):
628
+ k = 1.3806503e-23 # Boltzmann constant (J/K)
629
+ q = 1.60217646e-19 # Elementary charge (C)
630
+
631
+ #self.Tmes = int(chemin.split("\\")[-1].split("_")[1]) + 273.15
632
+ Tmes = 300
633
+
634
+ Vth = k * Tmes / q
635
+
636
+ params_to_fit = { "Rsh": params['Rsh'],
637
+ "Rs": params['Rs'],
638
+ "nVth": params['n']*Vth,
639
+ "J0": params['J0'],
640
+ "Jph": params['Jph']}
641
+ bounds = {
642
+ "Rsh": [1, 4000],
643
+ "Rs": [0.1, 5],
644
+ "nVth": [0.8*Vth, 3*Vth],
645
+ "J0": [1e-20, 1e-5],
646
+ }
647
+ params_to_fit["Jph"] = -I[0]
648
+
649
+ if params_to_fit["Jph"] > 0:
650
+ low_bounds = [bounds["Rsh"][0],bounds["Rs"][0], bounds["nVth"][0], bounds["J0"][0], params_to_fit["Jph"] * 0.9]
651
+ high_bounds = [bounds["Rsh"][1],bounds["Rs"][1], bounds["nVth"][1], bounds["J0"][1],params_to_fit["Jph"] * 1.1]
652
+ else:
653
+ low_bounds = [bounds["Rsh"][0],bounds["Rs"][0], bounds["nVth"][0], bounds["J0"][0], params_to_fit["Jph"] * 1.1]
654
+ high_bounds = [bounds["Rsh"][1],bounds["Rs"][1], bounds["nVth"][1], bounds["J0"][1],params_to_fit["Jph"] * 0.9]
655
+ #print("low_bounds", low_bounds)
656
+ #print("high_bounds", high_bounds)
657
+
658
+ # Ajustement automatique des paramètres s'ils dépassent les bornes
659
+ params_to_fit["Rsh"] = min(max(params_to_fit["Rsh"], bounds["Rsh"][0]), bounds["Rsh"][1])
660
+ params_to_fit["Rs"] = min(max(params_to_fit["Rs"], bounds["Rs"][0]), bounds["Rs"][1])
661
+ params_to_fit["nVth"] = min(max(params_to_fit["nVth"], bounds["nVth"][0]), bounds["nVth"][1])
662
+ params_to_fit["J0"] = min(max(params_to_fit["J0"], bounds["J0"][0]), bounds["J0"][1])
663
+
664
+ popt, pcov = curve_fit(iv_curve, V, -I,
665
+ p0=list(params_to_fit.values()), bounds=(low_bounds, high_bounds), maxfev=10000)
666
+ param_fit = { "Rsh": popt[0],
667
+ "Rs": popt[1],
668
+ "nVth": popt[2],
669
+ "J0": popt[3],
670
+ "Jph":popt[4]}
671
+ param_fit["n"] = param_fit["nVth"] / Vth
672
+ I_after_fit = -iv_curve(V, param_fit['Rsh'], param_fit['Rs'], param_fit['n']*Vth, param_fit['J0'], param_fit['Jph'])
673
+ ssd = np.mean((I - I_after_fit) ** 2)
674
+ print("SSD après ajustement:", ssd)
675
+ return param_fit,I_after_fit, ssd
676
 
 
677
 
678
+ def plot_comparaison_courbes(self,data_processor, model, X_test, lst_I_real, lst_V, Plot =True):
679
+
680
  param_names = ['Rsh', 'Rs', 'n', 'J0', 'Jph']
681
+
682
  y_pred = model.predict(X_test)
683
  # Inverser la normalisation
684
  y_pred_orig = data_processor.inverse_transform_params(y_pred)
685
+
686
  for i in range (len(X_test)):
687
  params = {'Rsh':0, 'Rs':0, 'n':0, 'J0':0, 'Jph':0}
688
  params_pred = y_pred_orig[i]
689
  for j, param in enumerate(param_names):
690
  params[param] = params_pred[j]
 
691
  I_model = -iv_curve(lst_V[i], params['Rsh'], params['Rs'], params['n']*self.Vth, params['J0'], params['Jph'])
692
+
693
  if Plot:
694
  plt.plot(lst_V[i], I_model, label='Courbe I-V prédite', color='red')
695
  plt.plot(lst_V[i], lst_I_real[i], label='Courbe I-V réelle', color='blue')
 
700
  plt.legend(fontsize=12)
701
  plt.show()
702
  return params, I_model
703
+
704
 
705
  def comparaison_courbes(self,data_processor, model, X_test, lst_I_real, lst_V):
706
 
 
712
  for i in range (len(X_test)):
713
  params = {'Rsh':0, 'Rs':0, 'n':0, 'J0':0, 'Jph':0}
714
  params_pred = y_pred_orig[i]
715
+ for j, param in enumerate(param_names):
716
+ params[param] = params_pred[j]
717
 
718
  I_model = -iv_curve(lst_V, params['Rsh'], params['Rs'], params['n']*self.Vth, params['J0'], params['Jph'])
719
  return params, I_model