Spaces:
Sleeping

douglasribeiro commited on
Commit
7b876e9
·
verified ·
1 Parent(s): f959984

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -124
app.py CHANGED
@@ -5,7 +5,7 @@ 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()
@@ -25,10 +25,7 @@ def _parse_constraint(line: str, n_var: int):
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}'")
@@ -42,6 +39,9 @@ def _parse_constraint(line: str, n_var: int):
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]]
@@ -57,28 +57,26 @@ def pivotar(tabela, linha_pivo, coluna_pivo):
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}]"
@@ -86,13 +84,10 @@ def _to_markdown_table(tabela, headers, linha_pivo=None, coluna_pivo=None):
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"):
@@ -102,16 +97,14 @@ def simplex_trace(tipo: str, n_var: int, c, 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 == "<=":
@@ -128,138 +121,153 @@ def simplex_trace(tipo: str, n_var: int, c, constraints):
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)",
@@ -274,9 +282,16 @@ with gr.Blocks(title="Simplex Interativo (com iterações e pivôs)") as demo:
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()
 
5
 
6
 
7
  # -------------------------
8
+ # Parsing (entrada do aluno)
9
  # -------------------------
10
  def _parse_vector(line: str, n: int, name="vetor"):
11
  parts = (line or "").strip().split()
 
25
  if not line:
26
  raise ValueError("Há uma linha de restrição vazia.")
27
 
 
28
  line = re.sub(r"\s+", " ", line)
 
 
29
  m = re.search(r"(<=|>=|=)", line)
30
  if not m:
31
  raise ValueError(f"Restrição inválida (faltou operador <=, >= ou =): '{line}'")
 
39
  return coef, op, b
40
 
41
 
42
+ # -------------------------
43
+ # Simplex (tableau) + utilitários
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]]
 
57
  def _to_markdown_table(tabela, headers, linha_pivo=None, coluna_pivo=None):
58
  df = pd.DataFrame(tabela, columns=headers)
59
 
 
60
  df_disp = df.copy()
61
  for r in range(df_disp.shape[0]):
62
  for c in range(df_disp.shape[1]):
63
+ df_disp.iat[r, c] = f"{float(df_disp.iat[r, c]):.4f}"
 
64
 
65
+ # index com destaque de linha pivô
66
  if linha_pivo is not None:
67
  df_disp.index = [
68
+ (f"L{idx} ⬅️ linha pivô" if idx == linha_pivo else f"L{idx}")
69
  for idx in range(df_disp.shape[0])
70
  ]
71
  else:
72
  df_disp.index = [f"L{idx}" for idx in range(df_disp.shape[0])]
73
 
74
+ # colunas com destaque de coluna pivô
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
  if linha_pivo is not None:
81
  v = df_disp.iloc[linha_pivo, coluna_pivo]
82
  df_disp.iloc[linha_pivo, coluna_pivo] = f"[{v}]"
 
84
  return df_disp.to_markdown(tablefmt="github")
85
 
86
 
87
+ def montar_tableau(tipo: str, n_var: int, c, constraints):
 
 
 
88
  """
89
+ Monta o tableau inicial (bem didático, com folgas/excesso simples).
90
+ Obs.: para >= e = isso NÃO implementa Big-M/2 fases (é abordagem básica).
91
  """
92
  tipo = (tipo or "").strip().lower()
93
  if tipo not in ("max", "min"):
 
97
  if n_rest < 1:
98
  raise ValueError("Informe pelo menos 1 restrição.")
99
 
100
+ # para MAX no tableau: linha Z recebe -c
101
  c_row = [-ci for ci in c] if tipo == "max" else [ci for ci in c]
102
 
103
  tabela = []
 
 
104
  for i, (coef, op, b) in enumerate(constraints):
105
  linha = list(coef)
106
 
107
+ # folgas/excesso (básico)
108
  for j in range(n_rest):
109
  if j == i:
110
  if op == "<=":
 
121
  linha.append(float(b))
122
  tabela.append(linha)
123
 
124
+ # linha Z
125
  z = c_row + [0.0] * n_rest + [0.0]
126
  tabela.append(z)
127
 
128
  headers = [f"x{i+1}" for i in range(n_var)] + [f"f{i+1}" for i in range(n_rest)] + ["b"]
129
+ return tabela, headers
130
 
131
+
132
+ def escolher_pivo(tabela):
133
+ """
134
+ Retorna (lin_pivo, col_pivo) ou (None, None) se ótimo.
135
+ """
136
+ ultima = tabela[-1][:-1]
137
+ if all(x >= -1e-12 for x in ultima):
138
+ return None, None
139
+
140
+ col_pivo = ultima.index(min(ultima))
141
+
142
+ razoes = []
143
+ for i in range(len(tabela) - 1):
144
+ a = tabela[i][col_pivo]
145
+ if a > 1e-12:
146
+ razoes.append(tabela[i][-1] / a)
147
+ else:
148
+ razoes.append(float("inf"))
149
+
150
+ if all(r == float("inf") for r in razoes):
151
+ raise ValueError("Solução ilimitada (coluna pivô não tem entradas positivas).")
152
+
153
+ lin_pivo = razoes.index(min(razoes))
154
+ return lin_pivo, col_pivo
155
+
156
+
157
+ def extrair_solucao(tabela, n_var, n_rest, tipo):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  total_vars = n_var + n_rest
159
  resultado = [0.0] * total_vars
160
+
161
  for j in range(total_vars):
162
+ coluna = [tabela[i][j] for i in range(len(tabela))]
163
+ if coluna.count(1.0) == 1 and coluna.count(0.0) == len(tabela) - 1:
164
+ i1 = coluna.index(1.0)
165
  resultado[j] = tabela[i1][-1]
166
 
 
 
 
167
  valor_bruto = tabela[-1][-1]
168
  valor_otimo = (-valor_bruto) if tipo == "max" else (valor_bruto)
169
+ return resultado[:n_var], valor_otimo
 
170
 
171
 
172
  # -------------------------
173
+ # Estado + callbacks
174
  # -------------------------
175
+ def iniciar(tipo, n_var, obj_line, restricoes_texto):
176
  n_var = int(n_var)
 
177
  c = _parse_vector(obj_line, n_var, name="função objetivo")
178
 
179
  linhas = [l.strip() for l in (restricoes_texto or "").splitlines() if l.strip()]
180
  constraints = [_parse_constraint(l, n_var) for l in linhas]
181
 
182
+ tabela, headers = montar_tableau(tipo, n_var, c, constraints)
183
+
184
+ # estado inicial
185
+ state = {
186
+ "tipo": tipo,
187
+ "n_var": n_var,
188
+ "n_rest": len(constraints),
189
+ "headers": headers,
190
+ "tabela": tabela,
191
+ "iter": 0,
192
+ "finalizado": False,
193
+ }
194
+
195
+ md = []
196
+ md.append("## Tabela inicial (Iteração 0)\n")
197
+ md.append(_to_markdown_table(tabela, headers))
198
+ md.append("\n\n➡️ Clique em **Próxima iteração** para escolher pivô e pivotear.\n")
199
+
200
+ return "\n".join(md), state
201
+
202
+
203
+ def proxima_iteracao(state):
204
+ if not state:
205
+ return "⚠️ Primeiro clique em **Iniciar**.", state
206
+
207
+ if state.get("finalizado"):
208
+ return "✅ Já está ótimo. Clique em **Reiniciar** para novo problema.", state
209
+
210
+ tabela = state["tabela"]
211
+ headers = state["headers"]
212
+ tipo = state["tipo"]
213
+ n_var = state["n_var"]
214
+ n_rest = state["n_rest"]
215
+
216
+ lin_pivo, col_pivo = escolher_pivo(tabela)
217
 
218
+ # já ótimo
219
+ if lin_pivo is None:
220
+ x, z = extrair_solucao(tabela, n_var, n_rest, tipo)
221
+ state["finalizado"] = True
 
 
 
222
 
223
+ md = []
224
+ md.append("## ✅ Ótimo encontrado\n")
225
+ md.append(_to_markdown_table(tabela, headers))
226
+ md.append("\n### Resultado final\n")
227
+ for i, val in enumerate(x, start=1):
228
+ md.append(f"- x{i} = **{val:.4f}**")
229
+ md.append(f"\n**Valor ótimo (Z):** **{z:.4f}**\n")
230
+ return "\n".join(md), state
231
 
232
+ state["iter"] += 1
233
+ it = state["iter"]
234
+ pivo_val = tabela[lin_pivo][col_pivo]
 
 
 
235
 
236
+ md = []
237
+ md.append(f"## Iteração {it}\n")
238
+ md.append(f"**Coluna pivô:** {col_pivo} | **Linha pivô:** {lin_pivo} | **Pivô:** {pivo_val:.6f}\n")
239
 
240
+ md.append("### Antes do pivoteamento\n")
241
+ md.append(_to_markdown_table(tabela, headers, lin_pivo, col_pivo))
242
 
243
+ pivotar(tabela, lin_pivo, col_pivo)
244
 
245
+ md.append("\n### Depois do pivoteamento\n")
246
+ md.append(_to_markdown_table(tabela, headers, lin_pivo, col_pivo))
247
+ md.append("\n\n➡️ Clique em **Próxima iteração** novamente.\n")
248
 
249
+ state["tabela"] = tabela
250
+ return "\n".join(md), state
251
+
252
+
253
+ def reiniciar():
254
+ return "", None
255
+
256
+
257
+ # -------------------------
258
+ # UI
259
+ # -------------------------
260
+ with gr.Blocks(title="Simplex Passo a Passo (Tableau + Pivôs)") as demo:
261
+ gr.Markdown(
262
+ "# Simplex Passo a Passo (ensino)\n"
263
+ "1) Preencha o problema\n"
264
+ "2) Clique **Iniciar**\n"
265
+ "3) Clique **Próxima iteração** para avançar pivoteando"
266
+ )
267
 
268
  with gr.Row():
269
+ tipo = gr.Dropdown(choices=["max", "min"], value="max", label="Tipo")
270
+ n_var = gr.Number(value=2, precision=0, label="Nº variáveis (x1..xn)")
271
 
272
  obj = gr.Textbox(
273
  label="Função objetivo (coeficientes separados por espaço)",
 
282
  placeholder="Ex.: 2 1 <= 80\n1 1 <= 100\n1 0 <= 40"
283
  )
284
 
285
+ with gr.Row():
286
+ btn_init = gr.Button("Iniciar")
287
+ btn_next = gr.Button("Próxima iteração")
288
+ btn_reset = gr.Button("Reiniciar")
289
+
290
+ out = gr.Markdown()
291
+ state = gr.State(None)
292
 
293
+ btn_init.click(fn=iniciar, inputs=[tipo, n_var, obj, restr], outputs=[out, state])
294
+ btn_next.click(fn=proxima_iteracao, inputs=[state], outputs=[out, state])
295
+ btn_reset.click(fn=reiniciar, inputs=[], outputs=[out, state])
296
 
297
  demo.launch()