| 1 | initial version |
Personally I would try to find a way to avoid the symbolic ring (with var, etc.) altogether.
If you want to use the symbolic ring, then you have to do the conversion to a LinearFunction somehow.
Assuming this setup:
sage: var('x,y')
sage: expr = 2*x + y
sage: p = MixedIntegerLinearProgram(maximization=False)
sage: pvar = p.new_variable(real=True, nonnegative=True)
You can do it e.g. like this:
def linear_function_from_symbolic(expr, pvar):
constant_coeff = pvar.mip().base_ring()(expr.subs(dict(zip(expr.variables(), [0]*len(expr.variables())))))
return sum(expr.coefficient(v)*pvar[v] for v in expr.variables()) + constant_coeff
and use it as follows:
sage: linear_function_from_symbolic(expr, pvar)
2*x_0 + x_1
You can convert constraints too:
def linear_constraint_from_symbolic(expr, pvar):
return expr.operator()(linear_function_from_symbolic(expr.lhs(), pvar),
linear_function_from_symbolic(expr.rhs(), pvar))
for example:
sage: linear_constraint_from_symbolic(x <= 1, pvar)
x_0 <= 1
It is reasonable that there is no coercion from the Symbolic Ring to Linear functions over RDF, because it would not be well-defined with respect to the ordering of variables: e.g. coercion of two functions of different variables would depend on the order in which you do it. The function above "suffers" from the same (but probably you don't care).
Copyright Sage, 2010. Some rights reserved under creative commons license. Content on this site is licensed under a Creative Commons Attribution Share Alike 3.0 license.