-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathload_model.py
41 lines (33 loc) · 1.19 KB
/
load_model.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from amplpy import AMPL
import amplpy_gurobi as ampls
SOLVER = "gurobi"
# Example description
# Shows how to export a model from amplpy to ampls,
# how to solve it and how to get the solution as a vector or
# as a dictionary
def doStuff(a):
'''Generic function doing the optimization and reading the results'''
# Optimize with default settings
a.optimize()
print("Model status:", a.get_status())
# Print the objective function
print("Objective:", a.get_obj())
# Get the solution as vector and count the nonzeroes
sol = a.get_solution_vector()
countnz = sum(x != 0 for x in sol)
# Get the solution as dictionary (name : value)
sol = a.get_solution_dict()
nonzeroes = {name : value for name, value in sol.items() if value != 0}
for (name, value) in nonzeroes.items():
print("{} = {}".format(name, value))
print(f"Non zeroes: vector = {countnz}, dict = {len(nonzeroes)}")
# Using amplpy
ampl = AMPL()
ampl.read("models/queens.mod")
ampl.param["size"]=10
# Export to specified solver
ampls_model = ampl.to_ampls(SOLVER)
# Call generic function
doStuff(ampls_model)