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_html_table(tabela, headers, linha_pivo=None, coluna_pivo=None, title=None): df = pd.DataFrame(tabela, columns=headers).copy() # mantém numérico para poder pivotar e etc; só formatamos no display df_num = df.astype(float) # versão "display" já formatada df_disp = df_num.copy() for c in df_disp.columns: df_disp[c] = df_disp[c].map(lambda x: f"{x:.4f}") sty = df_disp.style # destaque coluna pivô if coluna_pivo is not None: colname = headers[coluna_pivo] sty = sty.set_properties(subset=[colname], **{"background-color": "#fff3cd"}) # destaque célula pivô (precisa retornar DataFrame de estilos) if linha_pivo is not None and coluna_pivo is not None: def highlight_pivot(data): styles = pd.DataFrame("", index=data.index, columns=data.columns) styles.iloc[linha_pivo, coluna_pivo] = "background-color:#ffe08a;font-weight:bold;" return styles sty = sty.apply(highlight_pivot, axis=None) html_table = sty.hide(axis="index").to_html() head = f"

{title}

" if title else "" wrapper = f"""
{head} {html_table}
""" return wrapper 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, c_original): """ Extrai x a partir do tableau (colunas canônicas) e calcula Z diretamente pela função objetivo original: Z = c · x. Isso evita qualquer problema de sinal/convenção da linha Z no tableau. """ 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] = float(tabela[i1][-1]) x = resultado[:n_var] # ✅ Valor ótimo robusto (independente do tableau): Z = c_original · x z = sum(float(c_original[i]) * float(x[i]) for i in range(n_var)) return x, z # ------------------------- # UI dinâmica via DataFrame (grade de caixinhas) # ------------------------- 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(obj_df.columns) if n_var < 1: raise ValueError("Objetivo sem colunas.") # 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)) # 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)." "
" ) 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, } state["c_original"] = c html = aviso html += _to_html_table(tabela, headers, title="✅ Tabela inicial (Iteração 0)") html += "

➡️ Clique em Próxima iteração.

" return html, 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) # ótimo if lin_pivo is None: x, z = extrair_solucao(tabela, n_var, n_rest, state["c_original"]) state["finalizado"] = True html = _to_html_table(tabela, headers, title="✅ Ótimo encontrado") html += "

Resultado final

Valor ótimo (Z): {z:.4f}

" return html, state # pivot state["iter"] += 1 it = state["iter"] pivo_val = tabela[lin_pivo][col_pivo] html = f"""
Iteração {it} — Coluna pivô: {col_pivo} | Linha pivô: {lin_pivo} | Pivô: {pivo_val:.6f}
""" html += _to_html_table(tabela, headers, lin_pivo, col_pivo, title="Antes do pivoteamento") pivotar(tabela, lin_pivo, col_pivo) html += "
" html += _to_html_table(tabela, headers, lin_pivo, col_pivo, title="Depois do pivoteamento") html += "

➡️ Clique em Próxima iteração novamente.

" state["tabela"] = tabela return html, state def reiniciar(n_var, n_rest): obj = make_obj_df(int(n_var)) rest = make_rest_df(int(n_var), int(n_rest)) return "", None, obj, rest, "🔄 Reiniciado." # ------------------------- # Layout # ------------------------- CSS = """ #output_html { max-height: 560px; overflow: auto; padding: 10px; border: 1px solid #e5e7eb; border-radius: 12px; } table { width: 100%; } """ with gr.Blocks(title="Simplex Passo a Passo (ensino)") as demo: gr.Markdown( "# Simplex Passo a Passo (ensino)\n" "✅ Inputs em **grade (caixinhas)** + coluna **sinal** por restrição.\n" "1) Ajuste 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"), column_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, ) 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.HTML(elem_id="output_html") state = gr.State(None) btn_gen.click(fn=gerar_tabelas, inputs=[n_var, n_rest], outputs=[obj_df, rest_df, info]) btn_init.click(fn=iniciar, inputs=[tipo, obj_df, rest_df], outputs=[out, state]) btn_next.click(fn=proxima_iteracao, inputs=[state], outputs=[out, state]) btn_reset.click(fn=reiniciar, inputs=[n_var, n_rest], outputs=[out, state, obj_df, rest_df, info]) demo.queue() demo.launch(css=CSS)