Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def create_mip(solver, J, dur, S, c, r, EST, relax=False, sense=MINIMIZE):
"""Creates a mip model to solve the RCPSP"""
NR = len(c)
mip = Model(solver_name=solver)
sd = sum(dur[j] for j in J)
vt = CONTINUOUS if relax else BINARY
x = [
{
t: mip.add_var("x(%d,%d)" % (j, t), var_type=vt)
for t in range(EST[j], sd + 1)
}
for j in J
]
TJ = [set(x[j].keys()) for j in J]
T = set()
for j in J:
T = T.union(TJ[j])
def set_objective_sense(self, sense: str):
if sense.strip().upper() == MAXIMIZE.strip().upper():
cbclib.Cbc_setObjSense(self._model, -1.0)
elif sense.strip().upper() == MINIMIZE.strip().upper():
cbclib.Cbc_setObjSense(self._model, 1.0)
else:
raise ValueError(
"Unknown sense: {}, use {} or {}".format(sense, MAXIMIZE, MINIMIZE)
)
# collecting variable coefficients
c = ffi.new("double[]", [0.0 for i in range(self.num_cols())])
for var, coeff in lin_expr.expr.items():
c[var.idx] = coeff
for i in range(self.num_cols()):
cbclib.Cbc_setObjCoeff(self._model, i, c[i])
# objective function constant
self._objconst = lin_expr.const
# setting objective sense
if MAXIMIZE in (lin_expr.sense, sense):
cbclib.Cbc_setObjSense(self._model, -1.0)
elif MINIMIZE in (lin_expr.sense, sense):
cbclib.Cbc_setObjSense(self._model, 1.0)
def check_optimization_results(self):
"""Checks the consistency of the optimization results, i.e., if the
solution(s) produced by the MIP solver respect all constraints and
variable values are within acceptable bounds and are integral when
requested"""
if self.status in [
mip.OptimizationStatus.FEASIBLE,
mip.OptimizationStatus.OPTIMAL,
]:
assert self.num_solutions >= 1
if self.num_solutions or self.status in [
mip.OptimizationStatus.FEASIBLE,
mip.OptimizationStatus.OPTIMAL,
]:
if self.sense == mip.MINIMIZE:
assert self.objective_bound <= self.objective_value + 1e-10
else:
assert self.objective_bound + 1e-10 >= self.objective_value
for c in self.constrs:
if c.expr.violation >= self.infeas_tol + self.infeas_tol * 0.1:
raise mip.InfeasibleSolution(
"Constraint {}:\n{}\n is violated."
"Computed violation is {}."
"Tolerance for infeasibility is {}."
"Solution status is {}.".format(
c.name,
str(c),
c.expr.violation,
self.infeas_tol,
self.status,
def __str__(self) -> str:
result = []
if hasattr(self, "__sense"):
if self.__sense == mip.MINIMIZE:
result.append("Minimize ")
elif self.__sense == mip.MAXIMIZE:
result.append("Minimize ")
if self.__expr:
for var, coeff in self.__expr.items():
result.append("+ " if coeff >= 0 else "- ")
result.append(str(abs(coeff)) if abs(coeff) != 1 else "")
result.append("{var} ".format(**locals()))
if hasattr(self, "__sense"):
if self.__sense == mip.EQUAL:
result.append(" = ")
if self.__sense == mip.LESS_OR_EQUAL:
result.append(" <= ")
if self.__sense == mip.GREATER_OR_EQUAL:
def minimize(objective: Union["mip.LinExpr", "mip.Var"]) -> "mip.LinExpr":
"""
Function that should be used to set the objective function to MINIMIZE
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.MINIMIZE
return objective
def set_objective_sense(self, sense: str):
if sense.strip().upper() == MAXIMIZE.strip().upper():
self.set_int_attr("ModelSense", -1)
elif sense.strip().upper() == MINIMIZE.strip().upper():
self.set_int_attr("ModelSense", 1)
else:
raise ValueError(
"Unknown sense: {}, use {} or {}".format(sense, MAXIMIZE, MINIMIZE)
)
self.__updated = False
def set_objective_sense(self, sense: str):
if sense.strip().upper() == MAXIMIZE.strip().upper():
cbclib.Osi_setObjSense(self.osi, -1.0)
elif sense.strip().upper() == MINIMIZE.strip().upper():
cbclib.Osi_setObjSense(self.osi, 1.0)
else:
raise ValueError(
"Unknown sense: {}, use {} or {}".format(sense, MAXIMIZE, MINIMIZE)
)
def get_objective_sense(self) -> str:
objs = cbclib.Osi_getObjSense(self.osi)
if objs <= -0.5:
return MAXIMIZE
return MINIMIZE