Spaces:
Sleeping

File size: 11,290 Bytes
f959984
 
 
 
 
7b876e9
 
 
f959984
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b876e9
f959984
 
 
7b876e9
f959984
 
 
 
 
 
 
7b876e9
f959984
 
 
 
 
 
 
 
 
d314ff1
 
f959984
 
 
 
 
 
d314ff1
f959984
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b876e9
f959984
7b876e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f959984
 
7b876e9
f959984
d314ff1
 
 
 
f959984
 
 
 
7b876e9
f959984
 
 
56512a6
f959984
56512a6
 
 
d314ff1
 
56512a6
 
 
 
 
 
d314ff1
 
56512a6
 
 
 
 
 
 
d314ff1
 
 
56512a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f959984
d314ff1
56512a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f959984
56512a6
 
 
 
 
7b876e9
56512a6
7b876e9
56512a6
 
7b876e9
 
 
 
56512a6
7b876e9
 
56512a6
7b876e9
 
 
 
 
 
 
 
f959984
7b876e9
 
 
f959984
7b876e9
 
 
 
 
 
 
 
f959984
7b876e9
 
 
f959984
7b876e9
 
 
f959984
7b876e9
 
f959984
7b876e9
f959984
7b876e9
 
d314ff1
f959984
7b876e9
 
 
 
56512a6
 
 
 
 
7b876e9
 
d314ff1
 
 
 
56512a6
 
7b876e9
 
56512a6
 
7b876e9
f959984
 
7b876e9
56512a6
 
f959984
56512a6
f959984
d314ff1
 
 
56512a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f959984
7b876e9
d314ff1
 
 
7b876e9
d314ff1
7b876e9
f959984
56512a6
d314ff1
56512a6
 
 
d314ff1
 
56512a6
d314ff1
56512a6
 
d314ff1
 
 
56512a6
 
 
 
 
 
f959984
56512a6
 
 
 
 
 
d314ff1
 
56512a6
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
352
353
354
355
356
357
358
359
360
361
362
363
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)