-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathgenerate_code.py
91 lines (71 loc) · 2.34 KB
/
generate_code.py
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
import os
import numpy as np
import json
def get_var_code(symbol, shape, type, definition, solver="gurobipy"):
if solver == "gurobipy":
if shape == []:
return (
f'{symbol} = model.addVar(vtype=GRB.{type.upper()}, name="{symbol}")\n'
)
else:
return (
f"{symbol} = model.addVars("
+ ", ".join([str(i) for i in shape])
+ f', vtype=GRB.{type.upper()}, name="{symbol}")\n'
)
else:
raise NotImplementedError(f"Solver {solver} is not implemented")
def get_param_code(symbol, shape, definition):
return f'{symbol} = data["{symbol}"] # shape: {shape}, definition: {definition}\n'
def generate_code(state, dir):
code = []
code.append(
f"""
import os
import numpy as np
import json
from gurobipy import Model, GRB, quicksum
model = Model("OptimizationProblem")
with open("data.json", "r") as f:
data = json.load(f)
"""
)
code.append("\n\n### Define the parameters\n")
for symbol, v in state["parameters"].items():
print(v)
code.append(get_param_code(symbol, v["shape"], v["definition"]))
code.append("\n\n### Define the variables\n")
for symbol, v in state["variables"].items():
code.append(
get_var_code(
symbol,
v["shape"],
v["type"],
v["definition"],
solver="gurobipy",
)
)
code.append("\n\n### Define the constraints\n")
for c in state["constraints"]:
code.append(c["code"])
code.append("\n\n### Define the objective\n")
code.append(state["objective"]["code"])
code.append("\n\n### Optimize the model\n")
code.append("model.optimize()\n")
code.append("\n\n### Output optimal objective value\n")
code.append(f'print("Optimal Objective Value: ", model.objVal)\n')
# code to save the optimal value if it exists
code.append(
"""
if model.status == GRB.OPTIMAL:
with open("output_solution.txt", "w") as f:
f.write(str(model.objVal))
print("Optimal Objective Value: ", model.objVal)
else:
with open("output_solution.txt", "w") as f:
f.write(model.status)
"""
)
code_str = "\n".join(code)
with open(os.path.join(dir, "code.py"), "w") as f:
f.write(code_str)