File size: 4,618 Bytes
825dfaa
 
 
e2442a4
825dfaa
a8d88fc
 
2f059b3
7a51cfa
 
 
 
1da7516
e2442a4
825dfaa
 
1a4fcc7
63cb22a
a642b65
825dfaa
 
 
 
 
 
 
 
cba67eb
825dfaa
 
7a51cfa
63cb22a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a51cfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd266c2
 
 
 
 
 
 
4ddb85f
bd266c2
 
 
4ddb85f
bd266c2
 
 
4ddb85f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd266c2
4ddb85f
 
 
 
 
bd266c2
 
 
4ddb85f
 
4fc4d1a
bd266c2
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
# 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


def comp_iv_curve(filename):
    path_data = tempfile.gettempdir()
    path_model = os.path.join(os.getcwd(), "models", "final_model_mlp.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)

    return params, I_model

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

    # Chargement modèle CNN1D
    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)

    # Reshape pour CNN1D
    X_scaled = X_scaled[..., np.newaxis]

    params, I_model = visualizer.plot_comparaison_courbes(processor, model, X_scaled, I_list, V_list, Plot=False)

    return params, I_model

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