Spaces:
Sleeping
Sleeping
Download app/api_utils.py from ClementGERARD/Polyfit: direct link, hf CLI and curl.
- Browser
- Download file 5.23 kB
-
https://huggingface.co/spaces/ClementGERARD/Polyfit/resolve/main/app/api_utils.py
- Command line
-
hf download hf://spaces/ClementGERARD/Polyfit/app/api_utils.py
-
curl -L -o api_utils.py https://huggingface.co/spaces/ClementGERARD/Polyfit/resolve/main/app/api_utils.py
5.23 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 | |
| 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 |