Polyfit / src /visualization.py
axelrvite's picture
Update src/visualization.py
0f98710 verified
Raw History Blame
30.4 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Module de visualisation pour le projet d'IA solaire.
Ce module permet de visualiser les résultats du modèle d'IA
pour la prédiction des paramètres des cellules solaires.
"""
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pandas as pd
import logging
import matplotlib.gridspec as gridspec
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import Axes3D
from pvlib.pvsystem import i_from_v
from scipy.optimize import curve_fit
from scipy.interpolate import interp1d
def iv_curve(voltage, rsh, rs, nNsVth, J0, Jph):
"""
Compute the current for a given voltage based on the single-diode equation.
"""
return i_from_v(voltage, Jph,J0, rs, rsh, nNsVth,method="lambertw")
# Configuration du logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class SolarCellVisualizer:
"""
Classe pour la visualisation des résultats du modèle d'IA
pour la prédiction des paramètres des cellules solaires.
"""
def __init__(self):
"""
Initialise le visualiseur.
Args:
results_dir (str): Répertoire pour sauvegarder les résultats.
"""
# Constants
self.k = 1.3806503e-23 # Boltzmann constant (J/K)
self.q = 1.60217646e-19 # Elementary charge (C)
#self.Tmes = int(chemin.split("\\")[-1].split("_")[1]) + 273.15
self.Tmes = 23 + 273.15
self.Vth = self.k * self.Tmes / self.q # Thermal voltage
def plot_training_progress(self, history_callback, save_path=None, show=True):
"""
Trace l'évolution de la perte et des métriques pendant l'entraînement.
Args:
history_callback (tensorflow.keras.callbacks.History): Historique d'entraînement.
save_path (str): Chemin pour sauvegarder le graphique.
show (bool): Afficher le graphique.
"""
history = history_callback.history
plt.figure(figsize=(15, 10))
# Grille pour organiser les sous-graphiques
gs = gridspec.GridSpec(2, 2, height_ratios=[2, 1])
# Tracer la perte
ax1 = plt.subplot(gs[0, 0])
ax1.plot(history['loss'], 'b-', linewidth=2, label='Entraînement')
ax1.plot(history['val_loss'], 'r-', linewidth=2, label='Validation')
ax1.set_title('Évolution de la perte (MSE)', fontsize=14, fontweight='bold')
ax1.set_xlabel('Époque', fontsize=12)
ax1.set_ylabel('Perte', fontsize=12)
ax1.grid(True, linestyle='--', alpha=0.7)
ax1.legend(fontsize=12)
# Tracer l'erreur absolue moyenne
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)
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)
ax2 = plt.subplot(gs[0, 1])
ax2.plot(mae_moy, 'g-', linewidth=2, label='Entraînement')
ax2.plot(val_mae_moy, 'm-', linewidth=2, label='Validation')
ax2.set_title('Évolution de l\'erreur absolue moyenne', fontsize=14, fontweight='bold')
ax2.set_xlabel('Époque', fontsize=12)
ax2.set_ylabel('MAE', fontsize=12)
ax2.grid(True, linestyle='--', alpha=0.7)
ax2.legend(fontsize=12)
# Tracer le taux d'apprentissage si disponible
if 'lr' in history:
ax3 = plt.subplot(gs[1, 0])
ax3.plot(history['lr'], 'k-', linewidth=2)
ax3.set_title('Taux d\'apprentissage', fontsize=14, fontweight='bold')
ax3.set_xlabel('Époque', fontsize=12)
ax3.set_ylabel('Taux', fontsize=12)
ax3.set_yscale('log')
ax3.grid(True, linestyle='--', alpha=0.7)
# Tableau récapitulatif
ax4 = plt.subplot(gs[1, 1])
ax4.axis('off')
# Calculer les statistiques
best_epoch = np.argmin(history['val_loss'])
best_val_loss = history['val_loss'][best_epoch]
best_val_mae = val_mae_moy[best_epoch]
# Créer le tableau
table_data = [
['Meilleure époque', f"{best_epoch + 1}"],
['Perte minimale (validation)', f"{best_val_loss:.6f}"],
['MAE minimale (validation)', f"{best_val_mae:.6f}"],
['Nombre total d\'époques', f"{len(history['loss'])}"]
]
table = ax4.table(cellText=table_data, loc='center', cellLoc='center',
colWidths=[0.5, 0.5], bbox=[0.1, 0.1, 0.8, 0.8])
table.auto_set_font_size(False)
table.set_fontsize(12)
table.scale(1, 1.5)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
logger.info(f"Graphique d'évolution de l'entraînement sauvegardé à {save_path}")
if show:
plt.show()
else:
plt.close()
def create_animated_training_progress(self, history, save_path=None, interval=200):
"""
Crée une animation de l'évolution de la perte pendant l'entraînement.
Args:
history (dict): Historique d'entraînement.
save_path (str): Chemin pour sauvegarder l'animation.
interval (int): Intervalle entre les images en millisecondes.
"""
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
# Initialiser les lignes
line1, = ax1.plot([], [], 'b-', linewidth=2, label='Entraînement')
line2, = ax1.plot([], [], 'r-', linewidth=2, label='Validation')
line3, = ax2.plot([], [], 'g-', linewidth=2, label='Entraînement')
line4, = ax2.plot([], [], 'm-', linewidth=2, label='Validation')
# Configurer les axes
ax1.set_title('Évolution de la perte (MSE)', fontsize=14, fontweight='bold')
ax1.set_xlabel('Époque', fontsize=12)
ax1.set_ylabel('Perte', fontsize=12)
ax1.grid(True, linestyle='--', alpha=0.7)
ax1.legend(fontsize=12)
ax2.set_title('Évolution de l\'erreur absolue moyenne', fontsize=14, fontweight='bold')
ax2.set_xlabel('Époque', fontsize=12)
ax2.set_ylabel('MAE', fontsize=12)
ax2.grid(True, linestyle='--', alpha=0.7)
ax2.legend(fontsize=12)
# Définir les limites des axes
ax1.set_xlim(0, len(history['loss']))
ax1.set_ylim(0, max(history['loss']) * 1.1)
ax2.set_xlim(0, len(history['mae']))
ax2.set_ylim(0, max(history['mae']) * 1.1)
def init():
line1.set_data([], [])
line2.set_data([], [])
line3.set_data([], [])
line4.set_data([], [])
return line1, line2, line3, line4
def animate(i):
x = np.arange(i+1)
line1.set_data(x, history['loss'][:i+1])
line2.set_data(x, history['val_loss'][:i+1])
line3.set_data(x, history['mae'][:i+1])
line4.set_data(x, history['val_mae'][:i+1])
return line1, line2, line3, line4
anim = FuncAnimation(fig, animate, frames=len(history['loss']),
init_func=init, blit=True, interval=interval)
plt.tight_layout()
if save_path:
anim.save(save_path, writer='pillow', fps=5)
logger.info(f"Animation de l'évolution de l'entraînement sauvegardée à {save_path}")
plt.show()
def plot_parameter_distributions(self, y_true, y_pred, param_names=None, save_path=None, show=True):
"""
Trace les distributions des paramètres réels et prédits.
Args:
y_true (numpy.ndarray): Paramètres réels.
y_pred (numpy.ndarray): Paramètres prédits.
param_names (list): Noms des paramètres.
save_path (str): Chemin pour sauvegarder le graphique.
show (bool): Afficher le graphique.
"""
if param_names is None:
param_names = ['Rsh', 'Rs', 'n', 'J0', 'Jph']
n_params = y_true.shape[1]
plt.figure(figsize=(15, 10))
for i in range(n_params):
plt.subplot(2, 3, i+1)
# Histogramme des valeurs réelles
plt.hist(y_true[:, i], bins=30, alpha=0.5, label='Réel', color='blue')
# Histogramme des valeurs prédites
plt.hist(y_pred[:, i], bins=30, alpha=0.5, label='Prédit', color='red')
plt.title(f'Distribution de {param_names[i]}', fontsize=12, fontweight='bold')
plt.xlabel('Valeur', fontsize=10)
plt.ylabel('Fréquence', fontsize=10)
plt.legend()
plt.grid(True, linestyle='--', alpha=0.7)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
logger.info(f"Graphique des distributions de paramètres sauvegardé à {save_path}")
if show:
plt.show()
else:
plt.close()
def plot_parameter_correlations(self, y_true, y_pred, param_names=None, save_path=None, show=True):
"""
Trace les corrélations entre les paramètres réels et prédits.
Args:
y_true (numpy.ndarray): Paramètres réels.
y_pred (numpy.ndarray): Paramètres prédits.
param_names (list): Noms des paramètres.
save_path (str): Chemin pour sauvegarder le graphique.
show (bool): Afficher le graphique.
"""
if param_names is None:
param_names = ['Rsh', 'Rs', 'n', 'J0', 'Jph']
n_params = y_true.shape[1]
plt.figure(figsize=(15, 10))
for i in range(n_params):
plt.subplot(2, 3, i+1)
# Nuage de points
plt.scatter(y_true[:, i], y_pred[:, i], alpha=0.5, color='blue')
# Ligne de référence (y = x)
min_val = min(y_true[:, i].min(), y_pred[:, i].min())
max_val = max(y_true[:, i].max(), y_pred[:, i].max())
plt.plot([min_val, max_val], [min_val, max_val], 'r--')
plt.title(f'Corrélation pour {param_names[i]}', fontsize=12, fontweight='bold')
plt.xlabel('Valeur réelle', fontsize=10)
plt.ylabel('Valeur prédite', fontsize=10)
# Calculer et afficher le coefficient de corrélation
corr = np.corrcoef(y_true[:, i], y_pred[:, i])[0, 1]
plt.annotate(f'r = {corr:.4f}', xy=(0.05, 0.95), xycoords='axes fraction',
fontsize=10, fontweight='bold', bbox=dict(boxstyle="round,pad=0.3", fc="white", ec="black", alpha=0.8))
plt.grid(True, linestyle='--', alpha=0.7)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
logger.info(f"Graphique des corrélations de paramètres sauvegardé à {save_path}")
if show:
plt.show()
else:
plt.close()
def plot_iv_curve_comparison(self, v_values, i_real, i_pred, params_real, params_pred,
param_names=None, sample_id=0, save_path=None, show=True):
"""
Trace une comparaison détaillée entre les courbes I-V réelles et reconstruites.
Args:
v_values (numpy.ndarray): Valeurs de tension.
i_real (numpy.ndarray): Valeurs de courant réelles.
i_pred (numpy.ndarray): Valeurs de courant prédites.
params_real (numpy.ndarray): Paramètres réels.
params_pred (numpy.ndarray): Paramètres prédits.
param_names (list): Noms des paramètres.
sample_id (int): Identifiant de l'échantillon.
save_path (str): Chemin pour sauvegarder le graphique.
show (bool): Afficher le graphique.
"""
if param_names is None:
param_names = ['Rsh', 'Rs', 'n', 'J0', 'Jph']
plt.figure(figsize=(15, 10))
# Grille pour organiser les sous-graphiques
gs = gridspec.GridSpec(2, 2, height_ratios=[2, 1])
# Courbes I-V
ax1 = plt.subplot(gs[0, :])
ax1.plot(v_values, i_real, 'o-', color='blue', linewidth=2, markersize=6, label='Courbe I-V réelle')
ax1.plot(v_values, i_pred, 's--', color='red', linewidth=2, markersize=6, label='Courbe I-V reconstruite')
ax1.set_title(f'Comparaison des courbes I-V - Échantillon {sample_id}', fontsize=14, fontweight='bold')
ax1.set_xlabel('Tension (V)', fontsize=12)
ax1.set_ylabel('Courant (I)', fontsize=12)
ax1.grid(True, linestyle='--', alpha=0.7)
ax1.legend(fontsize=12)
# Erreur relative
ax2 = plt.subplot(gs[1, 0])
rel_error = np.abs((i_real - i_pred) / (i_real + 1e-10)) * 100
ax2.plot(v_values, rel_error, 'g-', linewidth=2)
ax2.set_title('Erreur relative (%)', fontsize=14, fontweight='bold')
ax2.set_xlabel('Tension (V)', fontsize=12)
ax2.set_ylabel('Erreur (%)', fontsize=12)
ax2.grid(True, linestyle='--', alpha=0.7)
# Tableau des paramètres
ax3 = plt.subplot(gs[1, 1])
ax3.axis('off')
# Créer le tableau
table_data = []
for i, param in enumerate(param_names):
real_val = params_real[i]
pred_val = params_pred[i]
rel_err = np.abs((real_val - pred_val) / (real_val + 1e-10)) * 100
# Formater les valeurs en notation scientifique si nécessaire
if abs(real_val) < 0.01 or abs(real_val) > 1000:
real_str = f"{real_val:.4e}"
pred_str = f"{pred_val:.4e}"
else:
real_str = f"{real_val:.4f}"
pred_str = f"{pred_val:.4f}"
table_data.append([param, real_str, pred_str, f"{rel_err:.2f}%"])
table = ax3.table(cellText=table_data,
colLabels=['Paramètre', 'Réel', 'Prédit', 'Erreur (%)'],
loc='center', cellLoc='center',
colWidths=[0.25, 0.25, 0.25, 0.25],
bbox=[0.0, 0.0, 1.0, 1.0])
table.auto_set_font_size(False)
table.set_fontsize(12)
table.scale(1, 1.5)
# Colorer les cellules en fonction de l'erreur
for i in range(len(param_names)):
err_val = float(table_data[i][3].strip('%'))
if err_val < 5:
color = (0.8, 1.0, 0.8) # Vert clair
elif err_val < 10:
color = (1.0, 1.0, 0.8) # Jaune clair
else:
color = (1.0, 0.8, 0.8) # Rouge clair
table[(i+1, 3)].set_facecolor(color)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
logger.info(f"Graphique de comparaison de courbe I-V sauvegardé à {save_path}")
if show:
plt.show()
else:
plt.close()
def plot_parameter_importance(self, model, param_names=None, save_path=None, show=True):
"""
Visualise l'importance des paramètres dans le modèle.
Args:
model (tensorflow.keras.Model): Modèle entraîné.
param_names (list): Noms des paramètres.
save_path (str): Chemin pour sauvegarder le graphique.
show (bool): Afficher le graphique.
"""
if param_names is None:
param_names = ['Rsh', 'Rs', 'n', 'J0', 'Jph']
# Extraire les poids de la dernière couche dense
weights = model.layers[-1].get_weights()[0]
# Calculer l'importance relative (somme des valeurs absolues des poids)
importance = np.sum(np.abs(weights), axis=0)
importance = importance / np.sum(importance) # Normaliser
plt.figure(figsize=(10, 6))
# Graphique à barres
bars = plt.bar(param_names, importance, color='skyblue')
# Ajouter les valeurs sur les barres
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 0.01,
f'{height:.2f}', ha='center', va='bottom', fontsize=10)
plt.title('Importance relative des paramètres dans le modèle', fontsize=14, fontweight='bold')
plt.xlabel('Paramètre', fontsize=12)
plt.ylabel('Importance relative', fontsize=12)
plt.ylim(0, max(importance) * 1.2)
plt.grid(True, linestyle='--', alpha=0.7, axis='y')
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
logger.info(f"Graphique d'importance des paramètres sauvegardé à {save_path}")
if show:
plt.show()
else:
plt.close()
def create_interactive_dashboard(self, data_processor, model, X_test, y_test, n_samples=5, save_dir=None):
"""
Crée un tableau de bord interactif pour explorer les résultats du modèle.
Args:
data_processor (SolarDataProcessor): Processeur de données.
model (SolarCellModel): Modèle entraîné.
X_test (numpy.ndarray): Données de test.
y_test (numpy.ndarray): Cibles de test.
n_samples (int): Nombre d'échantillons à afficher.
save_dir (str): Répertoire pour sauvegarder les graphiques.
"""
# Sélectionner des échantillons aléatoires
if n_samples > len(X_test):
n_samples = len(X_test)
indices = np.random.choice(len(X_test), n_samples, replace=False)
# Prédire les paramètres
y_pred = model.predict(X_test)
# Inverser la normalisation
y_test_orig = data_processor.inverse_transform_params(y_test)
y_pred_orig = data_processor.inverse_transform_params(y_pred)
# Créer le répertoire de sauvegarde si nécessaire
if save_dir:
os.makedirs(save_dir, exist_ok=True)
ssd_mean = 0
for i in range(len(X_test)):
X_orig = data_processor.input_scaler.inverse_transform(X_test[i].reshape(1, -1)).reshape(-1, 2)
v_values = X_orig[:, 0]
i_real = X_orig[:, 1]
# Paramètres réels et prédits
params_real = y_test_orig[i]
params_pred = y_pred_orig[i]
# Reconstruire la courbe I-V à partir des paramètres prédits
i_pred = model.reconstruct_iv_curve(params_pred, v_values)
ssd_mean += np.mean((i_real - i_pred)**2, axis=0)
ssd_mean = ssd_mean / len(X_test)
logger.info(f"SSD moyen pour les échantillons de test: {ssd_mean:.4g}")
# Pour chaque échantillon sélectionné
for i, idx in enumerate(indices):
# Récupérer les données originales
X_orig = data_processor.input_scaler.inverse_transform(X_test[idx].reshape(1, -1)).reshape(-1, 2)
v_values = X_orig[:, 0]
i_real = X_orig[:, 1]
# Paramètres réels et prédits
params_real = y_test_orig[idx]
params_pred = y_pred_orig[idx]
# Reconstruire la courbe I-V à partir des paramètres prédits
i_pred = model.reconstruct_iv_curve(params_pred, v_values)
# Tracer la comparaison détaillée
save_path = os.path.join(save_dir, f'dashboard_sample_{idx}.png') if save_dir else None
self.plot_iv_curve_comparison(v_values, i_real, i_pred, params_real, params_pred,
sample_id=idx, save_path=save_path)
# Tracer les distributions et corrélations globales
if save_dir:
self.plot_parameter_distributions(y_test_orig, y_pred_orig,
save_path=os.path.join(save_dir, 'parameter_distributions.png'))
self.plot_parameter_correlations(y_test_orig, y_pred_orig,
save_path=os.path.join(save_dir, 'parameter_correlations.png'))
# Tracer l'importance des paramètres si possible
try:
self.plot_parameter_importance(model.model,
save_path=os.path.join(save_dir, 'parameter_importance.png'))
except:
logger.warning("Impossible de tracer l'importance des paramètres.")
def create_3d_visualization(self, v_values, i_values, params, param_idx=0, param_name=None,
save_path=None, show=True):
"""
Crée une visualisation 3D de l'influence d'un paramètre sur la courbe I-V.
Args:
v_values (numpy.ndarray): Valeurs de tension.
i_values (list): Liste de courbes I-V pour différentes valeurs du paramètre.
params (numpy.ndarray): Valeurs du paramètre.
param_idx (int): Indice du paramètre à visualiser.
param_name (str): Nom du paramètre.
save_path (str): Chemin pour sauvegarder le graphique.
show (bool): Afficher le graphique.
"""
if param_name is None:
param_names = ['Rsh', 'Rs', 'n', 'J0', 'Jph']
param_name = param_names[param_idx]
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')
# Créer une grille pour la surface
V, P = np.meshgrid(v_values, params)
I = np.array(i_values)
# Tracer la surface
surf = ax.plot_surface(V, P, I, cmap='viridis', edgecolor='none', alpha=0.8)
# Ajouter une barre de couleur
fig.colorbar(surf, ax=ax, shrink=0.5, aspect=5, label='Courant (I)')
# Configurer les axes
ax.set_xlabel('Tension (V)', fontsize=12)
ax.set_ylabel(f'Paramètre {param_name}', fontsize=12)
ax.set_zlabel('Courant (I)', fontsize=12)
ax.set_title(f'Influence du paramètre {param_name} sur la courbe I-V', fontsize=14, fontweight='bold')
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
logger.info(f"Visualisation 3D sauvegardée à {save_path}")
if show:
plt.show()
else:
plt.close()
def test_all_data(self,data_processor, model, X_test, y_test, Fit = False, Plot = False):
param_names = ['Rsh', 'Rs', 'n', 'J0', 'Jph']
y_pred = model.predict(X_test)
# Inverser la normalisation
y_test_orig = data_processor.inverse_transform_params(y_test)
y_pred_orig = data_processor.inverse_transform_params(y_pred)
rel_error = {'Rsh':0, 'Rs':0, 'n':0, 'J0':0, 'Jph':0}
ssd_mean = 0
nb_good_samples = 0
for i in range (len(X_test)):
X_orig = data_processor.input_scaler.inverse_transform(X_test[i].reshape(1, -1)).reshape(-1, 2)
v_values = X_orig[:, 0]
params_real = y_test_orig[i]
params_pred = y_pred_orig[i]
params = {}
for i, param in enumerate(param_names):
params[param] = params_pred[i]
if Fit:
params, I_after_fit, ssd = self.fit_after_model(X_orig[:, 1], X_orig[:, 0], params)
I_model = -iv_curve(v_values, params['Rsh'], params['Rs'], params['n']*self.Vth, params['J0'], params['Jph'])
I_reel = X_orig[:, 1]
if Plot:
plt.plot(v_values, I_model, label='Modèle')
plt.plot(v_values, I_reel, label='Réel')
plt.title(f'Comparaison des courbes I-V - Échantillon {i}')
plt.xlabel('Tension (V)')
plt.ylabel('Courant (I)')
plt.legend()
plt.show()
ssd = np.mean(np.square(I_model - I_reel), axis=0)
if not np.isnan(ssd):
ssd_mean += ssd
nb_good_samples += 1
for i, param in enumerate(param_names):
real_val = params_real[i]
pred_val = params[param]
#logger.info(f"vraies infos {real_val} {pred_val}")
rel_error[param] += np.abs((real_val - pred_val) / (real_val)) * 100
for i, param in enumerate(param_names):
rel_error[param] = rel_error[param] / len(X_test)
logger.info(f"Erreur relative moyenne pour {param}: {rel_error[param]:.2f}%")
ssd_mean = ssd_mean / nb_good_samples
logger.info(f"SSD moyen pour les échantillons de test: {ssd_mean:.4g}")
return rel_error, ssd_mean
def fit_after_model(self, I, V, params, temp):
k = 1.3806503e-23 # Boltzmann constant (J/K)
q = 1.60217646e-19 # Elementary charge (C)
#self.Tmes = int(chemin.split("\\")[-1].split("_")[1]) + 273.15
if temp != None:
Tmes = 273.15 + float(temp)
else:
Tmes = 300
Vth = k * Tmes / q
params_to_fit = { "Rsh": params['Rsh'],
"Rs": params['Rs'],
"nVth": params['n']*Vth,
"J0": params['J0'],
"Jph": params['Jph']}
bounds = {
"Rsh": [1, 4000],
"Rs": [0.1, 5],
"nVth": [0.8*Vth, 3*Vth],
"J0": [1e-20, 1e-5],
}
params_to_fit["Jph"] = -I[0]
print("Jph", -I[0])
if params_to_fit["Jph"] > 0:
low_bounds = [bounds["Rsh"][0],bounds["Rs"][0], bounds["nVth"][0], bounds["J0"][0], params_to_fit["Jph"] * 0.9]
high_bounds = [bounds["Rsh"][1],bounds["Rs"][1], bounds["nVth"][1], bounds["J0"][1],params_to_fit["Jph"] * 1.1]
else:
low_bounds = [bounds["Rsh"][0],bounds["Rs"][0], bounds["nVth"][0], bounds["J0"][0], params_to_fit["Jph"] * 1.1]
high_bounds = [bounds["Rsh"][1],bounds["Rs"][1], bounds["nVth"][1], bounds["J0"][1],params_to_fit["Jph"] * 0.9]
#print("low_bounds", low_bounds)
#print("high_bounds", high_bounds)
# Ajustement automatique des paramètres s'ils dépassent les bornes
params_to_fit["Rsh"] = min(max(params_to_fit["Rsh"], bounds["Rsh"][0]), bounds["Rsh"][1])
params_to_fit["Rs"] = min(max(params_to_fit["Rs"], bounds["Rs"][0]), bounds["Rs"][1])
params_to_fit["nVth"] = min(max(params_to_fit["nVth"], bounds["nVth"][0]), bounds["nVth"][1])
params_to_fit["J0"] = min(max(params_to_fit["J0"], bounds["J0"][0]), bounds["J0"][1])
popt, pcov = curve_fit(iv_curve, V, -I,
p0=list(params_to_fit.values()), bounds=(low_bounds, high_bounds), maxfev=10000)
param_fit = { "Rsh": popt[0],
"Rs": popt[1],
"nVth": popt[2],
"J0": popt[3],
"Jph":popt[4]}
param_fit["n"] = param_fit["nVth"] / Vth
I_after_fit = -iv_curve(V, param_fit['Rsh'], param_fit['Rs'], param_fit['n']*Vth, param_fit['J0'], param_fit['Jph'])
ssd = np.mean((I - I_after_fit) ** 2)
return param_fit,I_after_fit, ssd
def plot_comparaison_courbes(self,data_processor, model, X_test, lst_I_real, lst_V, Plot =True):
param_names = ['Rsh', 'Rs', 'n', 'J0', 'Jph']
y_pred = model.predict(X_test)
# Inverser la normalisation
y_pred_orig = data_processor.inverse_transform_params(y_pred)
for i in range (len(X_test)):
params = {'Rsh':0, 'Rs':0, 'n':0, 'J0':0, 'Jph':0}
params_pred = y_pred_orig[i]
for j, param in enumerate(param_names):
params[param] = params_pred[j]
I_model = -iv_curve(lst_V[i], params['Rsh'], params['Rs'], params['n']*self.Vth, params['J0'], params['Jph'])
if Plot:
plt.plot(lst_V[i], I_model, label='Courbe I-V prédite', color='red')
plt.plot(lst_V[i], lst_I_real[i], label='Courbe I-V réelle', color='blue')
plt.title(f'Comparaison des courbes I-V - Échantillon {i}', fontsize=14, fontweight='bold')
plt.xlabel('Tension (V)', fontsize=12)
plt.ylabel('Courant (I)', fontsize=12)
plt.grid(True, linestyle='--', alpha=0.7)
plt.legend(fontsize=12)
plt.show()
return params, I_model
def comparaison_courbes(self,data_processor, model, X_test, lst_I_real, lst_V):
param_names = ['Rsh', 'Rs', 'n', 'J0', 'Jph']
y_pred = model.predict(X_test)
# Inverser la normalisation
y_pred_orig = data_processor.inverse_transform_params(y_pred)
for i in range (len(X_test)):
params = {'Rsh':0, 'Rs':0, 'n':0, 'J0':0, 'Jph':0}
params_pred = y_pred_orig[i]
for j, param in enumerate(param_names):
params[param] = params_pred[j]
I_model = -iv_curve(lst_V, params['Rsh'], params['Rs'], params['n']*self.Vth, params['J0'], params['Jph'])
return params, I_model