wintergw commited on
Commit
24ba902
·
verified ·
1 Parent(s): 894240e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -0
app.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pyscipopt
3
+
4
+ def knapsack_optimization(values, weights, capacity):
5
+ n = len(values)
6
+ model = pyscipopt.Model("Knapsack")
7
+
8
+ # Define decision variables
9
+ x = {i: model.addVar(f"x_{i}", vtype="B") for i in range(n)}
10
+
11
+ # Objective: Maximize total value
12
+ model.setObjective(sum(values[i] * x[i] for i in range(n)), "maximize")
13
+
14
+ # Constraint: Total weight should not exceed capacity
15
+ model.addCons(sum(weights[i] * x[i] for i in range(n)) <= capacity)
16
+
17
+ # Solve the problem
18
+ model.optimize()
19
+
20
+ # Get results
21
+ selected_items = [i for i in range(n) if model.getVal(x[i]) > 0.5]
22
+ total_value = sum(values[i] for i in selected_items)
23
+ total_weight = sum(weights[i] for i in selected_items)
24
+
25
+ return f"Optimal Value: {total_value}", f"Total Weight: {total_weight}", f"Selected Items: {selected_items}"
26
+
27
+ # Define the UI
28
+ with gr.Blocks() as demo:
29
+ gr.Markdown("# 📦 Knapsack Optimization with SCIP")
30
+
31
+ with gr.Row():
32
+ values_input = gr.Textbox(label="Item Values (comma-separated)", placeholder="10, 40, 30, 50")
33
+ weights_input = gr.Textbox(label="Item Weights (comma-separated)", placeholder="5, 8, 3, 6")
34
+
35
+ capacity_input = gr.Number(label="Knapsack Capacity", value=10)
36
+ submit_button = gr.Button("Optimize")
37
+
38
+ output1 = gr.Textbox(label="Optimal Value")
39
+ output2 = gr.Textbox(label="Total Weight")
40
+ output3 = gr.Textbox(label="Selected Items")
41
+
42
+ submit_button.click(
43
+ fn=lambda v, w, c: knapsack_optimization(
44
+ list(map(int, v.split(","))), list(map(int, w.split(","))), int(c)
45
+ ),
46
+ inputs=[values_input, weights_input, capacity_input],
47
+ outputs=[output1, output2, output3]
48
+ )
49
+
50
+ # Run the Gradio app
51
+ demo.launch()