I'm using the Python interface to Minizinc and read both model (.mzn) and data (.dzn) from external files. Is there a way to access problem data from Python?
As example I use cakes2-model from Minizinc manual, which has a decision variable b and a data field flour.
from minizinc import Instance, Model, Solver
solverToUse = "coinbc"
solver = Solver.lookup(solverToUse)
print(solver.name, ",", solver.version)
model = Model("cakes2.mzn")
model.add_file("cakes2.dzn")
instance = Instance(solver, model)
print(instance.method)
result=instance.solve()
b = result.solution.b
print(b)
This runs fine. But how can I access the data/parameter flour? Below is result when interactively asking for data in the same way as for decision variables:
C:\Users\MartinJo>python -i callingMinizinc2.py
COIN-BC , 2.10.5/1.17.5
Method.MAXIMIZE
3
>>> result.solution.b
3
>>> result.solution.flour
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Solution' object has no attribute 'flour'
>>>
The MiniZinc Python interface is currently an interface that communicates using the minizinc
executable. By default, MiniZinc does doesn't provide any information about its parameter variable in the solution output. There are two solutions to the problem.
If you can change the model and no Python code before solving depend on the data, then you can add ::add_to_output
annotations to both the decision variables and parameter variables that you are interesting in. This way result.solution.flour
will be available.
Alternatively, MiniZinc Python has its own DZN parser. This can be enabled by installing the package as pip install minizinc[dzn]
, and then including your data file with the parse_data
flag set to True
. In your example model.add_file("cakes2.dzn", parse_data=True)
. Afterwards the data will be available by index of the Model
object: model["flour"]
.