File size: 30,283 Bytes
d4ee94e
5295455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4ee94e
 
 
5295455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a242e83
5295455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4ee94e
 
5295455
d4ee94e
 
5295455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4ee94e
5295455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4ee94e
5295455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4ee94e
 
 
5295455
d4ee94e
 
 
 
 
 
 
 
 
5295455
 
 
 
 
 
 
 
 
d4ee94e
 
5295455
 
 
 
 
 
 
 
d4ee94e
5295455
d4ee94e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5295455
f69fe41
d4ee94e
 
f69fe41
d4ee94e
5295455
 
 
d4ee94e
5295455
 
 
f69fe41
 
5295455
d4ee94e
f69fe41
 
 
 
 
 
 
 
 
 
d4ee94e
5295455
 
 
 
 
 
 
 
 
 
 
d4ee94e
 
5295455
 
0e767d3
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
    #!/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):
        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
        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]
    
        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)
        print("SSD après ajustement:", ssd)
        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