from copy import deepcopy import pandas as pd import gradio as gr # ------------------------- # Simplex (tableau) + utilitários # ------------------------- def pivotar(tabela, linha_pivo, coluna_pivo): pivo = tabela[linha_pivo][coluna_pivo] tabela[linha_pivo] = [x / pivo for x in tabela[linha_pivo]] for i in range(len(tabela)): if i != linha_pivo: fator = tabela[i][coluna_pivo] tabela[i] = [ tabela[i][j] - fator * tabela[linha_pivo][j] for j in range(len(tabela[0])) ] def _to_markdown_table(tabela, headers, linha_pivo=None, coluna_pivo=None): df = pd.DataFrame(tabela, columns=headers) df_disp = df.copy() for r in range(df_disp.shape[0]): for c in range(df_disp.shape[1]): df_disp.iat[r, c] = f"{float(df_disp.iat[r, c]):.4f}" if linha_pivo is not None: df_disp.index = [ (f"L{idx} ⬅️ linha pivô" if idx == linha_pivo else f"L{idx}") for idx in range(df_disp.shape[0]) ] else: df_disp.index = [f"L{idx}" for idx in range(df_disp.shape[0])] if coluna_pivo is not None: df_disp.columns = [ (f"{col} ⬅️ col pivô" if j == coluna_pivo else col) for j, col in enumerate(df_disp.columns) ] if linha_pivo is not None: v = df_disp.iloc[linha_pivo, coluna_pivo] df_disp.iloc[linha_pivo, coluna_pivo] = f"[{v}]" return df_disp.to_markdown(tablefmt="github") def montar_tableau(tipo, c, constraints, n_var, n_rest): # MAX: linha Z = -c c_row = [-ci for ci in c] if tipo == "max" else [ci for ci in c] tabela = [] for i, (coef, op, b) in enumerate(constraints): linha = list(coef) # folga/excesso simples (didático) for j in range(n_rest): if j == i: if op == "<=": linha.append(1.0) elif op == ">=": linha.append(-1.0) elif op == "=": linha.append(0.0) else: raise ValueError(f"Operador inválido: {op}") else: linha.append(0.0) linha.append(float(b)) tabela.append(linha) z = c_row + [0.0] * n_rest + [0.0] tabela.append(z) headers = [f"x{i+1}" for i in range(n_var)] + [f"f{i+1}" for i in range(n_rest)] + ["b"] return tabela, headers def escolher_pivo(tabela): ultima = tabela[-1][:-1] if all(x >= -1e-12 for x in ultima): return None, None col_pivo = ultima.index(min(ultima)) razoes = [] for i in range(len(tabela) - 1): a = tabela[i][col_pivo] if a > 1e-12: razoes.append(tabela[i][-1] / a) else: razoes.append(float("inf")) if all(r == float("inf") for r in razoes): raise ValueError("Solução ilimitada (coluna pivô não tem entradas positivas).") lin_pivo = razoes.index(min(razoes)) return lin_pivo, col_pivo def extrair_solucao(tabela, n_var, n_rest, tipo): total_vars = n_var + n_rest resultado = [0.0] * total_vars for j in range(total_vars): col = [tabela[i][j] for i in range(len(tabela))] col_round = [0.0 if abs(v) < 1e-10 else round(v, 10) for v in col] if col_round.count(1.0) == 1 and col_round.count(0.0) == len(tabela) - 1: i1 = col_round.index(1.0) resultado[j] = tabela[i1][-1] valor_bruto = tabela[-1][-1] valor_otimo = (-valor_bruto) if tipo == "max" else (valor_bruto) return resultado[:n_var], valor_otimo # ------------------------- # UI dinâmica via DataFrame # ------------------------- def make_obj_df(n_var): cols = [f"x{i+1}" for i in range(n_var)] return pd.DataFrame([[0.0] * n_var], columns=cols) def make_rest_df(n_var, n_rest): cols = [f"x{i+1}" for i in range(n_var)] + ["sinal", "b"] data = [] for _ in range(n_rest): data.append([0.0] * n_var + ["<=", 0.0]) return pd.DataFrame(data, columns=cols) def gerar_tabelas(n_var, n_rest): n_var = int(n_var) n_rest = int(n_rest) return ( make_obj_df(n_var), make_rest_df(n_var, n_rest), f"✅ Grade criada: **{n_var} variáveis** e **{n_rest} restrições**." ) def iniciar(tipo, obj_df, rest_df): try: if obj_df is None or rest_df is None: raise ValueError("Clique em **Gerar campos** primeiro.") obj_df = pd.DataFrame(obj_df) rest_df = pd.DataFrame(rest_df) n_var = len([c for c in obj_df.columns]) if n_var < 1: raise ValueError("Objetivo sem colunas.") # lê objetivo c = [] for col in obj_df.columns: v = obj_df.at[0, col] if v is None or v == "": raise ValueError(f"Função objetivo: coeficiente de {col} vazio.") c.append(float(v)) # lê restrições expected_cols = [f"x{i+1}" for i in range(n_var)] + ["sinal", "b"] if list(rest_df.columns) != expected_cols: raise ValueError("As colunas das restrições não batem com o número de variáveis. Gere novamente os campos.") n_rest = len(rest_df) constraints = [] for r in range(n_rest): coef = [] for i in range(n_var): v = rest_df.at[r, f"x{i+1}"] if v is None or v == "": raise ValueError(f"Restrição {r+1}: coeficiente x{i+1} vazio.") coef.append(float(v)) op = str(rest_df.at[r, "sinal"]).strip() if op not in ("<=", ">=", "="): raise ValueError(f"Restrição {r+1}: sinal inválido (use <=, >= ou =).") b = rest_df.at[r, "b"] if b is None or b == "": raise ValueError(f"Restrição {r+1}: b vazio.") b = float(b) constraints.append((coef, op, b)) aviso = "" if any(op in (">=", "=") for _, op, _ in constraints): aviso = ( "⚠️ **Aviso didático**: `>=` e `=` normalmente exigem Big-M ou Duas Fases para base inicial. " "Esta versão usa tableau simples (pode falhar em alguns casos).\n\n" ) tabela, headers = montar_tableau(tipo, c, constraints, n_var, n_rest) state = { "tipo": tipo, "n_var": n_var, "n_rest": n_rest, "headers": headers, "tabela": tabela, "iter": 0, "finalizado": False, } md = [] md.append(aviso) md.append("## ✅ Tabela inicial (Iteração 0)\n") md.append(_to_markdown_table(tabela, headers)) md.append("\n➡️ Clique em **Próxima iteração**.\n") return "\n".join(md), state except Exception as e: raise gr.Error(str(e)) def proxima_iteracao(state): if not state: raise gr.Error("Primeiro clique em **Iniciar**.") if state.get("finalizado"): return "✅ Já está ótimo. Clique em **Reiniciar**.", state tabela = state["tabela"] headers = state["headers"] tipo = state["tipo"] n_var = state["n_var"] n_rest = state["n_rest"] lin_pivo, col_pivo = escolher_pivo(tabela) if lin_pivo is None: x, z = extrair_solucao(tabela, n_var, n_rest, tipo) state["finalizado"] = True md = [] md.append("## ✅ Ótimo encontrado\n") md.append(_to_markdown_table(tabela, headers)) md.append("\n### Resultado final\n") for i, val in enumerate(x, start=1): md.append(f"- x{i} = **{val:.4f}**") md.append(f"\n**Valor ótimo (Z):** **{z:.4f}**\n") return "\n".join(md), state state["iter"] += 1 it = state["iter"] pivo_val = tabela[lin_pivo][col_pivo] md = [] md.append(f"## Iteração {it}\n") md.append(f"**Coluna pivô:** {col_pivo} | **Linha pivô:** {lin_pivo} | **Pivô:** {pivo_val:.6f}\n") md.append("### Antes do pivoteamento\n") md.append(_to_markdown_table(tabela, headers, lin_pivo, col_pivo)) pivotar(tabela, lin_pivo, col_pivo) md.append("\n### Depois do pivoteamento\n") md.append(_to_markdown_table(tabela, headers, lin_pivo, col_pivo)) md.append("\n➡️ Clique em **Próxima iteração** novamente.\n") state["tabela"] = tabela return "\n".join(md), state def reiniciar(n_var, n_rest): # reconstroi grades obj = make_obj_df(int(n_var)) rest = make_rest_df(int(n_var), int(n_rest)) return "", None, obj, rest, "🔄 Reiniciado." CSS = """ #output_md { max-height: 520px; overflow: auto; padding: 12px; border: 1px solid #e5e7eb; border-radius: 12px; } """ with gr.Blocks(title="Simplex Passo a Passo (ensino)") as demo: gr.Markdown( "# Simplex Passo a Passo (ensino)\n" "✅ Inputs em **grade** (caixinhas) + **seleção do sinal** por restrição.\n" "1) Escolha n_var e n_rest → 2) **Gerar campos** → 3) Preencha → 4) **Iniciar** → 5) **Próxima iteração**" ) with gr.Row(): tipo = gr.Dropdown(choices=["max", "min"], value="max", label="Tipo") n_var = gr.Slider(1, 8, value=2, step=1, label="Nº variáveis") n_rest = gr.Slider(1, 8, value=3, step=1, label="Nº restrições") info = gr.Markdown("Clique em **Gerar campos** para criar a grade.") btn_gen = gr.Button("🧩 Gerar campos", variant="primary") with gr.Row(): with gr.Column(scale=4): gr.Markdown("## Função objetivo") obj_df = gr.Dataframe( value=make_obj_df(2), interactive=True, row_count=(1, "fixed"), col_count=(2, "fixed"), wrap=True, ) with gr.Column(scale=6): gr.Markdown("## Restrições") rest_df = gr.Dataframe( value=make_rest_df(2, 3), interactive=True, row_count=(3, "fixed"), col_count=(4, "fixed"), wrap=True, ) gr.Markdown( "### Formato da grade\n" "- Objetivo: 1 linha com coeficientes de x1..xn\n" "- Restrições: cada linha = coeficientes + **sinal** + b\n" "- Sinal deve ser: `<=` ou `>=` ou `=`" ) with gr.Row(): btn_init = gr.Button("🚀 Iniciar", variant="primary") btn_next = gr.Button("➡️ Próxima iteração") btn_reset = gr.Button("🔄 Reiniciar") out = gr.Markdown(elem_id="output_md") state = gr.State(None) # Gera as grades com dimensões novas btn_gen.click( fn=gerar_tabelas, inputs=[n_var, n_rest], outputs=[obj_df, rest_df, info] ) # Inicia btn_init.click( fn=iniciar, inputs=[tipo, obj_df, rest_df], outputs=[out, state] ) # Próxima btn_next.click( fn=proxima_iteracao, inputs=[state], outputs=[out, state] ) # Reiniciar btn_reset.click( fn=reiniciar, inputs=[n_var, n_rest], outputs=[out, state, obj_df, rest_df, info] ) demo.queue() demo.launch(css=CSS)