Spaces:
Sleeping

douglasribeiro commited on
Commit
f959984
·
verified ·
1 Parent(s): 5ce1ba6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +282 -0
app.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from copy import deepcopy
3
+ import pandas as pd
4
+ import gradio as gr
5
+
6
+
7
+ # -------------------------
8
+ # Utilitários
9
+ # -------------------------
10
+ def _parse_vector(line: str, n: int, name="vetor"):
11
+ parts = (line or "").strip().split()
12
+ if len(parts) != n:
13
+ raise ValueError(f"{name}: esperado {n} coeficientes, recebido {len(parts)}.")
14
+ return [float(x) for x in parts]
15
+
16
+
17
+ def _parse_constraint(line: str, n_var: int):
18
+ """
19
+ Formato aceito:
20
+ "a1 a2 ... <= b"
21
+ "a1 a2 ... >= b"
22
+ "a1 a2 ... = b"
23
+ """
24
+ line = (line or "").strip()
25
+ if not line:
26
+ raise ValueError("Há uma linha de restrição vazia.")
27
+
28
+ # normaliza espaços
29
+ line = re.sub(r"\s+", " ", line)
30
+
31
+ # encontra operador
32
+ m = re.search(r"(<=|>=|=)", line)
33
+ if not m:
34
+ raise ValueError(f"Restrição inválida (faltou operador <=, >= ou =): '{line}'")
35
+
36
+ op = m.group(1)
37
+ left = line[: m.start()].strip()
38
+ right = line[m.end():].strip()
39
+
40
+ coef = _parse_vector(left, n_var, name=f"coeficientes em '{line}'")
41
+ b = float(right)
42
+ return coef, op, b
43
+
44
+
45
+ def pivotar(tabela, linha_pivo, coluna_pivo):
46
+ pivo = tabela[linha_pivo][coluna_pivo]
47
+ tabela[linha_pivo] = [x / pivo for x in tabela[linha_pivo]]
48
+ for i in range(len(tabela)):
49
+ if i != linha_pivo:
50
+ fator = tabela[i][coluna_pivo]
51
+ tabela[i] = [
52
+ tabela[i][j] - fator * tabela[linha_pivo][j]
53
+ for j in range(len(tabela[0]))
54
+ ]
55
+
56
+
57
+ def _to_markdown_table(tabela, headers, linha_pivo=None, coluna_pivo=None):
58
+ df = pd.DataFrame(tabela, columns=headers)
59
+
60
+ # marca pivôs (visual) criando cópia de string
61
+ df_disp = df.copy()
62
+ for r in range(df_disp.shape[0]):
63
+ for c in range(df_disp.shape[1]):
64
+ val = df_disp.iat[r, c]
65
+ df_disp.iat[r, c] = f"{val:.4f}"
66
+
67
+ if linha_pivo is not None:
68
+ df_disp.index = [
69
+ (f"L{idx} ⬅️ linha pivô" if idx == linha_pivo else f"L{idx}")
70
+ for idx in range(df_disp.shape[0])
71
+ ]
72
+ else:
73
+ df_disp.index = [f"L{idx}" for idx in range(df_disp.shape[0])]
74
+
75
+ if coluna_pivo is not None:
76
+ df_disp.columns = [
77
+ (f"{col} ⬅️ col pivô" if j == coluna_pivo else col)
78
+ for j, col in enumerate(df_disp.columns)
79
+ ]
80
+
81
+ # coloca [] no valor pivô (se linha também existir)
82
+ if linha_pivo is not None:
83
+ v = df_disp.iloc[linha_pivo, coluna_pivo]
84
+ df_disp.iloc[linha_pivo, coluna_pivo] = f"[{v}]"
85
+
86
+ return df_disp.to_markdown(tablefmt="github")
87
+
88
+
89
+ # -------------------------
90
+ # Simplex com histórico
91
+ # -------------------------
92
+ def simplex_trace(tipo: str, n_var: int, c, constraints):
93
+ """
94
+ constraints: lista de tuplas (coef, op, b)
95
+ Retorna: historico (lista) e solução final
96
+ """
97
+ tipo = (tipo or "").strip().lower()
98
+ if tipo not in ("max", "min"):
99
+ raise ValueError("Tipo deve ser 'max' ou 'min'.")
100
+
101
+ n_rest = len(constraints)
102
+ if n_rest < 1:
103
+ raise ValueError("Informe pelo menos 1 restrição.")
104
+
105
+ # linha Z no tableau: para MAX usamos -c (padrão de tableau)
106
+ c_row = [-ci for ci in c] if tipo == "max" else [ci for ci in c]
107
+
108
+ tabela = []
109
+ # Monta linhas das restrições com folgas/excesso (básico)
110
+ # Para <= adiciona +1 na folga; para >= adiciona -1; para = adiciona 0
111
+ for i, (coef, op, b) in enumerate(constraints):
112
+ linha = list(coef)
113
+
114
+ # colunas de folga/excesso
115
+ for j in range(n_rest):
116
+ if j == i:
117
+ if op == "<=":
118
+ linha.append(1.0)
119
+ elif op == ">=":
120
+ linha.append(-1.0)
121
+ elif op == "=":
122
+ linha.append(0.0)
123
+ else:
124
+ raise ValueError(f"Operador inválido: {op}")
125
+ else:
126
+ linha.append(0.0)
127
+
128
+ linha.append(float(b))
129
+ tabela.append(linha)
130
+
131
+ # adiciona linha Z
132
+ z = c_row + [0.0] * n_rest + [0.0]
133
+ tabela.append(z)
134
+
135
+ headers = [f"x{i+1}" for i in range(n_var)] + [f"f{i+1}" for i in range(n_rest)] + ["b"]
136
+
137
+ historico = []
138
+ historico.append({
139
+ "iter": 0,
140
+ "fase": "Tabela inicial",
141
+ "linha_pivo": None,
142
+ "coluna_pivo": None,
143
+ "pivo": None,
144
+ "tabela": deepcopy(tabela)
145
+ })
146
+
147
+ iteracao = 0
148
+
149
+ while True:
150
+ ultima_linha = tabela[-1][:-1] # sem b
151
+
152
+ # condição de parada: todos >= 0 (para tableau padrão)
153
+ if all(x >= -1e-12 for x in ultima_linha):
154
+ break
155
+
156
+ iteracao += 1
157
+ col_pivo = ultima_linha.index(min(ultima_linha))
158
+
159
+ # teste do quociente mínimo
160
+ razoes = []
161
+ for i in range(len(tabela) - 1):
162
+ a = tabela[i][col_pivo]
163
+ if a > 1e-12:
164
+ razoes.append(tabela[i][-1] / a)
165
+ else:
166
+ razoes.append(float("inf"))
167
+
168
+ if all(r == float("inf") for r in razoes):
169
+ raise ValueError("Solução ilimitada (coluna pivô não tem entradas positivas).")
170
+
171
+ lin_pivo = razoes.index(min(razoes))
172
+ pivo_val = tabela[lin_pivo][col_pivo]
173
+
174
+ historico.append({
175
+ "iter": iteracao,
176
+ "fase": "Antes do pivoteamento",
177
+ "linha_pivo": lin_pivo,
178
+ "coluna_pivo": col_pivo,
179
+ "pivo": pivo_val,
180
+ "tabela": deepcopy(tabela)
181
+ })
182
+
183
+ pivotar(tabela, lin_pivo, col_pivo)
184
+
185
+ historico.append({
186
+ "iter": iteracao,
187
+ "fase": "Depois do pivoteamento",
188
+ "linha_pivo": lin_pivo,
189
+ "coluna_pivo": col_pivo,
190
+ "pivo": pivo_val,
191
+ "tabela": deepcopy(tabela)
192
+ })
193
+
194
+ # trava didática para não entrar em loop infinito em casos degenerados
195
+ if iteracao > 50:
196
+ raise ValueError("Interrompido: muitas iterações (possível degeneração/ciclagem).")
197
+
198
+ # extrai solução (variáveis básicas)
199
+ total_vars = n_var + n_rest
200
+ resultado = [0.0] * total_vars
201
+ for j in range(total_vars):
202
+ col = [tabela[i][j] for i in range(len(tabela))]
203
+ if col.count(1.0) == 1 and col.count(0.0) == len(tabela) - 1:
204
+ i1 = col.index(1.0)
205
+ resultado[j] = tabela[i1][-1]
206
+
207
+ # valor ótimo:
208
+ # - no tableau MAX com -c, o ótimo é +b na linha Z? depende do sinal.
209
+ # Aqui, como usamos -c, o valor ótimo fica: (MAX) = - (último b da linha Z)
210
+ valor_bruto = tabela[-1][-1]
211
+ valor_otimo = (-valor_bruto) if tipo == "max" else (valor_bruto)
212
+
213
+ return historico, resultado[:n_var], valor_otimo, headers
214
+
215
+
216
+ # -------------------------
217
+ # Gradio: UI
218
+ # -------------------------
219
+ def resolver(tipo, n_var, obj_line, restricoes_texto):
220
+ n_var = int(n_var)
221
+
222
+ c = _parse_vector(obj_line, n_var, name="função objetivo")
223
+
224
+ linhas = [l.strip() for l in (restricoes_texto or "").splitlines() if l.strip()]
225
+ constraints = [_parse_constraint(l, n_var) for l in linhas]
226
+
227
+ historico, x, z, headers = simplex_trace(tipo, n_var, c, constraints)
228
+
229
+ # monta saída em markdown com TODAS iterações
230
+ out = []
231
+ out.append(f"## ✅ Resultado final\n")
232
+ out.append("**Variáveis:**\n")
233
+ for i, val in enumerate(x, start=1):
234
+ out.append(f"- x{i} = **{val:.4f}**")
235
+ out.append(f"\n**Valor ótimo (Z):** **{z:.4f}**\n")
236
+
237
+ out.append("---\n")
238
+ out.append("## 📌 Iterações (tableaux)\n")
239
+
240
+ for item in historico:
241
+ it = item["iter"]
242
+ fase = item["fase"]
243
+ lp = item["linha_pivo"]
244
+ cp = item["coluna_pivo"]
245
+ pv = item["pivo"]
246
+
247
+ out.append(f"### Iteração {it} — {fase}\n")
248
+ if lp is not None and cp is not None:
249
+ out.append(f"**Linha pivô:** {lp} | **Coluna pivô:** {cp} | **Pivô:** {pv:.6f}\n")
250
+
251
+ out.append(_to_markdown_table(item["tabela"], headers, linha_pivo=lp, coluna_pivo=cp))
252
+ out.append("\n")
253
+
254
+ return "\n".join(out)
255
+
256
+
257
+ with gr.Blocks(title="Simplex Interativo (com iterações e pivôs)") as demo:
258
+ gr.Markdown("# Simplex Interativo (ensino)\nCole o problema e veja **todas as iterações**, incluindo **linha pivô** e **coluna pivô**.")
259
+
260
+ with gr.Row():
261
+ tipo = gr.Dropdown(choices=["max", "min"], value="max", label="Tipo do problema")
262
+ n_var = gr.Number(value=2, precision=0, label="Número de variáveis (x1..xn)")
263
+
264
+ obj = gr.Textbox(
265
+ label="Função objetivo (coeficientes separados por espaço)",
266
+ value="3 2",
267
+ placeholder="Ex.: 3 2 1"
268
+ )
269
+
270
+ restr = gr.Textbox(
271
+ label="Restrições (1 por linha): a1 a2 ... <= b",
272
+ lines=6,
273
+ value="2 1 <= 80\n1 1 <= 100\n1 0 <= 40",
274
+ placeholder="Ex.: 2 1 <= 80\n1 1 <= 100\n1 0 <= 40"
275
+ )
276
+
277
+ btn = gr.Button("Rodar Simplex e mostrar iterações")
278
+ saida = gr.Markdown()
279
+
280
+ btn.click(fn=resolver, inputs=[tipo, n_var, obj, restr], outputs=[saida])
281
+
282
+ demo.launch()