def _linear_constraint( cls, var_names: Dict[Var, str], constraint: LinearConstraint ) -> Tuple[Dict[str, float], str, float]: left_expr = constraint.get_left_expr() right_expr = constraint.get_right_expr() # for linear constraints we may get an instance of Var instead of expression, # e.g. x + y = z if not isinstance(left_expr, (AbstractLinearExpr, Var)): raise QiskitOptimizationError( f"Unsupported expression: {left_expr} {type(left_expr)}") if not isinstance(right_expr, (AbstractLinearExpr, Var)): raise QiskitOptimizationError( f"Unsupported expression: {right_expr} {type(right_expr)}") if isinstance(left_expr, Var): left_expr = left_expr + 0 if isinstance(right_expr, Var): right_expr = right_expr + 0 linear = {} for x in left_expr.iter_variables(): linear[var_names[x]] = left_expr.get_coef(x) for x in right_expr.iter_variables(): linear[var_names[x]] = linear.get(var_names[x], 0.0) - right_expr.get_coef(x) rhs = right_expr.constant - left_expr.constant if constraint.sense not in cls._sense_dict: raise QiskitOptimizationError( f"Unsupported constraint sense: {constraint}") return linear, cls._sense_dict[constraint.sense], rhs
def _linear_constraint( self, constraint: LinearConstraint ) -> Tuple[Dict[str, float], str, float]: left_expr = constraint.get_left_expr() right_expr = constraint.get_right_expr() # for linear constraints we may get an instance of Var instead of expression, # e.g. x + y = z if not isinstance(left_expr, (Expr, Var)): raise QiskitOptimizationError( f"Unsupported expression: {left_expr} {type(left_expr)}") if not isinstance(right_expr, (Expr, Var)): raise QiskitOptimizationError( f"Unsupported expression: {right_expr} {type(right_expr)}") if constraint.sense not in self._sense_dict: raise QiskitOptimizationError( f"Unsupported constraint sense: {constraint}") if isinstance(left_expr, Var): left_expr = left_expr + 0 # Var + 0 -> LinearExpr left_linear = self._linear_expr(left_expr) if isinstance(right_expr, Var): right_expr = right_expr + 0 right_linear = self._linear_expr(right_expr) linear = self._subtract(left_linear, right_linear) rhs = right_expr.constant - left_expr.constant return linear, self._sense_dict[constraint.sense], rhs