How to use the mip.LinExpr function in mip

To help you get started, we’ve selected a few mip examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github coin-or / python-mip / mip / cbc.py View on Github external
sense = ""
            if rsense == "E":
                sense = EQUAL
            elif rsense == "L":
                sense = LESS_OR_EQUAL
            elif rsense == "G":
                sense = GREATER_OR_EQUAL
            else:
                raise ValueError("Unknow sense: {}".format(rsense))
            idx = OsiCuts_idxRowCut(osi_cuts, i)
            coef = OsiCuts_coefRowCut(osi_cuts, i)
            nz = OsiCuts_nzRowCut(osi_cuts, i)
            model = self.model
            levars = [model.vars[idx[j]] for j in range(nz)]
            lecoefs = [coef[j] for j in range(nz)]
            cut = LinExpr(levars, lecoefs, -rhs, sense)
            if cut.violation < min_viol:
                continue
            cp.add(cut)

        OsiCuts_delete(osi_cuts)
        return cp
github coin-or / python-mip / mip / cbc.py View on Github external
if rcoef == ffi.NULL:
            raise ParameterNotAvailable("Error getting row coefficients.")

        rhs = cbclib.Cbc_getRowRHS(self._model, constr.idx)
        rsense = cbclib.Cbc_getRowSense(self._model, constr.idx).decode("utf-8").upper()
        sense = ""
        if rsense == "E":
            sense = EQUAL
        elif rsense == "L":
            sense = LESS_OR_EQUAL
        elif rsense == "G":
            sense = GREATER_OR_EQUAL
        else:
            raise ValueError("Unknow sense: {}".format(rsense))

        expr = LinExpr(const=-rhs, sense=sense)
        for i in range(numnz):
            expr.add_var(self.model.vars[ridx[i]], rcoef[i])

        return expr
github coin-or / python-mip / mip / model.py View on Github external
def __iadd__(self: "Model", other) -> "Model":
        if isinstance(other, mip.LinExpr):
            if len(other.sense) == 0:
                # adding objective function components
                self.objective = other
            else:
                # adding constraint
                self.add_constr(other)
        elif isinstance(other, tuple):
            if len(other) == 2:
                if isinstance(other[0], mip.LinExpr) and isinstance(other[1], str):
                    if len(other[0].sense) == 0:
                        self.objective = other[0]
                    else:
                        self.add_constr(other[0], other[1])
                elif isinstance(other[0], mip.LinExprTensor) and isinstance(
                    other[1], str
                ):
                    if np is None:
                        raise ModuleNotFoundError(
                            "You need to install package numpy to use tensors"
                        )
                    for index, element in np.ndenumerate(other[0]):
                        # add all elements of the tensor
                        self._iadd_tensor_element(other[0], element, index, other[1])
                else:
                    raise TypeError(
github coin-or / python-mip / mip / model.py View on Github external
def xsum(terms) -> "mip.LinExpr":
    """
    Function that should be used to create a linear expression from a
    summation. While the python function sum() can also be used, this
    function is optimized version for quickly generating the linear
    expression.

    Args:
        terms: set (ideally a list) of terms to be summed

    :rtype: mip.LinExpr
    """
    result = mip.LinExpr()
    for term in terms:
        result.add_term(term)
    return result
github coin-or / python-mip / mip / model.py View on Github external
Returns:
            clone of current model
        """
        if not solver_name:
            solver_name = self.solver_name
        copy = Model(self.name, self.sense, solver_name)

        # adding variables
        for v in self.vars:
            copy.add_var(name=v.name, lb=v.lb, ub=v.ub, obj=v.obj, var_type=v.var_type)

        # adding constraints
        for c in self.constrs:
            orig_expr = c.expr
            expr = mip.LinExpr(const=orig_expr.const, sense=orig_expr.sense)
            for (var, value) in orig_expr.expr.items():
                expr.add_term(self.vars[var.idx], value)
            copy.add_constr(lin_expr=expr, name=c.name)

        # setting objective function"s constant
        copy.objective_const = self.objective_const

        return copy
github coin-or / python-mip / mip / model.py View on Github external
def maximize(objective: Union["mip.LinExpr", "mip.Var"]) -> "mip.LinExpr":
    """
    Function that should be used to set the objective function to MAXIMIZE
    a given linear expression (passed as argument).

    Args:
        objective(Union[mip.LinExpr, Var]): linear expression

    :rtype: mip.LinExpr
    """
    if isinstance(objective, mip.Var):
        objective = mip.LinExpr([objective], [1.0])
    objective.sense = mip.MAXIMIZE
    return objective
github coin-or / python-mip / mip / model.py View on Github external
def objective(
        self: "Model",
        objective: Union[numbers.Real, "mip.Var", "mip.LinExpr", "mip.LinExprTensor"],
    ):
        if isinstance(objective, numbers.Real):
            self.solver.set_objective(mip.LinExpr([], [], objective))
        elif isinstance(objective, mip.Var):
            self.solver.set_objective(mip.LinExpr([objective], [1]))
        elif isinstance(objective, mip.LinExpr):
            self.solver.set_objective(objective)
        elif isinstance(objective, mip.LinExprTensor):
            if np is None:
                raise ModuleNotFoundError(
                    "You need to install package numpy to use tensors"
                )
            if objective.size != 1:
                raise ValueError(
                    "objective set to tensor of shape {}, only scalars are allowed".format(
                        objective.shape
                    )
                )
            self.solver.set_objective(objective.flatten()[0])
        else:
            raise TypeError("type {} not supported".format(type(objective)))
github coin-or / python-mip / mip / model.py View on Github external
def objective(
        self: "Model",
        objective: Union[numbers.Real, "mip.Var", "mip.LinExpr", "mip.LinExprTensor"],
    ):
        if isinstance(objective, numbers.Real):
            self.solver.set_objective(mip.LinExpr([], [], objective))
        elif isinstance(objective, mip.Var):
            self.solver.set_objective(mip.LinExpr([objective], [1]))
        elif isinstance(objective, mip.LinExpr):
            self.solver.set_objective(objective)
        elif isinstance(objective, mip.LinExprTensor):
            if np is None:
                raise ModuleNotFoundError(
                    "You need to install package numpy to use tensors"
                )
            if objective.size != 1:
                raise ValueError(
                    "objective set to tensor of shape {}, only scalars are allowed".format(
                        objective.shape
                    )
                )
            self.solver.set_objective(objective.flatten()[0])