Polyfit / app /api_utils.py
ClementGERARD's picture
Update app/api_utils.py
4fc4d1a verified
Raw History Blame
4.62 kB
# 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