def _decompose_sum(children): quadratic = [] linear = [] constant = None other = [] for child in children: if isinstance(child, core.QuadraticExpression): quadratic.append(child) elif isinstance(child, core.LinearExpression): linear.append(child) elif isinstance(child, core.Variable): linear.append(core.LinearExpression([child], [1.0], 0.0)) elif isinstance(child, core.Constant): if constant is None: constant = 0.0 constant += child.value else: other.append(child) if len(linear) > 0 and constant is not None: linear.append(core.LinearExpression([], [], constant)) elif constant is not None: other.append(core.Constant(constant)) return quadratic, linear, other
def visiting_potential_leaf(self, node): if node.__class__ in nonpyomo_leaf_types: expr = NumericConstant(float(node)) const = core.Constant(float(node)) self.set(expr, const) return True, const if node.is_variable_type(): return True, self.get(node) # LinearExpression is special because it does not have # args even thought it has children. if isinstance(node, LinearExpression): variables = [self.get(var) for var in node.linear_vars] return True, core.LinearExpression(variables, node.linear_coefs, node.constant) return False, None
def problem_from_pyomo_model(model): """Convert the Pyomo ``model`` to GALINI Problem. Parameters ---------- model : ConcreteModel the Pyomo model. Returns ------- galini.core.Problem GALINI problem. """ if model.name: name = model.name else: name = 'unknown' problem = core.Problem(name) factory = _ComponentFactory(problem) for omo_var in model_variables(model): factory.add_variable(omo_var) for omo_cons in model_constraints(model): factory.add_constraint(omo_cons) for omo_obj in model_objectives(model): factory.add_objective(omo_obj) if not problem.objective: # Add constant objective problem.add_objective( core.Objective( '_constant_objective', core.Constant(0.0), core.Sense.MINIMIZE, ), ) detect_auxiliary_variables(problem) detect_rlt_constraints(problem) return problem
def _clone_expression(expr, children): type_ = expr.expression_type if type_ == ExpressionType.Linear: coefficients = [expr.coefficient(v) for v in expr.children] return core.LinearExpression(children, coefficients, expr.constant_term) elif type_ == ExpressionType.Quadratic: child_by_index = dict([(ch.idx, ch) for ch in children]) terms = expr.terms coefficients = [t.coefficient for t in terms] vars1 = [child_by_index[t.var1.idx] for t in terms] vars2 = [child_by_index[t.var2.idx] for t in terms] return core.QuadraticExpression(vars1, vars2, coefficients) elif type_ == ExpressionType.Constant: return core.Constant(expr.value) elif type_ == ExpressionType.UnaryFunction: func_type = expr.func_type cls = _FUNC_TYPE_TO_CLS[func_type] return cls(children) else: cls = _EXPR_TYPE_TO_CLS[type_] return cls(children)
def _convert_reciprocal(_node, values): assert len(values) == 1 return core.DivisionExpression([core.Constant(1.0), values[0]])