coin-or / python-mip

Python-MIP: collection of Python tools for the modeling and solution of Mixed-Integer Linear programs
Eclipse Public License 2.0
525 stars 92 forks source link

use float(var/linexpr) to get solution #110

Closed jurasofish closed 4 years ago

jurasofish commented 4 years ago

this feature lets you use float(var) or float(linexpr) as an alternative to var.x or linexpr.x.

My use-case for this is metaprogramming of python-mip models. In example below, can use float to get solution values whether they are python floats or mip LinExpr/Var.

I haven't tested this yet because master is a tad cooked. Give me a yell when things are working and I'll bump the PR to trigger tests.

import mip
m = mip.Model()
enable_feature = False
if enable_feature:
    my_vars = [m.add_var() for _ in range(10)]
else:
    my_vars = [0 for _ in range(10)]
# ...
m.optimize()

# doesn't work when feature not enabled! Would have to use if statements :(
# result = [my_var.x for my_var in my_vars]

# instead, float() works in both cases
result = [float(my_var) for my_var in my_vars]