Spaces:
Sleeping
Sleeping
File size: 11,886 Bytes
4178567 32e7a52 4178567 32e7a52 4178567 32e7a52 4178567 32e7a52 4178567 32e7a52 4178567 32e7a52 4178567 32e7a52 4178567 32e7a52 4178567 32e7a52 4178567 32e7a52 4178567 bc67abd 4178567 bc67abd 4178567 bc67abd 4178567 bc67abd 4178567 bc67abd 4178567 bc67abd 4178567 bc67abd 4178567 bc67abd 4178567 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | 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"<h3 style='margin:8px 0 12px 0'>{title}</h3>" if title else ""
wrapper = f"""
<div style="border:1px solid #e5e7eb;border-radius:12px;padding:12px;overflow:auto;">
{head}
{html_table}
</div>
"""
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 = (
"<div style='padding:10px;border-radius:10px;border:1px solid #f59e0b;background:#fffbeb;margin-bottom:12px;'>"
"⚠️ <b>Aviso didático</b>: `>=` e `=` normalmente exigem Big-M ou Duas Fases para base inicial. "
"Esta versão usa tableau simples (pode falhar em alguns casos)."
"</div>"
)
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 += "<p style='margin-top:10px;'>➡️ Clique em <b>Próxima iteração</b>.</p>"
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 += "<h3 style='margin:14px 0 8px 0;'>Resultado final</h3><ul>"
for i, val in enumerate(x, start=1):
html += f"<li>x{i} = <b>{val:.4f}</b></li>"
html += f"</ul><p><b>Valor ótimo (Z): {z:.4f}</b></p>"
return html, state
# pivot
state["iter"] += 1
it = state["iter"]
pivo_val = tabela[lin_pivo][col_pivo]
html = f"""
<div style='padding:10px;border-radius:10px;border:1px solid #e5e7eb;background:#f9fafb;margin-bottom:12px;'>
<b>Iteração {it}</b> — Coluna pivô: <b>{col_pivo}</b> | Linha pivô: <b>{lin_pivo}</b> | Pivô: <b>{pivo_val:.6f}</b>
</div>
"""
html += _to_html_table(tabela, headers, lin_pivo, col_pivo, title="Antes do pivoteamento")
pivotar(tabela, lin_pivo, col_pivo)
html += "<div style='height:10px'></div>"
html += _to_html_table(tabela, headers, lin_pivo, col_pivo, title="Depois do pivoteamento")
html += "<p style='margin-top:10px;'>➡️ Clique em <b>Próxima iteração</b> novamente.</p>"
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) |