File size: 5,225 Bytes
825dfaa
 
 
e2442a4
825dfaa
a8d88fc
 
2f059b3
7a51cfa
 
 
 
1da7516
eb5283d
 
e2442a4
825dfaa
eb5283d
 
 
 
 
 
781702c
1a4fcc7
9ffb2e0
a642b65
825dfaa
 
 
 
 
 
 
 
cba67eb
eb5283d
781702c
eb5283d
 
7a51cfa
e5db543
63cb22a
9ffb2e0
63cb22a
 
 
9ffb2e0
 
 
 
63cb22a
 
9ffb2e0
 
e5db543
eb5283d
 
 
8089e1b
7a51cfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a9eda6
 
 
7a51cfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd266c2
 
 
 
 
 
 
4ddb85f
bd266c2
 
 
4ddb85f
bd266c2
 
 
4ddb85f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd266c2
4fc520c
 
 
 
4ddb85f
 
 
 
 
bd266c2
 
 
4ddb85f
 
4fc4d1a
8f63f5f
4ddb85f
bd266c2
4ddb85f
bd266c2
 
 
 
 
8276400
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
# app/api_utils.py
import tensorflow as tf
from tensorflow.keras import losses, metrics
import sys
import os
from src.data_preprocessing import SolarDataProcessor
from src.visualization import SolarCellVisualizer
import tempfile
import csv
import matplotlib.pyplot as plt
import io
import base64
import numpy as np
from scipy.optimize import curve_fit
from pvlib.pvsystem import i_from_v


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")

def comp_iv_curve(filename, temp):
    path_data = tempfile.gettempdir()
    path_model = os.path.join(os.getcwd(), "models", "final_model.h5")
    path_input = os.path.join(os.getcwd(), "models")
    visualizer = SolarCellVisualizer()

    # Chargement modèle
    model = tf.keras.models.load_model(path_model, 
                custom_objects={'mse': losses.MeanSquaredError(), 'mae': metrics.MeanAbsoluteError()})
    
    processor = SolarDataProcessor(path_input, path_data)
    X_scaled, I_list, V_list = processor.preprocess_input([filename], path_data)
    params, I_model = visualizer.plot_comparaison_courbes(processor, model, X_scaled, I_list, V_list, Plot = False)
    
    param_fit, I_after_fit, ssd = visualizer.fit_after_model(I_list[0], V_list[0], params, temp)
    
    return param_fit, I_after_fit

def comp_iv_curve_cnn1d(filename, temp):
    path_data = tempfile.gettempdir()
    path_model = os.path.join(os.getcwd(), "models", "final_model.h5")
    path_input = os.path.join(os.getcwd(), "models")
    visualizer = SolarCellVisualizer()

    # Chargement modèle
    model = tf.keras.models.load_model(path_model, 
                custom_objects={'mse': losses.MeanSquaredError(), 'mae': metrics.MeanAbsoluteError()})
    
    processor = SolarDataProcessor(path_input, path_data)
    X_scaled, I_list, V_list = processor.preprocess_input([filename], path_data)
    params, I_model = visualizer.plot_comparaison_courbes(processor, model, X_scaled, I_list, V_list, Plot = False)
    
    param_fit, I_after_fit, ssd = visualizer.fit_after_model(I_list[0], V_list[0], params, temp)
    
    return param_fit, I_after_fit

    
def read_iv_csv(filepath):
    points = []
    with open(filepath, newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            try:
                V = float(row['V'])
                I = float(row['I'])
                points.append((V, I))
            except ValueError:
                continue  # Ignorer les lignes invalides
    return points

def generate_curve_plot(points, model_points):
    fig, ax = plt.subplots()

    # Extraction des points
    V_input, I_input = zip(*points)

    if I_input[-1] < 0:
        I_input = tuple(-i for i in I_input)
    V_model, I_model = zip(*model_points)

    ax.scatter(V_input, I_input, color='blue', label='Données expérimentales', alpha=0.6)
    ax.plot(V_model, I_model, color='red', label='Courbe modélisée', linewidth=2)

    ax.set_xlabel('Tension (V)')
    ax.set_ylabel('Courant (I)')
    ax.set_title('Courbe I-V : Expérimental vs Modèle')
    ax.legend()
    ax.grid(True)

    # Sauvegarde de la figure dans un buffer mémoire
    buf = io.BytesIO()
    plt.savefig(buf, format='png', bbox_inches='tight')
    buf.seek(0)

    # Conversion en base64
    img_base64 = base64.b64encode(buf.read()).decode('utf-8')
    buf.close()
    plt.close(fig)
    return img_base64

def generate_multi_curve_plot(exp_points, model_dict):
    """
    Génère un graphique avec les points expérimentaux et plusieurs courbes modèles.
    Parameters:
        exp_points (list of tuple): Liste de tuples (V, I) expérimentaux.
        model_dict (dict): Dictionnaire de courbes à tracer.
    Returns:
        str: Image encodée en base64 (format PNG).
    """
    fig, ax = plt.subplots(figsize=(8, 5))

    # Points expérimentaux
    V_exp, I_exp = zip(*exp_points)
    ax.scatter(V_exp, I_exp, color='royalblue', label='Données expérimentales', alpha=0.5, s=25)

    # Styles personnalisés
    color_map = {
        'MLP': 'crimson',
        'GENETIQUE': 'darkgreen',
        'RANDOM': 'darkorange'
    }
    line_styles = {
        'MLP': '-',
        'GENETIQUE': '--',
        'RANDOM': ':'
    }

    for label, model_points in model_dict.items():
        V_model, I_model = zip(*model_points)
        I_model = np.array(I_model)

        V_model = np.array(V_model)
        
        ax.plot(V_model, I_model,
                label=label,
                color=color_map.get(label, 'gray'),
                linestyle=line_styles.get(label, '-.'),
                linewidth=2)

    ax.set_xlabel('Tension (V)')
    ax.set_ylabel('Courant (I)')
    ax.set_title('Courbe I-V : Comparaison des méthodes')
    ax.grid(True, linestyle='--', alpha=0.3)
    ax.legend(loc='upper left', fontsize='small')
    
    # Export en base64
    buf = io.BytesIO()
    plt.tight_layout()
    plt.savefig(buf, format='png', bbox_inches='tight')
    buf.seek(0)
    img_base64 = base64.b64encode(buf.read()).decode('utf-8')
    buf.close()
    plt.close(fig)
    return img_base64