Spaces:
Sleeping

douglasribeiro commited on
Commit
56512a6
·
verified ·
1 Parent(s): d314ff1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -167
app.py CHANGED
@@ -117,140 +117,114 @@ def extrair_solucao(tabela, n_var, n_rest, tipo):
117
 
118
 
119
  # -------------------------
120
- # UI dinâmica
121
  # -------------------------
122
- MAX_VARS = 6
123
- MAX_RESTS = 6
124
-
125
- def _components_for_objective():
126
- return [gr.Number(value=0.0, label=f"x{i+1}", precision=4, interactive=True, visible=False)
127
- for i in range(MAX_VARS)]
128
-
129
- def _components_for_constraints():
130
- # Para cada restrição: coeficientes (MAX_VARS) + sinal + b
131
- rows = []
132
- for r in range(MAX_RESTS):
133
- coef_inputs = [gr.Number(value=0.0, label=f"a{r+1},{c+1}", precision=4, interactive=True, visible=False)
134
- for c in range(MAX_VARS)]
135
- sign = gr.Dropdown(choices=["<=", ">=", "="], value="<=", label=f"Sinal r{r+1}", visible=False)
136
- b = gr.Number(value=0.0, label=f"b{r+1}", precision=4, interactive=True, visible=False)
137
- rows.append((coef_inputs, sign, b))
138
- return rows
139
-
140
-
141
- def gerar_campos(n_var, n_rest, obj_inputs, cons_rows):
142
- n_var = int(n_var)
143
- n_rest = int(n_rest)
144
-
145
- if not (1 <= n_var <= MAX_VARS):
146
- raise gr.Error(f"Nº variáveis deve estar entre 1 e {MAX_VARS}.")
147
- if not (1 <= n_rest <= MAX_RESTS):
148
- raise gr.Error(f"Nº restrições deve estar entre 1 e {MAX_RESTS}.")
149
-
150
- # objetivo: mostra só n_var
151
- obj_updates = []
152
- for i, comp in enumerate(obj_inputs):
153
- obj_updates.append(gr.update(visible=(i < n_var), label=f"Coef. de x{i+1}"))
154
 
155
- # restrições: mostra só n_rest e só n_var coef por linha
156
- cons_updates = []
157
- for r in range(MAX_RESTS):
158
- coef_inputs, sign, b = cons_rows[r]
159
- row_visible = (r < n_rest)
160
 
161
- for c in range(MAX_VARS):
162
- cons_updates.append(gr.update(visible=(row_visible and c < n_var),
163
- label=f"r{r+1}: coef x{c+1}"))
 
 
 
164
 
165
- cons_updates.append(gr.update(visible=row_visible, label=f"r{r+1}: sinal"))
166
- cons_updates.append(gr.update(visible=row_visible, label=f"r{r+1}: b"))
167
 
168
- info = (
169
- f"✅ Campos gerados: **{n_var} variáveis** e **{n_rest} restrições**.\n\n"
170
- "Agora preencha os coeficientes e clique **Iniciar**."
 
 
 
 
171
  )
172
 
173
- return [info] + obj_updates + cons_updates
174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
- def iniciar(tipo, n_var, n_rest, obj_vals, cons_vals):
177
- n_var = int(n_var)
178
- n_rest = int(n_rest)
179
-
180
- # valida objetivo
181
- c = []
182
- for i in range(n_var):
183
- v = obj_vals[i]
184
- if v is None:
185
- raise gr.Error(f"Função objetivo: coeficiente de x{i+1} está vazio.")
186
- c.append(float(v))
187
-
188
- # monta constraints (coef, op, b)
189
- constraints = []
190
- idx = 0
191
- # cons_vals vem como: para cada restrição r:
192
- # - MAX_VARS coef
193
- # - sign
194
- # - b
195
- for r in range(n_rest):
196
- coef = []
197
- for i in range(n_var):
198
- v = cons_vals[idx + i]
199
- if v is None:
200
- raise gr.Error(f"Restrição {r+1}: coeficiente de x{i+1} está vazio.")
201
- coef.append(float(v))
202
- idx += MAX_VARS # pula todos os coef (mesmo os invisíveis)
203
-
204
- op = cons_vals[idx]
205
- idx += 1
206
-
207
- b = cons_vals[idx]
208
- idx += 1
209
-
210
- if op is None:
211
- raise gr.Error(f"Restrição {r+1}: selecione o sinal.")
212
- if b is None:
213
- raise gr.Error(f"Restrição {r+1}: termo b está vazio.")
214
-
215
- constraints.append((coef, op, float(b)))
216
-
217
- # alerta didático
218
- if any(op in (">=", "=") for _, op, _ in constraints):
219
- # não impede, só avisa
220
- aviso = (
221
- "⚠️ **Aviso didático**: restrições `>=` e `=` normalmente exigem Big-M ou Duas Fases "
222
- "para garantir base inicial. Esta versão usa tableau simples (pode falhar em alguns casos).\n\n"
223
- )
224
- else:
225
  aviso = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
 
227
- tabela, headers = montar_tableau(tipo, c, constraints, n_var, n_rest)
228
-
229
- state = {
230
- "tipo": tipo,
231
- "n_var": n_var,
232
- "n_rest": n_rest,
233
- "headers": headers,
234
- "tabela": tabela,
235
- "iter": 0,
236
- "finalizado": False,
237
- }
238
 
239
- md = []
240
- md.append(aviso)
241
- md.append("## ✅ Tabela inicial (Iteração 0)\n")
242
- md.append(_to_markdown_table(tabela, headers))
243
- md.append("\n➡️ Clique em **Próxima iteração**.\n")
244
 
245
- return "\n".join(md), state
 
246
 
247
 
248
  def proxima_iteracao(state):
249
  if not state:
250
- raise gr.Error("Primeiro gere os campos e clique em **Iniciar**.")
251
 
252
  if state.get("finalizado"):
253
- return "✅ Já está ótimo. Clique **Reiniciar** para outro problema.", state
254
 
255
  tabela = state["tabela"]
256
  headers = state["headers"]
@@ -294,60 +268,60 @@ def proxima_iteracao(state):
294
  return "\n".join(md), state
295
 
296
 
297
- def reiniciar():
298
- return "", None, gr.update(value=""), gr.update(value=""), None
 
 
 
299
 
300
 
301
- # -------------------------
302
- # Layout (melhor)
303
- # -------------------------
304
  CSS = """
305
  #output_md { max-height: 520px; overflow: auto; padding: 12px; border: 1px solid #e5e7eb; border-radius: 12px; }
306
- .small-note { font-size: 0.95rem; opacity: 0.9; }
307
  """
308
 
309
- with gr.Blocks(css=CSS, title="Simplex Passo a Passo (ensino)") as demo:
 
310
  gr.Markdown(
311
  "# Simplex Passo a Passo (ensino)\n"
312
- "<div class='small-note'>"
313
- "1) Defina nº de variáveis e restrições ➜ 2) Clique <b>Gerar campos</b> ➜ "
314
- "3) Preencha coeficientes ➜ 4) Clique <b>Iniciar</b> ➜ 5) Clique <b>Próxima iteração</b>"
315
- "</div>"
316
  )
317
 
318
  with gr.Row():
319
  tipo = gr.Dropdown(choices=["max", "min"], value="max", label="Tipo")
320
- n_var = gr.Slider(1, MAX_VARS, value=2, step=1, label="Nº variáveis")
321
- n_rest = gr.Slider(1, MAX_RESTS, value=3, step=1, label="Nº restrições")
322
 
323
- info = gr.Markdown("⬅️ Ajuste os números e clique **Gerar campos**.")
324
 
325
  btn_gen = gr.Button("🧩 Gerar campos", variant="primary")
326
 
327
- gr.Markdown("## Função objetivo")
328
-
329
- obj_inputs = _components_for_objective()
330
  with gr.Row():
331
- for comp in obj_inputs:
332
- comp.render()
333
-
334
- gr.Markdown("## Restrições")
335
-
336
- cons_rows = _components_for_constraints()
337
-
338
- # Renderiza as linhas de restrição em blocos (cada linha em uma Row)
339
- # coef (até MAX_VARS) + sinal + b
340
- cons_components_flat = []
341
- for r in range(MAX_RESTS):
342
- coef_inputs, sign, b = cons_rows[r]
343
- with gr.Row():
344
- for comp in coef_inputs:
345
- comp.render()
346
- cons_components_flat.append(comp)
347
- sign.render()
348
- b.render()
349
- cons_components_flat.append(sign)
350
- cons_components_flat.append(b)
 
 
 
 
 
351
 
352
  with gr.Row():
353
  btn_init = gr.Button("🚀 Iniciar", variant="primary")
@@ -357,28 +331,33 @@ with gr.Blocks(css=CSS, title="Simplex Passo a Passo (ensino)") as demo:
357
  out = gr.Markdown(elem_id="output_md")
358
  state = gr.State(None)
359
 
360
- # ---- wiring
361
- # Gerar campos: atualiza visibilidade/labels de todos inputs
362
  btn_gen.click(
363
- fn=gerar_campos,
364
- inputs=[n_var, n_rest, obj_inputs, cons_rows],
365
- outputs=[info] + obj_inputs + cons_components_flat
366
  )
367
 
368
- # Iniciar: coleta os valores atuais (obj + constraints)
369
  btn_init.click(
370
- fn=lambda tipo, nv, nr, *vals: iniciar(
371
- tipo, nv, nr,
372
- obj_vals=list(vals[:MAX_VARS]),
373
- cons_vals=list(vals[MAX_VARS:])
374
- ),
375
- inputs=[tipo, n_var, n_rest] + obj_inputs + cons_components_flat,
376
  outputs=[out, state]
377
  )
378
 
379
- btn_next.click(fn=proxima_iteracao, inputs=[state], outputs=[out, state])
 
 
 
 
 
380
 
381
- btn_reset.click(fn=lambda: ("", None), inputs=[], outputs=[out, state])
 
 
 
 
 
382
 
383
  demo.queue()
384
- demo.launch()
 
117
 
118
 
119
  # -------------------------
120
+ # UI dinâmica via DataFrame
121
  # -------------------------
122
+ def make_obj_df(n_var):
123
+ cols = [f"x{i+1}" for i in range(n_var)]
124
+ return pd.DataFrame([[0.0] * n_var], columns=cols)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
 
 
 
 
 
126
 
127
+ def make_rest_df(n_var, n_rest):
128
+ cols = [f"x{i+1}" for i in range(n_var)] + ["sinal", "b"]
129
+ data = []
130
+ for _ in range(n_rest):
131
+ data.append([0.0] * n_var + ["<=", 0.0])
132
+ return pd.DataFrame(data, columns=cols)
133
 
 
 
134
 
135
+ def gerar_tabelas(n_var, n_rest):
136
+ n_var = int(n_var)
137
+ n_rest = int(n_rest)
138
+ return (
139
+ make_obj_df(n_var),
140
+ make_rest_df(n_var, n_rest),
141
+ f"✅ Grade criada: **{n_var} variáveis** e **{n_rest} restrições**."
142
  )
143
 
 
144
 
145
+ def iniciar(tipo, obj_df, rest_df):
146
+ try:
147
+ if obj_df is None or rest_df is None:
148
+ raise ValueError("Clique em **Gerar campos** primeiro.")
149
+
150
+ obj_df = pd.DataFrame(obj_df)
151
+ rest_df = pd.DataFrame(rest_df)
152
+
153
+ n_var = len([c for c in obj_df.columns])
154
+ if n_var < 1:
155
+ raise ValueError("Objetivo sem colunas.")
156
+
157
+ # lê objetivo
158
+ c = []
159
+ for col in obj_df.columns:
160
+ v = obj_df.at[0, col]
161
+ if v is None or v == "":
162
+ raise ValueError(f"Função objetivo: coeficiente de {col} vazio.")
163
+ c.append(float(v))
164
+
165
+ # lê restrições
166
+ expected_cols = [f"x{i+1}" for i in range(n_var)] + ["sinal", "b"]
167
+ if list(rest_df.columns) != expected_cols:
168
+ raise ValueError("As colunas das restrições não batem com o número de variáveis. Gere novamente os campos.")
169
+
170
+ n_rest = len(rest_df)
171
+ constraints = []
172
+ for r in range(n_rest):
173
+ coef = []
174
+ for i in range(n_var):
175
+ v = rest_df.at[r, f"x{i+1}"]
176
+ if v is None or v == "":
177
+ raise ValueError(f"Restrição {r+1}: coeficiente x{i+1} vazio.")
178
+ coef.append(float(v))
179
+
180
+ op = str(rest_df.at[r, "sinal"]).strip()
181
+ if op not in ("<=", ">=", "="):
182
+ raise ValueError(f"Restrição {r+1}: sinal inválido (use <=, >= ou =).")
183
+
184
+ b = rest_df.at[r, "b"]
185
+ if b is None or b == "":
186
+ raise ValueError(f"Restrição {r+1}: b vazio.")
187
+ b = float(b)
188
+
189
+ constraints.append((coef, op, b))
190
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  aviso = ""
192
+ if any(op in (">=", "=") for _, op, _ in constraints):
193
+ aviso = (
194
+ "⚠️ **Aviso didático**: `>=` e `=` normalmente exigem Big-M ou Duas Fases para base inicial. "
195
+ "Esta versão usa tableau simples (pode falhar em alguns casos).\n\n"
196
+ )
197
+
198
+ tabela, headers = montar_tableau(tipo, c, constraints, n_var, n_rest)
199
+
200
+ state = {
201
+ "tipo": tipo,
202
+ "n_var": n_var,
203
+ "n_rest": n_rest,
204
+ "headers": headers,
205
+ "tabela": tabela,
206
+ "iter": 0,
207
+ "finalizado": False,
208
+ }
209
 
210
+ md = []
211
+ md.append(aviso)
212
+ md.append("## ✅ Tabela inicial (Iteração 0)\n")
213
+ md.append(_to_markdown_table(tabela, headers))
214
+ md.append("\n➡️ Clique em **Próxima iteração**.\n")
 
 
 
 
 
 
215
 
216
+ return "\n".join(md), state
 
 
 
 
217
 
218
+ except Exception as e:
219
+ raise gr.Error(str(e))
220
 
221
 
222
  def proxima_iteracao(state):
223
  if not state:
224
+ raise gr.Error("Primeiro clique em **Iniciar**.")
225
 
226
  if state.get("finalizado"):
227
+ return "✅ Já está ótimo. Clique em **Reiniciar**.", state
228
 
229
  tabela = state["tabela"]
230
  headers = state["headers"]
 
268
  return "\n".join(md), state
269
 
270
 
271
+ def reiniciar(n_var, n_rest):
272
+ # reconstroi grades
273
+ obj = make_obj_df(int(n_var))
274
+ rest = make_rest_df(int(n_var), int(n_rest))
275
+ return "", None, obj, rest, "🔄 Reiniciado."
276
 
277
 
 
 
 
278
  CSS = """
279
  #output_md { max-height: 520px; overflow: auto; padding: 12px; border: 1px solid #e5e7eb; border-radius: 12px; }
 
280
  """
281
 
282
+
283
+ with gr.Blocks(title="Simplex Passo a Passo (ensino)") as demo:
284
  gr.Markdown(
285
  "# Simplex Passo a Passo (ensino)\n"
286
+ "✅ Inputs em **grade** (caixinhas) + **seleção do sinal** por restrição.\n"
287
+ "1) Escolha n_var e n_rest → 2) **Gerar campos** → 3) Preencha → 4) **Iniciar** → 5) **Próxima iteração**"
 
 
288
  )
289
 
290
  with gr.Row():
291
  tipo = gr.Dropdown(choices=["max", "min"], value="max", label="Tipo")
292
+ n_var = gr.Slider(1, 8, value=2, step=1, label="Nº variáveis")
293
+ n_rest = gr.Slider(1, 8, value=3, step=1, label="Nº restrições")
294
 
295
+ info = gr.Markdown("Clique em **Gerar campos** para criar a grade.")
296
 
297
  btn_gen = gr.Button("🧩 Gerar campos", variant="primary")
298
 
 
 
 
299
  with gr.Row():
300
+ with gr.Column(scale=4):
301
+ gr.Markdown("## Função objetivo")
302
+ obj_df = gr.Dataframe(
303
+ value=make_obj_df(2),
304
+ interactive=True,
305
+ row_count=(1, "fixed"),
306
+ col_count=(2, "fixed"),
307
+ wrap=True,
308
+ )
309
+ with gr.Column(scale=6):
310
+ gr.Markdown("## Restrições")
311
+ rest_df = gr.Dataframe(
312
+ value=make_rest_df(2, 3),
313
+ interactive=True,
314
+ row_count=(3, "fixed"),
315
+ col_count=(4, "fixed"),
316
+ wrap=True,
317
+ )
318
+
319
+ gr.Markdown(
320
+ "### Formato da grade\n"
321
+ "- Objetivo: 1 linha com coeficientes de x1..xn\n"
322
+ "- Restrições: cada linha = coeficientes + **sinal** + b\n"
323
+ "- Sinal deve ser: `<=` ou `>=` ou `=`"
324
+ )
325
 
326
  with gr.Row():
327
  btn_init = gr.Button("🚀 Iniciar", variant="primary")
 
331
  out = gr.Markdown(elem_id="output_md")
332
  state = gr.State(None)
333
 
334
+ # Gera as grades com dimensões novas
 
335
  btn_gen.click(
336
+ fn=gerar_tabelas,
337
+ inputs=[n_var, n_rest],
338
+ outputs=[obj_df, rest_df, info]
339
  )
340
 
341
+ # Inicia
342
  btn_init.click(
343
+ fn=iniciar,
344
+ inputs=[tipo, obj_df, rest_df],
 
 
 
 
345
  outputs=[out, state]
346
  )
347
 
348
+ # Próxima
349
+ btn_next.click(
350
+ fn=proxima_iteracao,
351
+ inputs=[state],
352
+ outputs=[out, state]
353
+ )
354
 
355
+ # Reiniciar
356
+ btn_reset.click(
357
+ fn=reiniciar,
358
+ inputs=[n_var, n_rest],
359
+ outputs=[out, state, obj_df, rest_df, info]
360
+ )
361
 
362
  demo.queue()
363
+ demo.launch(css=CSS)