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,766 | pulp.pulp | value | null | def value(self):
return self.varValue
| (self) |
38,767 | pulp.pulp | valueOrDefault | null | def valueOrDefault(self):
if self.varValue != None:
return self.varValue
elif self.lowBound != None:
if self.upBound != None:
if 0 >= self.lowBound and 0 <= self.upBound:
return 0
else:
if self.lowBound >= 0:
return self.lowBound
else:
return self.upBound
else:
if 0 >= self.lowBound:
return 0
else:
return self.lowBound
elif self.upBound != None:
if 0 <= self.upBound:
return 0
else:
return self.upBound
else:
return 0
| (self) |
38,768 | pulp.apis.mipcl_api | MIPCL_CMD | The MIPCL_CMD solver | class MIPCL_CMD(LpSolver_CMD):
"""The MIPCL_CMD solver"""
name = "MIPCL_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("mps_mipcl")
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)
tmpMps, tmpSol = self.create_tmp_files(lp.name, "mps", "sol")
if lp.sense == constants.LpMaximize:
# we swap the objectives
# because it does not handle maximization.
warnings.warn(
"MIPCL_CMD does not allow maximization, "
"we will minimize the inverse of the objective function."
)
lp += -lp.objective
lp.checkDuplicateVars()
lp.checkLengthVars(52)
lp.writeMPS(tmpMps, mpsSense=lp.sense)
# just to report duplicated variables:
try:
os.remove(tmpSol)
except:
pass
cmd = self.path
cmd += f" {tmpMps}"
cmd += f" -solfile {tmpSol}"
if self.timeLimit is not None:
cmd += f" -time {self.timeLimit}"
for option in self.options:
cmd += " " + option
if lp.isMIP():
if not self.mip:
warnings.warn("MIPCL_CMD cannot solve the relaxation of a problem")
if self.msg:
pipe = None
else:
pipe = open(os.devnull, "w")
return_code = subprocess.call(cmd.split(), stdout=pipe, stderr=pipe)
# We need to undo the objective swap before finishing
if lp.sense == constants.LpMaximize:
lp += -lp.objective
if return_code != 0:
raise PulpSolverError("PuLP: Error while trying to execute " + self.path)
if not os.path.exists(tmpSol):
status = constants.LpStatusNotSolved
status_sol = constants.LpSolutionNoSolutionFound
values = None
else:
status, values, status_sol = self.readsol(tmpSol)
self.delete_tmp_files(tmpMps, tmpSol)
lp.assignStatus(status, status_sol)
if status not in [constants.LpStatusInfeasible, constants.LpStatusNotSolved]:
lp.assignVarsVals(values)
return status
@staticmethod
def readsol(filename):
"""Read a MIPCL solution file"""
with open(filename) as f:
content = f.readlines()
content = [l.strip() for l in content]
values = {}
if not len(content):
return (
constants.LpStatusNotSolved,
values,
constants.LpSolutionNoSolutionFound,
)
first_line = content[0]
if first_line == "=infeas=":
return constants.LpStatusInfeasible, values, constants.LpSolutionInfeasible
objective, value = first_line.split()
# this is a workaround.
# Not sure if it always returns this limit when unbounded.
if abs(float(value)) >= 9.999999995e10:
return constants.LpStatusUnbounded, values, constants.LpSolutionUnbounded
for line in content[1:]:
name, value = line.split()
values[name] = float(value)
# I'm not sure how this solver announces the optimality
# of a solution so we assume it is integer feasible
return constants.LpStatusOptimal, values, constants.LpSolutionIntegerFeasible
| (path=None, keepFiles=False, mip=True, msg=True, options=None, timeLimit=None) |
38,771 | pulp.apis.mipcl_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)
tmpMps, tmpSol = self.create_tmp_files(lp.name, "mps", "sol")
if lp.sense == constants.LpMaximize:
# we swap the objectives
# because it does not handle maximization.
warnings.warn(
"MIPCL_CMD does not allow maximization, "
"we will minimize the inverse of the objective function."
)
lp += -lp.objective
lp.checkDuplicateVars()
lp.checkLengthVars(52)
lp.writeMPS(tmpMps, mpsSense=lp.sense)
# just to report duplicated variables:
try:
os.remove(tmpSol)
except:
pass
cmd = self.path
cmd += f" {tmpMps}"
cmd += f" -solfile {tmpSol}"
if self.timeLimit is not None:
cmd += f" -time {self.timeLimit}"
for option in self.options:
cmd += " " + option
if lp.isMIP():
if not self.mip:
warnings.warn("MIPCL_CMD cannot solve the relaxation of a problem")
if self.msg:
pipe = None
else:
pipe = open(os.devnull, "w")
return_code = subprocess.call(cmd.split(), stdout=pipe, stderr=pipe)
# We need to undo the objective swap before finishing
if lp.sense == constants.LpMaximize:
lp += -lp.objective
if return_code != 0:
raise PulpSolverError("PuLP: Error while trying to execute " + self.path)
if not os.path.exists(tmpSol):
status = constants.LpStatusNotSolved
status_sol = constants.LpSolutionNoSolutionFound
values = None
else:
status, values, status_sol = self.readsol(tmpSol)
self.delete_tmp_files(tmpMps, tmpSol)
lp.assignStatus(status, status_sol)
if status not in [constants.LpStatusInfeasible, constants.LpStatusNotSolved]:
lp.assignVarsVals(values)
return status
| (self, lp) |
38,775 | pulp.apis.mipcl_api | defaultPath | null | def defaultPath(self):
return self.executableExtension("mps_mipcl")
| (self) |
38,780 | pulp.apis.mipcl_api | readsol | Read a MIPCL solution file | @staticmethod
def readsol(filename):
"""Read a MIPCL solution file"""
with open(filename) as f:
content = f.readlines()
content = [l.strip() for l in content]
values = {}
if not len(content):
return (
constants.LpStatusNotSolved,
values,
constants.LpSolutionNoSolutionFound,
)
first_line = content[0]
if first_line == "=infeas=":
return constants.LpStatusInfeasible, values, constants.LpSolutionInfeasible
objective, value = first_line.split()
# this is a workaround.
# Not sure if it always returns this limit when unbounded.
if abs(float(value)) >= 9.999999995e10:
return constants.LpStatusUnbounded, values, constants.LpSolutionUnbounded
for line in content[1:]:
name, value = line.split()
values[name] = float(value)
# I'm not sure how this solver announces the optimality
# of a solution so we assume it is integer feasible
return constants.LpStatusOptimal, values, constants.LpSolutionIntegerFeasible
| (filename) |
38,788 | pulp.apis.mosek_api | MOSEK | Mosek lp and mip solver (via Mosek Optimizer API). | class MOSEK(LpSolver):
"""Mosek lp and mip solver (via Mosek Optimizer API)."""
name = "MOSEK"
try:
global mosek
import mosek
env = mosek.Env()
except ImportError:
def available(self):
"""True if Mosek is available."""
return False
def actualSolve(self, lp, callback=None):
"""Solves a well-formulated lp problem."""
raise PulpSolverError("MOSEK : Not Available")
else:
def __init__(
self,
mip=True,
msg=True,
timeLimit: Optional[float] = None,
options: Optional[dict] = None,
task_file_name="",
sol_type=mosek.soltype.bas,
):
"""Initializes the Mosek solver.
Keyword arguments:
@param mip: If False, then solve MIP as LP.
@param msg: Enable Mosek log output.
@param float timeLimit: maximum time for solver (in seconds)
@param options: Accepts a dictionary of Mosek solver parameters. Ignore to
use default parameter values. Eg: options = {mosek.dparam.mio_max_time:30}
sets the maximum time spent by the Mixed Integer optimizer to 30 seconds.
Equivalently, one could also write: options = {"MSK_DPAR_MIO_MAX_TIME":30}
which uses the generic parameter name as used within the solver, instead of
using an object from the Mosek Optimizer API (Python), as before.
@param task_file_name: Writes a Mosek task file of the given name. By default,
no task file will be written. Eg: task_file_name = "eg1.opf".
@param sol_type: Mosek supports three types of solutions: mosek.soltype.bas
(Basic solution, default), mosek.soltype.itr (Interior-point
solution) and mosek.soltype.itg (Integer solution).
For a full list of Mosek parameters (for the Mosek Optimizer API) and supported task file
formats, please see https://docs.mosek.com/9.1/pythonapi/parameters.html#doc-all-parameter-list.
"""
self.mip = mip
self.msg = msg
self.timeLimit = timeLimit
self.task_file_name = task_file_name
self.solution_type = sol_type
if options is None:
options = {}
self.options = options
if self.timeLimit is not None:
timeLimit_keys = {"MSK_DPAR_MIO_MAX_TIME", mosek.dparam.mio_max_time}
if not timeLimit_keys.isdisjoint(self.options.keys()):
raise ValueError(
"timeLimit parameter has been provided trough `timeLimit` and `options`."
)
self.options["MSK_DPAR_MIO_MAX_TIME"] = self.timeLimit
def available(self):
"""True if Mosek is available."""
return True
def setOutStream(self, text):
"""Sets the log-output stream."""
sys.stdout.write(text)
sys.stdout.flush()
def buildSolverModel(self, lp, inf=1e20):
"""Translate the problem into a Mosek task object."""
self.cons = lp.constraints
self.numcons = len(self.cons)
self.cons_dict = {}
i = 0
for c in self.cons:
self.cons_dict[c] = i
i = i + 1
self.vars = list(lp.variables())
self.numvars = len(self.vars)
self.var_dict = {}
# Checking for repeated names
lp.checkDuplicateVars()
self.task = MOSEK.env.Task()
self.task.appendcons(self.numcons)
self.task.appendvars(self.numvars)
if self.msg:
self.task.set_Stream(mosek.streamtype.log, self.setOutStream)
# Adding variables
for i in range(self.numvars):
vname = self.vars[i].name
self.var_dict[vname] = i
self.task.putvarname(i, vname)
# Variable type (Default: Continuous)
if self.mip & (self.vars[i].cat == constants.LpInteger):
self.task.putvartype(i, mosek.variabletype.type_int)
self.solution_type = mosek.soltype.itg
# Variable bounds
vbkey = mosek.boundkey.fr
vup = inf
vlow = -inf
if self.vars[i].lowBound != None:
vlow = self.vars[i].lowBound
if self.vars[i].upBound != None:
vup = self.vars[i].upBound
vbkey = mosek.boundkey.ra
else:
vbkey = mosek.boundkey.lo
elif self.vars[i].upBound != None:
vup = self.vars[i].upBound
vbkey = mosek.boundkey.up
self.task.putvarbound(i, vbkey, vlow, vup)
# Objective coefficient for the current variable.
self.task.putcj(i, lp.objective.get(self.vars[i], 0.0))
# Coefficient matrix
self.A_rows, self.A_cols, self.A_vals = zip(
*[
[self.cons_dict[row], self.var_dict[col], coeff]
for col, row, coeff in lp.coefficients()
]
)
self.task.putaijlist(self.A_rows, self.A_cols, self.A_vals)
# Constraints
self.constraint_data_list = []
for c in self.cons:
cname = self.cons[c].name
if cname != None:
self.task.putconname(self.cons_dict[c], cname)
else:
self.task.putconname(self.cons_dict[c], c)
csense = self.cons[c].sense
cconst = -self.cons[c].constant
clow = -inf
cup = inf
# Constraint bounds
if csense == constants.LpConstraintEQ:
cbkey = mosek.boundkey.fx
clow = cconst
cup = cconst
elif csense == constants.LpConstraintGE:
cbkey = mosek.boundkey.lo
clow = cconst
elif csense == constants.LpConstraintLE:
cbkey = mosek.boundkey.up
cup = cconst
else:
raise PulpSolverError("Invalid constraint type.")
self.constraint_data_list.append([self.cons_dict[c], cbkey, clow, cup])
self.cons_id_list, self.cbkey_list, self.clow_list, self.cup_list = zip(
*self.constraint_data_list
)
self.task.putconboundlist(
self.cons_id_list, self.cbkey_list, self.clow_list, self.cup_list
)
# Objective sense
if lp.sense == constants.LpMaximize:
self.task.putobjsense(mosek.objsense.maximize)
else:
self.task.putobjsense(mosek.objsense.minimize)
def findSolutionValues(self, lp):
"""
Read the solution values and status from the Mosek task object. Note: Since the status
map from mosek.solsta to LpStatus is not exact, it is recommended that one enables the
log output and then refer to Mosek documentation for a better understanding of the
solution (especially in the case of mip problems).
"""
self.solsta = self.task.getsolsta(self.solution_type)
self.solution_status_dict = {
mosek.solsta.optimal: constants.LpStatusOptimal,
mosek.solsta.prim_infeas_cer: constants.LpStatusInfeasible,
mosek.solsta.dual_infeas_cer: constants.LpStatusUnbounded,
mosek.solsta.unknown: constants.LpStatusUndefined,
mosek.solsta.integer_optimal: constants.LpStatusOptimal,
mosek.solsta.prim_illposed_cer: constants.LpStatusNotSolved,
mosek.solsta.dual_illposed_cer: constants.LpStatusNotSolved,
mosek.solsta.prim_feas: constants.LpStatusNotSolved,
mosek.solsta.dual_feas: constants.LpStatusNotSolved,
mosek.solsta.prim_and_dual_feas: constants.LpStatusNotSolved,
}
# Variable values.
try:
self.xx = [0.0] * self.numvars
self.task.getxx(self.solution_type, self.xx)
for var in lp.variables():
var.varValue = self.xx[self.var_dict[var.name]]
except mosek.Error:
pass
# Constraint slack variables.
try:
self.xc = [0.0] * self.numcons
self.task.getxc(self.solution_type, self.xc)
for con in lp.constraints:
lp.constraints[con].slack = -(
self.cons[con].constant + self.xc[self.cons_dict[con]]
)
except mosek.Error:
pass
# Reduced costs.
if self.solution_type != mosek.soltype.itg:
try:
self.x_rc = [0.0] * self.numvars
self.task.getreducedcosts(
self.solution_type, 0, self.numvars, self.x_rc
)
for var in lp.variables():
var.dj = self.x_rc[self.var_dict[var.name]]
except mosek.Error:
pass
# Constraint Pi variables.
try:
self.y = [0.0] * self.numcons
self.task.gety(self.solution_type, self.y)
for con in lp.constraints:
lp.constraints[con].pi = self.y[self.cons_dict[con]]
except mosek.Error:
pass
def putparam(self, par, val):
"""
Pass the values of valid parameters to Mosek.
"""
if isinstance(par, mosek.dparam):
self.task.putdouparam(par, val)
elif isinstance(par, mosek.iparam):
self.task.putintparam(par, val)
elif isinstance(par, mosek.sparam):
self.task.putstrparam(par, val)
elif isinstance(par, str):
if par.startswith("MSK_DPAR_"):
self.task.putnadouparam(par, val)
elif par.startswith("MSK_IPAR_"):
self.task.putnaintparam(par, val)
elif par.startswith("MSK_SPAR_"):
self.task.putnastrparam(par, val)
else:
raise PulpSolverError(
"Invalid MOSEK parameter: '{}'. Check MOSEK documentation for a list of valid parameters.".format(
par
)
)
def actualSolve(self, lp):
"""
Solve a well-formulated lp problem.
"""
self.buildSolverModel(lp)
# Set solver parameters
for msk_par in self.options:
self.putparam(msk_par, self.options[msk_par])
# Task file
if self.task_file_name:
self.task.writedata(self.task_file_name)
# Optimize
self.task.optimize()
# Mosek solver log (default: standard output stream)
if self.msg:
self.task.solutionsummary(mosek.streamtype.msg)
self.findSolutionValues(lp)
lp.assignStatus(self.solution_status_dict[self.solsta])
for var in lp.variables():
var.modified = False
for con in lp.constraints.values():
con.modified = False
return lp.status
def actualResolve(self, lp, inf=1e20, **kwargs):
"""
Modify constraints and re-solve an lp. The Mosek task object created in the first solve is used.
"""
for c in self.cons:
if self.cons[c].modified:
csense = self.cons[c].sense
cconst = -self.cons[c].constant
clow = -inf
cup = inf
# Constraint bounds
if csense == constants.LpConstraintEQ:
cbkey = mosek.boundkey.fx
clow = cconst
cup = cconst
elif csense == constants.LpConstraintGE:
cbkey = mosek.boundkey.lo
clow = cconst
elif csense == constants.LpConstraintLE:
cbkey = mosek.boundkey.up
cup = cconst
else:
raise PulpSolverError("Invalid constraint type.")
self.task.putconbound(self.cons_dict[c], cbkey, clow, cup)
# Re-solve
self.task.optimize()
self.findSolutionValues(lp)
lp.assignStatus(self.solution_status_dict[self.solsta])
for var in lp.variables():
var.modified = False
for con in lp.constraints.values():
con.modified = False
return lp.status
| (mip=True, msg=True, options=None, timeLimit=None, *args, **kwargs) |
38,791 | pulp.apis.mosek_api | actualSolve | Solves a well-formulated lp problem. | def actualSolve(self, lp, callback=None):
"""Solves a well-formulated lp problem."""
raise PulpSolverError("MOSEK : Not Available")
| (self, lp, callback=None) |
38,792 | pulp.apis.mosek_api | available | True if Mosek is available. | def available(self):
"""True if Mosek is available."""
return False
| (self) |
38,801 | pulp.apis.coin_api | PULP_CBC_CMD |
This solver uses a precompiled version of cbc provided with the package
| class PULP_CBC_CMD(COIN_CMD):
"""
This solver uses a precompiled version of cbc provided with the package
"""
name = "PULP_CBC_CMD"
pulp_cbc_path = pulp_cbc_path
try:
if os.name != "nt":
if not os.access(pulp_cbc_path, os.X_OK):
import stat
os.chmod(pulp_cbc_path, stat.S_IXUSR + stat.S_IXOTH)
except: # probably due to incorrect permissions
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(
"PULP_CBC_CMD: Not Available (check permissions on %s)"
% self.pulp_cbc_path
)
else:
def __init__(
self,
mip=True,
msg=True,
timeLimit=None,
gapRel=None,
gapAbs=None,
presolve=None,
cuts=None,
strong=None,
options=None,
warmStart=False,
keepFiles=False,
path=None,
threads=None,
logPath=None,
timeMode="elapsed",
):
if path is not None:
raise PulpSolverError("Use COIN_CMD if you want to set a path")
# check that the file is executable
COIN_CMD.__init__(
self,
path=self.pulp_cbc_path,
mip=mip,
msg=msg,
timeLimit=timeLimit,
gapRel=gapRel,
gapAbs=gapAbs,
presolve=presolve,
cuts=cuts,
strong=strong,
options=options,
warmStart=warmStart,
keepFiles=keepFiles,
threads=threads,
logPath=logPath,
timeMode=timeMode,
)
| (mip=True, msg=True, timeLimit=None, gapRel=None, gapAbs=None, presolve=None, cuts=None, strong=None, options=None, warmStart=False, keepFiles=False, path=None, threads=None, logPath=None, timeMode='elapsed') |
38,802 | pulp.apis.coin_api | __init__ | null | def __init__(
self,
mip=True,
msg=True,
timeLimit=None,
gapRel=None,
gapAbs=None,
presolve=None,
cuts=None,
strong=None,
options=None,
warmStart=False,
keepFiles=False,
path=None,
threads=None,
logPath=None,
timeMode="elapsed",
):
if path is not None:
raise PulpSolverError("Use COIN_CMD if you want to set a path")
# check that the file is executable
COIN_CMD.__init__(
self,
path=self.pulp_cbc_path,
mip=mip,
msg=msg,
timeLimit=timeLimit,
gapRel=gapRel,
gapAbs=gapAbs,
presolve=presolve,
cuts=cuts,
strong=strong,
options=options,
warmStart=warmStart,
keepFiles=keepFiles,
threads=threads,
logPath=logPath,
timeMode=timeMode,
)
| (self, mip=True, msg=True, timeLimit=None, gapRel=None, gapAbs=None, presolve=None, cuts=None, strong=None, options=None, warmStart=False, keepFiles=False, path=None, threads=None, logPath=None, timeMode='elapsed') |
38,826 | pulp.apis.glpk_api | PYGLPK |
The glpk LP/MIP solver (via its python interface)
Copyright Christophe-Marie Duquesne 2012
The glpk variables are available (after a solve) in var.solverVar
The glpk constraints are available in constraint.solverConstraint
The Model is in prob.solverModel
| class PYGLPK(LpSolver):
"""
The glpk LP/MIP solver (via its python interface)
Copyright Christophe-Marie Duquesne 2012
The glpk variables are available (after a solve) in var.solverVar
The glpk constraints are available in constraint.solverConstraint
The Model is in prob.solverModel
"""
name = "PYGLPK"
try:
# import the model into the global scope
global glpk
import glpk.glpkpi as glpk
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("GLPK: Not Available")
else:
def __init__(
self, mip=True, msg=True, timeLimit=None, gapRel=None, **solverParams
):
"""
Initializes the glpk solver.
@param mip: if False the solver will solve a MIP as an LP
@param msg: displays information from the solver to stdout
@param timeLimit: not handled
@param gapRel: not handled
@param solverParams: not handled
"""
LpSolver.__init__(self, mip, msg)
if not self.msg:
glpk.glp_term_out(glpk.GLP_OFF)
def findSolutionValues(self, lp):
prob = lp.solverModel
if self.mip and self.hasMIPConstraints(lp.solverModel):
solutionStatus = glpk.glp_mip_status(prob)
else:
solutionStatus = glpk.glp_get_status(prob)
glpkLpStatus = {
glpk.GLP_OPT: constants.LpStatusOptimal,
glpk.GLP_UNDEF: constants.LpStatusUndefined,
glpk.GLP_FEAS: constants.LpStatusOptimal,
glpk.GLP_INFEAS: constants.LpStatusInfeasible,
glpk.GLP_NOFEAS: constants.LpStatusInfeasible,
glpk.GLP_UNBND: constants.LpStatusUnbounded,
}
# populate pulp solution values
for var in lp.variables():
if self.mip and self.hasMIPConstraints(lp.solverModel):
var.varValue = glpk.glp_mip_col_val(prob, var.glpk_index)
else:
var.varValue = glpk.glp_get_col_prim(prob, var.glpk_index)
var.dj = glpk.glp_get_col_dual(prob, var.glpk_index)
# put pi and slack variables against the constraints
for constr in lp.constraints.values():
if self.mip and self.hasMIPConstraints(lp.solverModel):
row_val = glpk.glp_mip_row_val(prob, constr.glpk_index)
else:
row_val = glpk.glp_get_row_prim(prob, constr.glpk_index)
constr.slack = -constr.constant - row_val
constr.pi = glpk.glp_get_row_dual(prob, constr.glpk_index)
lp.resolveOK = True
for var in lp.variables():
var.isModified = False
status = glpkLpStatus.get(solutionStatus, constants.LpStatusUndefined)
lp.assignStatus(status)
return status
def available(self):
"""True if the solver is available"""
return True
def hasMIPConstraints(self, solverModel):
return (
glpk.glp_get_num_int(solverModel) > 0
or glpk.glp_get_num_bin(solverModel) > 0
)
def callSolver(self, lp, callback=None):
"""Solves the problem with glpk"""
self.solveTime = -clock()
glpk.glp_adv_basis(lp.solverModel, 0)
glpk.glp_simplex(lp.solverModel, None)
if self.mip and self.hasMIPConstraints(lp.solverModel):
status = glpk.glp_get_status(lp.solverModel)
if status in (glpk.GLP_OPT, glpk.GLP_UNDEF, glpk.GLP_FEAS):
glpk.glp_intopt(lp.solverModel, None)
self.solveTime += clock()
def buildSolverModel(self, lp):
"""
Takes the pulp lp model and translates it into a glpk model
"""
log.debug("create the glpk model")
prob = glpk.glp_create_prob()
glpk.glp_set_prob_name(prob, lp.name)
log.debug("set the sense of the problem")
if lp.sense == constants.LpMaximize:
glpk.glp_set_obj_dir(prob, glpk.GLP_MAX)
log.debug("add the constraints to the problem")
glpk.glp_add_rows(prob, len(list(lp.constraints.keys())))
for i, v in enumerate(lp.constraints.items(), start=1):
name, constraint = v
glpk.glp_set_row_name(prob, i, name)
if constraint.sense == constants.LpConstraintLE:
glpk.glp_set_row_bnds(
prob, i, glpk.GLP_UP, 0.0, -constraint.constant
)
elif constraint.sense == constants.LpConstraintGE:
glpk.glp_set_row_bnds(
prob, i, glpk.GLP_LO, -constraint.constant, 0.0
)
elif constraint.sense == constants.LpConstraintEQ:
glpk.glp_set_row_bnds(
prob, i, glpk.GLP_FX, -constraint.constant, -constraint.constant
)
else:
raise PulpSolverError("Detected an invalid constraint type")
constraint.glpk_index = i
log.debug("add the variables to the problem")
glpk.glp_add_cols(prob, len(lp.variables()))
for j, var in enumerate(lp.variables(), start=1):
glpk.glp_set_col_name(prob, j, var.name)
lb = 0.0
ub = 0.0
t = glpk.GLP_FR
if not var.lowBound is None:
lb = var.lowBound
t = glpk.GLP_LO
if not var.upBound is None:
ub = var.upBound
t = glpk.GLP_UP
if not var.upBound is None and not var.lowBound is None:
if ub == lb:
t = glpk.GLP_FX
else:
t = glpk.GLP_DB
glpk.glp_set_col_bnds(prob, j, t, lb, ub)
if var.cat == constants.LpInteger:
glpk.glp_set_col_kind(prob, j, glpk.GLP_IV)
assert glpk.glp_get_col_kind(prob, j) == glpk.GLP_IV
var.glpk_index = j
log.debug("set the objective function")
for var in lp.variables():
value = lp.objective.get(var)
if value:
glpk.glp_set_obj_coef(prob, var.glpk_index, value)
log.debug("set the problem matrix")
for constraint in lp.constraints.values():
l = len(list(constraint.items()))
ind = glpk.intArray(l + 1)
val = glpk.doubleArray(l + 1)
for j, v in enumerate(constraint.items(), start=1):
var, value = v
ind[j] = var.glpk_index
val[j] = value
glpk.glp_set_mat_row(prob, constraint.glpk_index, l, ind, val)
lp.solverModel = prob
# glpk.glp_write_lp(prob, None, "glpk.lp")
def actualSolve(self, lp, callback=None):
"""
Solve a well formulated lp problem
creates a glpk 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 glpk")
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
"""
prob = lp.solverModel
log.debug("Resolve the Model using glpk")
for constraint in lp.constraints.values():
i = constraint.glpk_index
if constraint.modified:
if constraint.sense == constants.LpConstraintLE:
glpk.glp_set_row_bnds(
prob, i, glpk.GLP_UP, 0.0, -constraint.constant
)
elif constraint.sense == constants.LpConstraintGE:
glpk.glp_set_row_bnds(
prob, i, glpk.GLP_LO, -constraint.constant, 0.0
)
elif constraint.sense == constants.LpConstraintEQ:
glpk.glp_set_row_bnds(
prob,
i,
glpk.GLP_FX,
-constraint.constant,
-constraint.constant,
)
else:
raise PulpSolverError("Detected an invalid constraint type")
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,829 | pulp.apis.glpk_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp, callback=None):
"""Solve a well formulated lp problem"""
raise PulpSolverError("GLPK: Not Available")
| (self, lp, callback=None) |
38,885 | pulp.constants | PulpError |
Pulp Exception Class
| class PulpError(Exception):
"""
Pulp Exception Class
"""
pass
| null |
38,886 | pulp.apis.core | PulpSolverError |
Pulp Solver-related exceptions
| class PulpSolverError(const.PulpError):
"""
Pulp Solver-related exceptions
"""
pass
| null |
38,887 | pulp.apis.scip_api | SCIP_CMD | The SCIP optimization solver | class SCIP_CMD(LpSolver_CMD):
"""The SCIP optimization solver"""
name = "SCIP_CMD"
def __init__(
self,
path=None,
mip=True,
keepFiles=False,
msg=True,
options=None,
timeLimit=None,
gapRel=None,
gapAbs=None,
maxNodes=None,
logPath=None,
threads=None,
):
"""
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
: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
: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 maxNodes: max number of nodes during branching. Stops the solving when reached.
:param int threads: sets the maximum number of threads
:param str logPath: path to the log file
"""
LpSolver_CMD.__init__(
self,
mip=mip,
msg=msg,
options=options,
path=path,
keepFiles=keepFiles,
timeLimit=timeLimit,
gapRel=gapRel,
gapAbs=gapAbs,
maxNodes=maxNodes,
threads=threads,
logPath=logPath,
)
SCIP_STATUSES = {
"unknown": constants.LpStatusUndefined,
"user interrupt": constants.LpStatusNotSolved,
"node limit reached": constants.LpStatusNotSolved,
"total node limit reached": constants.LpStatusNotSolved,
"stall node limit reached": constants.LpStatusNotSolved,
"time limit reached": constants.LpStatusNotSolved,
"memory limit reached": constants.LpStatusNotSolved,
"gap limit reached": constants.LpStatusOptimal,
"solution limit reached": constants.LpStatusNotSolved,
"solution improvement limit reached": constants.LpStatusNotSolved,
"restart limit reached": constants.LpStatusNotSolved,
"optimal solution found": constants.LpStatusOptimal,
"infeasible": constants.LpStatusInfeasible,
"unbounded": constants.LpStatusUnbounded,
"infeasible or unbounded": constants.LpStatusNotSolved,
}
NO_SOLUTION_STATUSES = {
constants.LpStatusInfeasible,
constants.LpStatusUnbounded,
constants.LpStatusNotSolved,
}
def defaultPath(self):
return self.executableExtension(scip_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, tmpOptions = self.create_tmp_files(lp.name, "lp", "sol", "set")
lp.writeLP(tmpLp)
file_options: List[str] = []
if self.timeLimit is not None:
file_options.append(f"limits/time={self.timeLimit}")
if "gapRel" in self.optionsDict:
file_options.append(f"limits/gap={self.optionsDict['gapRel']}")
if "gapAbs" in self.optionsDict:
file_options.append(f"limits/absgap={self.optionsDict['gapAbs']}")
if "maxNodes" in self.optionsDict:
file_options.append(f"limits/nodes={self.optionsDict['maxNodes']}")
if "threads" in self.optionsDict and int(self.optionsDict["threads"]) > 1:
warnings.warn(
"SCIP can only run with a single thread - use FSCIP_CMD for a parallel version of SCIP"
)
if not self.mip:
warnings.warn(f"{self.name} does not allow a problem to be relaxed")
command: List[str] = []
command.append(self.path)
command.extend(["-s", tmpOptions])
if not self.msg:
command.append("-q")
if "logPath" in self.optionsDict:
command.extend(["-l", self.optionsDict["logPath"]])
options = iter(self.options)
for option in options:
# identify cli options by a leading dash (-) and treat other options as file options
if option.startswith("-"):
# assumption: all cli options require an argument which is provided as a separate parameter
argument = next(options)
command.extend([option, argument])
else:
# assumption: all file options require an argument which is provided after the equal sign (=)
if "=" not in option:
argument = next(options)
option += f"={argument}"
file_options.append(option)
# append scip commands after parsing self.options to allow the user to specify additional -c arguments
command.extend(["-c", f'read "{tmpLp}"'])
command.extend(["-c", "optimize"])
command.extend(["-c", f'write solution "{tmpSol}"'])
command.extend(["-c", "quit"])
with open(tmpOptions, "w") as options_file:
options_file.write("\n".join(file_options))
subprocess.check_call(command, stdout=sys.stdout, stderr=sys.stderr)
if not os.path.exists(tmpSol):
raise PulpSolverError("PuLP: Error while executing " + self.path)
status, values = self.readsol(tmpSol)
# Make sure to add back in any 0-valued variables SCIP leaves out.
finalVals = {}
for v in lp.variables():
finalVals[v.name] = values.get(v.name, 0.0)
lp.assignVarsVals(finalVals)
lp.assignStatus(status)
self.delete_tmp_files(tmpLp, tmpSol, tmpOptions)
return status
@staticmethod
def readsol(filename):
"""Read a SCIP solution file"""
with open(filename) as f:
# First line must contain 'solution status: <something>'
try:
line = f.readline()
comps = line.split(": ")
assert comps[0] == "solution status"
assert len(comps) == 2
except Exception:
raise PulpSolverError(f"Can't get SCIP solver status: {line!r}")
status = SCIP_CMD.SCIP_STATUSES.get(
comps[1].strip(), constants.LpStatusUndefined
)
values = {}
if status in SCIP_CMD.NO_SOLUTION_STATUSES:
return status, values
# Look for an objective value. If we can't find one, stop.
try:
line = f.readline()
comps = line.split(": ")
assert comps[0] == "objective value"
assert len(comps) == 2
float(comps[1].strip())
except Exception:
raise PulpSolverError(f"Can't get SCIP solver objective: {line!r}")
# Parse the variable values.
for line in f:
try:
comps = line.split()
values[comps[0]] = float(comps[1])
except:
raise PulpSolverError(f"Can't read SCIP solver output: {line!r}")
return status, values
| (path=None, mip=True, keepFiles=False, msg=True, options=None, timeLimit=None, gapRel=None, gapAbs=None, maxNodes=None, logPath=None, threads=None) |
38,888 | pulp.apis.scip_api | __init__ |
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
: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
: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 maxNodes: max number of nodes during branching. Stops the solving when reached.
:param int threads: sets the maximum number of threads
:param str logPath: path to the log file
| def __init__(
self,
path=None,
mip=True,
keepFiles=False,
msg=True,
options=None,
timeLimit=None,
gapRel=None,
gapAbs=None,
maxNodes=None,
logPath=None,
threads=None,
):
"""
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
: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
: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 maxNodes: max number of nodes during branching. Stops the solving when reached.
:param int threads: sets the maximum number of threads
:param str logPath: path to the log file
"""
LpSolver_CMD.__init__(
self,
mip=mip,
msg=msg,
options=options,
path=path,
keepFiles=keepFiles,
timeLimit=timeLimit,
gapRel=gapRel,
gapAbs=gapAbs,
maxNodes=maxNodes,
threads=threads,
logPath=logPath,
)
| (self, path=None, mip=True, keepFiles=False, msg=True, options=None, timeLimit=None, gapRel=None, gapAbs=None, maxNodes=None, logPath=None, threads=None) |
38,890 | pulp.apis.scip_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, tmpOptions = self.create_tmp_files(lp.name, "lp", "sol", "set")
lp.writeLP(tmpLp)
file_options: List[str] = []
if self.timeLimit is not None:
file_options.append(f"limits/time={self.timeLimit}")
if "gapRel" in self.optionsDict:
file_options.append(f"limits/gap={self.optionsDict['gapRel']}")
if "gapAbs" in self.optionsDict:
file_options.append(f"limits/absgap={self.optionsDict['gapAbs']}")
if "maxNodes" in self.optionsDict:
file_options.append(f"limits/nodes={self.optionsDict['maxNodes']}")
if "threads" in self.optionsDict and int(self.optionsDict["threads"]) > 1:
warnings.warn(
"SCIP can only run with a single thread - use FSCIP_CMD for a parallel version of SCIP"
)
if not self.mip:
warnings.warn(f"{self.name} does not allow a problem to be relaxed")
command: List[str] = []
command.append(self.path)
command.extend(["-s", tmpOptions])
if not self.msg:
command.append("-q")
if "logPath" in self.optionsDict:
command.extend(["-l", self.optionsDict["logPath"]])
options = iter(self.options)
for option in options:
# identify cli options by a leading dash (-) and treat other options as file options
if option.startswith("-"):
# assumption: all cli options require an argument which is provided as a separate parameter
argument = next(options)
command.extend([option, argument])
else:
# assumption: all file options require an argument which is provided after the equal sign (=)
if "=" not in option:
argument = next(options)
option += f"={argument}"
file_options.append(option)
# append scip commands after parsing self.options to allow the user to specify additional -c arguments
command.extend(["-c", f'read "{tmpLp}"'])
command.extend(["-c", "optimize"])
command.extend(["-c", f'write solution "{tmpSol}"'])
command.extend(["-c", "quit"])
with open(tmpOptions, "w") as options_file:
options_file.write("\n".join(file_options))
subprocess.check_call(command, stdout=sys.stdout, stderr=sys.stderr)
if not os.path.exists(tmpSol):
raise PulpSolverError("PuLP: Error while executing " + self.path)
status, values = self.readsol(tmpSol)
# Make sure to add back in any 0-valued variables SCIP leaves out.
finalVals = {}
for v in lp.variables():
finalVals[v.name] = values.get(v.name, 0.0)
lp.assignVarsVals(finalVals)
lp.assignStatus(status)
self.delete_tmp_files(tmpLp, tmpSol, tmpOptions)
return status
| (self, lp) |
38,894 | pulp.apis.scip_api | defaultPath | null | def defaultPath(self):
return self.executableExtension(scip_path)
| (self) |
38,899 | pulp.apis.scip_api | readsol | Read a SCIP solution file | @staticmethod
def readsol(filename):
"""Read a SCIP solution file"""
with open(filename) as f:
# First line must contain 'solution status: <something>'
try:
line = f.readline()
comps = line.split(": ")
assert comps[0] == "solution status"
assert len(comps) == 2
except Exception:
raise PulpSolverError(f"Can't get SCIP solver status: {line!r}")
status = SCIP_CMD.SCIP_STATUSES.get(
comps[1].strip(), constants.LpStatusUndefined
)
values = {}
if status in SCIP_CMD.NO_SOLUTION_STATUSES:
return status, values
# Look for an objective value. If we can't find one, stop.
try:
line = f.readline()
comps = line.split(": ")
assert comps[0] == "objective value"
assert len(comps) == 2
float(comps[1].strip())
except Exception:
raise PulpSolverError(f"Can't get SCIP solver objective: {line!r}")
# Parse the variable values.
for line in f:
try:
comps = line.split()
values[comps[0]] = float(comps[1])
except:
raise PulpSolverError(f"Can't read SCIP solver output: {line!r}")
return status, values
| (filename) |
38,927 | pulp.apis.scip_api | SCIP_PY |
The SCIP Optimization Suite (via its python interface)
The SCIP internals are available after calling solve as:
- each variable in variable.solverVar
- each constraint in constraint.solverConstraint
- the model in problem.solverModel
| class SCIP_PY(LpSolver):
"""
The SCIP Optimization Suite (via its python interface)
The SCIP internals are available after calling solve as:
- each variable in variable.solverVar
- each constraint in constraint.solverConstraint
- the model in problem.solverModel
"""
name = "SCIP_PY"
try:
global scip
import pyscipopt as scip
except ImportError:
def available(self):
"""True if the solver is available"""
return False
def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
raise PulpSolverError(f"The {self.name} solver is not available")
else:
def __init__(
self,
mip=True,
msg=True,
options=None,
timeLimit=None,
gapRel=None,
gapAbs=None,
maxNodes=None,
logPath=None,
threads=None,
warmStart=False,
):
"""
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param list options: list of additional options to pass to solver
: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 maxNodes: max number of nodes during branching. Stops the solving when reached.
:param str logPath: path to the log file
:param int threads: sets the maximum number of threads
:param bool warmStart: if True, the solver will use the current value of variables as a start
"""
super().__init__(
mip=mip,
msg=msg,
options=options,
timeLimit=timeLimit,
gapRel=gapRel,
gapAbs=gapAbs,
maxNodes=maxNodes,
logPath=logPath,
threads=threads,
warmStart=warmStart,
)
def findSolutionValues(self, lp):
lp.resolveOK = True
solutionStatus = lp.solverModel.getStatus()
scip_to_pulp_status = {
"optimal": constants.LpStatusOptimal,
"unbounded": constants.LpStatusUnbounded,
"infeasible": constants.LpStatusInfeasible,
"inforunbd": constants.LpStatusNotSolved,
"timelimit": constants.LpStatusNotSolved,
"userinterrupt": constants.LpStatusNotSolved,
"nodelimit": constants.LpStatusNotSolved,
"totalnodelimit": constants.LpStatusNotSolved,
"stallnodelimit": constants.LpStatusNotSolved,
"gaplimit": constants.LpStatusNotSolved,
"memlimit": constants.LpStatusNotSolved,
"sollimit": constants.LpStatusNotSolved,
"bestsollimit": constants.LpStatusNotSolved,
"restartlimit": constants.LpStatusNotSolved,
"unknown": constants.LpStatusUndefined,
}
possible_solution_found_statuses = (
"optimal",
"timelimit",
"userinterrupt",
"nodelimit",
"totalnodelimit",
"stallnodelimit",
"gaplimit",
"memlimit",
)
status = scip_to_pulp_status[solutionStatus]
if solutionStatus in possible_solution_found_statuses:
try: # Feasible solution found
solution = lp.solverModel.getBestSol()
for variable in lp._variables:
variable.varValue = solution[variable.solverVar]
for constraint in lp.constraints.values():
constraint.slack = lp.solverModel.getSlack(
constraint.solverConstraint, solution
)
if status == constants.LpStatusOptimal:
lp.assignStatus(status, constants.LpSolutionOptimal)
else:
status = constants.LpStatusOptimal
lp.assignStatus(status, constants.LpSolutionIntegerFeasible)
except: # No solution found
lp.assignStatus(status, constants.LpSolutionNoSolutionFound)
else:
lp.assignStatus(status)
# TODO: check if problem is an LP i.e. does not have integer variables
# if :
# for variable in lp._variables:
# variable.dj = lp.solverModel.getVarRedcost(variable.solverVar)
# for constraint in lp.constraints.values():
# constraint.pi = lp.solverModel.getDualSolVal(constraint.solverConstraint)
return status
def available(self):
"""True if the solver is available"""
# if pyscipopt can be installed (and therefore imported) it has access to scip
return True
def callSolver(self, lp):
"""Solves the problem with scip"""
lp.solverModel.optimize()
def buildSolverModel(self, lp):
"""
Takes the pulp lp model and translates it into a scip model
"""
##################################################
# create model
##################################################
lp.solverModel = scip.Model(lp.name)
if lp.sense == constants.LpMaximize:
lp.solverModel.setMaximize()
else:
lp.solverModel.setMinimize()
##################################################
# add options
##################################################
if not self.msg:
lp.solverModel.hideOutput()
if self.timeLimit is not None:
lp.solverModel.setParam("limits/time", self.timeLimit)
if "gapRel" in self.optionsDict:
lp.solverModel.setParam("limits/gap", self.optionsDict["gapRel"])
if "gapAbs" in self.optionsDict:
lp.solverModel.setParam("limits/absgap", self.optionsDict["gapAbs"])
if "maxNodes" in self.optionsDict:
lp.solverModel.setParam("limits/nodes", self.optionsDict["maxNodes"])
if "logPath" in self.optionsDict:
lp.solverModel.setLogfile(self.optionsDict["logPath"])
if "threads" in self.optionsDict and int(self.optionsDict["threads"]) > 1:
warnings.warn(
f"The solver {self.name} can only run with a single thread"
)
if not self.mip:
warnings.warn(f"{self.name} does not allow a problem to be relaxed")
options = iter(self.options)
for option in options:
# assumption: all file options require an argument which is provided after the equal sign (=)
if "=" in option:
name, value = option.split("=", maxsplit=2)
else:
name, value = option, next(options)
lp.solverModel.setParam(name, value)
##################################################
# add variables
##################################################
category_to_vtype = {
constants.LpBinary: "B",
constants.LpContinuous: "C",
constants.LpInteger: "I",
}
for var in lp.variables():
var.solverVar = lp.solverModel.addVar(
name=var.name,
vtype=category_to_vtype[var.cat],
lb=var.lowBound, # a lower bound of None represents -infinity
ub=var.upBound, # an upper bound of None represents +infinity
obj=lp.objective.get(var, 0.0),
)
##################################################
# add constraints
##################################################
sense_to_operator = {
constants.LpConstraintLE: operator.le,
constants.LpConstraintGE: operator.ge,
constants.LpConstraintEQ: operator.eq,
}
for name, constraint in lp.constraints.items():
constraint.solverConstraint = lp.solverModel.addCons(
cons=sense_to_operator[constraint.sense](
scip.quicksum(
coefficient * variable.solverVar
for variable, coefficient in constraint.items()
),
-constraint.constant,
),
name=name,
)
##################################################
# add warm start
##################################################
if self.optionsDict.get("warmStart", False):
s = lp.solverModel.createPartialSol()
for var in lp.variables():
if var.varValue is not None:
# Warm start variables having an initial value
lp.solverModel.setSolVal(s, var.solverVar, var.varValue)
lp.solverModel.addSol(s)
def actualSolve(self, lp):
"""
Solve a well formulated lp problem
creates a scip model, variables and constraints and attaches
them to the lp model which it then solves
"""
self.buildSolverModel(lp)
self.callSolver(lp)
solutionStatus = self.findSolutionValues(lp)
for variable in lp._variables:
variable.modified = False
for constraint in lp.constraints.values():
constraint.modified = False
return solutionStatus
def actualResolve(self, lp):
"""
Solve a well formulated lp problem
uses the old solver and modifies the rhs of the modified constraints
"""
# TODO: add ability to resolve pysciptopt models
# - http://listserv.zib.de/pipermail/scip/2020-May/003977.html
# - https://scipopt.org/doc-8.0.0/html/REOPT.php
raise PulpSolverError(
f"The {self.name} solver does not implement resolving"
)
| (mip=True, msg=True, options=None, timeLimit=None, *args, **kwargs) |
38,930 | pulp.apis.scip_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
raise PulpSolverError(f"The {self.name} solver is not available")
| (self, lp) |
38,939 | pulp.apis.xpress_api | XPRESS | The XPRESS LP solver that uses the XPRESS command line tool
in a subprocess | class XPRESS(LpSolver_CMD):
"""The XPRESS LP solver that uses the XPRESS command line tool
in a subprocess"""
name = "XPRESS"
def __init__(
self,
mip=True,
msg=True,
timeLimit=None,
gapRel=None,
options=None,
keepFiles=False,
path=None,
heurFreq=None,
heurStra=None,
coverCuts=None,
preSolve=None,
warmStart=False,
):
"""
Initializes the Xpress solver.
: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 heurFreq: the frequency at which heuristics are used in the tree search
:param heurStra: heuristic strategy
:param coverCuts: the number of rounds of lifted cover inequalities at the top node
:param preSolve: whether presolving should be performed before the main algorithm
:param options: Adding more options, e.g. options = ["NODESELECTION=1", "HEURDEPTH=5"]
More about Xpress options and control parameters please see
https://www.fico.com/fico-xpress-optimization/docs/latest/solver/optimizer/HTML/chapter7.html
:param bool warmStart: if True, then use current variable values as start
"""
LpSolver_CMD.__init__(
self,
gapRel=gapRel,
mip=mip,
msg=msg,
timeLimit=timeLimit,
options=options,
path=path,
keepFiles=keepFiles,
heurFreq=heurFreq,
heurStra=heurStra,
coverCuts=coverCuts,
preSolve=preSolve,
warmStart=warmStart,
)
def defaultPath(self):
return self.executableExtension("optimizer")
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, tmpCmd, tmpAttr, tmpStart = self.create_tmp_files(
lp.name, "lp", "prt", "cmd", "attr", "slx"
)
variables = lp.writeLP(tmpLp, writeSOS=1, mip=self.mip)
if self.optionsDict.get("warmStart", False):
start = [(v.name, v.value()) for v in variables if v.value() is not None]
self.writeslxsol(tmpStart, start)
# Explicitly capture some attributes so that we can easily get
# information about the solution.
attrNames = []
if _ismip(lp) and self.mip:
attrNames.extend(["mipobjval", "bestbound", "mipstatus"])
statusmap = {
0: constants.LpStatusUndefined, # XPRS_MIP_NOT_LOADED
1: constants.LpStatusUndefined, # XPRS_MIP_LP_NOT_OPTIMAL
2: constants.LpStatusUndefined, # XPRS_MIP_LP_OPTIMAL
3: constants.LpStatusUndefined, # XPRS_MIP_NO_SOL_FOUND
4: constants.LpStatusUndefined, # XPRS_MIP_SOLUTION
5: constants.LpStatusInfeasible, # XPRS_MIP_INFEAS
6: constants.LpStatusOptimal, # XPRS_MIP_OPTIMAL
7: constants.LpStatusUndefined, # XPRS_MIP_UNBOUNDED
}
statuskey = "mipstatus"
else:
attrNames.extend(["lpobjval", "lpstatus"])
statusmap = {
0: constants.LpStatusNotSolved, # XPRS_LP_UNSTARTED
1: constants.LpStatusOptimal, # XPRS_LP_OPTIMAL
2: constants.LpStatusInfeasible, # XPRS_LP_INFEAS
3: constants.LpStatusUndefined, # XPRS_LP_CUTOFF
4: constants.LpStatusUndefined, # XPRS_LP_UNFINISHED
5: constants.LpStatusUnbounded, # XPRS_LP_UNBOUNDED
6: constants.LpStatusUndefined, # XPRS_LP_CUTOFF_IN_DUAL
7: constants.LpStatusNotSolved, # XPRS_LP_UNSOLVED
8: constants.LpStatusUndefined, # XPRS_LP_NONCONVEX
}
statuskey = "lpstatus"
with open(tmpCmd, "w") as cmd:
if not self.msg:
cmd.write("OUTPUTLOG=0\n")
# The readprob command must be in lower case for correct filename handling
cmd.write("readprob " + self.quote_path(tmpLp) + "\n")
if self.timeLimit is not None:
cmd.write("MAXTIME=%d\n" % self.timeLimit)
targetGap = self.optionsDict.get("gapRel")
if targetGap is not None:
cmd.write(f"MIPRELSTOP={targetGap:f}\n")
heurFreq = self.optionsDict.get("heurFreq")
if heurFreq is not None:
cmd.write("HEURFREQ=%d\n" % heurFreq)
heurStra = self.optionsDict.get("heurStra")
if heurStra is not None:
cmd.write("HEURSTRATEGY=%d\n" % heurStra)
coverCuts = self.optionsDict.get("coverCuts")
if coverCuts is not None:
cmd.write("COVERCUTS=%d\n" % coverCuts)
preSolve = self.optionsDict.get("preSolve")
if preSolve is not None:
cmd.write("PRESOLVE=%d\n" % preSolve)
if self.optionsDict.get("warmStart", False):
cmd.write("readslxsol " + self.quote_path(tmpStart) + "\n")
for option in self.options:
cmd.write(option + "\n")
if _ismip(lp) and self.mip:
cmd.write("mipoptimize\n")
else:
cmd.write("lpoptimize\n")
# The writeprtsol command must be in lower case for correct filename handling
cmd.write("writeprtsol " + self.quote_path(tmpSol) + "\n")
cmd.write(
f"set fh [open {self.quote_path(tmpAttr)} w]; list\n"
) # `list` to suppress output
for attr in attrNames:
cmd.write(f'puts $fh "{attr}=${attr}"\n')
cmd.write("close $fh\n")
cmd.write("QUIT\n")
with open(tmpCmd) as cmd:
consume = False
subout = None
suberr = None
if not self.msg:
# Xpress writes a banner before we can disable output. So
# we have to explicitly consume the banner.
if sys.hexversion >= 0x03030000:
subout = subprocess.DEVNULL
suberr = subprocess.DEVNULL
else:
# We could also use open(os.devnull, 'w') but then we
# would be responsible for closing the file.
subout = subprocess.PIPE
suberr = subprocess.STDOUT
consume = True
xpress = subprocess.Popen(
[self.path, lp.name],
shell=True,
stdin=cmd,
stdout=subout,
stderr=suberr,
universal_newlines=True,
)
if consume:
# Special case in which messages are disabled and we have
# to consume any output
for _ in xpress.stdout:
pass
if xpress.wait() != 0:
raise PulpSolverError("PuLP: Error while executing " + self.path)
values, redcost, slacks, duals, attrs = self.readsol(tmpSol, tmpAttr)
self.delete_tmp_files(tmpLp, tmpSol, tmpCmd, tmpAttr)
status = statusmap.get(attrs.get(statuskey, -1), constants.LpStatusUndefined)
lp.assignVarsVals(values)
lp.assignVarsDj(redcost)
lp.assignConsSlack(slacks)
lp.assignConsPi(duals)
lp.assignStatus(status)
return status
@staticmethod
def readsol(filename, attrfile):
"""Read an XPRESS solution file"""
values = {}
redcost = {}
slacks = {}
duals = {}
with open(filename) as f:
for lineno, _line in enumerate(f):
# The first 6 lines are status information
if lineno < 6:
continue
elif lineno == 6:
# Line with status information
_line = _line.split()
rows = int(_line[2])
cols = int(_line[5])
elif lineno < 10:
# Empty line, "Solution Statistics", objective direction
pass
elif lineno == 10:
# Solution status
pass
else:
# There is some more stuff and then follows the "Rows" and
# "Columns" section. That other stuff does not match the
# format of the rows/columns lines, so we can keep the
# parser simple
line = _line.split()
if len(line) > 1:
if line[0] == "C":
# A column
# (C, Number, Name, At, Value, Input Cost, Reduced Cost)
name = line[2]
values[name] = float(line[4])
redcost[name] = float(line[6])
elif len(line[0]) == 1 and line[0] in "LGRE":
# A row
# ([LGRE], Number, Name, At, Value, Slack, Dual, RHS)
name = line[2]
slacks[name] = float(line[5])
duals[name] = float(line[6])
# Read the attributes that we wrote explicitly
attrs = dict()
with open(attrfile) as f:
for line in f:
fields = line.strip().split("=")
if len(fields) == 2 and fields[0].lower() == fields[0]:
value = fields[1].strip()
try:
value = int(fields[1].strip())
except ValueError:
try:
value = float(fields[1].strip())
except ValueError:
pass
attrs[fields[0].strip()] = value
return values, redcost, slacks, duals, attrs
def writeslxsol(self, name, *values):
"""
Write a solution file in SLX format.
The function can write multiple solutions to the same file, each
solution must be passed as a list of (name,value) pairs. Solutions
are written in the order specified and are given names "solutionN"
where N is the index of the solution in the list.
:param string name: file name
:param list values: list of lists of (name,value) pairs
"""
with open(name, "w") as slx:
for i, sol in enumerate(values):
slx.write("NAME solution%d\n" % i)
for name, value in sol:
slx.write(f" C {name} {value:.16f}\n")
slx.write("ENDATA\n")
@staticmethod
def quote_path(path):
r"""
Quotes a path for the Xpress optimizer console, by wrapping it in
double quotes and escaping the following characters, which would
otherwise be interpreted by the Tcl shell: \ $ " [
"""
return '"' + re.sub(r'([\\$"[])', r"\\\1", path) + '"'
| (mip=True, msg=True, timeLimit=None, gapRel=None, options=None, keepFiles=False, path=None, heurFreq=None, heurStra=None, coverCuts=None, preSolve=None, warmStart=False) |
38,940 | pulp.apis.xpress_api | __init__ |
Initializes the Xpress solver.
: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 heurFreq: the frequency at which heuristics are used in the tree search
:param heurStra: heuristic strategy
:param coverCuts: the number of rounds of lifted cover inequalities at the top node
:param preSolve: whether presolving should be performed before the main algorithm
:param options: Adding more options, e.g. options = ["NODESELECTION=1", "HEURDEPTH=5"]
More about Xpress options and control parameters please see
https://www.fico.com/fico-xpress-optimization/docs/latest/solver/optimizer/HTML/chapter7.html
:param bool warmStart: if True, then use current variable values as start
| def __init__(
self,
mip=True,
msg=True,
timeLimit=None,
gapRel=None,
options=None,
keepFiles=False,
path=None,
heurFreq=None,
heurStra=None,
coverCuts=None,
preSolve=None,
warmStart=False,
):
"""
Initializes the Xpress solver.
: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 heurFreq: the frequency at which heuristics are used in the tree search
:param heurStra: heuristic strategy
:param coverCuts: the number of rounds of lifted cover inequalities at the top node
:param preSolve: whether presolving should be performed before the main algorithm
:param options: Adding more options, e.g. options = ["NODESELECTION=1", "HEURDEPTH=5"]
More about Xpress options and control parameters please see
https://www.fico.com/fico-xpress-optimization/docs/latest/solver/optimizer/HTML/chapter7.html
:param bool warmStart: if True, then use current variable values as start
"""
LpSolver_CMD.__init__(
self,
gapRel=gapRel,
mip=mip,
msg=msg,
timeLimit=timeLimit,
options=options,
path=path,
keepFiles=keepFiles,
heurFreq=heurFreq,
heurStra=heurStra,
coverCuts=coverCuts,
preSolve=preSolve,
warmStart=warmStart,
)
| (self, mip=True, msg=True, timeLimit=None, gapRel=None, options=None, keepFiles=False, path=None, heurFreq=None, heurStra=None, coverCuts=None, preSolve=None, warmStart=False) |
38,942 | pulp.apis.xpress_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, tmpCmd, tmpAttr, tmpStart = self.create_tmp_files(
lp.name, "lp", "prt", "cmd", "attr", "slx"
)
variables = lp.writeLP(tmpLp, writeSOS=1, mip=self.mip)
if self.optionsDict.get("warmStart", False):
start = [(v.name, v.value()) for v in variables if v.value() is not None]
self.writeslxsol(tmpStart, start)
# Explicitly capture some attributes so that we can easily get
# information about the solution.
attrNames = []
if _ismip(lp) and self.mip:
attrNames.extend(["mipobjval", "bestbound", "mipstatus"])
statusmap = {
0: constants.LpStatusUndefined, # XPRS_MIP_NOT_LOADED
1: constants.LpStatusUndefined, # XPRS_MIP_LP_NOT_OPTIMAL
2: constants.LpStatusUndefined, # XPRS_MIP_LP_OPTIMAL
3: constants.LpStatusUndefined, # XPRS_MIP_NO_SOL_FOUND
4: constants.LpStatusUndefined, # XPRS_MIP_SOLUTION
5: constants.LpStatusInfeasible, # XPRS_MIP_INFEAS
6: constants.LpStatusOptimal, # XPRS_MIP_OPTIMAL
7: constants.LpStatusUndefined, # XPRS_MIP_UNBOUNDED
}
statuskey = "mipstatus"
else:
attrNames.extend(["lpobjval", "lpstatus"])
statusmap = {
0: constants.LpStatusNotSolved, # XPRS_LP_UNSTARTED
1: constants.LpStatusOptimal, # XPRS_LP_OPTIMAL
2: constants.LpStatusInfeasible, # XPRS_LP_INFEAS
3: constants.LpStatusUndefined, # XPRS_LP_CUTOFF
4: constants.LpStatusUndefined, # XPRS_LP_UNFINISHED
5: constants.LpStatusUnbounded, # XPRS_LP_UNBOUNDED
6: constants.LpStatusUndefined, # XPRS_LP_CUTOFF_IN_DUAL
7: constants.LpStatusNotSolved, # XPRS_LP_UNSOLVED
8: constants.LpStatusUndefined, # XPRS_LP_NONCONVEX
}
statuskey = "lpstatus"
with open(tmpCmd, "w") as cmd:
if not self.msg:
cmd.write("OUTPUTLOG=0\n")
# The readprob command must be in lower case for correct filename handling
cmd.write("readprob " + self.quote_path(tmpLp) + "\n")
if self.timeLimit is not None:
cmd.write("MAXTIME=%d\n" % self.timeLimit)
targetGap = self.optionsDict.get("gapRel")
if targetGap is not None:
cmd.write(f"MIPRELSTOP={targetGap:f}\n")
heurFreq = self.optionsDict.get("heurFreq")
if heurFreq is not None:
cmd.write("HEURFREQ=%d\n" % heurFreq)
heurStra = self.optionsDict.get("heurStra")
if heurStra is not None:
cmd.write("HEURSTRATEGY=%d\n" % heurStra)
coverCuts = self.optionsDict.get("coverCuts")
if coverCuts is not None:
cmd.write("COVERCUTS=%d\n" % coverCuts)
preSolve = self.optionsDict.get("preSolve")
if preSolve is not None:
cmd.write("PRESOLVE=%d\n" % preSolve)
if self.optionsDict.get("warmStart", False):
cmd.write("readslxsol " + self.quote_path(tmpStart) + "\n")
for option in self.options:
cmd.write(option + "\n")
if _ismip(lp) and self.mip:
cmd.write("mipoptimize\n")
else:
cmd.write("lpoptimize\n")
# The writeprtsol command must be in lower case for correct filename handling
cmd.write("writeprtsol " + self.quote_path(tmpSol) + "\n")
cmd.write(
f"set fh [open {self.quote_path(tmpAttr)} w]; list\n"
) # `list` to suppress output
for attr in attrNames:
cmd.write(f'puts $fh "{attr}=${attr}"\n')
cmd.write("close $fh\n")
cmd.write("QUIT\n")
with open(tmpCmd) as cmd:
consume = False
subout = None
suberr = None
if not self.msg:
# Xpress writes a banner before we can disable output. So
# we have to explicitly consume the banner.
if sys.hexversion >= 0x03030000:
subout = subprocess.DEVNULL
suberr = subprocess.DEVNULL
else:
# We could also use open(os.devnull, 'w') but then we
# would be responsible for closing the file.
subout = subprocess.PIPE
suberr = subprocess.STDOUT
consume = True
xpress = subprocess.Popen(
[self.path, lp.name],
shell=True,
stdin=cmd,
stdout=subout,
stderr=suberr,
universal_newlines=True,
)
if consume:
# Special case in which messages are disabled and we have
# to consume any output
for _ in xpress.stdout:
pass
if xpress.wait() != 0:
raise PulpSolverError("PuLP: Error while executing " + self.path)
values, redcost, slacks, duals, attrs = self.readsol(tmpSol, tmpAttr)
self.delete_tmp_files(tmpLp, tmpSol, tmpCmd, tmpAttr)
status = statusmap.get(attrs.get(statuskey, -1), constants.LpStatusUndefined)
lp.assignVarsVals(values)
lp.assignVarsDj(redcost)
lp.assignConsSlack(slacks)
lp.assignConsPi(duals)
lp.assignStatus(status)
return status
| (self, lp) |
38,946 | pulp.apis.xpress_api | defaultPath | null | def defaultPath(self):
return self.executableExtension("optimizer")
| (self) |
38,951 | pulp.apis.xpress_api | quote_path |
Quotes a path for the Xpress optimizer console, by wrapping it in
double quotes and escaping the following characters, which would
otherwise be interpreted by the Tcl shell: \ $ " [
| @staticmethod
def quote_path(path):
r"""
Quotes a path for the Xpress optimizer console, by wrapping it in
double quotes and escaping the following characters, which would
otherwise be interpreted by the Tcl shell: \ $ " [
"""
return '"' + re.sub(r'([\\$"[])', r"\\\1", path) + '"'
| (path) |
38,952 | pulp.apis.xpress_api | readsol | Read an XPRESS solution file | @staticmethod
def readsol(filename, attrfile):
"""Read an XPRESS solution file"""
values = {}
redcost = {}
slacks = {}
duals = {}
with open(filename) as f:
for lineno, _line in enumerate(f):
# The first 6 lines are status information
if lineno < 6:
continue
elif lineno == 6:
# Line with status information
_line = _line.split()
rows = int(_line[2])
cols = int(_line[5])
elif lineno < 10:
# Empty line, "Solution Statistics", objective direction
pass
elif lineno == 10:
# Solution status
pass
else:
# There is some more stuff and then follows the "Rows" and
# "Columns" section. That other stuff does not match the
# format of the rows/columns lines, so we can keep the
# parser simple
line = _line.split()
if len(line) > 1:
if line[0] == "C":
# A column
# (C, Number, Name, At, Value, Input Cost, Reduced Cost)
name = line[2]
values[name] = float(line[4])
redcost[name] = float(line[6])
elif len(line[0]) == 1 and line[0] in "LGRE":
# A row
# ([LGRE], Number, Name, At, Value, Slack, Dual, RHS)
name = line[2]
slacks[name] = float(line[5])
duals[name] = float(line[6])
# Read the attributes that we wrote explicitly
attrs = dict()
with open(attrfile) as f:
for line in f:
fields = line.strip().split("=")
if len(fields) == 2 and fields[0].lower() == fields[0]:
value = fields[1].strip()
try:
value = int(fields[1].strip())
except ValueError:
try:
value = float(fields[1].strip())
except ValueError:
pass
attrs[fields[0].strip()] = value
return values, redcost, slacks, duals, attrs
| (filename, attrfile) |
38,960 | pulp.apis.xpress_api | writeslxsol |
Write a solution file in SLX format.
The function can write multiple solutions to the same file, each
solution must be passed as a list of (name,value) pairs. Solutions
are written in the order specified and are given names "solutionN"
where N is the index of the solution in the list.
:param string name: file name
:param list values: list of lists of (name,value) pairs
| def writeslxsol(self, name, *values):
"""
Write a solution file in SLX format.
The function can write multiple solutions to the same file, each
solution must be passed as a list of (name,value) pairs. Solutions
are written in the order specified and are given names "solutionN"
where N is the index of the solution in the list.
:param string name: file name
:param list values: list of lists of (name,value) pairs
"""
with open(name, "w") as slx:
for i, sol in enumerate(values):
slx.write("NAME solution%d\n" % i)
for name, value in sol:
slx.write(f" C {name} {value:.16f}\n")
slx.write("ENDATA\n")
| (self, name, *values) |
38,983 | pulp.apis.xpress_api | XPRESS_PY | The XPRESS LP solver that uses XPRESS Python API | class XPRESS_PY(LpSolver):
"""The XPRESS LP solver that uses XPRESS Python API"""
name = "XPRESS_PY"
def __init__(
self,
mip=True,
msg=True,
timeLimit=None,
gapRel=None,
heurFreq=None,
heurStra=None,
coverCuts=None,
preSolve=None,
warmStart=None,
export=None,
options=None,
):
"""
Initializes the Xpress solver.
: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 heurFreq: the frequency at which heuristics are used in the tree search
:param heurStra: heuristic strategy
:param coverCuts: the number of rounds of lifted cover inequalities at the top node
:param preSolve: whether presolving should be performed before the main algorithm
:param bool warmStart: if set then use current variable values as warm start
:param string export: if set then the model will be exported to this file before solving
:param options: Adding more options. This is a list the elements of which
are either (name,value) pairs or strings "name=value".
More about Xpress options and control parameters please see
https://www.fico.com/fico-xpress-optimization/docs/latest/solver/optimizer/HTML/chapter7.html
"""
if timeLimit is not None:
# The Xpress time limit has this interpretation:
# timelimit <0: Stop after -timelimit, no matter what
# timelimit >0: Stop after timelimit only if a feasible solution
# exists. We overwrite this meaning here since it is
# somewhat counterintuitive when compared to other
# solvers. You can always pass a positive timlimit
# via `options` to get that behavior.
timeLimit = -abs(timeLimit)
LpSolver.__init__(
self,
gapRel=gapRel,
mip=mip,
msg=msg,
timeLimit=timeLimit,
options=options,
heurFreq=heurFreq,
heurStra=heurStra,
coverCuts=coverCuts,
preSolve=preSolve,
warmStart=warmStart,
)
self._available = None
self._export = export
def available(self):
"""True if the solver is available"""
if self._available is None:
try:
global xpress
import xpress
# Always disable the global output. We only want output if
# we install callbacks explicitly
xpress.setOutputEnabled(False)
self._available = True
except:
self._available = False
return self._available
def callSolver(self, lp, prepare=None):
"""Perform the actual solve from actualSolve() or actualResolve().
:param prepare: a function that is called with `lp` as argument
and allows final tweaks to `lp.solverModel` before
the low level solve is started.
"""
try:
model = lp.solverModel
# Mark all variables and constraints as unmodified so that
# actualResolve will do the correct thing.
for v in lp.variables():
v.modified = False
for c in lp.constraints.values():
c.modified = False
if self._export is not None:
if self._export.lower().endswith(".lp"):
model.write(self._export, "l")
else:
model.write(self._export)
if prepare is not None:
prepare(lp)
if _ismip(lp) and not self.mip:
# Solve only the LP relaxation
model.lpoptimize()
else:
# In all other cases, solve() does the correct thing
model.solve()
except (xpress.ModelError, xpress.InterfaceError, xpress.SolverError) as err:
raise PulpSolverError(str(err))
def findSolutionValues(self, lp):
try:
model = lp.solverModel
# Collect results
if _ismip(lp) and self.mip:
# Solved as MIP
x, slacks, duals, djs = [], [], None, None
try:
model.getmipsol(x, slacks)
except:
x, slacks = None, None
statusmap = {
0: constants.LpStatusUndefined, # XPRS_MIP_NOT_LOADED
1: constants.LpStatusUndefined, # XPRS_MIP_LP_NOT_OPTIMAL
2: constants.LpStatusUndefined, # XPRS_MIP_LP_OPTIMAL
3: constants.LpStatusUndefined, # XPRS_MIP_NO_SOL_FOUND
4: constants.LpStatusUndefined, # XPRS_MIP_SOLUTION
5: constants.LpStatusInfeasible, # XPRS_MIP_INFEAS
6: constants.LpStatusOptimal, # XPRS_MIP_OPTIMAL
7: constants.LpStatusUndefined, # XPRS_MIP_UNBOUNDED
}
statuskey = "mipstatus"
else:
# Solved as continuous
x, slacks, duals, djs = [], [], [], []
try:
model.getlpsol(x, slacks, duals, djs)
except:
# No solution available
x, slacks, duals, djs = None, None, None, None
statusmap = {
0: constants.LpStatusNotSolved, # XPRS_LP_UNSTARTED
1: constants.LpStatusOptimal, # XPRS_LP_OPTIMAL
2: constants.LpStatusInfeasible, # XPRS_LP_INFEAS
3: constants.LpStatusUndefined, # XPRS_LP_CUTOFF
4: constants.LpStatusUndefined, # XPRS_LP_UNFINISHED
5: constants.LpStatusUnbounded, # XPRS_LP_UNBOUNDED
6: constants.LpStatusUndefined, # XPRS_LP_CUTOFF_IN_DUAL
7: constants.LpStatusNotSolved, # XPRS_LP_UNSOLVED
8: constants.LpStatusUndefined, # XPRS_LP_NONCONVEX
}
statuskey = "lpstatus"
if x is not None:
lp.assignVarsVals({v.name: x[v._xprs[0]] for v in lp.variables()})
if djs is not None:
lp.assignVarsDj({v.name: djs[v._xprs[0]] for v in lp.variables()})
if duals is not None:
lp.assignConsPi(
{c.name: duals[c._xprs[0]] for c in lp.constraints.values()}
)
if slacks is not None:
lp.assignConsSlack(
{c.name: slacks[c._xprs[0]] for c in lp.constraints.values()}
)
status = statusmap.get(
model.getAttrib(statuskey), constants.LpStatusUndefined
)
lp.assignStatus(status)
return status
except (xpress.ModelError, xpress.InterfaceError, xpress.SolverError) as err:
raise PulpSolverError(str(err))
def actualSolve(self, lp, prepare=None):
"""Solve a well formulated lp problem"""
if not self.available():
# Import again to get a more verbose error message
message = "XPRESS Python API not available"
try:
import xpress
except ImportError as err:
message = str(err)
raise PulpSolverError(message)
self.buildSolverModel(lp)
self.callSolver(lp, prepare)
return self.findSolutionValues(lp)
def buildSolverModel(self, lp):
"""
Takes the pulp lp model and translates it into an xpress model
"""
self._extract(lp)
try:
# Apply controls, warmstart etc. We do this here rather than in
# callSolver() so that the caller has a chance to overwrite things
# either using the `prepare` argument to callSolver() or by
# explicitly calling
# self.buildSolverModel()
# self.callSolver()
# self.findSolutionValues()
# This also avoids setting warmstart information passed to the
# constructor from actualResolve(), which would almost certainly
# be unintended.
model = lp.solverModel
# Apply controls that were passed to the constructor
for key, name in [
("gapRel", "MIPRELSTOP"),
("timeLimit", "MAXTIME"),
("heurFreq", "HEURFREQ"),
("heurStra", "HEURSTRATEGY"),
("coverCuts", "COVERCUTS"),
("preSolve", "PRESOLVE"),
]:
value = self.optionsDict.get(key, None)
if value is not None:
model.setControl(name, value)
# Apply any other controls. These overwrite controls that were
# passed explicitly into the constructor.
for option in self.options:
if isinstance(option, tuple):
name = optione[0]
value = option[1]
else:
fields = option.split("=", 1)
if len(fields) != 2:
raise PulpSolverError("Invalid option " + str(option))
name = fields[0].strip()
value = fields[1].strip()
try:
model.setControl(name, int(value))
continue
except ValueError:
pass
try:
model.setControl(name, float(value))
continue
except ValueError:
pass
model.setControl(name, value)
# Setup warmstart information
if self.optionsDict.get("warmStart", False):
solval = list()
colind = list()
for v in sorted(lp.variables(), key=lambda x: x._xprs[0]):
if v.value() is not None:
solval.append(v.value())
colind.append(v._xprs[0])
if _ismip(lp) and self.mip:
# If we have a value for every variable then use
# loadmipsol(), which requires a dense solution. Otherwise
# use addmipsol() which allows sparse vectors.
if len(solval) == model.attributes.cols:
model.loadmipsol(solval)
else:
model.addmipsol(solval, colind, "warmstart")
else:
model.loadlpsol(solval, None, None, None)
# Setup message callback if output is requested
if self.msg:
def message(prob, data, msg, msgtype):
if msgtype > 0:
print(msg)
model.addcbmessage(message)
except (xpress.ModelError, xpress.InterfaceError, xpress.SolverError) as err:
raise PulpSolverError(str(err))
def actualResolve(self, lp, prepare=None):
"""Resolve a problem that was previously solved by actualSolve()."""
try:
rhsind = list()
rhsval = list()
for name in sorted(lp.constraints):
con = lp.constraints[name]
if not con.modified:
continue
if not hasattr(con, "_xprs"):
# Adding constraints is not implemented at the moment
raise PulpSolverError("Cannot add new constraints")
# At the moment only RHS can change in pulp.py
rhsind.append(con._xprs[0])
rhsval.append(-con.constant)
if len(rhsind) > 0:
lp.solverModel.chgrhs(rhsind, rhsval)
bndind = list()
bndtype = list()
bndval = list()
for v in lp.variables():
if not v.modified:
continue
if not hasattr(v, "_xprs"):
# Adding variables is not implemented at the moment
raise PulpSolverError("Cannot add new variables")
# At the moment only bounds can change in pulp.py
bndind.append(v._xprs[0])
bndtype.append("L")
bndval.append(-xpress.infinity if v.lowBound is None else v.lowBound)
bndind.append(v._xprs[0])
bndtype.append("G")
bndval.append(xpress.infinity if v.upBound is None else v.upBound)
if len(bndtype) > 0:
lp.solverModel.chgbounds(bndind, bndtype, bndval)
self.callSolver(lp, prepare)
return self.findSolutionValues(lp)
except (xpress.ModelError, xpress.InterfaceError, xpress.SolverError) as err:
raise PulpSolverError(str(err))
@staticmethod
def _reset(lp):
"""Reset any XPRESS specific information in lp."""
if hasattr(lp, "solverModel"):
delattr(lp, "solverModel")
for v in lp.variables():
if hasattr(v, "_xprs"):
delattr(v, "_xprs")
for c in lp.constraints.values():
if hasattr(c, "_xprs"):
delattr(c, "_xprs")
def _extract(self, lp):
"""Extract a given model to an XPRESS Python API instance.
The function stores XPRESS specific information in the `solverModel` property
of `lp` and each variable and constraint. These information can be
removed by calling `_reset`.
"""
self._reset(lp)
try:
model = xpress.problem()
if lp.sense == constants.LpMaximize:
model.chgobjsense(xpress.maximize)
# Create variables. We first collect the info for all variables
# and then create all of them in one shot. This is supposed to
# be faster in case we have to create a lot of variables.
obj = list()
lb = list()
ub = list()
ctype = list()
names = list()
for v in lp.variables():
lb.append(-xpress.infinity if v.lowBound is None else v.lowBound)
ub.append(xpress.infinity if v.upBound is None else v.upBound)
obj.append(lp.objective.get(v, 0.0))
if v.cat == constants.LpInteger:
ctype.append("I")
elif v.cat == constants.LpBinary:
ctype.append("B")
else:
ctype.append("C")
names.append(v.name)
model.addcols(obj, [0] * (len(obj) + 1), [], [], lb, ub, names, ctype)
for j, (v, x) in enumerate(zip(lp.variables(), model.getVariable())):
v._xprs = (j, x)
# Generate constraints. Sort by name to get deterministic
# ordering of constraints.
# Constraints are generated in blocks of 100 constraints to speed
# up things a bit but still keep memory usage small.
cons = list()
for i, name in enumerate(sorted(lp.constraints)):
con = lp.constraints[name]
# Sort the variables by index to get deterministic
# ordering of variables in the row.
lhs = xpress.Sum(
a * x._xprs[1]
for x, a in sorted(con.items(), key=lambda x: x[0]._xprs[0])
)
rhs = -con.constant
if con.sense == constants.LpConstraintLE:
c = xpress.constraint(body=lhs, sense=xpress.leq, rhs=rhs)
elif con.sense == constants.LpConstraintGE:
c = xpress.constraint(body=lhs, sense=xpress.geq, rhs=rhs)
elif con.sense == constants.LpConstraintEQ:
c = xpress.constraint(body=lhs, sense=xpress.eq, rhs=rhs)
else:
raise PulpSolverError(
"Unsupprted constraint type " + str(con.sense)
)
cons.append((i, c, con))
if len(cons) > 100:
model.addConstraint([c for _, c, _ in cons])
for i, c, con in cons:
con._xprs = (i, c)
cons = list()
if len(cons) > 0:
model.addConstraint([c for _, c, _ in cons])
for i, c, con in cons:
con._xprs = (i, c)
# SOS constraints
def addsos(m, sosdict, sostype):
"""Extract sos constraints from PuLP."""
soslist = []
# Sort by name to get deterministic ordering. Note that
# names may be plain integers, that is why we use str(name)
# to pass them to the SOS constructor.
for name in sorted(sosdict):
indices = []
weights = []
for v, val in sosdict[name].items():
indices.append(v._xprs[0])
weights.append(val)
soslist.append(xpress.sos(indices, weights, sostype, str(name)))
if len(soslist):
m.addSOS(soslist)
addsos(model, lp.sos1, 1)
addsos(model, lp.sos2, 2)
lp.solverModel = model
except (xpress.ModelError, xpress.InterfaceError, xpress.SolverError) as err:
# Undo everything
self._reset(lp)
raise PulpSolverError(str(err))
def getAttribute(self, lp, which):
"""Get an arbitrary attribute for the model that was previously
solved using actualSolve()."""
return lp.solverModel.getAttrib(which)
| (mip=True, msg=True, timeLimit=None, gapRel=None, heurFreq=None, heurStra=None, coverCuts=None, preSolve=None, warmStart=None, export=None, options=None) |
38,984 | pulp.apis.xpress_api | __init__ |
Initializes the Xpress solver.
: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 heurFreq: the frequency at which heuristics are used in the tree search
:param heurStra: heuristic strategy
:param coverCuts: the number of rounds of lifted cover inequalities at the top node
:param preSolve: whether presolving should be performed before the main algorithm
:param bool warmStart: if set then use current variable values as warm start
:param string export: if set then the model will be exported to this file before solving
:param options: Adding more options. This is a list the elements of which
are either (name,value) pairs or strings "name=value".
More about Xpress options and control parameters please see
https://www.fico.com/fico-xpress-optimization/docs/latest/solver/optimizer/HTML/chapter7.html
| def __init__(
self,
mip=True,
msg=True,
timeLimit=None,
gapRel=None,
heurFreq=None,
heurStra=None,
coverCuts=None,
preSolve=None,
warmStart=None,
export=None,
options=None,
):
"""
Initializes the Xpress solver.
: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 heurFreq: the frequency at which heuristics are used in the tree search
:param heurStra: heuristic strategy
:param coverCuts: the number of rounds of lifted cover inequalities at the top node
:param preSolve: whether presolving should be performed before the main algorithm
:param bool warmStart: if set then use current variable values as warm start
:param string export: if set then the model will be exported to this file before solving
:param options: Adding more options. This is a list the elements of which
are either (name,value) pairs or strings "name=value".
More about Xpress options and control parameters please see
https://www.fico.com/fico-xpress-optimization/docs/latest/solver/optimizer/HTML/chapter7.html
"""
if timeLimit is not None:
# The Xpress time limit has this interpretation:
# timelimit <0: Stop after -timelimit, no matter what
# timelimit >0: Stop after timelimit only if a feasible solution
# exists. We overwrite this meaning here since it is
# somewhat counterintuitive when compared to other
# solvers. You can always pass a positive timlimit
# via `options` to get that behavior.
timeLimit = -abs(timeLimit)
LpSolver.__init__(
self,
gapRel=gapRel,
mip=mip,
msg=msg,
timeLimit=timeLimit,
options=options,
heurFreq=heurFreq,
heurStra=heurStra,
coverCuts=coverCuts,
preSolve=preSolve,
warmStart=warmStart,
)
self._available = None
self._export = export
| (self, mip=True, msg=True, timeLimit=None, gapRel=None, heurFreq=None, heurStra=None, coverCuts=None, preSolve=None, warmStart=None, export=None, options=None) |
38,985 | pulp.apis.xpress_api | _extract | Extract a given model to an XPRESS Python API instance.
The function stores XPRESS specific information in the `solverModel` property
of `lp` and each variable and constraint. These information can be
removed by calling `_reset`.
| def _extract(self, lp):
"""Extract a given model to an XPRESS Python API instance.
The function stores XPRESS specific information in the `solverModel` property
of `lp` and each variable and constraint. These information can be
removed by calling `_reset`.
"""
self._reset(lp)
try:
model = xpress.problem()
if lp.sense == constants.LpMaximize:
model.chgobjsense(xpress.maximize)
# Create variables. We first collect the info for all variables
# and then create all of them in one shot. This is supposed to
# be faster in case we have to create a lot of variables.
obj = list()
lb = list()
ub = list()
ctype = list()
names = list()
for v in lp.variables():
lb.append(-xpress.infinity if v.lowBound is None else v.lowBound)
ub.append(xpress.infinity if v.upBound is None else v.upBound)
obj.append(lp.objective.get(v, 0.0))
if v.cat == constants.LpInteger:
ctype.append("I")
elif v.cat == constants.LpBinary:
ctype.append("B")
else:
ctype.append("C")
names.append(v.name)
model.addcols(obj, [0] * (len(obj) + 1), [], [], lb, ub, names, ctype)
for j, (v, x) in enumerate(zip(lp.variables(), model.getVariable())):
v._xprs = (j, x)
# Generate constraints. Sort by name to get deterministic
# ordering of constraints.
# Constraints are generated in blocks of 100 constraints to speed
# up things a bit but still keep memory usage small.
cons = list()
for i, name in enumerate(sorted(lp.constraints)):
con = lp.constraints[name]
# Sort the variables by index to get deterministic
# ordering of variables in the row.
lhs = xpress.Sum(
a * x._xprs[1]
for x, a in sorted(con.items(), key=lambda x: x[0]._xprs[0])
)
rhs = -con.constant
if con.sense == constants.LpConstraintLE:
c = xpress.constraint(body=lhs, sense=xpress.leq, rhs=rhs)
elif con.sense == constants.LpConstraintGE:
c = xpress.constraint(body=lhs, sense=xpress.geq, rhs=rhs)
elif con.sense == constants.LpConstraintEQ:
c = xpress.constraint(body=lhs, sense=xpress.eq, rhs=rhs)
else:
raise PulpSolverError(
"Unsupprted constraint type " + str(con.sense)
)
cons.append((i, c, con))
if len(cons) > 100:
model.addConstraint([c for _, c, _ in cons])
for i, c, con in cons:
con._xprs = (i, c)
cons = list()
if len(cons) > 0:
model.addConstraint([c for _, c, _ in cons])
for i, c, con in cons:
con._xprs = (i, c)
# SOS constraints
def addsos(m, sosdict, sostype):
"""Extract sos constraints from PuLP."""
soslist = []
# Sort by name to get deterministic ordering. Note that
# names may be plain integers, that is why we use str(name)
# to pass them to the SOS constructor.
for name in sorted(sosdict):
indices = []
weights = []
for v, val in sosdict[name].items():
indices.append(v._xprs[0])
weights.append(val)
soslist.append(xpress.sos(indices, weights, sostype, str(name)))
if len(soslist):
m.addSOS(soslist)
addsos(model, lp.sos1, 1)
addsos(model, lp.sos2, 2)
lp.solverModel = model
except (xpress.ModelError, xpress.InterfaceError, xpress.SolverError) as err:
# Undo everything
self._reset(lp)
raise PulpSolverError(str(err))
| (self, lp) |
38,986 | pulp.apis.xpress_api | _reset | Reset any XPRESS specific information in lp. | @staticmethod
def _reset(lp):
"""Reset any XPRESS specific information in lp."""
if hasattr(lp, "solverModel"):
delattr(lp, "solverModel")
for v in lp.variables():
if hasattr(v, "_xprs"):
delattr(v, "_xprs")
for c in lp.constraints.values():
if hasattr(c, "_xprs"):
delattr(c, "_xprs")
| (lp) |
38,987 | pulp.apis.xpress_api | actualResolve | Resolve a problem that was previously solved by actualSolve(). | def actualResolve(self, lp, prepare=None):
"""Resolve a problem that was previously solved by actualSolve()."""
try:
rhsind = list()
rhsval = list()
for name in sorted(lp.constraints):
con = lp.constraints[name]
if not con.modified:
continue
if not hasattr(con, "_xprs"):
# Adding constraints is not implemented at the moment
raise PulpSolverError("Cannot add new constraints")
# At the moment only RHS can change in pulp.py
rhsind.append(con._xprs[0])
rhsval.append(-con.constant)
if len(rhsind) > 0:
lp.solverModel.chgrhs(rhsind, rhsval)
bndind = list()
bndtype = list()
bndval = list()
for v in lp.variables():
if not v.modified:
continue
if not hasattr(v, "_xprs"):
# Adding variables is not implemented at the moment
raise PulpSolverError("Cannot add new variables")
# At the moment only bounds can change in pulp.py
bndind.append(v._xprs[0])
bndtype.append("L")
bndval.append(-xpress.infinity if v.lowBound is None else v.lowBound)
bndind.append(v._xprs[0])
bndtype.append("G")
bndval.append(xpress.infinity if v.upBound is None else v.upBound)
if len(bndtype) > 0:
lp.solverModel.chgbounds(bndind, bndtype, bndval)
self.callSolver(lp, prepare)
return self.findSolutionValues(lp)
except (xpress.ModelError, xpress.InterfaceError, xpress.SolverError) as err:
raise PulpSolverError(str(err))
| (self, lp, prepare=None) |
38,988 | pulp.apis.xpress_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp, prepare=None):
"""Solve a well formulated lp problem"""
if not self.available():
# Import again to get a more verbose error message
message = "XPRESS Python API not available"
try:
import xpress
except ImportError as err:
message = str(err)
raise PulpSolverError(message)
self.buildSolverModel(lp)
self.callSolver(lp, prepare)
return self.findSolutionValues(lp)
| (self, lp, prepare=None) |
38,989 | pulp.apis.xpress_api | available | True if the solver is available | def available(self):
"""True if the solver is available"""
if self._available is None:
try:
global xpress
import xpress
# Always disable the global output. We only want output if
# we install callbacks explicitly
xpress.setOutputEnabled(False)
self._available = True
except:
self._available = False
return self._available
| (self) |
38,990 | pulp.apis.xpress_api | buildSolverModel |
Takes the pulp lp model and translates it into an xpress model
| def buildSolverModel(self, lp):
"""
Takes the pulp lp model and translates it into an xpress model
"""
self._extract(lp)
try:
# Apply controls, warmstart etc. We do this here rather than in
# callSolver() so that the caller has a chance to overwrite things
# either using the `prepare` argument to callSolver() or by
# explicitly calling
# self.buildSolverModel()
# self.callSolver()
# self.findSolutionValues()
# This also avoids setting warmstart information passed to the
# constructor from actualResolve(), which would almost certainly
# be unintended.
model = lp.solverModel
# Apply controls that were passed to the constructor
for key, name in [
("gapRel", "MIPRELSTOP"),
("timeLimit", "MAXTIME"),
("heurFreq", "HEURFREQ"),
("heurStra", "HEURSTRATEGY"),
("coverCuts", "COVERCUTS"),
("preSolve", "PRESOLVE"),
]:
value = self.optionsDict.get(key, None)
if value is not None:
model.setControl(name, value)
# Apply any other controls. These overwrite controls that were
# passed explicitly into the constructor.
for option in self.options:
if isinstance(option, tuple):
name = optione[0]
value = option[1]
else:
fields = option.split("=", 1)
if len(fields) != 2:
raise PulpSolverError("Invalid option " + str(option))
name = fields[0].strip()
value = fields[1].strip()
try:
model.setControl(name, int(value))
continue
except ValueError:
pass
try:
model.setControl(name, float(value))
continue
except ValueError:
pass
model.setControl(name, value)
# Setup warmstart information
if self.optionsDict.get("warmStart", False):
solval = list()
colind = list()
for v in sorted(lp.variables(), key=lambda x: x._xprs[0]):
if v.value() is not None:
solval.append(v.value())
colind.append(v._xprs[0])
if _ismip(lp) and self.mip:
# If we have a value for every variable then use
# loadmipsol(), which requires a dense solution. Otherwise
# use addmipsol() which allows sparse vectors.
if len(solval) == model.attributes.cols:
model.loadmipsol(solval)
else:
model.addmipsol(solval, colind, "warmstart")
else:
model.loadlpsol(solval, None, None, None)
# Setup message callback if output is requested
if self.msg:
def message(prob, data, msg, msgtype):
if msgtype > 0:
print(msg)
model.addcbmessage(message)
except (xpress.ModelError, xpress.InterfaceError, xpress.SolverError) as err:
raise PulpSolverError(str(err))
| (self, lp) |
38,991 | pulp.apis.xpress_api | callSolver | Perform the actual solve from actualSolve() or actualResolve().
:param prepare: a function that is called with `lp` as argument
and allows final tweaks to `lp.solverModel` before
the low level solve is started.
| def callSolver(self, lp, prepare=None):
"""Perform the actual solve from actualSolve() or actualResolve().
:param prepare: a function that is called with `lp` as argument
and allows final tweaks to `lp.solverModel` before
the low level solve is started.
"""
try:
model = lp.solverModel
# Mark all variables and constraints as unmodified so that
# actualResolve will do the correct thing.
for v in lp.variables():
v.modified = False
for c in lp.constraints.values():
c.modified = False
if self._export is not None:
if self._export.lower().endswith(".lp"):
model.write(self._export, "l")
else:
model.write(self._export)
if prepare is not None:
prepare(lp)
if _ismip(lp) and not self.mip:
# Solve only the LP relaxation
model.lpoptimize()
else:
# In all other cases, solve() does the correct thing
model.solve()
except (xpress.ModelError, xpress.InterfaceError, xpress.SolverError) as err:
raise PulpSolverError(str(err))
| (self, lp, prepare=None) |
38,993 | pulp.apis.xpress_api | findSolutionValues | null | def findSolutionValues(self, lp):
try:
model = lp.solverModel
# Collect results
if _ismip(lp) and self.mip:
# Solved as MIP
x, slacks, duals, djs = [], [], None, None
try:
model.getmipsol(x, slacks)
except:
x, slacks = None, None
statusmap = {
0: constants.LpStatusUndefined, # XPRS_MIP_NOT_LOADED
1: constants.LpStatusUndefined, # XPRS_MIP_LP_NOT_OPTIMAL
2: constants.LpStatusUndefined, # XPRS_MIP_LP_OPTIMAL
3: constants.LpStatusUndefined, # XPRS_MIP_NO_SOL_FOUND
4: constants.LpStatusUndefined, # XPRS_MIP_SOLUTION
5: constants.LpStatusInfeasible, # XPRS_MIP_INFEAS
6: constants.LpStatusOptimal, # XPRS_MIP_OPTIMAL
7: constants.LpStatusUndefined, # XPRS_MIP_UNBOUNDED
}
statuskey = "mipstatus"
else:
# Solved as continuous
x, slacks, duals, djs = [], [], [], []
try:
model.getlpsol(x, slacks, duals, djs)
except:
# No solution available
x, slacks, duals, djs = None, None, None, None
statusmap = {
0: constants.LpStatusNotSolved, # XPRS_LP_UNSTARTED
1: constants.LpStatusOptimal, # XPRS_LP_OPTIMAL
2: constants.LpStatusInfeasible, # XPRS_LP_INFEAS
3: constants.LpStatusUndefined, # XPRS_LP_CUTOFF
4: constants.LpStatusUndefined, # XPRS_LP_UNFINISHED
5: constants.LpStatusUnbounded, # XPRS_LP_UNBOUNDED
6: constants.LpStatusUndefined, # XPRS_LP_CUTOFF_IN_DUAL
7: constants.LpStatusNotSolved, # XPRS_LP_UNSOLVED
8: constants.LpStatusUndefined, # XPRS_LP_NONCONVEX
}
statuskey = "lpstatus"
if x is not None:
lp.assignVarsVals({v.name: x[v._xprs[0]] for v in lp.variables()})
if djs is not None:
lp.assignVarsDj({v.name: djs[v._xprs[0]] for v in lp.variables()})
if duals is not None:
lp.assignConsPi(
{c.name: duals[c._xprs[0]] for c in lp.constraints.values()}
)
if slacks is not None:
lp.assignConsSlack(
{c.name: slacks[c._xprs[0]] for c in lp.constraints.values()}
)
status = statusmap.get(
model.getAttrib(statuskey), constants.LpStatusUndefined
)
lp.assignStatus(status)
return status
except (xpress.ModelError, xpress.InterfaceError, xpress.SolverError) as err:
raise PulpSolverError(str(err))
| (self, lp) |
38,994 | pulp.apis.xpress_api | getAttribute | Get an arbitrary attribute for the model that was previously
solved using actualSolve(). | def getAttribute(self, lp, which):
"""Get an arbitrary attribute for the model that was previously
solved using actualSolve()."""
return lp.solverModel.getAttrib(which)
| (self, lp, which) |
39,001 | pulp.apis.coin_api | YAPOSIB |
COIN OSI (via its python interface)
Copyright Christophe-Marie Duquesne 2012
The yaposib variables are available (after a solve) in var.solverVar
The yaposib constraints are available in constraint.solverConstraint
The Model is in prob.solverModel
| class YAPOSIB(LpSolver):
"""
COIN OSI (via its python interface)
Copyright Christophe-Marie Duquesne 2012
The yaposib variables are available (after a solve) in var.solverVar
The yaposib constraints are available in constraint.solverConstraint
The Model is in prob.solverModel
"""
name = "YAPOSIB"
try:
# import the model into the global scope
global yaposib
import yaposib
except ImportError:
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("YAPOSIB: Not Available")
else:
def __init__(
self,
mip=True,
msg=True,
timeLimit=None,
epgap=None,
solverName=None,
**solverParams,
):
"""
Initializes the yaposib solver.
@param mip: if False the solver will solve a MIP as
an LP
@param msg: displays information from the solver to
stdout
@param timeLimit: not supported
@param epgap: not supported
@param solverParams: not supported
"""
LpSolver.__init__(self, mip, msg)
if solverName:
self.solverName = solverName
else:
self.solverName = yaposib.available_solvers()[0]
def findSolutionValues(self, lp):
model = lp.solverModel
solutionStatus = model.status
yaposibLpStatus = {
"optimal": constants.LpStatusOptimal,
"undefined": constants.LpStatusUndefined,
"abandoned": constants.LpStatusInfeasible,
"infeasible": constants.LpStatusInfeasible,
"limitreached": constants.LpStatusInfeasible,
}
# populate pulp solution values
for var in lp.variables():
var.varValue = var.solverVar.solution
var.dj = var.solverVar.reducedcost
# put pi and slack variables against the constraints
for constr in lp.constraints.values():
constr.pi = constr.solverConstraint.dual
constr.slack = -constr.constant - constr.solverConstraint.activity
if self.msg:
print("yaposib status=", solutionStatus)
lp.resolveOK = True
for var in lp.variables():
var.isModified = False
status = yaposibLpStatus.get(solutionStatus, constants.LpStatusUndefined)
lp.assignStatus(status)
return status
def available(self):
"""True if the solver is available"""
return True
def callSolver(self, lp, callback=None):
"""Solves the problem with yaposib"""
savestdout = None
if self.msg == 0:
# close stdout to get rid of messages
tempfile = open(mktemp(), "w")
savestdout = os.dup(1)
os.close(1)
if os.dup(tempfile.fileno()) != 1:
raise PulpSolverError("couldn't redirect stdout - dup() error")
self.solveTime = -clock()
lp.solverModel.solve(self.mip)
self.solveTime += clock()
if self.msg == 0:
# reopen stdout
os.close(1)
os.dup(savestdout)
os.close(savestdout)
def buildSolverModel(self, lp):
"""
Takes the pulp lp model and translates it into a yaposib model
"""
log.debug("create the yaposib model")
lp.solverModel = yaposib.Problem(self.solverName)
prob = lp.solverModel
prob.name = lp.name
log.debug("set the sense of the problem")
if lp.sense == constants.LpMaximize:
prob.obj.maximize = True
log.debug("add the variables to the problem")
for var in lp.variables():
col = prob.cols.add(yaposib.vec([]))
col.name = var.name
if not var.lowBound is None:
col.lowerbound = var.lowBound
if not var.upBound is None:
col.upperbound = var.upBound
if var.cat == constants.LpInteger:
col.integer = True
prob.obj[col.index] = lp.objective.get(var, 0.0)
var.solverVar = col
log.debug("add the Constraints to the problem")
for name, constraint in lp.constraints.items():
row = prob.rows.add(
yaposib.vec(
[
(var.solverVar.index, value)
for var, value in constraint.items()
]
)
)
if constraint.sense == constants.LpConstraintLE:
row.upperbound = -constraint.constant
elif constraint.sense == constants.LpConstraintGE:
row.lowerbound = -constraint.constant
elif constraint.sense == constants.LpConstraintEQ:
row.upperbound = -constraint.constant
row.lowerbound = -constraint.constant
else:
raise PulpSolverError("Detected an invalid constraint type")
row.name = name
constraint.solverConstraint = row
def actualSolve(self, lp, callback=None):
"""
Solve a well formulated lp problem
creates a yaposib 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 yaposib")
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 yaposib")
for constraint in lp.constraints.values():
row = constraint.solverConstraint
if constraint.modified:
if constraint.sense == constants.LpConstraintLE:
row.upperbound = -constraint.constant
elif constraint.sense == constants.LpConstraintGE:
row.lowerbound = -constraint.constant
elif constraint.sense == constants.LpConstraintEQ:
row.upperbound = -constraint.constant
row.lowerbound = -constraint.constant
else:
raise PulpSolverError("Detected an invalid constraint type")
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) |
39,004 | pulp.apis.coin_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp, callback=None):
"""Solve a well formulated lp problem"""
raise PulpSolverError("YAPOSIB: Not Available")
| (self, lp, callback=None) |
39,013 | pulp.utilities | allcombinations |
returns all combinations of orgset with up to k items
:param orgset: the list to be iterated
:param k: the maxcardinality of the subsets
:return: an iterator of the subsets
example:
>>> c = allcombinations([1,2,3,4],2)
>>> for s in c:
... print(s)
(1,)
(2,)
(3,)
(4,)
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
| def allcombinations(orgset, k):
"""
returns all combinations of orgset with up to k items
:param orgset: the list to be iterated
:param k: the maxcardinality of the subsets
:return: an iterator of the subsets
example:
>>> c = allcombinations([1,2,3,4],2)
>>> for s in c:
... print(s)
(1,)
(2,)
(3,)
(4,)
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
"""
return itertools.chain(*[combination(orgset, i) for i in range(1, k + 1)])
| (orgset, k) |
39,014 | pulp.utilities | allpermutations |
returns all permutations of orgset with up to k items
:param orgset: the list to be iterated
:param k: the maxcardinality of the subsets
:return: an iterator of the subsets
example:
>>> c = allpermutations([1,2,3,4],2)
>>> for s in c:
... print(s)
(1,)
(2,)
(3,)
(4,)
(1, 2)
(1, 3)
(1, 4)
(2, 1)
(2, 3)
(2, 4)
(3, 1)
(3, 2)
(3, 4)
(4, 1)
(4, 2)
(4, 3)
| def allpermutations(orgset, k):
"""
returns all permutations of orgset with up to k items
:param orgset: the list to be iterated
:param k: the maxcardinality of the subsets
:return: an iterator of the subsets
example:
>>> c = allpermutations([1,2,3,4],2)
>>> for s in c:
... print(s)
(1,)
(2,)
(3,)
(4,)
(1, 2)
(1, 3)
(1, 4)
(2, 1)
(2, 3)
(2, 4)
(3, 1)
(3, 2)
(3, 4)
(4, 1)
(4, 2)
(4, 3)
"""
return itertools.chain(*[permutation(orgset, i) for i in range(1, k + 1)])
| (orgset, k) |
39,019 | itertools | combinations | Return successive r-length combinations of elements in the iterable.
combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3) | from itertools import combinations
| (iterable, r) |
39,020 | pulp.apis | configSolvers |
Configure the path the the solvers on the command line
Designed to configure the file locations of the solvers from the
command line after installation
| def configSolvers():
"""
Configure the path the the solvers on the command line
Designed to configure the file locations of the solvers from the
command line after installation
"""
configlist = [
(cplex_dll_path, "cplexpath", "CPLEX: "),
(coinMP_path, "coinmppath", "CoinMP dll (windows only): "),
]
print(
"Please type the full path including filename and extension \n"
+ "for each solver available"
)
configdict = {}
for default, key, msg in configlist:
value = input(msg + "[" + str(default) + "]")
if value:
configdict[key] = value
setConfigInformation(**configdict)
| () |
39,025 | pulp.apis.copt_api | <lambda> | null | coptstr = lambda x: bytes(x, "utf-8")
| (x) |
39,029 | pulp.apis.core | ctypesArrayFill |
Creates a c array with ctypes from a python list
type is the type of the c array
| def ctypesArrayFill(myList, type=ctypes.c_double):
"""
Creates a c array with ctypes from a python list
type is the type of the c array
"""
ctype = type * len(myList)
cList = ctype()
for i, elem in enumerate(myList):
cList[i] = elem
return cList
| (myList, type=<class 'ctypes.c_double'>) |
39,030 | pulp.apis | getSolver |
Instantiates a solver from its name
:param str solver: solver name to create
:param args: additional arguments to the solver
:param kwargs: additional keyword arguments to the solver
:return: solver of type :py:class:`LpSolver`
| def getSolver(solver, *args, **kwargs):
"""
Instantiates a solver from its name
:param str solver: solver name to create
:param args: additional arguments to the solver
:param kwargs: additional keyword arguments to the solver
:return: solver of type :py:class:`LpSolver`
"""
mapping = {k.name: k for k in _all_solvers}
try:
return mapping[solver](*args, **kwargs)
except KeyError:
raise PulpSolverError(
"The solver {} does not exist in PuLP.\nPossible options are: \n{}".format(
solver, mapping.keys()
)
)
| (solver, *args, **kwargs) |
39,031 | pulp.apis | getSolverFromDict |
Instantiates a solver from a dictionary with its data
:param dict data: a dictionary with, at least an "solver" key with the name
of the solver to create
:return: a solver of type :py:class:`LpSolver`
:raises PulpSolverError: if the dictionary does not have the "solver" key
:rtype: LpSolver
| def getSolverFromDict(data):
"""
Instantiates a solver from a dictionary with its data
:param dict data: a dictionary with, at least an "solver" key with the name
of the solver to create
:return: a solver of type :py:class:`LpSolver`
:raises PulpSolverError: if the dictionary does not have the "solver" key
:rtype: LpSolver
"""
solver = data.pop("solver", None)
if solver is None:
raise PulpSolverError("The json file has no solver attribute.")
return getSolver(solver, **data)
| (data) |
39,032 | pulp.apis | getSolverFromJson |
Instantiates a solver from a json file with its data
:param str filename: name of the json file to read
:return: a solver of type :py:class:`LpSolver`
:rtype: LpSolver
| def getSolverFromJson(filename):
"""
Instantiates a solver from a json file with its data
:param str filename: name of the json file to read
:return: a solver of type :py:class:`LpSolver`
:rtype: LpSolver
"""
with open(filename) as f:
data = json.load(f)
return getSolverFromDict(data)
| (filename) |
39,036 | pulp.apis.core | initialize | reads the configuration file to initialise the module | def initialize(filename, operating_system="linux", arch="64"):
"""reads the configuration file to initialise the module"""
here = os.path.dirname(filename)
config = Parser({"here": here, "os": operating_system, "arch": arch})
config.read(filename)
try:
cplex_dll_path = config.get("locations", "CplexPath")
except configparser.Error:
cplex_dll_path = "libcplex110.so"
try:
try:
ilm_cplex_license = (
config.get("licenses", "ilm_cplex_license")
.decode("string-escape")
.replace('"', "")
)
except AttributeError:
ilm_cplex_license = config.get("licenses", "ilm_cplex_license").replace(
'"', ""
)
except configparser.Error:
ilm_cplex_license = ""
try:
ilm_cplex_license_signature = config.getint(
"licenses", "ilm_cplex_license_signature"
)
except configparser.Error:
ilm_cplex_license_signature = 0
try:
coinMP_path = config.get("locations", "CoinMPPath").split(", ")
except configparser.Error:
coinMP_path = ["libCoinMP.so"]
try:
gurobi_path = config.get("locations", "GurobiPath")
except configparser.Error:
gurobi_path = "/opt/gurobi201/linux32/lib/python2.5"
try:
cbc_path = config.get("locations", "CbcPath")
except configparser.Error:
cbc_path = "cbc"
try:
glpk_path = config.get("locations", "GlpkPath")
except configparser.Error:
glpk_path = "glpsol"
try:
pulp_cbc_path = config.get("locations", "PulpCbcPath")
except configparser.Error:
pulp_cbc_path = "cbc"
try:
scip_path = config.get("locations", "ScipPath")
except configparser.Error:
scip_path = "scip"
try:
fscip_path = config.get("locations", "FscipPath")
except configparser.Error:
fscip_path = "fscip"
for i, path in enumerate(coinMP_path):
if not os.path.dirname(path):
# if no pathname is supplied assume the file is in the same directory
coinMP_path[i] = os.path.join(os.path.dirname(config_filename), path)
return (
cplex_dll_path,
ilm_cplex_license,
ilm_cplex_license_signature,
coinMP_path,
gurobi_path,
cbc_path,
glpk_path,
pulp_cbc_path,
scip_path,
fscip_path,
)
| (filename, operating_system='linux', arch='64') |
39,037 | pulp.utilities | isNumber | Returns true if x is an int or a float | def isNumber(x):
"""Returns true if x is an int or a float"""
return isinstance(x, (int, float))
| (x) |
39,038 | pulp.constants | isiterable | null | def isiterable(obj):
try:
obj = iter(obj)
except:
return False
else:
return True
| (obj) |
39,041 | pulp.apis | listSolvers |
List the names of all the existing solvers in PuLP
:param bool onlyAvailable: if True, only show the available solvers
:return: list of solver names
:rtype: list
| def listSolvers(onlyAvailable=False):
"""
List the names of all the existing solvers in PuLP
:param bool onlyAvailable: if True, only show the available solvers
:return: list of solver names
:rtype: list
"""
result = []
for s in _all_solvers:
solver = s()
if (not onlyAvailable) or solver.available():
result.append(solver.name)
del solver
return result
| (onlyAvailable=False) |
39,043 | pulp.pulp | lpDot | Calculate the dot product of two lists of linear expressions | def lpDot(v1, v2):
"""Calculate the dot product of two lists of linear expressions"""
if not const.isiterable(v1) and not const.isiterable(v2):
return v1 * v2
elif not const.isiterable(v1):
return lpDot([v1] * len(v2), v2)
elif not const.isiterable(v2):
return lpDot(v1, [v2] * len(v1))
else:
return lpSum([lpDot(e1, e2) for e1, e2 in zip(v1, v2)])
| (v1, v2) |
39,044 | pulp.pulp | lpSum |
Calculate the sum of a list of linear expressions
:param vector: A list of linear expressions
| def lpSum(vector):
"""
Calculate the sum of a list of linear expressions
:param vector: A list of linear expressions
"""
return LpAffineExpression().addInPlace(vector)
| (vector) |
39,045 | pulp.utilities | makeDict |
makes a list into a dictionary with the headings given in headings
headers is a list of header lists
array is a list with the data
| def makeDict(headers, array, default=None):
"""
makes a list into a dictionary with the headings given in headings
headers is a list of header lists
array is a list with the data
"""
result, defdict = __makeDict(headers, array, default)
return result
| (headers, array, default=None) |
39,047 | tempfile | mktemp | User-callable function to return a unique temporary file name. The
file is not created.
Arguments are similar to mkstemp, except that the 'text' argument is
not accepted, and suffix=None, prefix=None and bytes file names are not
supported.
THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may
refer to a file that did not exist at some point, but by the time
you get around to creating it, someone else may have beaten you to
the punch.
| def mktemp(suffix="", prefix=template, dir=None):
"""User-callable function to return a unique temporary file name. The
file is not created.
Arguments are similar to mkstemp, except that the 'text' argument is
not accepted, and suffix=None, prefix=None and bytes file names are not
supported.
THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may
refer to a file that did not exist at some point, but by the time
you get around to creating it, someone else may have beaten you to
the punch.
"""
## from warnings import warn as _warn
## _warn("mktemp is a potential security risk to your program",
## RuntimeWarning, stacklevel=2)
if dir is None:
dir = gettempdir()
names = _get_candidate_names()
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.join(dir, prefix + name + suffix)
if not _exists(file):
return file
raise FileExistsError(_errno.EEXIST,
"No usable temporary filename found")
| (suffix='', prefix='tmp', dir=None) |
39,053 | itertools | permutations | Return successive r-length permutations of elements in the iterable.
permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1) | from itertools import permutations
| (iterable, r=None) |
39,056 | pulp.tests.run_tests | pulpTestAll | null | def pulpTestAll(test_docs=False):
runner = unittest.TextTestRunner()
suite_all = get_test_suite(test_docs)
# we run all tests at the same time
ret = runner.run(suite_all)
if not ret.wasSuccessful():
raise pulp.PulpError("Tests Failed")
| (test_docs=False) |
39,058 | pulp.utilities | read_table |
Reads in data from a simple table and forces it to be a particular type
This is a helper function that allows data to be easily constained in a
simple script
::return: a dictionary of with the keys being a tuple of the strings
in the first row and colum of the table
::param data: the multiline string containing the table data
::param coerce_type: the type that the table data is converted to
::param transpose: reverses the data if needed
Example:
>>> table_data = '''
... L1 L2 L3 L4 L5 L6
... C1 6736 42658 70414 45170 184679 111569
... C2 217266 227190 249640 203029 153531 117487
... C3 35936 28768 126316 2498 130317 74034
... C4 73446 52077 108368 75011 49827 62850
... C5 174664 177461 151589 153300 59916 135162
... C6 186302 189099 147026 164938 149836 286307
... '''
>>> table = read_table(table_data, int)
>>> table[("C1","L1")]
6736
>>> table[("C6","L5")]
149836
| def read_table(data, coerce_type, transpose=False):
"""
Reads in data from a simple table and forces it to be a particular type
This is a helper function that allows data to be easily constained in a
simple script
::return: a dictionary of with the keys being a tuple of the strings
in the first row and colum of the table
::param data: the multiline string containing the table data
::param coerce_type: the type that the table data is converted to
::param transpose: reverses the data if needed
Example:
>>> table_data = '''
... L1 L2 L3 L4 L5 L6
... C1 6736 42658 70414 45170 184679 111569
... C2 217266 227190 249640 203029 153531 117487
... C3 35936 28768 126316 2498 130317 74034
... C4 73446 52077 108368 75011 49827 62850
... C5 174664 177461 151589 153300 59916 135162
... C6 186302 189099 147026 164938 149836 286307
... '''
>>> table = read_table(table_data, int)
>>> table[("C1","L1")]
6736
>>> table[("C6","L5")]
149836
"""
lines = data.splitlines()
headings = lines[1].split()
result = {}
for row in lines[2:]:
items = row.split()
for i, item in enumerate(items[1:]):
if transpose:
key = (headings[i], items[0])
else:
key = (items[0], headings[i])
result[key] = coerce_type(item)
return result
| (data, coerce_type, transpose=False) |
39,059 | pulp.utilities | resource_clock | null | def resource_clock():
import resource
return resource.getrusage(resource.RUSAGE_CHILDREN).ru_utime
| () |
39,061 | pulp.apis | setConfigInformation |
set the data in the configuration file
at the moment will only edit things in [locations]
the keyword value pairs come from the keywords dictionary
| def setConfigInformation(**keywords):
"""
set the data in the configuration file
at the moment will only edit things in [locations]
the keyword value pairs come from the keywords dictionary
"""
# TODO: extend if we ever add another section in the config file
# read the old configuration
config = Parser()
config.read(config_filename)
# set the new keys
for key, val in keywords.items():
config.set("locations", key, val)
# write the new configuration
fp = open(config_filename, "w")
config.write(fp)
fp.close()
| (**keywords) |
39,064 | pulp.utilities | splitDict |
Split a dictionary with lists as the data, into smaller dictionaries
:param data: A dictionary with lists as the values
:return: A tuple of dictionaries each containing the data separately,
with the same dictionary keys
| def splitDict(data):
"""
Split a dictionary with lists as the data, into smaller dictionaries
:param data: A dictionary with lists as the values
:return: A tuple of dictionaries each containing the data separately,
with the same dictionary keys
"""
# find the maximum number of items in the dictionary
maxitems = max([len(values) for values in data.values()])
output = [dict() for _ in range(maxitems)]
for key, values in data.items():
for i, val in enumerate(values):
output[i][key] = val
return tuple(output)
| (data) |
39,068 | pulp.apis.core | <lambda> | null | to_string = lambda _obj: str(_obj).encode()
| (_obj) |
39,071 | pulp.utilities | value | Returns the value of the variable/expression x, or x if it is a number | def value(x):
"""Returns the value of the variable/expression x, or x if it is a number"""
if isNumber(x):
return x
else:
return x.value()
| (x) |
39,072 | pulp.utilities | valueOrDefault | Returns the value of the variable/expression x, or x if it is a number
Variable without value (None) are affected a possible value (within their
bounds). | def valueOrDefault(x):
"""Returns the value of the variable/expression x, or x if it is a number
Variable without value (None) are affected a possible value (within their
bounds)."""
if isNumber(x):
return x
else:
return x.valueOrDefault()
| (x) |
39,075 | htmldocx.h2d | HtmlToDocx | null | class HtmlToDocx(HTMLParser):
def __init__(self):
super().__init__()
self.options = {
'fix-html': True,
'images': True,
'tables': True,
'styles': True,
}
self.table_row_selectors = [
'table > tr',
'table > thead > tr',
'table > tbody > tr',
'table > tfoot > tr'
]
self.table_style = DEFAULT_TABLE_STYLE
def set_initial_attrs(self, document=None):
self.tags = {
'span': [],
'list': [],
}
if document:
self.doc = document
else:
self.doc = Document()
self.bs = self.options['fix-html'] # whether or not to clean with BeautifulSoup
self.document = self.doc
self.include_tables = True #TODO add this option back in?
self.include_images = self.options['images']
self.include_styles = self.options['styles']
self.paragraph = None
self.skip = False
self.skip_tag = None
self.instances_to_skip = 0
def copy_settings_from(self, other):
"""Copy settings from another instance of HtmlToDocx"""
self.table_style = other.table_style
def get_cell_html(self, soup):
# Returns string of td element with opening and closing <td> tags removed
# Cannot use find_all as it only finds element tags and does not find text which
# is not inside an element
return ' '.join([str(i) for i in soup.contents])
def add_styles_to_paragraph(self, style):
if 'text-align' in style:
align = style['text-align']
if align == 'center':
self.paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
elif align == 'right':
self.paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.RIGHT
elif align == 'justify':
self.paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
if 'margin-left' in style:
margin = style['margin-left']
units = re.sub(r'[0-9]+', '', margin)
margin = int(float(re.sub(r'[a-z]+', '', margin)))
if units == 'px':
self.paragraph.paragraph_format.left_indent = Inches(min(margin // 10 * INDENT, MAX_INDENT))
# TODO handle non px units
def add_styles_to_run(self, style):
if 'color' in style:
if 'rgb' in style['color']:
color = re.sub(r'[a-z()]+', '', style['color'])
colors = [int(x) for x in color.split(',')]
elif '#' in style['color']:
color = style['color'].lstrip('#')
colors = tuple(int(color[i:i+2], 16) for i in (0, 2, 4))
else:
colors = [0, 0, 0]
# TODO map colors to named colors (and extended colors...)
# For now set color to black to prevent crashing
self.run.font.color.rgb = RGBColor(*colors)
if 'background-color' in style:
if 'rgb' in style['background-color']:
color = color = re.sub(r'[a-z()]+', '', style['background-color'])
colors = [int(x) for x in color.split(',')]
elif '#' in style['background-color']:
color = style['background-color'].lstrip('#')
colors = tuple(int(color[i:i+2], 16) for i in (0, 2, 4))
else:
colors = [0, 0, 0]
# TODO map colors to named colors (and extended colors...)
# For now set color to black to prevent crashing
self.run.font.highlight_color = WD_COLOR.GRAY_25 #TODO: map colors
def parse_dict_string(self, string, separator=';'):
new_string = string.replace(" ", '').split(separator)
string_dict = dict([x.split(':') for x in new_string if ':' in x])
return string_dict
def handle_li(self):
# check list stack to determine style and depth
list_depth = len(self.tags['list'])
if list_depth:
list_type = self.tags['list'][-1]
else:
list_type = 'ul' # assign unordered if no tag
if list_type == 'ol':
list_style = styles['LIST_NUMBER']
else:
list_style = styles['LIST_BULLET']
self.paragraph = self.doc.add_paragraph(style=list_style)
self.paragraph.paragraph_format.left_indent = Inches(min(list_depth * LIST_INDENT, MAX_INDENT))
self.paragraph.paragraph_format.line_spacing = 1
def add_image_to_cell(self, cell, image):
# python-docx doesn't have method yet for adding images to table cells. For now we use this
paragraph = cell.add_paragraph()
run = paragraph.add_run()
run.add_picture(image)
def handle_img(self, current_attrs):
if not self.include_images:
self.skip = True
self.skip_tag = 'img'
return
src = current_attrs['src']
# fetch image
src_is_url = is_url(src)
if src_is_url:
try:
image = fetch_image(src)
except urllib.error.URLError:
image = None
else:
image = src
# add image to doc
if image:
try:
if isinstance(self.doc, docx.document.Document):
self.doc.add_picture(image)
else:
self.add_image_to_cell(self.doc, image)
except FileNotFoundError:
image = None
if not image:
if src_is_url:
self.doc.add_paragraph("<image: %s>" % src)
else:
# avoid exposing filepaths in document
self.doc.add_paragraph("<image: %s>" % get_filename_from_url(src))
# add styles?
def handle_table(self):
"""
To handle nested tables, we will parse tables manually as follows:
Get table soup
Create docx table
Iterate over soup and fill docx table with new instances of this parser
Tell HTMLParser to ignore any tags until the corresponding closing table tag
"""
table_soup = self.tables[self.table_no]
rows, cols = self.get_table_dimensions(table_soup)
self.table = self.doc.add_table(rows, cols)
if self.table_style:
try:
self.table.style = self.table_style
except KeyError as e:
raise ValueError(f"Unable to apply style {self.table_style}.") from e
rows = self.get_table_rows(table_soup)
cell_row = 0
for row in rows:
cols = self.get_table_columns(row)
cell_col = 0
for col in cols:
cell_html = self.get_cell_html(col)
if col.name == 'th':
cell_html = "<b>%s</b>" % cell_html
docx_cell = self.table.cell(cell_row, cell_col)
child_parser = HtmlToDocx()
child_parser.copy_settings_from(self)
child_parser.add_html_to_cell(cell_html, docx_cell)
cell_col += 1
cell_row += 1
# skip all tags until corresponding closing tag
self.instances_to_skip = len(table_soup.find_all('table'))
self.skip_tag = 'table'
self.skip = True
self.table = None
def handle_link(self, href, text):
# Link requires a relationship
is_external = href.startswith('http')
rel_id = self.paragraph.part.relate_to(
href,
docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK,
is_external=True # don't support anchor links for this library yet
)
# Create the w:hyperlink tag and add needed values
hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
hyperlink.set(docx.oxml.shared.qn('r:id'), rel_id)
# Create sub-run
subrun = self.paragraph.add_run()
rPr = docx.oxml.shared.OxmlElement('w:rPr')
# add default color
c = docx.oxml.shared.OxmlElement('w:color')
c.set(docx.oxml.shared.qn('w:val'), "0000EE")
rPr.append(c)
# add underline
u = docx.oxml.shared.OxmlElement('w:u')
u.set(docx.oxml.shared.qn('w:val'), 'single')
rPr.append(u)
subrun._r.append(rPr)
subrun._r.text = text
# Add subrun to hyperlink
hyperlink.append(subrun._r)
# Add hyperlink to run
self.paragraph._p.append(hyperlink)
def handle_starttag(self, tag, attrs):
if self.skip:
return
if tag == 'head':
self.skip = True
self.skip_tag = tag
self.instances_to_skip = 0
return
elif tag == 'body':
return
current_attrs = dict(attrs)
if tag == 'span':
self.tags['span'].append(current_attrs)
return
elif tag == 'ol' or tag == 'ul':
self.tags['list'].append(tag)
return # don't apply styles for now
elif tag == 'br':
self.run.add_break()
return
self.tags[tag] = current_attrs
if tag in ['p', 'pre']:
self.paragraph = self.doc.add_paragraph()
elif tag == 'li':
self.handle_li()
elif tag == "hr":
# This implementation was taken from:
# https://github.com/python-openxml/python-docx/issues/105#issuecomment-62806373
self.paragraph = self.doc.add_paragraph()
pPr = self.paragraph._p.get_or_add_pPr()
pBdr = OxmlElement('w:pBdr')
pPr.insert_element_before(pBdr,
'w:shd', 'w:tabs', 'w:suppressAutoHyphens', 'w:kinsoku', 'w:wordWrap',
'w:overflowPunct', 'w:topLinePunct', 'w:autoSpaceDE', 'w:autoSpaceDN',
'w:bidi', 'w:adjustRightInd', 'w:snapToGrid', 'w:spacing', 'w:ind',
'w:contextualSpacing', 'w:mirrorIndents', 'w:suppressOverlap', 'w:jc',
'w:textDirection', 'w:textAlignment', 'w:textboxTightWrap',
'w:outlineLvl', 'w:divId', 'w:cnfStyle', 'w:rPr', 'w:sectPr',
'w:pPrChange'
)
bottom = OxmlElement('w:bottom')
bottom.set(qn('w:val'), 'single')
bottom.set(qn('w:sz'), '6')
bottom.set(qn('w:space'), '1')
bottom.set(qn('w:color'), 'auto')
pBdr.append(bottom)
elif re.match('h[1-9]', tag):
if isinstance(self.doc, docx.document.Document):
h_size = int(tag[1])
self.paragraph = self.doc.add_heading(level=min(h_size, 9))
else:
self.paragraph = self.doc.add_paragraph()
elif tag == 'img':
self.handle_img(current_attrs)
return
elif tag == 'table':
self.handle_table()
return
# set new run reference point in case of leading line breaks
if tag in ['p', 'li', 'pre']:
self.run = self.paragraph.add_run()
# add style
if not self.include_styles:
return
if 'style' in current_attrs and self.paragraph:
style = self.parse_dict_string(current_attrs['style'])
self.add_styles_to_paragraph(style)
def handle_endtag(self, tag):
if self.skip:
if not tag == self.skip_tag:
return
if self.instances_to_skip > 0:
self.instances_to_skip -= 1
return
self.skip = False
self.skip_tag = None
self.paragraph = None
if tag == 'span':
if self.tags['span']:
self.tags['span'].pop()
return
elif tag == 'ol' or tag == 'ul':
remove_last_occurence(self.tags['list'], tag)
return
elif tag == 'table':
self.table_no += 1
self.table = None
self.doc = self.document
self.paragraph = None
if tag in self.tags:
self.tags.pop(tag)
# maybe set relevant reference to None?
def handle_data(self, data):
if self.skip:
return
# Only remove white space if we're not in a pre block.
if 'pre' not in self.tags:
# remove leading and trailing whitespace in all instances
data = remove_whitespace(data, True, True)
if not self.paragraph:
self.paragraph = self.doc.add_paragraph()
# There can only be one nested link in a valid html document
# You cannot have interactive content in an A tag, this includes links
# https://html.spec.whatwg.org/#interactive-content
link = self.tags.get('a')
if link:
self.handle_link(link['href'], data)
else:
# If there's a link, dont put the data directly in the run
self.run = self.paragraph.add_run(data)
spans = self.tags['span']
for span in spans:
if 'style' in span:
style = self.parse_dict_string(span['style'])
self.add_styles_to_run(style)
# add font style and name
for tag in self.tags:
if tag in font_styles:
font_style = font_styles[tag]
setattr(self.run.font, font_style, True)
if tag in font_names:
font_name = font_names[tag]
self.run.font.name = font_name
def ignore_nested_tables(self, tables_soup):
"""
Returns array containing only the highest level tables
Operates on the assumption that bs4 returns child elements immediately after
the parent element in `find_all`. If this changes in the future, this method will need to be updated
:return:
"""
new_tables = []
nest = 0
for table in tables_soup:
if nest:
nest -= 1
continue
new_tables.append(table)
nest = len(table.find_all('table'))
return new_tables
def get_table_rows(self, table_soup):
# If there's a header, body, footer or direct child tr tags, add row dimensions from there
return table_soup.select(', '.join(self.table_row_selectors), recursive=False)
def get_table_columns(self, row):
# Get all columns for the specified row tag.
return row.find_all(['th', 'td'], recursive=False) if row else []
def get_table_dimensions(self, table_soup):
# Get rows for the table
rows = self.get_table_rows(table_soup)
# Table is either empty or has non-direct children between table and tr tags
# Thus the row dimensions and column dimensions are assumed to be 0
cols = self.get_table_columns(rows[0]) if rows else []
return len(rows), len(cols)
def get_tables(self):
if not hasattr(self, 'soup'):
self.include_tables = False
return
# find other way to do it, or require this dependency?
self.tables = self.ignore_nested_tables(self.soup.find_all('table'))
self.table_no = 0
def run_process(self, html):
if self.bs and BeautifulSoup:
self.soup = BeautifulSoup(html, 'html.parser')
html = str(self.soup)
if self.include_tables:
self.get_tables()
self.feed(html)
def add_html_to_document(self, html, document):
if not isinstance(html, str):
raise ValueError('First argument needs to be a %s' % str)
elif not isinstance(document, docx.document.Document) and not isinstance(document, docx.table._Cell):
raise ValueError('Second argument needs to be a %s' % docx.document.Document)
self.set_initial_attrs(document)
self.run_process(html)
def add_html_to_cell(self, html, cell):
if not isinstance(cell, docx.table._Cell):
raise ValueError('Second argument needs to be a %s' % docx.table._Cell)
unwanted_paragraph = cell.paragraphs[0]
delete_paragraph(unwanted_paragraph)
self.set_initial_attrs(cell)
self.run_process(html)
# cells must end with a paragraph or will get message about corrupt file
# https://stackoverflow.com/a/29287121
if not self.doc.paragraphs:
self.doc.add_paragraph('')
def parse_html_file(self, filename_html, filename_docx=None):
with open(filename_html, 'r') as infile:
html = infile.read()
self.set_initial_attrs()
self.run_process(html)
if not filename_docx:
path, filename = os.path.split(filename_html)
filename_docx = '%s/new_docx_file_%s' % (path, filename)
self.doc.save('%s.docx' % filename_docx)
def parse_html_string(self, html):
self.set_initial_attrs()
self.run_process(html)
return self.doc
| () |
39,076 | htmldocx.h2d | __init__ | null | def __init__(self):
super().__init__()
self.options = {
'fix-html': True,
'images': True,
'tables': True,
'styles': True,
}
self.table_row_selectors = [
'table > tr',
'table > thead > tr',
'table > tbody > tr',
'table > tfoot > tr'
]
self.table_style = DEFAULT_TABLE_STYLE
| (self) |
39,083 | htmldocx.h2d | add_html_to_cell | null | def add_html_to_cell(self, html, cell):
if not isinstance(cell, docx.table._Cell):
raise ValueError('Second argument needs to be a %s' % docx.table._Cell)
unwanted_paragraph = cell.paragraphs[0]
delete_paragraph(unwanted_paragraph)
self.set_initial_attrs(cell)
self.run_process(html)
# cells must end with a paragraph or will get message about corrupt file
# https://stackoverflow.com/a/29287121
if not self.doc.paragraphs:
self.doc.add_paragraph('')
| (self, html, cell) |
39,084 | htmldocx.h2d | add_html_to_document | null | def add_html_to_document(self, html, document):
if not isinstance(html, str):
raise ValueError('First argument needs to be a %s' % str)
elif not isinstance(document, docx.document.Document) and not isinstance(document, docx.table._Cell):
raise ValueError('Second argument needs to be a %s' % docx.document.Document)
self.set_initial_attrs(document)
self.run_process(html)
| (self, html, document) |
39,085 | htmldocx.h2d | add_image_to_cell | null | def add_image_to_cell(self, cell, image):
# python-docx doesn't have method yet for adding images to table cells. For now we use this
paragraph = cell.add_paragraph()
run = paragraph.add_run()
run.add_picture(image)
| (self, cell, image) |
39,086 | htmldocx.h2d | add_styles_to_paragraph | null | def add_styles_to_paragraph(self, style):
if 'text-align' in style:
align = style['text-align']
if align == 'center':
self.paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
elif align == 'right':
self.paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.RIGHT
elif align == 'justify':
self.paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
if 'margin-left' in style:
margin = style['margin-left']
units = re.sub(r'[0-9]+', '', margin)
margin = int(float(re.sub(r'[a-z]+', '', margin)))
if units == 'px':
self.paragraph.paragraph_format.left_indent = Inches(min(margin // 10 * INDENT, MAX_INDENT))
# TODO handle non px units
| (self, style) |
39,087 | htmldocx.h2d | add_styles_to_run | null | def add_styles_to_run(self, style):
if 'color' in style:
if 'rgb' in style['color']:
color = re.sub(r'[a-z()]+', '', style['color'])
colors = [int(x) for x in color.split(',')]
elif '#' in style['color']:
color = style['color'].lstrip('#')
colors = tuple(int(color[i:i+2], 16) for i in (0, 2, 4))
else:
colors = [0, 0, 0]
# TODO map colors to named colors (and extended colors...)
# For now set color to black to prevent crashing
self.run.font.color.rgb = RGBColor(*colors)
if 'background-color' in style:
if 'rgb' in style['background-color']:
color = color = re.sub(r'[a-z()]+', '', style['background-color'])
colors = [int(x) for x in color.split(',')]
elif '#' in style['background-color']:
color = style['background-color'].lstrip('#')
colors = tuple(int(color[i:i+2], 16) for i in (0, 2, 4))
else:
colors = [0, 0, 0]
# TODO map colors to named colors (and extended colors...)
# For now set color to black to prevent crashing
self.run.font.highlight_color = WD_COLOR.GRAY_25 #TODO: map colors
| (self, style) |
39,091 | htmldocx.h2d | copy_settings_from | Copy settings from another instance of HtmlToDocx | def copy_settings_from(self, other):
"""Copy settings from another instance of HtmlToDocx"""
self.table_style = other.table_style
| (self, other) |
39,093 | htmldocx.h2d | get_cell_html | null | def get_cell_html(self, soup):
# Returns string of td element with opening and closing <td> tags removed
# Cannot use find_all as it only finds element tags and does not find text which
# is not inside an element
return ' '.join([str(i) for i in soup.contents])
| (self, soup) |
39,095 | htmldocx.h2d | get_table_columns | null | def get_table_columns(self, row):
# Get all columns for the specified row tag.
return row.find_all(['th', 'td'], recursive=False) if row else []
| (self, row) |
39,096 | htmldocx.h2d | get_table_dimensions | null | def get_table_dimensions(self, table_soup):
# Get rows for the table
rows = self.get_table_rows(table_soup)
# Table is either empty or has non-direct children between table and tr tags
# Thus the row dimensions and column dimensions are assumed to be 0
cols = self.get_table_columns(rows[0]) if rows else []
return len(rows), len(cols)
| (self, table_soup) |
39,097 | htmldocx.h2d | get_table_rows | null | def get_table_rows(self, table_soup):
# If there's a header, body, footer or direct child tr tags, add row dimensions from there
return table_soup.select(', '.join(self.table_row_selectors), recursive=False)
| (self, table_soup) |
39,098 | htmldocx.h2d | get_tables | null | def get_tables(self):
if not hasattr(self, 'soup'):
self.include_tables = False
return
# find other way to do it, or require this dependency?
self.tables = self.ignore_nested_tables(self.soup.find_all('table'))
self.table_no = 0
| (self) |
39,103 | htmldocx.h2d | handle_data | null | def handle_data(self, data):
if self.skip:
return
# Only remove white space if we're not in a pre block.
if 'pre' not in self.tags:
# remove leading and trailing whitespace in all instances
data = remove_whitespace(data, True, True)
if not self.paragraph:
self.paragraph = self.doc.add_paragraph()
# There can only be one nested link in a valid html document
# You cannot have interactive content in an A tag, this includes links
# https://html.spec.whatwg.org/#interactive-content
link = self.tags.get('a')
if link:
self.handle_link(link['href'], data)
else:
# If there's a link, dont put the data directly in the run
self.run = self.paragraph.add_run(data)
spans = self.tags['span']
for span in spans:
if 'style' in span:
style = self.parse_dict_string(span['style'])
self.add_styles_to_run(style)
# add font style and name
for tag in self.tags:
if tag in font_styles:
font_style = font_styles[tag]
setattr(self.run.font, font_style, True)
if tag in font_names:
font_name = font_names[tag]
self.run.font.name = font_name
| (self, data) |
39,105 | htmldocx.h2d | handle_endtag | null | def handle_endtag(self, tag):
if self.skip:
if not tag == self.skip_tag:
return
if self.instances_to_skip > 0:
self.instances_to_skip -= 1
return
self.skip = False
self.skip_tag = None
self.paragraph = None
if tag == 'span':
if self.tags['span']:
self.tags['span'].pop()
return
elif tag == 'ol' or tag == 'ul':
remove_last_occurence(self.tags['list'], tag)
return
elif tag == 'table':
self.table_no += 1
self.table = None
self.doc = self.document
self.paragraph = None
if tag in self.tags:
self.tags.pop(tag)
# maybe set relevant reference to None?
| (self, tag) |
39,107 | htmldocx.h2d | handle_img | null | def handle_img(self, current_attrs):
if not self.include_images:
self.skip = True
self.skip_tag = 'img'
return
src = current_attrs['src']
# fetch image
src_is_url = is_url(src)
if src_is_url:
try:
image = fetch_image(src)
except urllib.error.URLError:
image = None
else:
image = src
# add image to doc
if image:
try:
if isinstance(self.doc, docx.document.Document):
self.doc.add_picture(image)
else:
self.add_image_to_cell(self.doc, image)
except FileNotFoundError:
image = None
if not image:
if src_is_url:
self.doc.add_paragraph("<image: %s>" % src)
else:
# avoid exposing filepaths in document
self.doc.add_paragraph("<image: %s>" % get_filename_from_url(src))
# add styles?
| (self, current_attrs) |
39,108 | htmldocx.h2d | handle_li | null | def handle_li(self):
# check list stack to determine style and depth
list_depth = len(self.tags['list'])
if list_depth:
list_type = self.tags['list'][-1]
else:
list_type = 'ul' # assign unordered if no tag
if list_type == 'ol':
list_style = styles['LIST_NUMBER']
else:
list_style = styles['LIST_BULLET']
self.paragraph = self.doc.add_paragraph(style=list_style)
self.paragraph.paragraph_format.left_indent = Inches(min(list_depth * LIST_INDENT, MAX_INDENT))
self.paragraph.paragraph_format.line_spacing = 1
| (self) |
39,109 | htmldocx.h2d | handle_link | null | def handle_link(self, href, text):
# Link requires a relationship
is_external = href.startswith('http')
rel_id = self.paragraph.part.relate_to(
href,
docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK,
is_external=True # don't support anchor links for this library yet
)
# Create the w:hyperlink tag and add needed values
hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
hyperlink.set(docx.oxml.shared.qn('r:id'), rel_id)
# Create sub-run
subrun = self.paragraph.add_run()
rPr = docx.oxml.shared.OxmlElement('w:rPr')
# add default color
c = docx.oxml.shared.OxmlElement('w:color')
c.set(docx.oxml.shared.qn('w:val'), "0000EE")
rPr.append(c)
# add underline
u = docx.oxml.shared.OxmlElement('w:u')
u.set(docx.oxml.shared.qn('w:val'), 'single')
rPr.append(u)
subrun._r.append(rPr)
subrun._r.text = text
# Add subrun to hyperlink
hyperlink.append(subrun._r)
# Add hyperlink to run
self.paragraph._p.append(hyperlink)
| (self, href, text) |
39,112 | htmldocx.h2d | handle_starttag | null | def handle_starttag(self, tag, attrs):
if self.skip:
return
if tag == 'head':
self.skip = True
self.skip_tag = tag
self.instances_to_skip = 0
return
elif tag == 'body':
return
current_attrs = dict(attrs)
if tag == 'span':
self.tags['span'].append(current_attrs)
return
elif tag == 'ol' or tag == 'ul':
self.tags['list'].append(tag)
return # don't apply styles for now
elif tag == 'br':
self.run.add_break()
return
self.tags[tag] = current_attrs
if tag in ['p', 'pre']:
self.paragraph = self.doc.add_paragraph()
elif tag == 'li':
self.handle_li()
elif tag == "hr":
# This implementation was taken from:
# https://github.com/python-openxml/python-docx/issues/105#issuecomment-62806373
self.paragraph = self.doc.add_paragraph()
pPr = self.paragraph._p.get_or_add_pPr()
pBdr = OxmlElement('w:pBdr')
pPr.insert_element_before(pBdr,
'w:shd', 'w:tabs', 'w:suppressAutoHyphens', 'w:kinsoku', 'w:wordWrap',
'w:overflowPunct', 'w:topLinePunct', 'w:autoSpaceDE', 'w:autoSpaceDN',
'w:bidi', 'w:adjustRightInd', 'w:snapToGrid', 'w:spacing', 'w:ind',
'w:contextualSpacing', 'w:mirrorIndents', 'w:suppressOverlap', 'w:jc',
'w:textDirection', 'w:textAlignment', 'w:textboxTightWrap',
'w:outlineLvl', 'w:divId', 'w:cnfStyle', 'w:rPr', 'w:sectPr',
'w:pPrChange'
)
bottom = OxmlElement('w:bottom')
bottom.set(qn('w:val'), 'single')
bottom.set(qn('w:sz'), '6')
bottom.set(qn('w:space'), '1')
bottom.set(qn('w:color'), 'auto')
pBdr.append(bottom)
elif re.match('h[1-9]', tag):
if isinstance(self.doc, docx.document.Document):
h_size = int(tag[1])
self.paragraph = self.doc.add_heading(level=min(h_size, 9))
else:
self.paragraph = self.doc.add_paragraph()
elif tag == 'img':
self.handle_img(current_attrs)
return
elif tag == 'table':
self.handle_table()
return
# set new run reference point in case of leading line breaks
if tag in ['p', 'li', 'pre']:
self.run = self.paragraph.add_run()
# add style
if not self.include_styles:
return
if 'style' in current_attrs and self.paragraph:
style = self.parse_dict_string(current_attrs['style'])
self.add_styles_to_paragraph(style)
| (self, tag, attrs) |
39,113 | htmldocx.h2d | handle_table |
To handle nested tables, we will parse tables manually as follows:
Get table soup
Create docx table
Iterate over soup and fill docx table with new instances of this parser
Tell HTMLParser to ignore any tags until the corresponding closing table tag
| def handle_table(self):
"""
To handle nested tables, we will parse tables manually as follows:
Get table soup
Create docx table
Iterate over soup and fill docx table with new instances of this parser
Tell HTMLParser to ignore any tags until the corresponding closing table tag
"""
table_soup = self.tables[self.table_no]
rows, cols = self.get_table_dimensions(table_soup)
self.table = self.doc.add_table(rows, cols)
if self.table_style:
try:
self.table.style = self.table_style
except KeyError as e:
raise ValueError(f"Unable to apply style {self.table_style}.") from e
rows = self.get_table_rows(table_soup)
cell_row = 0
for row in rows:
cols = self.get_table_columns(row)
cell_col = 0
for col in cols:
cell_html = self.get_cell_html(col)
if col.name == 'th':
cell_html = "<b>%s</b>" % cell_html
docx_cell = self.table.cell(cell_row, cell_col)
child_parser = HtmlToDocx()
child_parser.copy_settings_from(self)
child_parser.add_html_to_cell(cell_html, docx_cell)
cell_col += 1
cell_row += 1
# skip all tags until corresponding closing tag
self.instances_to_skip = len(table_soup.find_all('table'))
self.skip_tag = 'table'
self.skip = True
self.table = None
| (self) |
39,114 | htmldocx.h2d | ignore_nested_tables |
Returns array containing only the highest level tables
Operates on the assumption that bs4 returns child elements immediately after
the parent element in `find_all`. If this changes in the future, this method will need to be updated
:return:
| def ignore_nested_tables(self, tables_soup):
"""
Returns array containing only the highest level tables
Operates on the assumption that bs4 returns child elements immediately after
the parent element in `find_all`. If this changes in the future, this method will need to be updated
:return:
"""
new_tables = []
nest = 0
for table in tables_soup:
if nest:
nest -= 1
continue
new_tables.append(table)
nest = len(table.find_all('table'))
return new_tables
| (self, tables_soup) |
39,118 | htmldocx.h2d | parse_dict_string | null | def parse_dict_string(self, string, separator=';'):
new_string = string.replace(" ", '').split(separator)
string_dict = dict([x.split(':') for x in new_string if ':' in x])
return string_dict
| (self, string, separator=';') |
39,121 | htmldocx.h2d | parse_html_file | null | def parse_html_file(self, filename_html, filename_docx=None):
with open(filename_html, 'r') as infile:
html = infile.read()
self.set_initial_attrs()
self.run_process(html)
if not filename_docx:
path, filename = os.path.split(filename_html)
filename_docx = '%s/new_docx_file_%s' % (path, filename)
self.doc.save('%s.docx' % filename_docx)
| (self, filename_html, filename_docx=None) |
39,122 | htmldocx.h2d | parse_html_string | null | def parse_html_string(self, html):
self.set_initial_attrs()
self.run_process(html)
return self.doc
| (self, html) |
39,127 | htmldocx.h2d | run_process | null | def run_process(self, html):
if self.bs and BeautifulSoup:
self.soup = BeautifulSoup(html, 'html.parser')
html = str(self.soup)
if self.include_tables:
self.get_tables()
self.feed(html)
| (self, html) |
39,129 | htmldocx.h2d | set_initial_attrs | null | def set_initial_attrs(self, document=None):
self.tags = {
'span': [],
'list': [],
}
if document:
self.doc = document
else:
self.doc = Document()
self.bs = self.options['fix-html'] # whether or not to clean with BeautifulSoup
self.document = self.doc
self.include_tables = True #TODO add this option back in?
self.include_images = self.options['images']
self.include_styles = self.options['styles']
self.paragraph = None
self.skip = False
self.skip_tag = None
self.instances_to_skip = 0
| (self, document=None) |
39,134 | click_plugins.core | with_plugins |
A decorator to register external CLI commands to an instance of
`click.Group()`.
Parameters
----------
plugins : iter
An iterable producing one `pkg_resources.EntryPoint()` per iteration.
attrs : **kwargs, optional
Additional keyword arguments for instantiating `click.Group()`.
Returns
-------
click.Group()
| def with_plugins(plugins):
"""
A decorator to register external CLI commands to an instance of
`click.Group()`.
Parameters
----------
plugins : iter
An iterable producing one `pkg_resources.EntryPoint()` per iteration.
attrs : **kwargs, optional
Additional keyword arguments for instantiating `click.Group()`.
Returns
-------
click.Group()
"""
def decorator(group):
if not isinstance(group, click.Group):
raise TypeError("Plugins can only be attached to an instance of click.Group()")
for entry_point in plugins or ():
try:
group.add_command(entry_point.load())
except Exception:
# Catch this so a busted plugin doesn't take down the CLI.
# Handled by registering a dummy command that does nothing
# other than explain the error.
group.add_command(BrokenCommand(entry_point.name))
return group
return decorator
| (plugins) |
39,135 | astunparse.printer | Printer | null | class Printer(ast.NodeVisitor):
def __init__(self, file=sys.stdout, indent=" "):
self.indentation = 0
self.indent_with = indent
self.f = file
# overridden to make the API obvious
def visit(self, node):
super(Printer, self).visit(node)
def write(self, text):
self.f.write(six.text_type(text))
def generic_visit(self, node):
if isinstance(node, list):
nodestart = "["
nodeend = "]"
children = [("", child) for child in node]
else:
nodestart = type(node).__name__ + "("
nodeend = ")"
children = [(name + "=", value) for name, value in ast.iter_fields(node)]
if len(children) > 1:
self.indentation += 1
self.write(nodestart)
for i, pair in enumerate(children):
attr, child = pair
if len(children) > 1:
self.write("\n" + self.indent_with * self.indentation)
if isinstance(child, (ast.AST, list)):
self.write(attr)
self.visit(child)
else:
self.write(attr + repr(child))
if i != len(children) - 1:
self.write(",")
self.write(nodeend)
if len(children) > 1:
self.indentation -= 1
| (file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, indent=' ') |
39,136 | astunparse.printer | __init__ | null | def __init__(self, file=sys.stdout, indent=" "):
self.indentation = 0
self.indent_with = indent
self.f = file
| (self, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, indent=' ') |
39,137 | astunparse.printer | generic_visit | null | def generic_visit(self, node):
if isinstance(node, list):
nodestart = "["
nodeend = "]"
children = [("", child) for child in node]
else:
nodestart = type(node).__name__ + "("
nodeend = ")"
children = [(name + "=", value) for name, value in ast.iter_fields(node)]
if len(children) > 1:
self.indentation += 1
self.write(nodestart)
for i, pair in enumerate(children):
attr, child = pair
if len(children) > 1:
self.write("\n" + self.indent_with * self.indentation)
if isinstance(child, (ast.AST, list)):
self.write(attr)
self.visit(child)
else:
self.write(attr + repr(child))
if i != len(children) - 1:
self.write(",")
self.write(nodeend)
if len(children) > 1:
self.indentation -= 1
| (self, node) |
39,138 | astunparse.printer | visit | null | def visit(self, node):
super(Printer, self).visit(node)
| (self, node) |
39,139 | ast | visit_Constant | null | def visit_Constant(self, node):
value = node.value
type_name = _const_node_type_names.get(type(value))
if type_name is None:
for cls, name in _const_node_type_names.items():
if isinstance(value, cls):
type_name = name
break
if type_name is not None:
method = 'visit_' + type_name
try:
visitor = getattr(self, method)
except AttributeError:
pass
else:
import warnings
warnings.warn(f"{method} is deprecated; add visit_Constant",
DeprecationWarning, 2)
return visitor(node)
return self.generic_visit(node)
| (self, node) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.