index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
38,214 | pulp.apis.scip_api | parse_status | null | @staticmethod
def parse_status(string: str) -> Optional[int]:
for fscip_status, pulp_status in FSCIP_CMD.FSCIP_STATUSES.items():
if fscip_status in string:
return pulp_status
return None
| (string: str) -> Optional[int] |
38,215 | pulp.apis.scip_api | parse_variable | null | @staticmethod
def parse_variable(string: str) -> Optional[Tuple[str, float]]:
fields = string.split()
if len(fields) < 2:
return None
name, value = fields[:2]
try:
value = float(value)
except ValueError:
return None
return name, value
| (string: str) -> Optional[Tuple[str, float]] |
38,216 | pulp.apis.scip_api | readsol | Read a FSCIP solution file | @staticmethod
def readsol(filename):
"""Read a FSCIP solution file"""
with open(filename) as file:
# First line must contain a solution status
status_line = file.readline()
status = FSCIP_CMD.parse_status(status_line)
if status is None:
raise PulpSolverError(f"Can't get FSCIP solver status: {status_line!r}")
if status in FSCIP_CMD.NO_SOLUTION_STATUSES:
return status, {}
# Look for an objective value. If we can't find one, stop.
objective_line = file.readline()
objective = FSCIP_CMD.parse_objective(objective_line)
if objective is None:
raise PulpSolverError(
f"Can't get FSCIP solver objective: {objective_line!r}"
)
# Parse the variable values.
variables: Dict[str, float] = {}
for variable_line in file:
variable = FSCIP_CMD.parse_variable(variable_line)
if variable is None:
raise PulpSolverError(
f"Can't read FSCIP solver output: {variable_line!r}"
)
name, value = variable
variables[name] = value
return status, variables
| (filename) |
38,247 | pulp.pulp | FixedElasticSubProblem |
Contains the subproblem generated by converting a fixed constraint
:math:`\sum_{i}a_i x_i = b` into an elastic constraint.
:param constraint: The LpConstraint that the elastic constraint is based on
:param penalty: penalty applied for violation (+ve or -ve) of the constraints
:param proportionFreeBound:
the proportional bound (+ve and -ve) on
constraint violation that is free from penalty
:param proportionFreeBoundList: the proportional bound on constraint violation that is free from penalty, expressed as a list where [-ve, +ve]
| class FixedElasticSubProblem(LpProblem):
"""
Contains the subproblem generated by converting a fixed constraint
:math:`\\sum_{i}a_i x_i = b` into an elastic constraint.
:param constraint: The LpConstraint that the elastic constraint is based on
:param penalty: penalty applied for violation (+ve or -ve) of the constraints
:param proportionFreeBound:
the proportional bound (+ve and -ve) on
constraint violation that is free from penalty
:param proportionFreeBoundList: the proportional bound on \
constraint violation that is free from penalty, expressed as a list\
where [-ve, +ve]
"""
def __init__(
self,
constraint,
penalty=None,
proportionFreeBound=None,
proportionFreeBoundList=None,
):
subProblemName = f"{constraint.name}_elastic_SubProblem"
LpProblem.__init__(self, subProblemName, const.LpMinimize)
self.objective = LpAffineExpression()
self.constraint = constraint
self.constant = constraint.constant
self.RHS = -constraint.constant
self.objective = LpAffineExpression()
self += constraint, "_Constraint"
# create and add these variables but disabled
self.freeVar = LpVariable("_free_bound", upBound=0, lowBound=0)
self.upVar = LpVariable("_pos_penalty_var", upBound=0, lowBound=0)
self.lowVar = LpVariable("_neg_penalty_var", upBound=0, lowBound=0)
constraint.addInPlace(self.freeVar + self.lowVar + self.upVar)
if proportionFreeBound:
proportionFreeBoundList = [proportionFreeBound, proportionFreeBound]
if proportionFreeBoundList:
# add a costless variable
self.freeVar.upBound = abs(constraint.constant * proportionFreeBoundList[0])
self.freeVar.lowBound = -abs(
constraint.constant * proportionFreeBoundList[1]
)
# Note the reversal of the upbound and lowbound due to the nature of the
# variable
if penalty is not None:
# activate these variables
self.upVar.upBound = None
self.lowVar.lowBound = None
self.objective = penalty * self.upVar - penalty * self.lowVar
def _findValue(self, attrib):
"""
safe way to get the value of a variable that may not exist
"""
var = getattr(self, attrib, 0)
if var:
if value(var) is not None:
return value(var)
else:
return 0.0
else:
return 0.0
def isViolated(self):
"""
returns true if the penalty variables are non-zero
"""
upVar = self._findValue("upVar")
lowVar = self._findValue("lowVar")
freeVar = self._findValue("freeVar")
result = abs(upVar + lowVar) >= const.EPS
if result:
log.debug(
"isViolated %s, upVar %s, lowVar %s, freeVar %s result %s"
% (self.name, upVar, lowVar, freeVar, result)
)
log.debug(f"isViolated value lhs {self.findLHSValue()} constant {self.RHS}")
return result
def findDifferenceFromRHS(self):
"""
The amount the actual value varies from the RHS (sense: LHS - RHS)
"""
return self.findLHSValue() - self.RHS
def findLHSValue(self):
"""
for elastic constraints finds the LHS value of the constraint without
the free variable and or penalty variable assumes the constant is on the
rhs
"""
upVar = self._findValue("upVar")
lowVar = self._findValue("lowVar")
freeVar = self._findValue("freeVar")
return self.constraint.value() - self.constant - upVar - lowVar - freeVar
def deElasticize(self):
"""de-elasticize constraint"""
self.upVar.upBound = 0
self.lowVar.lowBound = 0
def reElasticize(self):
"""
Make the Subproblem elastic again after deElasticize
"""
self.upVar.lowBound = 0
self.upVar.upBound = None
self.lowVar.upBound = 0
self.lowVar.lowBound = None
def alterName(self, name):
"""
Alters the name of anonymous parts of the problem
"""
self.name = f"{name}_elastic_SubProblem"
if hasattr(self, "freeVar"):
self.freeVar.name = self.name + "_free_bound"
if hasattr(self, "upVar"):
self.upVar.name = self.name + "_pos_penalty_var"
if hasattr(self, "lowVar"):
self.lowVar.name = self.name + "_neg_penalty_var"
| (constraint, penalty=None, proportionFreeBound=None, proportionFreeBoundList=None) |
38,248 | pulp.pulp | __getstate__ | null | def __getstate__(self):
# Remove transient data prior to pickling.
state = self.__dict__.copy()
del state["_variable_ids"]
return state
| (self) |
38,249 | pulp.pulp | __iadd__ | null | def __iadd__(self, other):
if isinstance(other, tuple):
other, name = other
else:
name = None
if other is True:
return self
elif other is False:
raise TypeError("A False object cannot be passed as a constraint")
elif isinstance(other, LpConstraintVar):
self.addConstraint(other.constraint)
elif isinstance(other, LpConstraint):
self.addConstraint(other, name)
elif isinstance(other, LpAffineExpression):
if self.objective is not None:
warnings.warn("Overwriting previously set objective.")
self.objective = other
if name is not None:
# we may keep the LpAffineExpression name
self.objective.name = name
elif isinstance(other, LpVariable) or isinstance(other, (int, float)):
if self.objective is not None:
warnings.warn("Overwriting previously set objective.")
self.objective = LpAffineExpression(other)
self.objective.name = name
else:
raise TypeError(
"Can only add LpConstraintVar, LpConstraint, LpAffineExpression or True objects"
)
return self
| (self, other) |
38,250 | pulp.pulp | __init__ | null | def __init__(
self,
constraint,
penalty=None,
proportionFreeBound=None,
proportionFreeBoundList=None,
):
subProblemName = f"{constraint.name}_elastic_SubProblem"
LpProblem.__init__(self, subProblemName, const.LpMinimize)
self.objective = LpAffineExpression()
self.constraint = constraint
self.constant = constraint.constant
self.RHS = -constraint.constant
self.objective = LpAffineExpression()
self += constraint, "_Constraint"
# create and add these variables but disabled
self.freeVar = LpVariable("_free_bound", upBound=0, lowBound=0)
self.upVar = LpVariable("_pos_penalty_var", upBound=0, lowBound=0)
self.lowVar = LpVariable("_neg_penalty_var", upBound=0, lowBound=0)
constraint.addInPlace(self.freeVar + self.lowVar + self.upVar)
if proportionFreeBound:
proportionFreeBoundList = [proportionFreeBound, proportionFreeBound]
if proportionFreeBoundList:
# add a costless variable
self.freeVar.upBound = abs(constraint.constant * proportionFreeBoundList[0])
self.freeVar.lowBound = -abs(
constraint.constant * proportionFreeBoundList[1]
)
# Note the reversal of the upbound and lowbound due to the nature of the
# variable
if penalty is not None:
# activate these variables
self.upVar.upBound = None
self.lowVar.lowBound = None
self.objective = penalty * self.upVar - penalty * self.lowVar
| (self, constraint, penalty=None, proportionFreeBound=None, proportionFreeBoundList=None) |
38,251 | pulp.pulp | __repr__ | null | def __repr__(self):
s = self.name + ":\n"
if self.sense == 1:
s += "MINIMIZE\n"
else:
s += "MAXIMIZE\n"
s += repr(self.objective) + "\n"
if self.constraints:
s += "SUBJECT TO\n"
for n, c in self.constraints.items():
s += c.asCplexLpConstraint(n) + "\n"
s += "VARIABLES\n"
for v in self.variables():
s += v.asCplexLpVariable() + " " + const.LpCategories[v.cat] + "\n"
return s
| (self) |
38,252 | pulp.pulp | __setstate__ | null | def __setstate__(self, state):
# Update transient data prior to unpickling.
self.__dict__.update(state)
self._variable_ids = {}
for v in self._variables:
self._variable_ids[v.hash] = v
| (self, state) |
38,253 | pulp.pulp | _findValue |
safe way to get the value of a variable that may not exist
| def _findValue(self, attrib):
"""
safe way to get the value of a variable that may not exist
"""
var = getattr(self, attrib, 0)
if var:
if value(var) is not None:
return value(var)
else:
return 0.0
else:
return 0.0
| (self, attrib) |
38,254 | pulp.pulp | add | null | def add(self, constraint, name=None):
self.addConstraint(constraint, name)
| (self, constraint, name=None) |
38,255 | pulp.pulp | addConstraint | null | def addConstraint(self, constraint, name=None):
if not isinstance(constraint, LpConstraint):
raise TypeError("Can only add LpConstraint objects")
if name:
constraint.name = name
try:
if constraint.name:
name = constraint.name
else:
name = self.unusedConstraintName()
except AttributeError:
raise TypeError("Can only add LpConstraint objects")
# removed as this test fails for empty constraints
# if len(constraint) == 0:
# if not constraint.valid():
# raise ValueError, "Cannot add false constraints"
if name in self.constraints:
if self.noOverlap:
raise const.PulpError("overlapping constraint names: " + name)
else:
print("Warning: overlapping constraint names:", name)
self.constraints[name] = constraint
self.modifiedConstraints.append(constraint)
self.addVariables(list(constraint.keys()))
| (self, constraint, name=None) |
38,256 | pulp.pulp | addVariable |
Adds a variable to the problem before a constraint is added
@param variable: the variable to be added
| def addVariable(self, variable):
"""
Adds a variable to the problem before a constraint is added
@param variable: the variable to be added
"""
if variable.hash not in self._variable_ids:
self._variables.append(variable)
self._variable_ids[variable.hash] = variable
| (self, variable) |
38,257 | pulp.pulp | addVariables |
Adds variables to the problem before a constraint is added
@param variables: the variables to be added
| def addVariables(self, variables):
"""
Adds variables to the problem before a constraint is added
@param variables: the variables to be added
"""
for v in variables:
self.addVariable(v)
| (self, variables) |
38,258 | pulp.pulp | alterName |
Alters the name of anonymous parts of the problem
| def alterName(self, name):
"""
Alters the name of anonymous parts of the problem
"""
self.name = f"{name}_elastic_SubProblem"
if hasattr(self, "freeVar"):
self.freeVar.name = self.name + "_free_bound"
if hasattr(self, "upVar"):
self.upVar.name = self.name + "_pos_penalty_var"
if hasattr(self, "lowVar"):
self.lowVar.name = self.name + "_neg_penalty_var"
| (self, name) |
38,259 | pulp.pulp | assignConsPi | null | def assignConsPi(self, values):
for name in values:
try:
self.constraints[name].pi = values[name]
except KeyError:
pass
| (self, values) |
38,260 | pulp.pulp | assignConsSlack | null | def assignConsSlack(self, values, activity=False):
for name in values:
try:
if activity:
# reports the activity not the slack
self.constraints[name].slack = -1 * (
self.constraints[name].constant + float(values[name])
)
else:
self.constraints[name].slack = float(values[name])
except KeyError:
pass
| (self, values, activity=False) |
38,261 | pulp.pulp | assignStatus |
Sets the status of the model after solving.
:param status: code for the status of the model
:param sol_status: code for the status of the solution
:return:
| def assignStatus(self, status, sol_status=None):
"""
Sets the status of the model after solving.
:param status: code for the status of the model
:param sol_status: code for the status of the solution
:return:
"""
if status not in const.LpStatus:
raise const.PulpError("Invalid status code: " + str(status))
if sol_status is not None and sol_status not in const.LpSolution:
raise const.PulpError("Invalid solution status code: " + str(sol_status))
self.status = status
if sol_status is None:
sol_status = const.LpStatusToSolution.get(
status, const.LpSolutionNoSolutionFound
)
self.sol_status = sol_status
return True
| (self, status, sol_status=None) |
38,262 | pulp.pulp | assignVarsDj | null | def assignVarsDj(self, values):
variables = self.variablesDict()
for name in values:
if name != "__dummy":
variables[name].dj = values[name]
| (self, values) |
38,263 | pulp.pulp | assignVarsVals | null | def assignVarsVals(self, values):
variables = self.variablesDict()
for name in values:
if name != "__dummy":
variables[name].varValue = values[name]
| (self, values) |
38,264 | pulp.pulp | checkDuplicateVars |
Checks if there are at least two variables with the same name
:return: 1
:raises `const.PulpError`: if there ar duplicates
| def checkDuplicateVars(self) -> None:
"""
Checks if there are at least two variables with the same name
:return: 1
:raises `const.PulpError`: if there ar duplicates
"""
name_counter = Counter(variable.name for variable in self.variables())
repeated_names = {
(name, count) for name, count in name_counter.items() if count >= 2
}
if repeated_names:
raise const.PulpError(f"Repeated variable names: {repeated_names}")
| (self) -> NoneType |
38,265 | pulp.pulp | checkLengthVars |
Checks if variables have names smaller than `max_length`
:param int max_length: max size for variable name
:return:
:raises const.PulpError: if there is at least one variable that has a long name
| def checkLengthVars(self, max_length: int) -> None:
"""
Checks if variables have names smaller than `max_length`
:param int max_length: max size for variable name
:return:
:raises const.PulpError: if there is at least one variable that has a long name
"""
long_names = [
variable.name
for variable in self.variables()
if len(variable.name) > max_length
]
if long_names:
raise const.PulpError(
f"Variable names too long for Lp format: {long_names}"
)
| (self, max_length: int) -> NoneType |
38,266 | pulp.pulp | coefficients | null | def coefficients(self, translation=None):
coefs = []
if translation == None:
for c in self.constraints:
cst = self.constraints[c]
coefs.extend([(v.name, c, cst[v]) for v in cst])
else:
for c in self.constraints:
ctr = translation[c]
cst = self.constraints[c]
coefs.extend([(translation[v.name], ctr, cst[v]) for v in cst])
return coefs
| (self, translation=None) |
38,267 | pulp.pulp | copy | Make a copy of self. Expressions are copied by reference | def copy(self):
"""Make a copy of self. Expressions are copied by reference"""
lpcopy = LpProblem(name=self.name, sense=self.sense)
lpcopy.objective = self.objective
lpcopy.constraints = self.constraints.copy()
lpcopy.sos1 = self.sos1.copy()
lpcopy.sos2 = self.sos2.copy()
return lpcopy
| (self) |
38,268 | pulp.pulp | deElasticize | de-elasticize constraint | def deElasticize(self):
"""de-elasticize constraint"""
self.upVar.upBound = 0
self.lowVar.lowBound = 0
| (self) |
38,269 | pulp.pulp | deepcopy | Make a copy of self. Expressions are copied by value | def deepcopy(self):
"""Make a copy of self. Expressions are copied by value"""
lpcopy = LpProblem(name=self.name, sense=self.sense)
if self.objective is not None:
lpcopy.objective = self.objective.copy()
lpcopy.constraints = {}
for k, v in self.constraints.items():
lpcopy.constraints[k] = v.copy()
lpcopy.sos1 = self.sos1.copy()
lpcopy.sos2 = self.sos2.copy()
return lpcopy
| (self) |
38,270 | pulp.pulp | extend |
extends an LpProblem by adding constraints either from a dictionary
a tuple or another LpProblem object.
@param use_objective: determines whether the objective is imported from
the other problem
For dictionaries the constraints will be named with the keys
For tuples an unique name will be generated
For LpProblems the name of the problem will be added to the constraints
name
| def extend(self, other, use_objective=True):
"""
extends an LpProblem by adding constraints either from a dictionary
a tuple or another LpProblem object.
@param use_objective: determines whether the objective is imported from
the other problem
For dictionaries the constraints will be named with the keys
For tuples an unique name will be generated
For LpProblems the name of the problem will be added to the constraints
name
"""
if isinstance(other, dict):
for name in other:
self.constraints[name] = other[name]
elif isinstance(other, LpProblem):
for v in set(other.variables()).difference(self.variables()):
v.name = other.name + v.name
for name, c in other.constraints.items():
c.name = other.name + name
self.addConstraint(c)
if use_objective:
self.objective += other.objective
else:
for c in other:
if isinstance(c, tuple):
name = c[0]
c = c[1]
else:
name = None
if not name:
name = c.name
if not name:
name = self.unusedConstraintName()
self.constraints[name] = c
| (self, other, use_objective=True) |
38,271 | pulp.pulp | findDifferenceFromRHS |
The amount the actual value varies from the RHS (sense: LHS - RHS)
| def findDifferenceFromRHS(self):
"""
The amount the actual value varies from the RHS (sense: LHS - RHS)
"""
return self.findLHSValue() - self.RHS
| (self) |
38,272 | pulp.pulp | findLHSValue |
for elastic constraints finds the LHS value of the constraint without
the free variable and or penalty variable assumes the constant is on the
rhs
| def findLHSValue(self):
"""
for elastic constraints finds the LHS value of the constraint without
the free variable and or penalty variable assumes the constant is on the
rhs
"""
upVar = self._findValue("upVar")
lowVar = self._findValue("lowVar")
freeVar = self._findValue("freeVar")
return self.constraint.value() - self.constant - upVar - lowVar - freeVar
| (self) |
38,273 | pulp.pulp | fixObjective | null | def fixObjective(self):
if self.objective is None:
self.objective = 0
wasNone = 1
else:
wasNone = 0
if not isinstance(self.objective, LpAffineExpression):
self.objective = LpAffineExpression(self.objective)
if self.objective.isNumericalConstant():
dummyVar = self.get_dummyVar()
self.objective += dummyVar
else:
dummyVar = None
return wasNone, dummyVar
| (self) |
38,274 | pulp.pulp | getSense | null | def getSense(self):
return self.sense
| (self) |
38,275 | pulp.pulp | get_dummyVar | null | def get_dummyVar(self):
if self.dummyVar is None:
self.dummyVar = LpVariable("__dummy", 0, 0)
return self.dummyVar
| (self) |
38,276 | pulp.pulp | infeasibilityGap | null | def infeasibilityGap(self, mip=1):
gap = 0
for v in self.variables():
gap = max(abs(v.infeasibilityGap(mip)), gap)
for c in self.constraints.values():
if not c.valid(0):
gap = max(abs(c.value()), gap)
return gap
| (self, mip=1) |
38,277 | pulp.pulp | isMIP | null | def isMIP(self):
for v in self.variables():
if v.cat == const.LpInteger:
return 1
return 0
| (self) |
38,278 | pulp.pulp | isViolated |
returns true if the penalty variables are non-zero
| def isViolated(self):
"""
returns true if the penalty variables are non-zero
"""
upVar = self._findValue("upVar")
lowVar = self._findValue("lowVar")
freeVar = self._findValue("freeVar")
result = abs(upVar + lowVar) >= const.EPS
if result:
log.debug(
"isViolated %s, upVar %s, lowVar %s, freeVar %s result %s"
% (self.name, upVar, lowVar, freeVar, result)
)
log.debug(f"isViolated value lhs {self.findLHSValue()} constant {self.RHS}")
return result
| (self) |
38,279 | pulp.pulp | normalisedNames | null | def normalisedNames(self):
constraintsNames = {k: "C%07d" % i for i, k in enumerate(self.constraints)}
_variables = self.variables()
variablesNames = {k.name: "X%07d" % i for i, k in enumerate(_variables)}
return constraintsNames, variablesNames, "OBJ"
| (self) |
38,280 | pulp.pulp | numConstraints |
:return: number of constraints in model
| def numConstraints(self):
"""
:return: number of constraints in model
"""
return len(self.constraints)
| (self) |
38,281 | pulp.pulp | numVariables |
:return: number of variables in model
| def numVariables(self):
"""
:return: number of variables in model
"""
return len(self._variable_ids)
| (self) |
38,282 | pulp.pulp | reElasticize |
Make the Subproblem elastic again after deElasticize
| def reElasticize(self):
"""
Make the Subproblem elastic again after deElasticize
"""
self.upVar.lowBound = 0
self.upVar.upBound = None
self.lowVar.upBound = 0
self.lowVar.lowBound = None
| (self) |
38,283 | pulp.pulp | resolve |
resolves an Problem using the same solver as previously
| def resolve(self, solver=None, **kwargs):
"""
resolves an Problem using the same solver as previously
"""
if not (solver):
solver = self.solver
if self.resolveOK:
return self.solver.actualResolve(self, **kwargs)
else:
return self.solve(solver=solver, **kwargs)
| (self, solver=None, **kwargs) |
38,284 | pulp.pulp | restoreObjective | null | def restoreObjective(self, wasNone, dummyVar):
if wasNone:
self.objective = None
elif not dummyVar is None:
self.objective -= dummyVar
| (self, wasNone, dummyVar) |
38,285 | pulp.pulp | roundSolution |
Rounds the lp variables
Inputs:
- none
Side Effects:
- The lp variables are rounded
| def roundSolution(self, epsInt=1e-5, eps=1e-7):
"""
Rounds the lp variables
Inputs:
- none
Side Effects:
- The lp variables are rounded
"""
for v in self.variables():
v.round(epsInt, eps)
| (self, epsInt=1e-05, eps=1e-07) |
38,286 | pulp.pulp | sequentialSolve |
Solve the given Lp problem with several objective functions.
This function sequentially changes the objective of the problem
and then adds the objective function as a constraint
:param objectives: the list of objectives to be used to solve the problem
:param absoluteTols: the list of absolute tolerances to be applied to
the constraints should be +ve for a minimise objective
:param relativeTols: the list of relative tolerances applied to the constraints
:param solver: the specific solver to be used, defaults to the default solver.
| def sequentialSolve(
self, objectives, absoluteTols=None, relativeTols=None, solver=None, debug=False
):
"""
Solve the given Lp problem with several objective functions.
This function sequentially changes the objective of the problem
and then adds the objective function as a constraint
:param objectives: the list of objectives to be used to solve the problem
:param absoluteTols: the list of absolute tolerances to be applied to
the constraints should be +ve for a minimise objective
:param relativeTols: the list of relative tolerances applied to the constraints
:param solver: the specific solver to be used, defaults to the default solver.
"""
# TODO Add a penalty variable to make problems elastic
# TODO add the ability to accept different status values i.e. infeasible etc
if not (solver):
solver = self.solver
if not (solver):
solver = LpSolverDefault
if not (absoluteTols):
absoluteTols = [0] * len(objectives)
if not (relativeTols):
relativeTols = [1] * len(objectives)
# time it
self.startClock()
statuses = []
for i, (obj, absol, rel) in enumerate(
zip(objectives, absoluteTols, relativeTols)
):
self.setObjective(obj)
status = solver.actualSolve(self)
statuses.append(status)
if debug:
self.writeLP(f"{i}Sequence.lp")
if self.sense == const.LpMinimize:
self += obj <= value(obj) * rel + absol, f"Sequence_Objective_{i}"
elif self.sense == const.LpMaximize:
self += obj >= value(obj) * rel + absol, f"Sequence_Objective_{i}"
self.stopClock()
self.solver = solver
return statuses
| (self, objectives, absoluteTols=None, relativeTols=None, solver=None, debug=False) |
38,287 | pulp.pulp | setObjective |
Sets the input variable as the objective function. Used in Columnwise Modelling
:param obj: the objective function of type :class:`LpConstraintVar`
Side Effects:
- The objective function is set
| def setObjective(self, obj):
"""
Sets the input variable as the objective function. Used in Columnwise Modelling
:param obj: the objective function of type :class:`LpConstraintVar`
Side Effects:
- The objective function is set
"""
if isinstance(obj, LpVariable):
# allows the user to add a LpVariable as an objective
obj = obj + 0.0
try:
obj = obj.constraint
name = obj.name
except AttributeError:
name = None
self.objective = obj
self.objective.name = name
self.resolveOK = False
| (self, obj) |
38,288 | pulp.pulp | setSolver | Sets the Solver for this problem useful if you are using
resolve
| def setSolver(self, solver=LpSolverDefault):
"""Sets the Solver for this problem useful if you are using
resolve
"""
self.solver = solver
| (self, solver=<pulp.apis.coin_api.PULP_CBC_CMD object at 0x7fae47fd56f0>) |
38,289 | pulp.pulp | solve |
Solve the given Lp problem.
This function changes the problem to make it suitable for solving
then calls the solver.actualSolve() method to find the solution
:param solver: Optional: the specific solver to be used, defaults to the
default solver.
Side Effects:
- The attributes of the problem object are changed in
:meth:`~pulp.solver.LpSolver.actualSolve()` to reflect the Lp solution
| def solve(self, solver=None, **kwargs):
"""
Solve the given Lp problem.
This function changes the problem to make it suitable for solving
then calls the solver.actualSolve() method to find the solution
:param solver: Optional: the specific solver to be used, defaults to the
default solver.
Side Effects:
- The attributes of the problem object are changed in
:meth:`~pulp.solver.LpSolver.actualSolve()` to reflect the Lp solution
"""
if not (solver):
solver = self.solver
if not (solver):
solver = LpSolverDefault
wasNone, dummyVar = self.fixObjective()
# time it
self.startClock()
status = solver.actualSolve(self, **kwargs)
self.stopClock()
self.restoreObjective(wasNone, dummyVar)
self.solver = solver
return status
| (self, solver=None, **kwargs) |
38,290 | pulp.pulp | startClock | initializes properties with the current time | def startClock(self):
"initializes properties with the current time"
self.solutionCpuTime = -clock()
self.solutionTime = -time()
| (self) |
38,291 | pulp.pulp | stopClock | updates time wall time and cpu time | def stopClock(self):
"updates time wall time and cpu time"
self.solutionTime += time()
self.solutionCpuTime += clock()
| (self) |
38,292 | pulp.pulp | toDict |
creates a dictionary from the model with as much data as possible.
It replaces variables by variable names.
So it requires to have unique names for variables.
:return: dictionary with model data
:rtype: dict
| def toDict(self):
"""
creates a dictionary from the model with as much data as possible.
It replaces variables by variable names.
So it requires to have unique names for variables.
:return: dictionary with model data
:rtype: dict
"""
try:
self.checkDuplicateVars()
except const.PulpError:
raise const.PulpError(
"Duplicated names found in variables:\nto export the model, variable names need to be unique"
)
self.fixObjective()
variables = self.variables()
return dict(
objective=dict(
name=self.objective.name, coefficients=self.objective.toDict()
),
constraints=[v.toDict() for v in self.constraints.values()],
variables=[v.toDict() for v in variables],
parameters=dict(
name=self.name,
sense=self.sense,
status=self.status,
sol_status=self.sol_status,
),
sos1=list(self.sos1.values()),
sos2=list(self.sos2.values()),
)
| (self) |
38,293 | pulp.pulp | toJson |
Creates a json file from the LpProblem information
:param str filename: filename to write json
:param args: additional arguments for json function
:param kwargs: additional keyword arguments for json function
:return: None
| def toJson(self, filename, *args, **kwargs):
"""
Creates a json file from the LpProblem information
:param str filename: filename to write json
:param args: additional arguments for json function
:param kwargs: additional keyword arguments for json function
:return: None
"""
with open(filename, "w") as f:
json.dump(self.toDict(), f, *args, **kwargs)
| (self, filename, *args, **kwargs) |
38,296 | pulp.pulp | unusedConstraintName | null | def unusedConstraintName(self):
self.lastUnused += 1
while 1:
s = "_C%d" % self.lastUnused
if s not in self.constraints:
break
self.lastUnused += 1
return s
| (self) |
38,297 | pulp.pulp | valid | null | def valid(self, eps=0):
for v in self.variables():
if not v.valid(eps):
return False
for c in self.constraints.values():
if not c.valid(eps):
return False
else:
return True
| (self, eps=0) |
38,298 | pulp.pulp | variables |
Returns the problem variables
:return: A list containing the problem variables
:rtype: (list, :py:class:`LpVariable`)
| def variables(self):
"""
Returns the problem variables
:return: A list containing the problem variables
:rtype: (list, :py:class:`LpVariable`)
"""
if self.objective:
self.addVariables(list(self.objective.keys()))
for c in self.constraints.values():
self.addVariables(list(c.keys()))
self._variables.sort(key=lambda v: v.name)
return self._variables
| (self) |
38,299 | pulp.pulp | variablesDict | null | def variablesDict(self):
variables = {}
if self.objective:
for v in self.objective:
variables[v.name] = v
for c in list(self.constraints.values()):
for v in c:
variables[v.name] = v
return variables
| (self) |
38,300 | pulp.pulp | writeLP |
Write the given Lp problem to a .lp file.
This function writes the specifications (objective function,
constraints, variables) of the defined Lp problem to a file.
:param str filename: the name of the file to be created.
:return: variables
Side Effects:
- The file is created
| def writeLP(self, filename, writeSOS=1, mip=1, max_length=100):
"""
Write the given Lp problem to a .lp file.
This function writes the specifications (objective function,
constraints, variables) of the defined Lp problem to a file.
:param str filename: the name of the file to be created.
:return: variables
Side Effects:
- The file is created
"""
return mpslp.writeLP(
self, filename=filename, writeSOS=writeSOS, mip=mip, max_length=max_length
)
| (self, filename, writeSOS=1, mip=1, max_length=100) |
38,301 | pulp.pulp | writeMPS |
Writes an mps files from the problem information
:param str filename: name of the file to write
:param int mpsSense:
:param bool rename: if True, normalized names are used for variables and constraints
:param mip: variables and variable renames
:return:
Side Effects:
- The file is created
| def writeMPS(
self, filename, mpsSense=0, rename=0, mip=1, with_objsense: bool = False
):
"""
Writes an mps files from the problem information
:param str filename: name of the file to write
:param int mpsSense:
:param bool rename: if True, normalized names are used for variables and constraints
:param mip: variables and variable renames
:return:
Side Effects:
- The file is created
"""
return mpslp.writeMPS(
self,
filename,
mpsSense=mpsSense,
rename=rename,
mip=mip,
with_objsense=with_objsense,
)
| (self, filename, mpsSense=0, rename=0, mip=1, with_objsense: bool = False) |
38,302 | pulp.pulp | FractionElasticSubProblem |
Contains the subproblem generated by converting a Fraction constraint
numerator/(numerator+complement) = b
into an elastic constraint
:param name: The name of the elastic subproblem
:param penalty: penalty applied for violation (+ve or -ve) of the constraints
:param proportionFreeBound: the proportional bound (+ve and -ve) on
constraint violation that is free from penalty
:param proportionFreeBoundList: the proportional bound on
constraint violation that is free from penalty, expressed as a list
where [-ve, +ve]
| class FractionElasticSubProblem(FixedElasticSubProblem):
"""
Contains the subproblem generated by converting a Fraction constraint
numerator/(numerator+complement) = b
into an elastic constraint
:param name: The name of the elastic subproblem
:param penalty: penalty applied for violation (+ve or -ve) of the constraints
:param proportionFreeBound: the proportional bound (+ve and -ve) on
constraint violation that is free from penalty
:param proportionFreeBoundList: the proportional bound on
constraint violation that is free from penalty, expressed as a list
where [-ve, +ve]
"""
def __init__(
self,
name,
numerator,
RHS,
sense,
complement=None,
denominator=None,
penalty=None,
proportionFreeBound=None,
proportionFreeBoundList=None,
):
subProblemName = f"{name}_elastic_SubProblem"
self.numerator = numerator
if denominator is None and complement is not None:
self.complement = complement
self.denominator = numerator + complement
elif denominator is not None and complement is None:
self.denominator = denominator
self.complement = denominator - numerator
else:
raise const.PulpError(
"only one of denominator and complement must be specified"
)
self.RHS = RHS
self.lowTarget = self.upTarget = None
LpProblem.__init__(self, subProblemName, const.LpMinimize)
self.freeVar = LpVariable("_free_bound", upBound=0, lowBound=0)
self.upVar = LpVariable("_pos_penalty_var", upBound=0, lowBound=0)
self.lowVar = LpVariable("_neg_penalty_var", upBound=0, lowBound=0)
if proportionFreeBound:
proportionFreeBoundList = [proportionFreeBound, proportionFreeBound]
if proportionFreeBoundList:
upProportionFreeBound, lowProportionFreeBound = proportionFreeBoundList
else:
upProportionFreeBound, lowProportionFreeBound = (0, 0)
# create an objective
self += LpAffineExpression()
# There are three cases if the constraint.sense is ==, <=, >=
if sense in [const.LpConstraintEQ, const.LpConstraintLE]:
# create a constraint the sets the upper bound of target
self.upTarget = RHS + upProportionFreeBound
self.upConstraint = LpFractionConstraint(
self.numerator,
self.complement,
const.LpConstraintLE,
self.upTarget,
denominator=self.denominator,
)
if penalty is not None:
self.lowVar.lowBound = None
self.objective += -1 * penalty * self.lowVar
self.upConstraint += self.lowVar
self += self.upConstraint, "_upper_constraint"
if sense in [const.LpConstraintEQ, const.LpConstraintGE]:
# create a constraint the sets the lower bound of target
self.lowTarget = RHS - lowProportionFreeBound
self.lowConstraint = LpFractionConstraint(
self.numerator,
self.complement,
const.LpConstraintGE,
self.lowTarget,
denominator=self.denominator,
)
if penalty is not None:
self.upVar.upBound = None
self.objective += penalty * self.upVar
self.lowConstraint += self.upVar
self += self.lowConstraint, "_lower_constraint"
def findLHSValue(self):
"""
for elastic constraints finds the LHS value of the constraint without
the free variable and or penalty variable assumes the constant is on the
rhs
"""
# uses code from LpFractionConstraint
if abs(value(self.denominator)) >= const.EPS:
return value(self.numerator) / value(self.denominator)
else:
if abs(value(self.numerator)) <= const.EPS:
# zero divided by zero will return 1
return 1.0
else:
raise ZeroDivisionError
def isViolated(self):
"""
returns true if the penalty variables are non-zero
"""
if abs(value(self.denominator)) >= const.EPS:
if self.lowTarget is not None:
if self.lowTarget > self.findLHSValue():
return True
if self.upTarget is not None:
if self.findLHSValue() > self.upTarget:
return True
else:
# if the denominator is zero the constraint is satisfied
return False
| (name, numerator, RHS, sense, complement=None, denominator=None, penalty=None, proportionFreeBound=None, proportionFreeBoundList=None) |
38,305 | pulp.pulp | __init__ | null | def __init__(
self,
name,
numerator,
RHS,
sense,
complement=None,
denominator=None,
penalty=None,
proportionFreeBound=None,
proportionFreeBoundList=None,
):
subProblemName = f"{name}_elastic_SubProblem"
self.numerator = numerator
if denominator is None and complement is not None:
self.complement = complement
self.denominator = numerator + complement
elif denominator is not None and complement is None:
self.denominator = denominator
self.complement = denominator - numerator
else:
raise const.PulpError(
"only one of denominator and complement must be specified"
)
self.RHS = RHS
self.lowTarget = self.upTarget = None
LpProblem.__init__(self, subProblemName, const.LpMinimize)
self.freeVar = LpVariable("_free_bound", upBound=0, lowBound=0)
self.upVar = LpVariable("_pos_penalty_var", upBound=0, lowBound=0)
self.lowVar = LpVariable("_neg_penalty_var", upBound=0, lowBound=0)
if proportionFreeBound:
proportionFreeBoundList = [proportionFreeBound, proportionFreeBound]
if proportionFreeBoundList:
upProportionFreeBound, lowProportionFreeBound = proportionFreeBoundList
else:
upProportionFreeBound, lowProportionFreeBound = (0, 0)
# create an objective
self += LpAffineExpression()
# There are three cases if the constraint.sense is ==, <=, >=
if sense in [const.LpConstraintEQ, const.LpConstraintLE]:
# create a constraint the sets the upper bound of target
self.upTarget = RHS + upProportionFreeBound
self.upConstraint = LpFractionConstraint(
self.numerator,
self.complement,
const.LpConstraintLE,
self.upTarget,
denominator=self.denominator,
)
if penalty is not None:
self.lowVar.lowBound = None
self.objective += -1 * penalty * self.lowVar
self.upConstraint += self.lowVar
self += self.upConstraint, "_upper_constraint"
if sense in [const.LpConstraintEQ, const.LpConstraintGE]:
# create a constraint the sets the lower bound of target
self.lowTarget = RHS - lowProportionFreeBound
self.lowConstraint = LpFractionConstraint(
self.numerator,
self.complement,
const.LpConstraintGE,
self.lowTarget,
denominator=self.denominator,
)
if penalty is not None:
self.upVar.upBound = None
self.objective += penalty * self.upVar
self.lowConstraint += self.upVar
self += self.lowConstraint, "_lower_constraint"
| (self, name, numerator, RHS, sense, complement=None, denominator=None, penalty=None, proportionFreeBound=None, proportionFreeBoundList=None) |
38,327 | pulp.pulp | findLHSValue |
for elastic constraints finds the LHS value of the constraint without
the free variable and or penalty variable assumes the constant is on the
rhs
| def findLHSValue(self):
"""
for elastic constraints finds the LHS value of the constraint without
the free variable and or penalty variable assumes the constant is on the
rhs
"""
# uses code from LpFractionConstraint
if abs(value(self.denominator)) >= const.EPS:
return value(self.numerator) / value(self.denominator)
else:
if abs(value(self.numerator)) <= const.EPS:
# zero divided by zero will return 1
return 1.0
else:
raise ZeroDivisionError
| (self) |
38,333 | pulp.pulp | isViolated |
returns true if the penalty variables are non-zero
| def isViolated(self):
"""
returns true if the penalty variables are non-zero
"""
if abs(value(self.denominator)) >= const.EPS:
if self.lowTarget is not None:
if self.lowTarget > self.findLHSValue():
return True
if self.upTarget is not None:
if self.findLHSValue() > self.upTarget:
return True
else:
# if the denominator is zero the constraint is satisfied
return False
| (self) |
38,357 | pulp.apis.glpk_api | GLPK_CMD | The GLPK LP solver | class GLPK_CMD(LpSolver_CMD):
"""The GLPK LP solver"""
name = "GLPK_CMD"
def __init__(
self,
path=None,
keepFiles=False,
mip=True,
msg=True,
options=None,
timeLimit=None,
):
"""
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param float timeLimit: maximum time for solver (in seconds)
:param list options: list of additional options to pass to solver
:param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
:param str path: path to the solver binary
"""
LpSolver_CMD.__init__(
self,
mip=mip,
msg=msg,
timeLimit=timeLimit,
options=options,
path=path,
keepFiles=keepFiles,
)
def defaultPath(self):
return self.executableExtension(glpk_path)
def available(self):
"""True if the solver is available"""
return self.executable(self.path)
def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
if not self.executable(self.path):
raise PulpSolverError("PuLP: cannot execute " + self.path)
tmpLp, tmpSol = self.create_tmp_files(lp.name, "lp", "sol")
lp.writeLP(tmpLp, writeSOS=0)
proc = ["glpsol", "--cpxlp", tmpLp, "-o", tmpSol]
if self.timeLimit:
proc.extend(["--tmlim", str(self.timeLimit)])
if not self.mip:
proc.append("--nomip")
proc.extend(self.options)
self.solution_time = clock()
if not self.msg:
proc[0] = self.path
pipe = open(os.devnull, "w")
if operating_system == "win":
# Prevent flashing windows if used from a GUI application
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
rc = subprocess.call(
proc, stdout=pipe, stderr=pipe, startupinfo=startupinfo
)
else:
rc = subprocess.call(proc, stdout=pipe, stderr=pipe)
if rc:
raise PulpSolverError(
"PuLP: Error while trying to execute " + self.path
)
pipe.close()
else:
if os.name != "nt":
rc = os.spawnvp(os.P_WAIT, self.path, proc)
else:
rc = os.spawnv(os.P_WAIT, self.executable(self.path), proc)
if rc == 127:
raise PulpSolverError(
"PuLP: Error while trying to execute " + self.path
)
self.solution_time += clock()
if not os.path.exists(tmpSol):
raise PulpSolverError("PuLP: Error while executing " + self.path)
status, values = self.readsol(tmpSol)
lp.assignVarsVals(values)
lp.assignStatus(status)
self.delete_tmp_files(tmpLp, tmpSol)
return status
def readsol(self, filename):
"""Read a GLPK solution file"""
with open(filename) as f:
f.readline()
rows = int(f.readline().split()[1])
cols = int(f.readline().split()[1])
f.readline()
statusString = f.readline()[12:-1]
glpkStatus = {
"INTEGER OPTIMAL": constants.LpStatusOptimal,
"INTEGER NON-OPTIMAL": constants.LpStatusOptimal,
"OPTIMAL": constants.LpStatusOptimal,
"INFEASIBLE (FINAL)": constants.LpStatusInfeasible,
"INTEGER UNDEFINED": constants.LpStatusUndefined,
"UNBOUNDED": constants.LpStatusUnbounded,
"UNDEFINED": constants.LpStatusUndefined,
"INTEGER EMPTY": constants.LpStatusInfeasible,
}
if statusString not in glpkStatus:
raise PulpSolverError("Unknown status returned by GLPK")
status = glpkStatus[statusString]
isInteger = statusString in [
"INTEGER NON-OPTIMAL",
"INTEGER OPTIMAL",
"INTEGER UNDEFINED",
"INTEGER EMPTY",
]
values = {}
for i in range(4):
f.readline()
for i in range(rows):
line = f.readline().split()
if len(line) == 2:
f.readline()
for i in range(3):
f.readline()
for i in range(cols):
line = f.readline().split()
name = line[1]
if len(line) == 2:
line = [0, 0] + f.readline().split()
if isInteger:
if line[2] == "*":
value = int(float(line[3]))
else:
value = float(line[2])
else:
value = float(line[3])
values[name] = value
return status, values
| (path=None, keepFiles=False, mip=True, msg=True, options=None, timeLimit=None) |
38,360 | pulp.apis.glpk_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
if not self.executable(self.path):
raise PulpSolverError("PuLP: cannot execute " + self.path)
tmpLp, tmpSol = self.create_tmp_files(lp.name, "lp", "sol")
lp.writeLP(tmpLp, writeSOS=0)
proc = ["glpsol", "--cpxlp", tmpLp, "-o", tmpSol]
if self.timeLimit:
proc.extend(["--tmlim", str(self.timeLimit)])
if not self.mip:
proc.append("--nomip")
proc.extend(self.options)
self.solution_time = clock()
if not self.msg:
proc[0] = self.path
pipe = open(os.devnull, "w")
if operating_system == "win":
# Prevent flashing windows if used from a GUI application
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
rc = subprocess.call(
proc, stdout=pipe, stderr=pipe, startupinfo=startupinfo
)
else:
rc = subprocess.call(proc, stdout=pipe, stderr=pipe)
if rc:
raise PulpSolverError(
"PuLP: Error while trying to execute " + self.path
)
pipe.close()
else:
if os.name != "nt":
rc = os.spawnvp(os.P_WAIT, self.path, proc)
else:
rc = os.spawnv(os.P_WAIT, self.executable(self.path), proc)
if rc == 127:
raise PulpSolverError(
"PuLP: Error while trying to execute " + self.path
)
self.solution_time += clock()
if not os.path.exists(tmpSol):
raise PulpSolverError("PuLP: Error while executing " + self.path)
status, values = self.readsol(tmpSol)
lp.assignVarsVals(values)
lp.assignStatus(status)
self.delete_tmp_files(tmpLp, tmpSol)
return status
| (self, lp) |
38,364 | pulp.apis.glpk_api | defaultPath | null | def defaultPath(self):
return self.executableExtension(glpk_path)
| (self) |
38,369 | pulp.apis.glpk_api | readsol | Read a GLPK solution file | def readsol(self, filename):
"""Read a GLPK solution file"""
with open(filename) as f:
f.readline()
rows = int(f.readline().split()[1])
cols = int(f.readline().split()[1])
f.readline()
statusString = f.readline()[12:-1]
glpkStatus = {
"INTEGER OPTIMAL": constants.LpStatusOptimal,
"INTEGER NON-OPTIMAL": constants.LpStatusOptimal,
"OPTIMAL": constants.LpStatusOptimal,
"INFEASIBLE (FINAL)": constants.LpStatusInfeasible,
"INTEGER UNDEFINED": constants.LpStatusUndefined,
"UNBOUNDED": constants.LpStatusUnbounded,
"UNDEFINED": constants.LpStatusUndefined,
"INTEGER EMPTY": constants.LpStatusInfeasible,
}
if statusString not in glpkStatus:
raise PulpSolverError("Unknown status returned by GLPK")
status = glpkStatus[statusString]
isInteger = statusString in [
"INTEGER NON-OPTIMAL",
"INTEGER OPTIMAL",
"INTEGER UNDEFINED",
"INTEGER EMPTY",
]
values = {}
for i in range(4):
f.readline()
for i in range(rows):
line = f.readline().split()
if len(line) == 2:
f.readline()
for i in range(3):
f.readline()
for i in range(cols):
line = f.readline().split()
name = line[1]
if len(line) == 2:
line = [0, 0] + f.readline().split()
if isInteger:
if line[2] == "*":
value = int(float(line[3]))
else:
value = float(line[2])
else:
value = float(line[3])
values[name] = value
return status, values
| (self, filename) |
38,397 | pulp.apis.gurobi_api | GUROBI |
The Gurobi LP/MIP solver (via its python interface)
The Gurobi variables are available (after a solve) in var.solverVar
Constraints in constraint.solverConstraint
and the Model is in prob.solverModel
| class GUROBI(LpSolver):
"""
The Gurobi LP/MIP solver (via its python interface)
The Gurobi variables are available (after a solve) in var.solverVar
Constraints in constraint.solverConstraint
and the Model is in prob.solverModel
"""
name = "GUROBI"
env = None
try:
sys.path.append(gurobi_path)
# to import the name into the module scope
global gp
import gurobipy as gp
except: # FIXME: Bug because gurobi returns
# a gurobi exception on failed imports
def available(self):
"""True if the solver is available"""
return False
def actualSolve(self, lp, callback=None):
"""Solve a well formulated lp problem"""
raise PulpSolverError("GUROBI: Not Available")
else:
def __init__(
self,
mip=True,
msg=True,
timeLimit=None,
gapRel=None,
warmStart=False,
logPath=None,
env=None,
envOptions=None,
manageEnv=False,
**solverParams,
):
"""
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param float timeLimit: maximum time for solver (in seconds)
:param float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param bool warmStart: if True, the solver will use the current value of variables as a start
:param str logPath: path to the log file
:param gp.Env env: Gurobi environment to use. Default None.
:param dict envOptions: environment options.
:param bool manageEnv: if False, assume the environment is handled by the user.
If ``manageEnv`` is set to True, the ``GUROBI`` object creates a
local Gurobi environment and manages all associated Gurobi
resources. Importantly, this enables Gurobi licenses to be freed
and connections terminated when the ``.close()`` function is called
(this function always disposes of the Gurobi model, and the
environment)::
solver = GUROBI(manageEnv=True)
prob.solve(solver)
solver.close() # Must be called to free Gurobi resources.
# All Gurobi models and environments are freed
``manageEnv=True`` is required when setting license or connection
parameters. The ``envOptions`` argument is used to pass parameters
to the Gurobi environment. For example, to connect to a Gurobi
Cluster Manager::
options = {
"CSManager": "<url>",
"CSAPIAccessID": "<access-id>",
"CSAPISecret": "<api-key>",
}
solver = GUROBI(manageEnv=True, envOptions=options)
solver.close()
# Compute server connection terminated
Alternatively, one can also pass a ``gp.Env`` object. In this case,
to be safe, one should still call ``.close()`` to dispose of the
model::
with gp.Env(params=options) as env:
# Pass environment as a parameter
solver = GUROBI(env=env)
prob.solve(solver)
solver.close()
# Still call `close` as this disposes the model which is required to correctly free env
If ``manageEnv`` is set to False (the default), the ``GUROBI``
object uses the global default Gurobi environment which will be
freed once the object is deleted. In this case, one can still call
``.close()`` to dispose of the model::
solver = GUROBI()
prob.solve(solver)
# The global default environment and model remain active
solver.close()
# Only the global default environment remains active
"""
self.env = env
self.env_options = envOptions if envOptions else {}
self.manage_env = False if self.env is not None else manageEnv
self.solver_params = solverParams
self.model = None
self.init_gurobi = False # whether env and model have been initialised
LpSolver.__init__(
self,
mip=mip,
msg=msg,
timeLimit=timeLimit,
gapRel=gapRel,
logPath=logPath,
warmStart=warmStart,
)
# set the output of gurobi
if not self.msg:
if self.manage_env:
self.env_options["OutputFlag"] = 0
else:
self.env_options["OutputFlag"] = 0
self.solver_params["OutputFlag"] = 0
def __del__(self):
self.close()
def close(self):
"""
Must be called when internal Gurobi model and/or environment
requires disposing. The environment (default or otherwise) will be
disposed only if ``manageEnv`` is set to True.
"""
if not self.init_gurobi:
return
self.model.dispose()
if self.manage_env:
self.env.dispose()
def findSolutionValues(self, lp):
model = lp.solverModel
solutionStatus = model.Status
GRB = gp.GRB
# TODO: check status for Integer Feasible
gurobiLpStatus = {
GRB.OPTIMAL: constants.LpStatusOptimal,
GRB.INFEASIBLE: constants.LpStatusInfeasible,
GRB.INF_OR_UNBD: constants.LpStatusInfeasible,
GRB.UNBOUNDED: constants.LpStatusUnbounded,
GRB.ITERATION_LIMIT: constants.LpStatusNotSolved,
GRB.NODE_LIMIT: constants.LpStatusNotSolved,
GRB.TIME_LIMIT: constants.LpStatusNotSolved,
GRB.SOLUTION_LIMIT: constants.LpStatusNotSolved,
GRB.INTERRUPTED: constants.LpStatusNotSolved,
GRB.NUMERIC: constants.LpStatusNotSolved,
}
if self.msg:
print("Gurobi status=", solutionStatus)
lp.resolveOK = True
for var in lp._variables:
var.isModified = False
status = gurobiLpStatus.get(solutionStatus, constants.LpStatusUndefined)
lp.assignStatus(status)
if model.SolCount >= 1:
# populate pulp solution values
for var, value in zip(
lp._variables, model.getAttr(GRB.Attr.X, model.getVars())
):
var.varValue = value
# populate pulp constraints slack
for constr, value in zip(
lp.constraints.values(),
model.getAttr(GRB.Attr.Slack, model.getConstrs()),
):
constr.slack = value
# put pi and slack variables against the constraints
if not model.IsMIP:
for var, value in zip(
lp._variables, model.getAttr(GRB.Attr.RC, model.getVars())
):
var.dj = value
for constr, value in zip(
lp.constraints.values(),
model.getAttr(GRB.Attr.Pi, model.getConstrs()),
):
constr.pi = value
return status
def available(self):
"""True if the solver is available"""
try:
with gp.Env(params=self.env_options):
pass
except gp.GurobiError as e:
warnings.warn(f"GUROBI error: {e}.")
return False
return True
def initGurobi(self):
if self.init_gurobi:
return
else:
self.init_gurobi = True
try:
if self.manage_env:
self.env = gp.Env(params=self.env_options)
self.model = gp.Model(env=self.env)
# Environment handled by user or default Env
else:
self.model = gp.Model(env=self.env)
# Set solver parameters
for param, value in self.solver_params.items():
self.model.setParam(param, value)
except gp.GurobiError as e:
raise e
def callSolver(self, lp, callback=None):
"""Solves the problem with gurobi"""
# solve the problem
self.solveTime = -clock()
lp.solverModel.optimize(callback=callback)
self.solveTime += clock()
def buildSolverModel(self, lp):
"""
Takes the pulp lp model and translates it into a gurobi model
"""
log.debug("create the gurobi model")
self.initGurobi()
self.model.ModelName = lp.name
lp.solverModel = self.model
log.debug("set the sense of the problem")
if lp.sense == constants.LpMaximize:
lp.solverModel.setAttr("ModelSense", -1)
if self.timeLimit:
lp.solverModel.setParam("TimeLimit", self.timeLimit)
gapRel = self.optionsDict.get("gapRel")
logPath = self.optionsDict.get("logPath")
if gapRel:
lp.solverModel.setParam("MIPGap", gapRel)
if logPath:
lp.solverModel.setParam("LogFile", logPath)
log.debug("add the variables to the problem")
lp.solverModel.update()
nvars = lp.solverModel.NumVars
for var in lp.variables():
lowBound = var.lowBound
if lowBound is None:
lowBound = -gp.GRB.INFINITY
upBound = var.upBound
if upBound is None:
upBound = gp.GRB.INFINITY
obj = lp.objective.get(var, 0.0)
varType = gp.GRB.CONTINUOUS
if var.cat == constants.LpInteger and self.mip:
varType = gp.GRB.INTEGER
# only add variable once, ow new variable will be created.
if not hasattr(var, "solverVar") or nvars == 0:
var.solverVar = lp.solverModel.addVar(
lowBound, upBound, vtype=varType, obj=obj, name=var.name
)
if self.optionsDict.get("warmStart", False):
# Once lp.variables() has been used at least once in the building of the model.
# we can use the lp._variables with the cache.
for var in lp._variables:
if var.varValue is not None:
var.solverVar.start = var.varValue
lp.solverModel.update()
log.debug("add the Constraints to the problem")
for name, constraint in lp.constraints.items():
# build the expression
expr = gp.LinExpr(
list(constraint.values()), [v.solverVar for v in constraint.keys()]
)
if constraint.sense == constants.LpConstraintLE:
constraint.solverConstraint = lp.solverModel.addConstr(
expr <= -constraint.constant, name=name
)
elif constraint.sense == constants.LpConstraintGE:
constraint.solverConstraint = lp.solverModel.addConstr(
expr >= -constraint.constant, name=name
)
elif constraint.sense == constants.LpConstraintEQ:
constraint.solverConstraint = lp.solverModel.addConstr(
expr == -constraint.constant, name=name
)
else:
raise PulpSolverError("Detected an invalid constraint type")
lp.solverModel.update()
def actualSolve(self, lp, callback=None):
"""
Solve a well formulated lp problem
creates a gurobi model, variables and constraints and attaches
them to the lp model which it then solves
"""
self.buildSolverModel(lp)
# set the initial solution
log.debug("Solve the Model using gurobi")
self.callSolver(lp, callback=callback)
# get the solution information
solutionStatus = self.findSolutionValues(lp)
for var in lp._variables:
var.modified = False
for constraint in lp.constraints.values():
constraint.modified = False
return solutionStatus
def actualResolve(self, lp, callback=None):
"""
Solve a well formulated lp problem
uses the old solver and modifies the rhs of the modified constraints
"""
log.debug("Resolve the Model using gurobi")
for constraint in lp.constraints.values():
if constraint.modified:
constraint.solverConstraint.setAttr(
gp.GRB.Attr.RHS, -constraint.constant
)
lp.solverModel.update()
self.callSolver(lp, callback=callback)
# get the solution information
solutionStatus = self.findSolutionValues(lp)
for var in lp._variables:
var.modified = False
for constraint in lp.constraints.values():
constraint.modified = False
return solutionStatus
| (mip=True, msg=True, options=None, timeLimit=None, *args, **kwargs) |
38,400 | pulp.apis.gurobi_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp, callback=None):
"""Solve a well formulated lp problem"""
raise PulpSolverError("GUROBI: Not Available")
| (self, lp, callback=None) |
38,409 | pulp.apis.gurobi_api | GUROBI_CMD | The GUROBI_CMD solver | class GUROBI_CMD(LpSolver_CMD):
"""The GUROBI_CMD solver"""
name = "GUROBI_CMD"
def __init__(
self,
mip=True,
msg=True,
timeLimit=None,
gapRel=None,
gapAbs=None,
options=None,
warmStart=False,
keepFiles=False,
path=None,
threads=None,
logPath=None,
mip_start=False,
):
"""
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param float timeLimit: maximum time for solver (in seconds)
:param float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param float gapAbs: absolute gap tolerance for the solver to stop
:param int threads: sets the maximum number of threads
:param list options: list of additional options to pass to solver
:param bool warmStart: if True, the solver will use the current value of variables as a start
:param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
:param str path: path to the solver binary
:param str logPath: path to the log file
"""
LpSolver_CMD.__init__(
self,
gapRel=gapRel,
mip=mip,
msg=msg,
timeLimit=timeLimit,
options=options,
warmStart=warmStart,
path=path,
keepFiles=keepFiles,
threads=threads,
gapAbs=gapAbs,
logPath=logPath,
)
def defaultPath(self):
return self.executableExtension("gurobi_cl")
def available(self):
"""True if the solver is available"""
if not self.executable(self.path):
return False
# we execute gurobi once to check the return code.
# this is to test that the license is active
result = subprocess.Popen(
self.path, stdout=subprocess.PIPE, universal_newlines=True
)
out, err = result.communicate()
if result.returncode == 0:
# normal execution
return True
# error: we display the gurobi message
warnings.warn(f"GUROBI error: {out}.")
return False
def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
if not self.executable(self.path):
raise PulpSolverError("PuLP: cannot execute " + self.path)
tmpLp, tmpSol, tmpMst = self.create_tmp_files(lp.name, "lp", "sol", "mst")
vs = lp.writeLP(tmpLp, writeSOS=1)
try:
os.remove(tmpSol)
except:
pass
cmd = self.path
options = self.options + self.getOptions()
if self.timeLimit is not None:
options.append(("TimeLimit", self.timeLimit))
cmd += " " + " ".join([f"{key}={value}" for key, value in options])
cmd += f" ResultFile={tmpSol}"
if self.optionsDict.get("warmStart", False):
self.writesol(filename=tmpMst, vs=vs)
cmd += f" InputFile={tmpMst}"
if lp.isMIP():
if not self.mip:
warnings.warn("GUROBI_CMD does not allow a problem to be relaxed")
cmd += f" {tmpLp}"
if self.msg:
pipe = None
else:
pipe = open(os.devnull, "w")
return_code = subprocess.call(cmd.split(), stdout=pipe, stderr=pipe)
# Close the pipe now if we used it.
if pipe is not None:
pipe.close()
if return_code != 0:
raise PulpSolverError("PuLP: Error while trying to execute " + self.path)
if not os.path.exists(tmpSol):
# TODO: the status should be infeasible here, I think
status = constants.LpStatusNotSolved
values = reducedCosts = shadowPrices = slacks = None
else:
# TODO: the status should be infeasible here, I think
status, values, reducedCosts, shadowPrices, slacks = self.readsol(tmpSol)
self.delete_tmp_files(tmpLp, tmpMst, tmpSol, "gurobi.log")
if status != constants.LpStatusInfeasible:
lp.assignVarsVals(values)
lp.assignVarsDj(reducedCosts)
lp.assignConsPi(shadowPrices)
lp.assignConsSlack(slacks)
lp.assignStatus(status)
return status
def readsol(self, filename):
"""Read a Gurobi solution file"""
with open(filename) as my_file:
try:
next(my_file) # skip the objective value
except StopIteration:
# Empty file not solved
status = constants.LpStatusNotSolved
return status, {}, {}, {}, {}
# We have no idea what the status is assume optimal
# TODO: check status for Integer Feasible
status = constants.LpStatusOptimal
shadowPrices = {}
slacks = {}
shadowPrices = {}
slacks = {}
values = {}
reducedCosts = {}
for line in my_file:
if line[0] != "#": # skip comments
name, value = line.split()
values[name] = float(value)
return status, values, reducedCosts, shadowPrices, slacks
def writesol(self, filename, vs):
"""Writes a GUROBI solution file"""
values = [(v.name, v.value()) for v in vs if v.value() is not None]
rows = []
for name, value in values:
rows.append(f"{name} {value}")
with open(filename, "w") as f:
f.write("\n".join(rows))
return True
def getOptions(self):
# GUROBI parameters: http://www.gurobi.com/documentation/7.5/refman/parameters.html#sec:Parameters
params_eq = dict(
logPath="LogFile",
gapRel="MIPGap",
gapAbs="MIPGapAbs",
threads="Threads",
)
return [
(v, self.optionsDict[k])
for k, v in params_eq.items()
if k in self.optionsDict and self.optionsDict[k] is not None
]
| (mip=True, msg=True, timeLimit=None, gapRel=None, gapAbs=None, options=None, warmStart=False, keepFiles=False, path=None, threads=None, logPath=None, mip_start=False) |
38,410 | pulp.apis.gurobi_api | __init__ |
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param float timeLimit: maximum time for solver (in seconds)
:param float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param float gapAbs: absolute gap tolerance for the solver to stop
:param int threads: sets the maximum number of threads
:param list options: list of additional options to pass to solver
:param bool warmStart: if True, the solver will use the current value of variables as a start
:param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
:param str path: path to the solver binary
:param str logPath: path to the log file
| def __init__(
self,
mip=True,
msg=True,
timeLimit=None,
gapRel=None,
gapAbs=None,
options=None,
warmStart=False,
keepFiles=False,
path=None,
threads=None,
logPath=None,
mip_start=False,
):
"""
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param float timeLimit: maximum time for solver (in seconds)
:param float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param float gapAbs: absolute gap tolerance for the solver to stop
:param int threads: sets the maximum number of threads
:param list options: list of additional options to pass to solver
:param bool warmStart: if True, the solver will use the current value of variables as a start
:param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
:param str path: path to the solver binary
:param str logPath: path to the log file
"""
LpSolver_CMD.__init__(
self,
gapRel=gapRel,
mip=mip,
msg=msg,
timeLimit=timeLimit,
options=options,
warmStart=warmStart,
path=path,
keepFiles=keepFiles,
threads=threads,
gapAbs=gapAbs,
logPath=logPath,
)
| (self, mip=True, msg=True, timeLimit=None, gapRel=None, gapAbs=None, options=None, warmStart=False, keepFiles=False, path=None, threads=None, logPath=None, mip_start=False) |
38,412 | pulp.apis.gurobi_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
if not self.executable(self.path):
raise PulpSolverError("PuLP: cannot execute " + self.path)
tmpLp, tmpSol, tmpMst = self.create_tmp_files(lp.name, "lp", "sol", "mst")
vs = lp.writeLP(tmpLp, writeSOS=1)
try:
os.remove(tmpSol)
except:
pass
cmd = self.path
options = self.options + self.getOptions()
if self.timeLimit is not None:
options.append(("TimeLimit", self.timeLimit))
cmd += " " + " ".join([f"{key}={value}" for key, value in options])
cmd += f" ResultFile={tmpSol}"
if self.optionsDict.get("warmStart", False):
self.writesol(filename=tmpMst, vs=vs)
cmd += f" InputFile={tmpMst}"
if lp.isMIP():
if not self.mip:
warnings.warn("GUROBI_CMD does not allow a problem to be relaxed")
cmd += f" {tmpLp}"
if self.msg:
pipe = None
else:
pipe = open(os.devnull, "w")
return_code = subprocess.call(cmd.split(), stdout=pipe, stderr=pipe)
# Close the pipe now if we used it.
if pipe is not None:
pipe.close()
if return_code != 0:
raise PulpSolverError("PuLP: Error while trying to execute " + self.path)
if not os.path.exists(tmpSol):
# TODO: the status should be infeasible here, I think
status = constants.LpStatusNotSolved
values = reducedCosts = shadowPrices = slacks = None
else:
# TODO: the status should be infeasible here, I think
status, values, reducedCosts, shadowPrices, slacks = self.readsol(tmpSol)
self.delete_tmp_files(tmpLp, tmpMst, tmpSol, "gurobi.log")
if status != constants.LpStatusInfeasible:
lp.assignVarsVals(values)
lp.assignVarsDj(reducedCosts)
lp.assignConsPi(shadowPrices)
lp.assignConsSlack(slacks)
lp.assignStatus(status)
return status
| (self, lp) |
38,413 | pulp.apis.gurobi_api | available | True if the solver is available | def available(self):
"""True if the solver is available"""
if not self.executable(self.path):
return False
# we execute gurobi once to check the return code.
# this is to test that the license is active
result = subprocess.Popen(
self.path, stdout=subprocess.PIPE, universal_newlines=True
)
out, err = result.communicate()
if result.returncode == 0:
# normal execution
return True
# error: we display the gurobi message
warnings.warn(f"GUROBI error: {out}.")
return False
| (self) |
38,416 | pulp.apis.gurobi_api | defaultPath | null | def defaultPath(self):
return self.executableExtension("gurobi_cl")
| (self) |
38,421 | pulp.apis.gurobi_api | getOptions | null | def getOptions(self):
# GUROBI parameters: http://www.gurobi.com/documentation/7.5/refman/parameters.html#sec:Parameters
params_eq = dict(
logPath="LogFile",
gapRel="MIPGap",
gapAbs="MIPGapAbs",
threads="Threads",
)
return [
(v, self.optionsDict[k])
for k, v in params_eq.items()
if k in self.optionsDict and self.optionsDict[k] is not None
]
| (self) |
38,422 | pulp.apis.gurobi_api | readsol | Read a Gurobi solution file | def readsol(self, filename):
"""Read a Gurobi solution file"""
with open(filename) as my_file:
try:
next(my_file) # skip the objective value
except StopIteration:
# Empty file not solved
status = constants.LpStatusNotSolved
return status, {}, {}, {}, {}
# We have no idea what the status is assume optimal
# TODO: check status for Integer Feasible
status = constants.LpStatusOptimal
shadowPrices = {}
slacks = {}
shadowPrices = {}
slacks = {}
values = {}
reducedCosts = {}
for line in my_file:
if line[0] != "#": # skip comments
name, value = line.split()
values[name] = float(value)
return status, values, reducedCosts, shadowPrices, slacks
| (self, filename) |
38,430 | pulp.apis.gurobi_api | writesol | Writes a GUROBI solution file | def writesol(self, filename, vs):
"""Writes a GUROBI solution file"""
values = [(v.name, v.value()) for v in vs if v.value() is not None]
rows = []
for name, value in values:
rows.append(f"{name} {value}")
with open(filename, "w") as f:
f.write("\n".join(rows))
return True
| (self, filename, vs) |
38,431 | pulp.apis.highs_api | HiGHS | null | class HiGHS(LpSolver):
name = "HiGHS"
try:
global highspy
import highspy
except:
def available(self):
"""True if the solver is available"""
return False
def actualSolve(self, lp, callback=None):
"""Solve a well formulated lp problem"""
raise PulpSolverError("HiGHS: Not Available")
else:
# Note(maciej): It was surprising to me that higshpy wasn't logging out of the box,
# even with the different logging options set. This callback seems to work, but there
# are probably better ways of doing this ¯\_(ツ)_/¯
DEFAULT_CALLBACK = lambda logType, logMsg, callbackValue: print(
f"[{logType.name}] {logMsg}"
)
DEFAULT_CALLBACK_VALUE = ""
def __init__(
self,
mip=True,
msg=True,
callbackTuple=None,
gapAbs=None,
gapRel=None,
threads=None,
timeLimit=None,
**solverParams,
):
"""
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param tuple callbackTuple: Tuple of log callback function (see DEFAULT_CALLBACK above for definition)
and callbackValue (tag embedded in every callback)
:param float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param float gapAbs: absolute gap tolerance for the solver to stop
:param int threads: sets the maximum number of threads
:param float timeLimit: maximum time for solver (in seconds)
:param dict solverParams: list of named options to pass directly to the HiGHS solver
"""
super().__init__(mip=mip, msg=msg, timeLimit=timeLimit, **solverParams)
self.callbackTuple = callbackTuple
self.gapAbs = gapAbs
self.gapRel = gapRel
self.threads = threads
def available(self):
return True
def callSolver(self, lp):
lp.solverModel.run()
def createAndConfigureSolver(self, lp):
lp.solverModel = highspy.Highs()
if self.msg or self.callbackTuple:
callbackTuple = self.callbackTuple or (
HiGHS.DEFAULT_CALLBACK,
HiGHS.DEFAULT_CALLBACK_VALUE,
)
lp.solverModel.setLogCallback(*callbackTuple)
if self.gapRel is not None:
lp.solverModel.setOptionValue("mip_rel_gap", self.gapRel)
if self.gapAbs is not None:
lp.solverModel.setOptionValue("mip_abs_gap", self.gapAbs)
if self.threads is not None:
lp.solverModel.setOptionValue("threads", self.threads)
if self.timeLimit is not None:
lp.solverModel.setOptionValue("time_limit", float(self.timeLimit))
# set remaining parameter values
for key, value in self.optionsDict.items():
lp.solverModel.setOptionValue(key, value)
def buildSolverModel(self, lp):
inf = highspy.kHighsInf
obj_mult = -1 if lp.sense == constants.LpMaximize else 1
for i, var in enumerate(lp.variables()):
lb = var.lowBound
ub = var.upBound
lp.solverModel.addCol(
obj_mult * lp.objective.get(var, 0.0),
-inf if lb is None else lb,
inf if ub is None else ub,
0,
[],
[],
)
var.index = i
if var.cat == constants.LpInteger and self.mip:
lp.solverModel.changeColIntegrality(
var.index, highspy.HighsVarType.kInteger
)
for constraint in lp.constraints.values():
non_zero_constraint_items = [
(var.index, coefficient)
for var, coefficient in constraint.items()
if coefficient != 0
]
if len(non_zero_constraint_items) == 0:
indices, coefficients = [], []
else:
indices, coefficients = zip(*non_zero_constraint_items)
lb = constraint.getLb()
ub = constraint.getUb()
lp.solverModel.addRow(
-inf if lb is None else lb,
inf if ub is None else ub,
len(indices),
indices,
coefficients,
)
def findSolutionValues(self, lp):
status = lp.solverModel.getModelStatus()
obj_value = lp.solverModel.getObjectiveValue()
solution = lp.solverModel.getSolution()
HighsModelStatus = highspy.HighsModelStatus
status_dict = {
HighsModelStatus.kNotset: (
constants.LpStatusNotSolved,
constants.LpSolutionNoSolutionFound,
),
HighsModelStatus.kLoadError: (
constants.LpStatusNotSolved,
constants.LpSolutionNoSolutionFound,
),
HighsModelStatus.kModelError: (
constants.LpStatusNotSolved,
constants.LpSolutionNoSolutionFound,
),
HighsModelStatus.kPresolveError: (
constants.LpStatusNotSolved,
constants.LpSolutionNoSolutionFound,
),
HighsModelStatus.kSolveError: (
constants.LpStatusNotSolved,
constants.LpSolutionNoSolutionFound,
),
HighsModelStatus.kPostsolveError: (
constants.LpStatusNotSolved,
constants.LpSolutionNoSolutionFound,
),
HighsModelStatus.kModelEmpty: (
constants.LpStatusNotSolved,
constants.LpSolutionNoSolutionFound,
),
HighsModelStatus.kOptimal: (
constants.LpStatusOptimal,
constants.LpSolutionOptimal,
),
HighsModelStatus.kInfeasible: (
constants.LpStatusInfeasible,
constants.LpSolutionInfeasible,
),
HighsModelStatus.kUnboundedOrInfeasible: (
constants.LpStatusInfeasible,
constants.LpSolutionInfeasible,
),
HighsModelStatus.kUnbounded: (
constants.LpStatusUnbounded,
constants.LpSolutionUnbounded,
),
HighsModelStatus.kObjectiveBound: (
constants.LpStatusOptimal,
constants.LpSolutionIntegerFeasible,
),
HighsModelStatus.kObjectiveTarget: (
constants.LpStatusOptimal,
constants.LpSolutionIntegerFeasible,
),
HighsModelStatus.kTimeLimit: (
constants.LpStatusOptimal,
constants.LpSolutionIntegerFeasible,
),
HighsModelStatus.kIterationLimit: (
constants.LpStatusOptimal,
constants.LpSolutionIntegerFeasible,
),
HighsModelStatus.kUnknown: (
constants.LpStatusNotSolved,
constants.LpSolutionNoSolutionFound,
),
}
col_values = list(solution.col_value)
# Assign values to the variables as with lp.assignVarsVals()
for var in lp.variables():
var.varValue = col_values[var.index]
if obj_value == float(inf) and status in (
HighsModelStatus.kTimeLimit,
HighsModelStatus.kIterationLimit,
):
return constants.LpStatusNotSolved, constants.LpSolutionNoSolutionFound
else:
return status_dict[status]
def actualSolve(self, lp):
self.createAndConfigureSolver(lp)
self.buildSolverModel(lp)
self.callSolver(lp)
status, sol_status = self.findSolutionValues(lp)
for var in lp.variables():
var.modified = False
for constraint in lp.constraints.values():
constraint.modifier = False
lp.assignStatus(status, sol_status)
return status
def actualResolve(self, lp, **kwargs):
raise PulpSolverError("HiGHS: Resolving is not supported")
| (mip=True, msg=True, options=None, timeLimit=None, *args, **kwargs) |
38,434 | pulp.apis.highs_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp, callback=None):
"""Solve a well formulated lp problem"""
raise PulpSolverError("HiGHS: Not Available")
| (self, lp, callback=None) |
38,443 | pulp.apis.highs_api | HiGHS_CMD | The HiGHS_CMD solver | class HiGHS_CMD(LpSolver_CMD):
"""The HiGHS_CMD solver"""
name: str = "HiGHS_CMD"
SOLUTION_STYLE: int = 0
def __init__(
self,
path=None,
keepFiles=False,
mip=True,
msg=True,
options=None,
timeLimit=None,
gapRel=None,
gapAbs=None,
threads=None,
logPath=None,
warmStart=False,
):
"""
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param float timeLimit: maximum time for solver (in seconds)
:param float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param float gapAbs: absolute gap tolerance for the solver to stop
:param list[str] options: list of additional options to pass to solver
:param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
:param str path: path to the solver binary (you can get binaries for your platform from https://github.com/JuliaBinaryWrappers/HiGHS_jll.jl/releases, or else compile from source - https://highs.dev)
:param int threads: sets the maximum number of threads
:param str logPath: path to the log file
:param bool warmStart: if True, the solver will use the current value of variables as a start
"""
LpSolver_CMD.__init__(
self,
mip=mip,
msg=msg,
timeLimit=timeLimit,
gapRel=gapRel,
gapAbs=gapAbs,
options=options,
path=path,
keepFiles=keepFiles,
threads=threads,
logPath=logPath,
warmStart=warmStart,
)
def defaultPath(self):
return self.executableExtension("highs")
def available(self):
"""True if the solver is available"""
return self.executable(self.path)
def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
if not self.executable(self.path):
raise PulpSolverError("PuLP: cannot execute " + self.path)
lp.checkDuplicateVars()
tmpMps, tmpSol, tmpOptions, tmpLog, tmpMst = self.create_tmp_files(
lp.name, "mps", "sol", "HiGHS", "HiGHS_log", "mst"
)
lp.writeMPS(tmpMps, with_objsense=True)
file_options: List[str] = []
file_options.append(f"solution_file={tmpSol}")
file_options.append("write_solution_to_file=true")
file_options.append(f"write_solution_style={HiGHS_CMD.SOLUTION_STYLE}")
if not self.msg:
file_options.append("log_to_console=false")
if "threads" in self.optionsDict:
file_options.append(f"threads={self.optionsDict['threads']}")
if "gapRel" in self.optionsDict:
file_options.append(f"mip_rel_gap={self.optionsDict['gapRel']}")
if "gapAbs" in self.optionsDict:
file_options.append(f"mip_abs_gap={self.optionsDict['gapAbs']}")
if "logPath" in self.optionsDict:
highs_log_file = self.optionsDict["logPath"]
else:
highs_log_file = tmpLog
file_options.append(f"log_file={highs_log_file}")
command: List[str] = []
command.append(self.path)
command.append(tmpMps)
command.append(f"--options_file={tmpOptions}")
if self.timeLimit is not None:
command.append(f"--time_limit={self.timeLimit}")
if not self.mip:
command.append("--solver=simplex")
if "threads" in self.optionsDict:
command.append("--parallel=on")
if self.optionsDict.get("warmStart", False):
self.writesol(tmpMst, lp)
command.append(f"--read_solution_file={tmpMst}")
options = iter(self.options)
for option in options:
# assumption: all cli and file options require an argument which is provided after the equal sign (=)
if "=" not in option:
option += f"={next(options)}"
# identify cli options by a leading dash (-) and treat other options as file options
if option.startswith("-"):
command.append(option)
else:
file_options.append(option)
with open(tmpOptions, "w") as options_file:
options_file.write("\n".join(file_options))
process = subprocess.run(command, stdout=sys.stdout, stderr=sys.stderr)
# HiGHS return code semantics (see: https://github.com/ERGO-Code/HiGHS/issues/527#issuecomment-946575028)
# - -1: error
# - 0: success
# - 1: warning
if process.returncode == -1:
raise PulpSolverError("Error while executing HiGHS")
with open(highs_log_file, "r") as log_file:
lines = log_file.readlines()
lines = [line.strip().split() for line in lines]
# LP
model_line = [line for line in lines if line[:2] == ["Model", "status"]]
if len(model_line) > 0:
model_status = " ".join(model_line[0][3:]) # Model status: ...
else:
# ILP
model_line = [line for line in lines if "Status" in line][0]
model_status = " ".join(model_line[1:])
sol_line = [line for line in lines if line[:2] == ["Solution", "status"]]
sol_line = sol_line[0] if len(sol_line) > 0 else ["Not solved"]
sol_status = sol_line[-1]
if model_status.lower() == "optimal": # optimal
status, status_sol = (
constants.LpStatusOptimal,
constants.LpSolutionOptimal,
)
elif sol_status.lower() == "feasible": # feasible
# Following the PuLP convention
status, status_sol = (
constants.LpStatusOptimal,
constants.LpSolutionIntegerFeasible,
)
elif model_status.lower() == "infeasible": # infeasible
status, status_sol = (
constants.LpStatusInfeasible,
constants.LpSolutionInfeasible,
)
elif model_status.lower() == "unbounded": # unbounded
status, status_sol = (
constants.LpStatusUnbounded,
constants.LpSolutionUnbounded,
)
else: # no solution
status, status_sol = (
constants.LpStatusNotSolved,
constants.LpSolutionNoSolutionFound,
)
if not os.path.exists(tmpSol) or os.stat(tmpSol).st_size == 0:
status_sol = constants.LpSolutionNoSolutionFound
values = None
elif status_sol == constants.LpSolutionNoSolutionFound:
values = None
else:
values = self.readsol(tmpSol)
self.delete_tmp_files(tmpMps, tmpSol, tmpOptions, tmpLog, tmpMst)
lp.assignStatus(status, status_sol)
if status == constants.LpStatusOptimal:
lp.assignVarsVals(values)
return status
def writesol(self, filename, lp):
"""Writes a HiGHS solution file"""
variable_rows = []
for var in lp.variables(): # zero variables must be included
variable_rows.append(f"{var.name} {var.varValue or 0}")
# Required preamble for HiGHS to accept a solution
all_rows = [
"Model status",
"None",
"",
"# Primal solution values",
"Feasible",
"",
f"# Columns {len(variable_rows)}",
]
all_rows.extend(variable_rows)
with open(filename, "w") as file:
file.write("\n".join(all_rows))
def readsol(self, filename):
"""Read a HiGHS solution file"""
with open(filename) as file:
lines = file.readlines()
begin, end = None, None
for index, line in enumerate(lines):
if begin is None and line.startswith("# Columns"):
begin = index + 1
if end is None and line.startswith("# Rows"):
end = index
if begin is None or end is None:
raise PulpSolverError("Cannot read HiGHS solver output")
values = {}
for line in lines[begin:end]:
name, value = line.split()
values[name] = float(value)
return values
| (path=None, keepFiles=False, mip=True, msg=True, options=None, timeLimit=None, gapRel=None, gapAbs=None, threads=None, logPath=None, warmStart=False) |
38,444 | pulp.apis.highs_api | __init__ |
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param float timeLimit: maximum time for solver (in seconds)
:param float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param float gapAbs: absolute gap tolerance for the solver to stop
:param list[str] options: list of additional options to pass to solver
:param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
:param str path: path to the solver binary (you can get binaries for your platform from https://github.com/JuliaBinaryWrappers/HiGHS_jll.jl/releases, or else compile from source - https://highs.dev)
:param int threads: sets the maximum number of threads
:param str logPath: path to the log file
:param bool warmStart: if True, the solver will use the current value of variables as a start
| def __init__(
self,
path=None,
keepFiles=False,
mip=True,
msg=True,
options=None,
timeLimit=None,
gapRel=None,
gapAbs=None,
threads=None,
logPath=None,
warmStart=False,
):
"""
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param float timeLimit: maximum time for solver (in seconds)
:param float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param float gapAbs: absolute gap tolerance for the solver to stop
:param list[str] options: list of additional options to pass to solver
:param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
:param str path: path to the solver binary (you can get binaries for your platform from https://github.com/JuliaBinaryWrappers/HiGHS_jll.jl/releases, or else compile from source - https://highs.dev)
:param int threads: sets the maximum number of threads
:param str logPath: path to the log file
:param bool warmStart: if True, the solver will use the current value of variables as a start
"""
LpSolver_CMD.__init__(
self,
mip=mip,
msg=msg,
timeLimit=timeLimit,
gapRel=gapRel,
gapAbs=gapAbs,
options=options,
path=path,
keepFiles=keepFiles,
threads=threads,
logPath=logPath,
warmStart=warmStart,
)
| (self, path=None, keepFiles=False, mip=True, msg=True, options=None, timeLimit=None, gapRel=None, gapAbs=None, threads=None, logPath=None, warmStart=False) |
38,446 | pulp.apis.highs_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
if not self.executable(self.path):
raise PulpSolverError("PuLP: cannot execute " + self.path)
lp.checkDuplicateVars()
tmpMps, tmpSol, tmpOptions, tmpLog, tmpMst = self.create_tmp_files(
lp.name, "mps", "sol", "HiGHS", "HiGHS_log", "mst"
)
lp.writeMPS(tmpMps, with_objsense=True)
file_options: List[str] = []
file_options.append(f"solution_file={tmpSol}")
file_options.append("write_solution_to_file=true")
file_options.append(f"write_solution_style={HiGHS_CMD.SOLUTION_STYLE}")
if not self.msg:
file_options.append("log_to_console=false")
if "threads" in self.optionsDict:
file_options.append(f"threads={self.optionsDict['threads']}")
if "gapRel" in self.optionsDict:
file_options.append(f"mip_rel_gap={self.optionsDict['gapRel']}")
if "gapAbs" in self.optionsDict:
file_options.append(f"mip_abs_gap={self.optionsDict['gapAbs']}")
if "logPath" in self.optionsDict:
highs_log_file = self.optionsDict["logPath"]
else:
highs_log_file = tmpLog
file_options.append(f"log_file={highs_log_file}")
command: List[str] = []
command.append(self.path)
command.append(tmpMps)
command.append(f"--options_file={tmpOptions}")
if self.timeLimit is not None:
command.append(f"--time_limit={self.timeLimit}")
if not self.mip:
command.append("--solver=simplex")
if "threads" in self.optionsDict:
command.append("--parallel=on")
if self.optionsDict.get("warmStart", False):
self.writesol(tmpMst, lp)
command.append(f"--read_solution_file={tmpMst}")
options = iter(self.options)
for option in options:
# assumption: all cli and file options require an argument which is provided after the equal sign (=)
if "=" not in option:
option += f"={next(options)}"
# identify cli options by a leading dash (-) and treat other options as file options
if option.startswith("-"):
command.append(option)
else:
file_options.append(option)
with open(tmpOptions, "w") as options_file:
options_file.write("\n".join(file_options))
process = subprocess.run(command, stdout=sys.stdout, stderr=sys.stderr)
# HiGHS return code semantics (see: https://github.com/ERGO-Code/HiGHS/issues/527#issuecomment-946575028)
# - -1: error
# - 0: success
# - 1: warning
if process.returncode == -1:
raise PulpSolverError("Error while executing HiGHS")
with open(highs_log_file, "r") as log_file:
lines = log_file.readlines()
lines = [line.strip().split() for line in lines]
# LP
model_line = [line for line in lines if line[:2] == ["Model", "status"]]
if len(model_line) > 0:
model_status = " ".join(model_line[0][3:]) # Model status: ...
else:
# ILP
model_line = [line for line in lines if "Status" in line][0]
model_status = " ".join(model_line[1:])
sol_line = [line for line in lines if line[:2] == ["Solution", "status"]]
sol_line = sol_line[0] if len(sol_line) > 0 else ["Not solved"]
sol_status = sol_line[-1]
if model_status.lower() == "optimal": # optimal
status, status_sol = (
constants.LpStatusOptimal,
constants.LpSolutionOptimal,
)
elif sol_status.lower() == "feasible": # feasible
# Following the PuLP convention
status, status_sol = (
constants.LpStatusOptimal,
constants.LpSolutionIntegerFeasible,
)
elif model_status.lower() == "infeasible": # infeasible
status, status_sol = (
constants.LpStatusInfeasible,
constants.LpSolutionInfeasible,
)
elif model_status.lower() == "unbounded": # unbounded
status, status_sol = (
constants.LpStatusUnbounded,
constants.LpSolutionUnbounded,
)
else: # no solution
status, status_sol = (
constants.LpStatusNotSolved,
constants.LpSolutionNoSolutionFound,
)
if not os.path.exists(tmpSol) or os.stat(tmpSol).st_size == 0:
status_sol = constants.LpSolutionNoSolutionFound
values = None
elif status_sol == constants.LpSolutionNoSolutionFound:
values = None
else:
values = self.readsol(tmpSol)
self.delete_tmp_files(tmpMps, tmpSol, tmpOptions, tmpLog, tmpMst)
lp.assignStatus(status, status_sol)
if status == constants.LpStatusOptimal:
lp.assignVarsVals(values)
return status
| (self, lp) |
38,450 | pulp.apis.highs_api | defaultPath | null | def defaultPath(self):
return self.executableExtension("highs")
| (self) |
38,455 | pulp.apis.highs_api | readsol | Read a HiGHS solution file | def readsol(self, filename):
"""Read a HiGHS solution file"""
with open(filename) as file:
lines = file.readlines()
begin, end = None, None
for index, line in enumerate(lines):
if begin is None and line.startswith("# Columns"):
begin = index + 1
if end is None and line.startswith("# Rows"):
end = index
if begin is None or end is None:
raise PulpSolverError("Cannot read HiGHS solver output")
values = {}
for line in lines[begin:end]:
name, value = line.split()
values[name] = float(value)
return values
| (self, filename) |
38,463 | pulp.apis.highs_api | writesol | Writes a HiGHS solution file | def writesol(self, filename, lp):
"""Writes a HiGHS solution file"""
variable_rows = []
for var in lp.variables(): # zero variables must be included
variable_rows.append(f"{var.name} {var.varValue or 0}")
# Required preamble for HiGHS to accept a solution
all_rows = [
"Model status",
"None",
"",
"# Primal solution values",
"Feasible",
"",
f"# Columns {len(variable_rows)}",
]
all_rows.extend(variable_rows)
with open(filename, "w") as file:
file.write("\n".join(all_rows))
| (self, filename, lp) |
38,466 | pulp.pulp | LpAffineExpression |
A linear combination of :class:`LpVariables<LpVariable>`.
Can be initialised with the following:
#. e = None: an empty Expression
#. e = dict: gives an expression with the values being the coefficients of the keys (order of terms is undetermined)
#. e = list or generator of 2-tuples: equivalent to dict.items()
#. e = LpElement: an expression of length 1 with the coefficient 1
#. e = other: the constant is initialised as e
Examples:
>>> f=LpAffineExpression(LpElement('x'))
>>> f
1*x + 0
>>> x_name = ['x_0', 'x_1', 'x_2']
>>> x = [LpVariable(x_name[i], lowBound = 0, upBound = 10) for i in range(3) ]
>>> c = LpAffineExpression([ (x[0],1), (x[1],-3), (x[2],4)])
>>> c
1*x_0 + -3*x_1 + 4*x_2 + 0
| class LpAffineExpression(_DICT_TYPE):
"""
A linear combination of :class:`LpVariables<LpVariable>`.
Can be initialised with the following:
#. e = None: an empty Expression
#. e = dict: gives an expression with the values being the coefficients of the keys (order of terms is undetermined)
#. e = list or generator of 2-tuples: equivalent to dict.items()
#. e = LpElement: an expression of length 1 with the coefficient 1
#. e = other: the constant is initialised as e
Examples:
>>> f=LpAffineExpression(LpElement('x'))
>>> f
1*x + 0
>>> x_name = ['x_0', 'x_1', 'x_2']
>>> x = [LpVariable(x_name[i], lowBound = 0, upBound = 10) for i in range(3) ]
>>> c = LpAffineExpression([ (x[0],1), (x[1],-3), (x[2],4)])
>>> c
1*x_0 + -3*x_1 + 4*x_2 + 0
"""
# to remove illegal characters from the names
trans = maketrans("-+[] ", "_____")
def setName(self, name):
if name:
self.__name = str(name).translate(self.trans)
else:
self.__name = None
def getName(self):
return self.__name
name = property(fget=getName, fset=setName)
def __init__(self, e=None, constant=0, name=None):
self.name = name
# TODO remove isinstance usage
if e is None:
e = {}
if isinstance(e, LpAffineExpression):
# Will not copy the name
self.constant = e.constant
super().__init__(list(e.items()))
elif isinstance(e, dict):
self.constant = constant
super().__init__(list(e.items()))
elif isinstance(e, Iterable):
self.constant = constant
super().__init__(e)
elif isinstance(e, LpElement):
self.constant = 0
super().__init__([(e, 1)])
else:
self.constant = e
super().__init__()
# Proxy functions for variables
def isAtomic(self):
return len(self) == 1 and self.constant == 0 and list(self.values())[0] == 1
def isNumericalConstant(self):
return len(self) == 0
def atom(self):
return list(self.keys())[0]
# Functions on expressions
def __bool__(self):
return (float(self.constant) != 0.0) or (len(self) > 0)
def value(self):
s = self.constant
for v, x in self.items():
if v.varValue is None:
return None
s += v.varValue * x
return s
def valueOrDefault(self):
s = self.constant
for v, x in self.items():
s += v.valueOrDefault() * x
return s
def addterm(self, key, value):
y = self.get(key, 0)
if y:
y += value
self[key] = y
else:
self[key] = value
def emptyCopy(self):
return LpAffineExpression()
def copy(self):
"""Make a copy of self except the name which is reset"""
# Will not copy the name
return LpAffineExpression(self)
def __str__(self, constant=1):
s = ""
for v in self.sorted_keys():
val = self[v]
if val < 0:
if s != "":
s += " - "
else:
s += "-"
val = -val
elif s != "":
s += " + "
if val == 1:
s += str(v)
else:
s += str(val) + "*" + str(v)
if constant:
if s == "":
s = str(self.constant)
else:
if self.constant < 0:
s += " - " + str(-self.constant)
elif self.constant > 0:
s += " + " + str(self.constant)
elif s == "":
s = "0"
return s
def sorted_keys(self):
"""
returns the list of keys sorted by name
"""
result = [(v.name, v) for v in self.keys()]
result.sort()
result = [v for _, v in result]
return result
def __repr__(self):
l = [str(self[v]) + "*" + str(v) for v in self.sorted_keys()]
l.append(str(self.constant))
s = " + ".join(l)
return s
@staticmethod
def _count_characters(line):
# counts the characters in a list of strings
return sum(len(t) for t in line)
def asCplexVariablesOnly(self, name):
"""
helper for asCplexLpAffineExpression
"""
result = []
line = [f"{name}:"]
notFirst = 0
variables = self.sorted_keys()
for v in variables:
val = self[v]
if val < 0:
sign = " -"
val = -val
elif notFirst:
sign = " +"
else:
sign = ""
notFirst = 1
if val == 1:
term = f"{sign} {v.name}"
else:
# adding zero to val to remove instances of negative zero
term = f"{sign} {val + 0:.12g} {v.name}"
if self._count_characters(line) + len(term) > const.LpCplexLPLineSize:
result += ["".join(line)]
line = [term]
else:
line += [term]
return result, line
def asCplexLpAffineExpression(self, name, constant=1):
"""
returns a string that represents the Affine Expression in lp format
"""
# refactored to use a list for speed in iron python
result, line = self.asCplexVariablesOnly(name)
if not self:
term = f" {self.constant}"
else:
term = ""
if constant:
if self.constant < 0:
term = " - %s" % (-self.constant)
elif self.constant > 0:
term = f" + {self.constant}"
if self._count_characters(line) + len(term) > const.LpCplexLPLineSize:
result += ["".join(line)]
line = [term]
else:
line += [term]
result += ["".join(line)]
result = "%s\n" % "\n".join(result)
return result
def addInPlace(self, other):
if isinstance(other, int) and (other == 0):
return self
if other is None:
return self
if isinstance(other, LpElement):
self.addterm(other, 1)
elif isinstance(other, LpAffineExpression):
self.constant += other.constant
for v, x in other.items():
self.addterm(v, x)
elif isinstance(other, dict):
for e in other.values():
self.addInPlace(e)
elif isinstance(other, list) or isinstance(other, Iterable):
for e in other:
self.addInPlace(e)
else:
self.constant += other
return self
def subInPlace(self, other):
if isinstance(other, int) and (other == 0):
return self
if other is None:
return self
if isinstance(other, LpElement):
self.addterm(other, -1)
elif isinstance(other, LpAffineExpression):
self.constant -= other.constant
for v, x in other.items():
self.addterm(v, -x)
elif isinstance(other, dict):
for e in other.values():
self.subInPlace(e)
elif isinstance(other, list) or isinstance(other, Iterable):
for e in other:
self.subInPlace(e)
else:
self.constant -= other
return self
def __neg__(self):
e = self.emptyCopy()
e.constant = -self.constant
for v, x in self.items():
e[v] = -x
return e
def __pos__(self):
return self
def __add__(self, other):
return self.copy().addInPlace(other)
def __radd__(self, other):
return self.copy().addInPlace(other)
def __iadd__(self, other):
return self.addInPlace(other)
def __sub__(self, other):
return self.copy().subInPlace(other)
def __rsub__(self, other):
return (-self).addInPlace(other)
def __isub__(self, other):
return (self).subInPlace(other)
def __mul__(self, other):
e = self.emptyCopy()
if isinstance(other, LpAffineExpression):
e.constant = self.constant * other.constant
if len(other):
if len(self):
raise TypeError("Non-constant expressions cannot be multiplied")
else:
c = self.constant
if c != 0:
for v, x in other.items():
e[v] = c * x
else:
c = other.constant
if c != 0:
for v, x in self.items():
e[v] = c * x
elif isinstance(other, LpVariable):
return self * LpAffineExpression(other)
else:
if other != 0:
e.constant = self.constant * other
for v, x in self.items():
e[v] = other * x
return e
def __rmul__(self, other):
return self * other
def __div__(self, other):
if isinstance(other, LpAffineExpression) or isinstance(other, LpVariable):
if len(other):
raise TypeError(
"Expressions cannot be divided by a non-constant expression"
)
other = other.constant
e = self.emptyCopy()
e.constant = self.constant / other
for v, x in self.items():
e[v] = x / other
return e
def __truediv__(self, other):
if isinstance(other, LpAffineExpression) or isinstance(other, LpVariable):
if len(other):
raise TypeError(
"Expressions cannot be divided by a non-constant expression"
)
other = other.constant
e = self.emptyCopy()
e.constant = self.constant / other
for v, x in self.items():
e[v] = x / other
return e
def __rdiv__(self, other):
e = self.emptyCopy()
if len(self):
raise TypeError(
"Expressions cannot be divided by a non-constant expression"
)
c = self.constant
if isinstance(other, LpAffineExpression):
e.constant = other.constant / c
for v, x in other.items():
e[v] = x / c
else:
e.constant = other / c
return e
def __le__(self, other):
return LpConstraint(self - other, const.LpConstraintLE)
def __ge__(self, other):
return LpConstraint(self - other, const.LpConstraintGE)
def __eq__(self, other):
return LpConstraint(self - other, const.LpConstraintEQ)
def toDict(self):
"""
exports the :py:class:`LpAffineExpression` into a list of dictionaries with the coefficients
it does not export the constant
:return: list of dictionaries with the coefficients
:rtype: list
"""
return [dict(name=k.name, value=v) for k, v in self.items()]
to_dict = toDict
| (e=None, constant=0, name=None) |
38,467 | pulp.pulp | __add__ | null | def __add__(self, other):
return self.copy().addInPlace(other)
| (self, other) |
38,468 | pulp.pulp | __bool__ | null | def __bool__(self):
return (float(self.constant) != 0.0) or (len(self) > 0)
| (self) |
38,469 | pulp.pulp | __div__ | null | def __div__(self, other):
if isinstance(other, LpAffineExpression) or isinstance(other, LpVariable):
if len(other):
raise TypeError(
"Expressions cannot be divided by a non-constant expression"
)
other = other.constant
e = self.emptyCopy()
e.constant = self.constant / other
for v, x in self.items():
e[v] = x / other
return e
| (self, other) |
38,470 | pulp.pulp | __eq__ | null | def __eq__(self, other):
return LpConstraint(self - other, const.LpConstraintEQ)
| (self, other) |
38,471 | pulp.pulp | __ge__ | null | def __ge__(self, other):
return LpConstraint(self - other, const.LpConstraintGE)
| (self, other) |
38,472 | pulp.pulp | __iadd__ | null | def __iadd__(self, other):
return self.addInPlace(other)
| (self, other) |
38,473 | pulp.pulp | __init__ | null | def __init__(self, e=None, constant=0, name=None):
self.name = name
# TODO remove isinstance usage
if e is None:
e = {}
if isinstance(e, LpAffineExpression):
# Will not copy the name
self.constant = e.constant
super().__init__(list(e.items()))
elif isinstance(e, dict):
self.constant = constant
super().__init__(list(e.items()))
elif isinstance(e, Iterable):
self.constant = constant
super().__init__(e)
elif isinstance(e, LpElement):
self.constant = 0
super().__init__([(e, 1)])
else:
self.constant = e
super().__init__()
| (self, e=None, constant=0, name=None) |
38,474 | pulp.pulp | __isub__ | null | def __isub__(self, other):
return (self).subInPlace(other)
| (self, other) |
38,475 | pulp.pulp | __le__ | null | def __le__(self, other):
return LpConstraint(self - other, const.LpConstraintLE)
| (self, other) |
38,476 | pulp.pulp | __mul__ | null | def __mul__(self, other):
e = self.emptyCopy()
if isinstance(other, LpAffineExpression):
e.constant = self.constant * other.constant
if len(other):
if len(self):
raise TypeError("Non-constant expressions cannot be multiplied")
else:
c = self.constant
if c != 0:
for v, x in other.items():
e[v] = c * x
else:
c = other.constant
if c != 0:
for v, x in self.items():
e[v] = c * x
elif isinstance(other, LpVariable):
return self * LpAffineExpression(other)
else:
if other != 0:
e.constant = self.constant * other
for v, x in self.items():
e[v] = other * x
return e
| (self, other) |
38,477 | pulp.pulp | __neg__ | null | def __neg__(self):
e = self.emptyCopy()
e.constant = -self.constant
for v, x in self.items():
e[v] = -x
return e
| (self) |
38,478 | pulp.pulp | __pos__ | null | def __pos__(self):
return self
| (self) |
38,479 | pulp.pulp | __radd__ | null | def __radd__(self, other):
return self.copy().addInPlace(other)
| (self, other) |
38,480 | pulp.pulp | __rdiv__ | null | def __rdiv__(self, other):
e = self.emptyCopy()
if len(self):
raise TypeError(
"Expressions cannot be divided by a non-constant expression"
)
c = self.constant
if isinstance(other, LpAffineExpression):
e.constant = other.constant / c
for v, x in other.items():
e[v] = x / c
else:
e.constant = other / c
return e
| (self, other) |
38,481 | pulp.pulp | __repr__ | null | def __repr__(self):
l = [str(self[v]) + "*" + str(v) for v in self.sorted_keys()]
l.append(str(self.constant))
s = " + ".join(l)
return s
| (self) |
38,482 | pulp.pulp | __rmul__ | null | def __rmul__(self, other):
return self * other
| (self, other) |
38,483 | pulp.pulp | __rsub__ | null | def __rsub__(self, other):
return (-self).addInPlace(other)
| (self, other) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.