File size: 1,460 Bytes
24ba902
 
 
 
 
 
 
f0c8c4f
24ba902
 
 
 
 
 
 
 
f0c8c4f
24ba902
 
 
 
 
 
 
f0c8c4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d9368b
 
f0c8c4f
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
import gradio as gr
import pyscipopt

def knapsack_optimization(values, weights, capacity):
    n = len(values)
    model = pyscipopt.Model("Knapsack")

    # Define decision variables
    x = {i: model.addVar(f"x_{i}", vtype="B") for i in range(n)}

    # Objective: Maximize total value
    model.setObjective(sum(values[i] * x[i] for i in range(n)), "maximize")

    # Constraint: Total weight should not exceed capacity
    model.addCons(sum(weights[i] * x[i] for i in range(n)) <= capacity)

    # Solve the problem
    model.optimize()

    # Get results
    selected_items = [i for i in range(n) if model.getVal(x[i]) > 0.5]
    total_value = sum(values[i] for i in selected_items)
    total_weight = sum(weights[i] for i in selected_items)

    return f"Optimal Value: {total_value}", f"Total Weight: {total_weight}", f"Selected Items: {selected_items}"

# Create a Gradio Interface
iface = gr.Interface(
    fn=lambda values, weights, capacity: knapsack_optimization(
        list(map(int, values.split(","))),
        list(map(int, weights.split(","))),
        int(capacity)
    ),
    inputs=[
        gr.Textbox(label="Item Values (comma-separated)", placeholder="10, 40, 30, 50"),
        gr.Textbox(label="Item Weights (comma-separated)", placeholder="5, 8, 3, 6"),
        gr.Number(label="Knapsack Capacity", value=10)
    ],
    outputs=gr.JSON(label="Optimization Results"),
    title="📦 Knapsack Optimization with SCIP"
)

iface.launch()