C2MV commited on
Commit
ccd76a9
1 Parent(s): 09f684a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +229 -0
app.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # interface.py
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ import matplotlib.pyplot as plt
6
+ from PIL import Image
7
+ import io
8
+
9
+ from bioprocess_model import BioprocessModel
10
+ from decorators import gpu_decorator # Asegúrate de que la ruta es correcta
11
+
12
+ def parse_bounds(bounds_str, num_params):
13
+ try:
14
+ # Reemplazar 'inf' por 'np.inf' si el usuario lo escribió así
15
+ bounds_str = bounds_str.replace('inf', 'np.inf')
16
+ # Evaluar la cadena de límites
17
+ bounds = eval(f"[{bounds_str}]")
18
+ if len(bounds) != num_params:
19
+ raise ValueError("Número de límites no coincide con el número de parámetros.")
20
+ lower_bounds = [b[0] for b in bounds]
21
+ upper_bounds = [b[1] for b in bounds]
22
+ return lower_bounds, upper_bounds
23
+ except Exception as e:
24
+ print(f"Error al parsear los límites: {e}. Usando límites por defecto.")
25
+ lower_bounds = [-np.inf] * num_params
26
+ upper_bounds = [np.inf] * num_params
27
+ return lower_bounds, upper_bounds
28
+
29
+ @gpu_decorator(duration=300)
30
+ def generate_analysis(prompt, max_length=1024, device=None):
31
+ # Implementación existente para generar análisis usando Hugging Face o similar
32
+ # Por ejemplo, podrías usar un modelo de lenguaje para generar texto
33
+ # Aquí se deja como placeholder
34
+ analysis = "Análisis generado por el modelo de lenguaje."
35
+ return analysis
36
+
37
+ @gpu_decorator(duration=600) # Ajusta la duración según tus necesidades
38
+ def process_and_plot(
39
+ file,
40
+ biomass_eq1, biomass_eq2, biomass_eq3,
41
+ biomass_param1, biomass_param2, biomass_param3,
42
+ biomass_bound1, biomass_bound2, biomass_bound3,
43
+ substrate_eq1, substrate_eq2, substrate_eq3,
44
+ substrate_param1, substrate_param2, substrate_param3,
45
+ substrate_bound1, substrate_bound2, substrate_bound3,
46
+ product_eq1, product_eq2, product_eq3,
47
+ product_param1, product_param2, product_param3,
48
+ product_bound1, product_bound2, product_bound3,
49
+ legend_position,
50
+ show_legend,
51
+ show_params,
52
+ biomass_eq_count,
53
+ substrate_eq_count,
54
+ product_eq_count,
55
+ device=None
56
+ ):
57
+ # Leer el archivo Excel
58
+ df = pd.read_excel(file.name)
59
+
60
+ # Verificar que las columnas necesarias estén presentes
61
+ expected_columns = ['Tiempo', 'Biomasa', 'Sustrato', 'Producto']
62
+ for col in expected_columns:
63
+ if col not in df.columns:
64
+ raise KeyError(f"La columna esperada '{col}' no se encuentra en el archivo Excel.")
65
+
66
+ # Asignar los datos desde las columnas
67
+ time = df['Tiempo'].values
68
+ biomass_data = df['Biomasa'].values
69
+ substrate_data = df['Sustrato'].values
70
+ product_data = df['Producto'].values
71
+
72
+ # Convierte los contadores a enteros
73
+ biomass_eq_count = int(biomass_eq_count)
74
+ substrate_eq_count = int(substrate_eq_count)
75
+ product_eq_count = int(product_eq_count)
76
+
77
+ # Recolecta las ecuaciones, parámetros y límites según los contadores
78
+ biomass_eqs = [biomass_eq1, biomass_eq2, biomass_eq3][:biomass_eq_count]
79
+ biomass_params = [biomass_param1, biomass_param2, biomass_param3][:biomass_eq_count]
80
+ biomass_bounds = [biomass_bound1, biomass_bound2, biomass_bound3][:biomass_eq_count]
81
+
82
+ substrate_eqs = [substrate_eq1, substrate_eq2, substrate_eq3][:substrate_eq_count]
83
+ substrate_params = [substrate_param1, substrate_param2, substrate_param3][:substrate_eq_count]
84
+ substrate_bounds = [substrate_bound1, substrate_bound2, substrate_bound3][:substrate_eq_count]
85
+
86
+ product_eqs = [product_eq1, product_eq2, product_eq3][:product_eq_count]
87
+ product_params = [product_param1, product_param2, product_param3][:product_eq_count]
88
+ product_bounds = [product_bound1, product_bound2, product_bound3][:product_eq_count]
89
+
90
+ biomass_results = []
91
+ substrate_results = []
92
+ product_results = []
93
+
94
+ # Inicializar el modelo principal
95
+ main_model = BioprocessModel()
96
+
97
+ # Ajusta los modelos de Biomasa
98
+ for i in range(len(biomass_eqs)):
99
+ equation = biomass_eqs[i]
100
+ params_str = biomass_params[i]
101
+ bounds_str = biomass_bounds[i]
102
+
103
+ try:
104
+ main_model.set_model_biomass(equation, params_str)
105
+ except ValueError as ve:
106
+ raise ValueError(f"Error en la configuración del modelo de biomasa {i+1}: {ve}")
107
+
108
+ params = [param.strip() for param in params_str.split(',')]
109
+ lower_bounds, upper_bounds = parse_bounds(bounds_str, len(params))
110
+
111
+ try:
112
+ y_pred = main_model.fit_model(
113
+ 'biomass', time, biomass_data,
114
+ bounds=(lower_bounds, upper_bounds)
115
+ )
116
+ biomass_results.append({
117
+ 'model': main_model,
118
+ 'y_pred': y_pred,
119
+ 'equation': equation,
120
+ 'params': main_model.params['biomass']
121
+ })
122
+ except Exception as e:
123
+ raise RuntimeError(f"Error al ajustar el modelo de biomasa {i+1}: {e}")
124
+
125
+ # Ajusta los modelos de Sustrato
126
+ for i in range(len(substrate_eqs)):
127
+ equation = substrate_eqs[i]
128
+ params_str = substrate_params[i]
129
+ bounds_str = substrate_bounds[i]
130
+
131
+ try:
132
+ main_model.set_model_substrate(equation, params_str)
133
+ except ValueError as ve:
134
+ raise ValueError(f"Error en la configuración del modelo de sustrato {i+1}: {ve}")
135
+
136
+ params = [param.strip() for param in params_str.split(',')]
137
+ lower_bounds, upper_bounds = parse_bounds(bounds_str, len(params))
138
+
139
+ try:
140
+ y_pred = main_model.fit_model(
141
+ 'substrate', time, substrate_data,
142
+ bounds=(lower_bounds, upper_bounds)
143
+ )
144
+ substrate_results.append({
145
+ 'model': main_model,
146
+ 'y_pred': y_pred,
147
+ 'equation': equation,
148
+ 'params': main_model.params['substrate']
149
+ })
150
+ except Exception as e:
151
+ raise RuntimeError(f"Error al ajustar el modelo de sustrato {i+1}: {e}")
152
+
153
+ # Ajusta los modelos de Producto
154
+ for i in range(len(product_eqs)):
155
+ equation = product_eqs[i]
156
+ params_str = product_params[i]
157
+ bounds_str = product_bounds[i]
158
+
159
+ try:
160
+ main_model.set_model_product(equation, params_str)
161
+ except ValueError as ve:
162
+ raise ValueError(f"Error en la configuración del modelo de producto {i+1}: {ve}")
163
+
164
+ params = [param.strip() for param in params_str.split(',')]
165
+ lower_bounds, upper_bounds = parse_bounds(bounds_str, len(params))
166
+
167
+ try:
168
+ y_pred = main_model.fit_model(
169
+ 'product', time, product_data,
170
+ bounds=(lower_bounds, upper_bounds)
171
+ )
172
+ product_results.append({
173
+ 'model': main_model,
174
+ 'y_pred': y_pred,
175
+ 'equation': equation,
176
+ 'params': main_model.params['product']
177
+ })
178
+ except Exception as e:
179
+ raise RuntimeError(f"Error al ajustar el modelo de producto {i+1}: {e}")
180
+
181
+ # Genera las gráficas
182
+ fig, axs = plt.subplots(3, 1, figsize=(10, 15))
183
+
184
+ # Gráfica de Biomasa
185
+ axs[0].plot(time, biomass_data, 'o', label='Datos de Biomasa')
186
+ for i, result in enumerate(biomass_results):
187
+ axs[0].plot(time, result['y_pred'], '-', label=f'Modelo de Biomasa {i+1}')
188
+ axs[0].set_xlabel('Tiempo')
189
+ axs[0].set_ylabel('Biomasa')
190
+ if show_legend:
191
+ axs[0].legend(loc=legend_position)
192
+
193
+ # Gráfica de Sustrato
194
+ axs[1].plot(time, substrate_data, 'o', label='Datos de Sustrato')
195
+ for i, result in enumerate(substrate_results):
196
+ axs[1].plot(time, result['y_pred'], '-', label=f'Modelo de Sustrato {i+1}')
197
+ axs[1].set_xlabel('Tiempo')
198
+ axs[1].set_ylabel('Sustrato')
199
+ if show_legend:
200
+ axs[1].legend(loc=legend_position)
201
+
202
+ # Gráfica de Producto
203
+ axs[2].plot(time, product_data, 'o', label='Datos de Producto')
204
+ for i, result in enumerate(product_results):
205
+ axs[2].plot(time, result['y_pred'], '-', label=f'Modelo de Producto {i+1}')
206
+ axs[2].set_xlabel('Tiempo')
207
+ axs[2].set_ylabel('Producto')
208
+ if show_legend:
209
+ axs[2].legend(loc=legend_position)
210
+
211
+ plt.tight_layout()
212
+ buf = io.BytesIO()
213
+ plt.savefig(buf, format='png')
214
+ buf.seek(0)
215
+ image = Image.open(buf)
216
+
217
+ prompt = f"""
218
+ Eres un experto en modelado de bioprocesos.
219
+ Analiza los siguientes resultados experimentales y proporciona un veredicto sobre la calidad de los modelos, sugiriendo mejoras si es necesario.
220
+ Biomasa:
221
+ {biomass_results}
222
+ Sustrato:
223
+ {substrate_results}
224
+ Producto:
225
+ {product_results}
226
+ """
227
+ analysis = generate_analysis(prompt, device=device)
228
+
229
+ return image, analysis