C2MV commited on
Commit
881af71
1 Parent(s): f228721

Update interface.py

Browse files
Files changed (1) hide show
  1. interface.py +256 -12
interface.py CHANGED
@@ -56,19 +56,263 @@ def parse_bounds(bounds_str, num_params):
56
  upper_bounds = [np.inf] * num_params
57
  return lower_bounds, upper_bounds
58
 
59
- # Aquí incluye la función process_and_plot completa, asegurándote de que no haya referencias a decorators o @spaces.GPU
60
-
61
  def process_and_plot(
62
- # Your parameters here
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  ):
64
- # Your implementation here
65
- # ...
66
- return [image], analysis
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
- # Importar la función create_interface desde UI.py
69
- from UI import create_interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
- # Si deseas ejecutar la interfaz desde este archivo, asegúrate de que este bloque no cause conflictos al importar
72
- if __name__ == "__main__":
73
- demo = create_interface()
74
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  upper_bounds = [np.inf] * num_params
57
  return lower_bounds, upper_bounds
58
 
 
 
59
  def process_and_plot(
60
+ file,
61
+ biomass_eq1, biomass_eq2, biomass_eq3,
62
+ biomass_param1, biomass_param2, biomass_param3,
63
+ biomass_bound1, biomass_bound2, biomass_bound3,
64
+ substrate_eq1, substrate_eq2, substrate_eq3,
65
+ substrate_param1, substrate_param2, substrate_param3,
66
+ substrate_bound1, substrate_bound2, substrate_bound3,
67
+ product_eq1, product_eq2, product_eq3,
68
+ product_param1, product_param2, product_param3,
69
+ product_bound1, product_bound2, product_bound3,
70
+ legend_position,
71
+ show_legend,
72
+ show_params,
73
+ biomass_eq_count,
74
+ substrate_eq_count,
75
+ product_eq_count
76
  ):
77
+ # Convierte los contadores a enteros
78
+ biomass_eq_count = int(biomass_eq_count)
79
+ substrate_eq_count = int(substrate_eq_count)
80
+ product_eq_count = int(product_eq_count)
81
+
82
+ # Recolecta las ecuaciones, parámetros y límites según los contadores
83
+ biomass_eqs = [biomass_eq1, biomass_eq2, biomass_eq3][:biomass_eq_count]
84
+ biomass_params = [biomass_param1, biomass_param2, biomass_param3][:biomass_eq_count]
85
+ biomass_bounds = [biomass_bound1, biomass_bound2, biomass_bound3][:biomass_eq_count]
86
+
87
+ substrate_eqs = [substrate_eq1, substrate_eq2, substrate_eq3][:substrate_eq_count]
88
+ substrate_params = [substrate_param1, substrate_param2, substrate_param3][:substrate_eq_count]
89
+ substrate_bounds = [substrate_bound1, substrate_bound2, substrate_bound3][:substrate_eq_count]
90
+
91
+ product_eqs = [product_eq1, product_eq2, product_eq3][:product_eq_count]
92
+ product_params = [product_param1, product_param2, product_param3][:product_eq_count]
93
+ product_bounds = [product_bound1, product_bound2, product_bound3][:product_eq_count]
94
+
95
+ # Lee el archivo Excel subido
96
+ df = pd.read_excel(file.name)
97
+ time = df['Time'].values
98
+ biomass_data = df['Biomass'].values
99
+ substrate_data = df['Substrate'].values
100
+ product_data = df['Product'].values
101
+
102
+ biomass_results = []
103
+ substrate_results = []
104
+ product_results = []
105
+
106
+ # Ajusta los modelos de Biomasa
107
+ for i in range(len(biomass_eqs)):
108
+ equation = biomass_eqs[i]
109
+ params_str = biomass_params[i]
110
+ bounds_str = biomass_bounds[i]
111
+
112
+ model = BioprocessModel()
113
+ model.set_model('biomass', equation, params_str)
114
+
115
+ params = [param.strip() for param in params_str.split(',')]
116
+ lower_bounds, upper_bounds = parse_bounds(bounds_str, len(params))
117
+
118
+ y_pred = model.fit_model(
119
+ 'biomass', time, biomass_data,
120
+ bounds=(lower_bounds, upper_bounds)
121
+ )
122
+ biomass_results.append({
123
+ 'model': copy.deepcopy(model),
124
+ 'y_pred': y_pred,
125
+ 'equation': equation
126
+ })
127
+
128
+ # Usa el primer modelo de biomasa para X(t)
129
+ biomass_model = biomass_results[0]['model']
130
+ X_t_func = biomass_model.models['biomass']['function']
131
+ biomass_params_values = list(biomass_model.params['biomass'].values())
132
+
133
+ # Ajusta los modelos de Sustrato
134
+ for i in range(len(substrate_eqs)):
135
+ equation = substrate_eqs[i]
136
+ params_str = substrate_params[i]
137
+ bounds_str = substrate_bounds[i]
138
+
139
+ model = BioprocessModel()
140
+
141
+ t_symbol = symbols('t')
142
+ expr_substrate = sympify(equation)
143
+ substrate_params_symbols = symbols([param.strip() for param in params_str.split(',')])
144
+ substrate_func_expr = expr_substrate.subs('X(t)', X_t_func(t_symbol, *biomass_params_values))
145
+ substrate_func = lambdify(
146
+ (t_symbol, *substrate_params_symbols),
147
+ substrate_func_expr,
148
+ 'numpy'
149
+ )
150
+ model.models['substrate'] = {
151
+ 'function': substrate_func,
152
+ 'params': [param.strip() for param in params_str.split(',')]
153
+ }
154
+
155
+ params = model.models['substrate']['params']
156
+ lower_bounds, upper_bounds = parse_bounds(bounds_str, len(params))
157
+
158
+ y_pred = model.fit_model(
159
+ 'substrate', time, substrate_data,
160
+ bounds=(lower_bounds, upper_bounds)
161
+ )
162
+ substrate_results.append({
163
+ 'model': copy.deepcopy(model),
164
+ 'y_pred': y_pred,
165
+ 'equation': equation
166
+ })
167
+
168
+ # Ajusta los modelos de Producto
169
+ for i in range(len(product_eqs)):
170
+ equation = product_eqs[i]
171
+ params_str = product_params[i]
172
+ bounds_str = product_bounds[i]
173
+
174
+ model = BioprocessModel()
175
 
176
+ t_symbol = symbols('t')
177
+ expr_product = sympify(equation)
178
+ product_params_symbols = symbols([param.strip() for param in params_str.split(',')])
179
+ product_func_expr = expr_product.subs('X(t)', X_t_func(t_symbol, *biomass_params_values))
180
+ product_func = lambdify(
181
+ (t_symbol, *product_params_symbols),
182
+ product_func_expr,
183
+ 'numpy'
184
+ )
185
+ model.models['product'] = {
186
+ 'function': product_func,
187
+ 'params': [param.strip() for param in params_str.split(',')]
188
+ }
189
+
190
+ params = model.models['product']['params']
191
+ lower_bounds, upper_bounds = parse_bounds(bounds_str, len(params))
192
+
193
+ y_pred = model.fit_model(
194
+ 'product', time, product_data,
195
+ bounds=(lower_bounds, upper_bounds)
196
+ )
197
+ product_results.append({
198
+ 'model': copy.deepcopy(model),
199
+ 'y_pred': y_pred,
200
+ 'equation': equation
201
+ })
202
+
203
+ # Genera las gráficas
204
+ fig, axs = plt.subplots(3, 1, figsize=(10, 15))
205
+
206
+ # Gráfica de Biomasa
207
+ axs[0].plot(time, biomass_data, 'o', label='Datos de Biomasa')
208
+ for i, result in enumerate(biomass_results):
209
+ axs[0].plot(time, result['y_pred'], '-', label=f'Modelo de Biomasa {i+1}')
210
+ axs[0].set_xlabel('Tiempo')
211
+ axs[0].set_ylabel('Biomasa')
212
+ if show_legend:
213
+ axs[0].legend(loc=legend_position)
214
+
215
+ # Gráfica de Sustrato
216
+ axs[1].plot(time, substrate_data, 'o', label='Datos de Sustrato')
217
+ for i, result in enumerate(substrate_results):
218
+ axs[1].plot(time, result['y_pred'], '-', label=f'Modelo de Sustrato {i+1}')
219
+ axs[1].set_xlabel('Tiempo')
220
+ axs[1].set_ylabel('Sustrato')
221
+ if show_legend:
222
+ axs[1].legend(loc=legend_position)
223
+
224
+ # Gráfica de Producto
225
+ axs[2].plot(time, product_data, 'o', label='Datos de Producto')
226
+ for i, result in enumerate(product_results):
227
+ axs[2].plot(time, result['y_pred'], '-', label=f'Modelo de Producto {i+1}')
228
+ axs[2].set_xlabel('Tiempo')
229
+ axs[2].set_ylabel('Producto')
230
+ if show_legend:
231
+ axs[2].legend(loc=legend_position)
232
+
233
+ plt.tight_layout()
234
+ buf = io.BytesIO()
235
+ plt.savefig(buf, format='png')
236
+ buf.seek(0)
237
+ image = Image.open(buf)
238
+
239
+ all_results = {
240
+ 'biomass_models': [],
241
+ 'substrate_models': [],
242
+ 'product_models': []
243
+ }
244
+
245
+ for i, result in enumerate(biomass_results):
246
+ model_info = {
247
+ 'model_number': i + 1,
248
+ 'equation': result['equation'],
249
+ 'parameters': result['model'].params['biomass'],
250
+ 'R2': result['model'].r2['biomass'],
251
+ 'RMSE': result['model'].rmse['biomass']
252
+ }
253
+ all_results['biomass_models'].append(model_info)
254
 
255
+ for i, result in enumerate(substrate_results):
256
+ model_info = {
257
+ 'model_number': i + 1,
258
+ 'equation': result['equation'],
259
+ 'parameters': result['model'].params['substrate'],
260
+ 'R2': result['model'].r2['substrate'],
261
+ 'RMSE': result['model'].rmse['substrate']
262
+ }
263
+ all_results['substrate_models'].append(model_info)
264
+
265
+ for i, result in enumerate(product_results):
266
+ model_info = {
267
+ 'model_number': i + 1,
268
+ 'equation': result['equation'],
269
+ 'parameters': result['model'].params['product'],
270
+ 'R2': result['model'].r2['product'],
271
+ 'RMSE': result['model'].rmse['product']
272
+ }
273
+ all_results['product_models'].append(model_info)
274
+
275
+ results_text = "Resultados Experimentales:\n\n"
276
+
277
+ results_text += "Modelos de Biomasa:\n"
278
+ for model_info in all_results['biomass_models']:
279
+ results_text += f"""
280
+ Modelo {model_info['model_number']}:
281
+ Ecuación: {model_info['equation']}
282
+ Parámetros: {model_info['parameters']}
283
+ R²: {model_info['R2']:.4f}
284
+ RMSE: {model_info['RMSE']:.4f}
285
+ """
286
+
287
+ results_text += "\nModelos de Sustrato:\n"
288
+ for model_info in all_results['substrate_models']:
289
+ results_text += f"""
290
+ Modelo {model_info['model_number']}:
291
+ Ecuación: {model_info['equation']}
292
+ Parámetros: {model_info['parameters']}
293
+ R²: {model_info['R2']:.4f}
294
+ RMSE: {model_info['RMSE']:.4f}
295
+ """
296
+
297
+ results_text += "\nModelos de Producto:\n"
298
+ for model_info in all_results['product_models']:
299
+ results_text += f"""
300
+ Modelo {model_info['model_number']}:
301
+ Ecuación: {model_info['equation']}
302
+ Parámetros: {model_info['parameters']}
303
+ R²: {model_info['R2']:.4f}
304
+ RMSE: {model_info['RMSE']:.4f}
305
+ """
306
+
307
+ prompt = f"""
308
+ Eres un experto en modelado de bioprocesos.
309
+
310
+ Analiza los siguientes resultados experimentales y proporciona un veredicto sobre la calidad de los modelos, sugiriendo mejoras si es necesario.
311
+
312
+ {results_text}
313
+
314
+ Tu análisis debe ser detallado y profesional.
315
+ """
316
+ analysis = generate_analysis(prompt)
317
+
318
+ return [image], analysis