-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
220 lines (182 loc) · 7.24 KB
/
Copy pathmain.py
File metadata and controls
220 lines (182 loc) · 7.24 KB
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import os
import sys
import ssl
# ── Fix SSL para ejecutables PyInstaller en Windows ──────────────────────────
if getattr(sys, 'frozen', False): # solo cuando corre como .exe
try:
import certifi
os.environ['SSL_CERT_FILE'] = certifi.where()
os.environ['REQUESTS_CA_BUNDLE'] = certifi.where()
except ImportError:
# Fallback: deshabilitar verificación (menos seguro)
ssl._create_default_https_context = ssl._create_unverified_context
# ─────────────────────────────────────────────────────────────────────────────
import flet as ft
import numpy as np
import traceback
from solver.solver_wrapper import SolverWrapper
from ui.components import Style, create_header
from ui.input_form import render_input_form
from ui.table_renderer import render_all_tables_cascade
from ui.results_display import create_final_summary
def main(page: ft.Page):
page.title = "Optimización de Producción - Equipo 6"
page.theme_mode = ft.ThemeMode.LIGHT
page.scroll = "adaptive"
page.padding = 40
# Estado global
state = {
"method": "simplex",
"tablas": [],
"inputs_c": [],
"inputs_A": [],
"inputs_b": [],
"inputs_signs": []
}
# Contenedores
input_container = ft.Column()
results_container = ft.Column()
# --- Cambio de tema ---
def on_theme_change(e):
if page.theme_mode == ft.ThemeMode.LIGHT:
page.theme_mode = ft.ThemeMode.DARK
theme_button.icon = ft.Icons.LIGHT_MODE_OUTLINED
else:
page.theme_mode = ft.ThemeMode.LIGHT
theme_button.icon = ft.Icons.DARK_MODE_OUTLINED
page.update()
theme_button = ft.IconButton(
icon=ft.Icons.DARK_MODE_OUTLINED,
tooltip="Cambiar tema",
on_click=on_theme_change
)
# --- Métodos ---
def on_simplex_select(e):
state["method"] = "simplex"
update_method_buttons()
def on_dos_fases_select(e):
state["method"] = "dos_fases"
update_method_buttons()
def update_method_buttons():
if state["method"] == "simplex":
btn_simplex.bgcolor = Style.PRIMARY
btn_simplex.color = "white"
btn_dos_fases.bgcolor = Style.SECONDARY
btn_dos_fases.color = "black"
else:
btn_simplex.bgcolor = Style.SECONDARY
btn_simplex.color = "black"
btn_dos_fases.bgcolor = Style.PRIMARY
btn_dos_fases.color = "white"
page.update()
btn_simplex = ft.Button("Simplex", on_click=on_simplex_select, bgcolor=Style.PRIMARY, color="white")
btn_dos_fases = ft.Button("Dos Fases", on_click=on_dos_fases_select, bgcolor=Style.SECONDARY, color="black")
# --- Generación de formulario ---
def show_error_dialog(title, message, traceback_text=None):
content = [ft.Text(message)]
if traceback_text:
content.append(ft.Text(traceback_text, size=12))
def close_dialog(e):
dialog.open = False
page.update()
dialog = ft.AlertDialog(
modal=True,
title=ft.Text(title),
content=ft.Column(content, tight=True),
actions=[
ft.TextButton("Cerrar", on_click=close_dialog)
],
actions_alignment=ft.MainAxisAlignment.END,
)
page.show_dialog(dialog)
page.update()
def on_generate_form(e):
try:
n_v = int(txt_vars.value)
n_r = int(txt_restrictions.value)
if n_v < 1 or n_r < 1:
raise ValueError("Mínimo 1 variable y 1 restricción")
generate_form(n_v, n_r)
except Exception as ex:
traceback.print_exc()
show_error_dialog(
"Error al generar el formulario",
"Por favor, ingresa valores válidos: mínimo 1 variable y 1 restricción"
)
def generate_form(n_v, n_r):
input_container.controls.clear()
results_container.controls.clear()
form_container, inputs_c, inputs_A, inputs_b, inputs_signs = render_input_form(
n_v, n_r, on_calculate
)
state["inputs_c"] = inputs_c
state["inputs_A"] = inputs_A
state["inputs_b"] = inputs_b
state["inputs_signs"] = inputs_signs
input_container.controls.append(form_container)
page.update()
# --- Cálculo y visualización ---
def on_calculate(e):
try:
c = [float(i.value) for i in state["inputs_c"]]
A = [[float(i.value) for i in fila] for fila in state["inputs_A"]]
b = [float(i.value) for i in state["inputs_b"]]
signos_ui = [sign.value for sign in state["inputs_signs"]]
signos = ["le" if s == "≤" else "ge" if s == "≥" else "=" for s in signos_ui]
# Resolver
tablas = SolverWrapper.solve(state["method"], c, A, b, signos)
state["tablas"] = tablas
# Mostrar resultados
display_results(tablas, len(c))
except Exception as ex:
user_msg = str(ex) if str(ex) else "Ocurrió un error al calcular. Verifica los datos ingresados."
show_error_dialog(
"Error en el cálculo",
f"No se pudo resolver el problema. Por favor verifica que todos los datos sean válidos.\nDetalle: {user_msg}"
)
def display_results(tablas, n_vars):
results_container.controls.clear()
# Mostrar todas las tablas en cascada
tables_view = render_all_tables_cascade(tablas)
results_container.controls.append(tables_view)
# Mostrar resumen final
tabla_optima = tablas[-1]["tabla"]
summary = create_final_summary(tabla_optima, n_vars, state["method"])
results_container.controls.append(summary)
page.update()
def window_event(e):
if e.data == "close":
# Le da tiempo a Flet de limpiar sus componentes antes de destruir todo
page.window_close()
page.on_window_event = window_event
# --- Layout ---
txt_vars = ft.TextField(label="Variables", width=150, hint_text="2")
txt_restrictions = ft.TextField(label="Restricciones", width=150, hint_text="3")
header_row = ft.Row(
controls=[create_header(), theme_button],
alignment=ft.MainAxisAlignment.SPACE_BETWEEN
)
controls_row = ft.Row(
[
txt_vars,
txt_restrictions,
btn_simplex,
btn_dos_fases,
ft.IconButton(ft.Icons.SETTINGS_SUGGEST_OUTLINED, on_click=on_generate_form),
],
alignment=ft.MainAxisAlignment.CENTER,
wrap=True
)
main_container = ft.Column(
controls=[
header_row,
controls_row,
input_container,
results_container
],
alignment=ft.MainAxisAlignment.START,
horizontal_alignment=ft.CrossAxisAlignment.CENTER
)
page.add(main_container)
if __name__ == "__main__":
ft.run(main)