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
⌀ |
---|---|---|---|---|---|
37,948 | justdays.day | __gt__ | null | def __gt__(self, other) -> bool:
return str(self) > str(other)
| (self, other) -> bool |
37,949 | justdays.day | __hash__ | null | def __hash__(self):
return hash(self.str)
| (self) |
37,950 | justdays.day | __init__ | Day can be intialized with: | def __init__(self, *args):
"""Day can be intialized with:"""
if len(args) == 3:
"""Three arguments: year, month, day"""
dt = datetime(*args)
elif len(args) == 2: # year, week
"""Two arguments: year, week. Day with be the Monday of that week"""
dt = datetime.strptime(f"{args[0]} {args[1]} 1", "%Y %W %w")
elif len(args) == 0:
"""No arguments: today"""
dt = datetime.today()
elif isinstance(args[0], str):
"""One argument: string in format YYYY-MM-DD"""
y, m, d = args[0].split("-")
dt = datetime(int(y), int(m), int(d))
elif isinstance(args[0], (date, datetime)):
"""One argument: datetime or date"""
dt = args[0]
else:
raise f"Invalid type passed to Day class: {args[0]} with type {type(args[0])}"
self.str = dt.strftime(DATE_FORMAT)
self.d, self.m, self.y = dt.day, dt.month, dt.year
| (self, *args) |
37,951 | justdays.day | __le__ | null | def __le__(self, other) -> bool:
return str(self) <= str(other)
| (self, other) -> bool |
37,952 | justdays.day | __lt__ | null | def __lt__(self, other) -> bool:
return str(self) < str(other)
| (self, other) -> bool |
37,953 | justdays.day | __radd__ | null | def __radd__(self, other):
if type(other) == int:
return self.plus_days(other)
elif type(other) == str:
return other + str(self)
else:
raise TypeError(f"Cannot add Day to {type(other)}")
| (self, other) |
37,954 | justdays.day | __repr__ | null | def __repr__(self) -> str:
return f"Day({self.str})"
| (self) -> str |
37,955 | justdays.day | __str__ | null | def __str__(self) -> str:
return self.str
| (self) -> str |
37,956 | justdays.day | __sub__ | Days can be substracted from each other
Or you can subtstract a number to go back as many days | def __sub__(self, other) -> int | Day:
""" Days can be substracted from each other
Or you can subtstract a number to go back as many days """
if type(other) == Day:
return (self.as_datetime() - other.as_datetime()).days
elif type(other) == int:
return self.plus_days(-other)
else:
raise TypeError(f"Cannot substract {type(other)} from Day")
| (self, other) -> int | justdays.day.Day |
37,957 | justdays.day | as_date | null | def as_date(self) -> date:
return date(self.y, self.m, self.d)
| (self) -> datetime.date |
37,958 | justdays.day | as_datetime | null | def as_datetime(self) -> datetime:
return datetime(self.y, self.m, self.d)
| (self) -> datetime.datetime |
37,959 | justdays.day | as_unix_timestamp | Returns the unix timestamp of the day | def as_unix_timestamp(self) -> int:
"""Returns the unix timestamp of the day"""
return int(self.as_datetime().timestamp())
| (self) -> int |
37,960 | justdays.day | day_of_week | Return day of the week, where Monday == 0 ... Sunday == 6. | def day_of_week(self) -> int:
"""Return day of the week, where Monday == 0 ... Sunday == 6."""
return self.as_datetime().weekday()
| (self) -> int |
37,961 | justdays.day | day_of_year | Day of the year is a number between 1 and 365/366, January 1st is day 1 | def day_of_year(self) -> int:
"""Day of the year is a number between 1 and 365/366, January 1st is day 1"""
return self.as_datetime().timetuple().tm_yday
| (self) -> int |
37,962 | justdays.day | fraction_of_the_year_past | Returns a fraction of how much of the year is past including the current day | def fraction_of_the_year_past(self) -> float:
"""Returns a fraction of how much of the year is past including the current day"""
is_leap_year = self.y % 4 == 0 and (self.y % 100 != 0 or self.y % 400 == 0)
return self.day_of_year() / (366 if is_leap_year else 365)
| (self) -> float |
37,963 | justdays.day | is_weekday | Returns True if day is a weekday (Monday to Friday) | def is_weekday(self) -> bool:
"""Returns True if day is a weekday (Monday to Friday)"""
return self.as_datetime().weekday() < 5
| (self) -> bool |
37,964 | justdays.day | is_weekend | Returns True of day is a Saturday or Sunday. | def is_weekend(self) -> bool:
"""Returns True of day is a Saturday or Sunday."""
return self.as_datetime().weekday() >= 5
| (self) -> bool |
37,965 | justdays.day | last_day_of_month | Returns the last day of the month | def last_day_of_month(self) -> Day:
"""Returns the last day of the month"""
return Day(self.y, self.m, calendar.monthrange(self.y, self.m)[1])
| (self) -> justdays.day.Day |
37,966 | justdays.day | last_monday | Returns the last day that was a Monday or the day itself if it is a Monday | def last_monday(self) -> Day:
"""Returns the last day that was a Monday or the day itself if it is a Monday"""
return self.plus_days(-self.as_datetime().weekday())
| (self) -> justdays.day.Day |
37,967 | justdays.day | next | Returns the next day | def next(self) -> Day:
"""Returns the next day"""
return self.plus_days(1)
| (self) -> justdays.day.Day |
37,968 | justdays.day | next_weekday | Returns the first day in the future that is on a weekday | def next_weekday(self) -> Day:
"""Returns the first day in the future that is on a weekday"""
day = self.plus_days(1)
while day.day_of_week() >= 5:
day = day.plus_days(1)
return day
| (self) -> justdays.day.Day |
37,969 | justdays.day | plus_days | Returns a new Day object increment days further in the future | def plus_days(self, increment) -> Day:
"""Returns a new Day object increment days further in the future"""
return Day(self.as_datetime() + timedelta(days=increment))
| (self, increment) -> justdays.day.Day |
37,970 | justdays.day | plus_months | Returns a new Day object increment months further in the future | def plus_months(self, increment) -> Day:
"""Returns a new Day object increment months further in the future"""
return Day(
self.as_datetime() + relativedelta(months=increment)
) # relativedelta
| (self, increment) -> justdays.day.Day |
37,971 | justdays.day | plus_weeks | Returns a new Day object increment weeks further in the future | def plus_weeks(self, increment) -> Day:
"""Returns a new Day object increment weeks further in the future"""
return Day(self.as_datetime() + relativedelta(weeks=increment)) # relativedelta
| (self, increment) -> justdays.day.Day |
37,972 | justdays.day | prev | Return the previous day | def prev(self) -> Day:
"""Return the previous day"""
return self.plus_days(-1)
| (self) -> justdays.day.Day |
37,973 | justdays.day | previous_weekday | Returns the first day in the future that is on a weekday | def previous_weekday(self) -> Day:
"""Returns the first day in the future that is on a weekday"""
day = self.plus_days(-1)
while day.day_of_week() >= 5:
day = day.plus_days(-1)
return day
| (self) -> justdays.day.Day |
37,974 | justdays.day | strftime | Works just like the strftime from datetime | def strftime(self, date_format: str) -> str:
"""Works just like the strftime from datetime"""
return self.as_datetime().strftime(date_format)
| (self, date_format: str) -> str |
37,975 | justdays.day | week_number | Return the week number of the year. | def week_number(self) -> int:
"""Return the week number of the year."""
if sys.version_info[1] >= 9:
return self.as_datetime().isocalendar().week
return self.as_datetime().isocalendar()[1]
| (self) -> int |
37,976 | justdays.period | Period | Bundles a startdate and optionally an end date to form a date range | class Period:
"""Bundles a startdate and optionally an end date to form a date range"""
def __init__(self, fromday, untilday=None):
"""Period is initalized with a startdate and optionally an end date
Start date can be a Day object or a string in the format 'YYYY-MM-DD'"""
if not isinstance(fromday, Day):
fromday = Day(fromday)
self.fromday = fromday
if untilday and not isinstance(untilday, Day):
untilday = Day(untilday)
self.untilday = untilday
self.current = fromday.prev() # Initialize iterator
@classmethod
def from_week(cls, year, weekno):
"""Returns a Period object for the week of the year"""
fromday = Day(year, weekno)
untilday = fromday.plus_weeks(1)
return cls(fromday, untilday)
@classmethod
def from_month(cls, year, month):
"""Returns a Period object for the month of the year"""
fromday = Day(year, month, 1)
untilday = fromday.plus_months(1)
return cls(fromday, untilday)
def __str__(self) -> str:
return f'{self.fromday} --> {self.untilday if self.untilday else ""}'
def __repr__(self) -> str:
return f"Period({str(self)})"
def __hash__(self):
return hash(str(self))
def __iter__(self) -> Period:
return self
def __next__(self) -> Day:
self.current = self.current.next()
if self.current >= self.untilday:
self.current = self.fromday.prev()
raise StopIteration
return self.current
def __contains__(self, other: Day | Period) -> bool:
if type(other) == Day:
return self.fromday <= other < self.untilday
elif type(other) == Period:
if not self.untilday:
return self.fromday <= other.fromday
if not other.untilday:
return False
return self.fromday <= other.fromday < self.untilday and self.fromday <= other.untilday < self.untilday
raise TypeError(f"Invalid type passed to Period.__contains__: {type(other)}")
def __len__(self) -> int:
return self.untilday - self.fromday
def __eq__(self, other) -> bool:
return self.fromday == other.fromday and self.untilday == other.untilday
| (fromday, untilday=None) |
37,977 | justdays.period | __contains__ | null | def __contains__(self, other: Day | Period) -> bool:
if type(other) == Day:
return self.fromday <= other < self.untilday
elif type(other) == Period:
if not self.untilday:
return self.fromday <= other.fromday
if not other.untilday:
return False
return self.fromday <= other.fromday < self.untilday and self.fromday <= other.untilday < self.untilday
raise TypeError(f"Invalid type passed to Period.__contains__: {type(other)}")
| (self, other: justdays.day.Day | justdays.period.Period) -> bool |
37,978 | justdays.period | __eq__ | null | def __eq__(self, other) -> bool:
return self.fromday == other.fromday and self.untilday == other.untilday
| (self, other) -> bool |
37,979 | justdays.period | __hash__ | null | def __hash__(self):
return hash(str(self))
| (self) |
37,980 | justdays.period | __init__ | Period is initalized with a startdate and optionally an end date
Start date can be a Day object or a string in the format 'YYYY-MM-DD' | def __init__(self, fromday, untilday=None):
"""Period is initalized with a startdate and optionally an end date
Start date can be a Day object or a string in the format 'YYYY-MM-DD'"""
if not isinstance(fromday, Day):
fromday = Day(fromday)
self.fromday = fromday
if untilday and not isinstance(untilday, Day):
untilday = Day(untilday)
self.untilday = untilday
self.current = fromday.prev() # Initialize iterator
| (self, fromday, untilday=None) |
37,981 | justdays.period | __iter__ | null | def __iter__(self) -> Period:
return self
| (self) -> justdays.period.Period |
37,982 | justdays.period | __len__ | null | def __len__(self) -> int:
return self.untilday - self.fromday
| (self) -> int |
37,983 | justdays.period | __next__ | null | def __next__(self) -> Day:
self.current = self.current.next()
if self.current >= self.untilday:
self.current = self.fromday.prev()
raise StopIteration
return self.current
| (self) -> justdays.day.Day |
37,984 | justdays.period | __repr__ | null | def __repr__(self) -> str:
return f"Period({str(self)})"
| (self) -> str |
37,985 | justdays.period | __str__ | null | def __str__(self) -> str:
return f'{self.fromday} --> {self.untilday if self.untilday else ""}'
| (self) -> str |
37,988 | pulp.apis.choco_api | CHOCO_CMD | The CHOCO_CMD solver | class CHOCO_CMD(LpSolver_CMD):
"""The CHOCO_CMD solver"""
name = "CHOCO_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("choco-parsers-with-dependencies.jar")
def available(self):
"""True if the solver is available"""
java_path = self.executableExtension("java")
return self.executable(self.path) and self.executable(java_path)
def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
java_path = self.executableExtension("java")
if not self.executable(java_path):
raise PulpSolverError(
"PuLP: java needs to be installed and accesible in order to use CHOCO_CMD"
)
if not os.path.exists(self.path):
raise PulpSolverError("PuLP: cannot execute " + self.path)
tmpMps, tmpLp, tmpSol = self.create_tmp_files(lp.name, "mps", "lp", "sol")
# just to report duplicated variables:
lp.checkDuplicateVars()
lp.writeMPS(tmpMps, mpsSense=lp.sense)
try:
os.remove(tmpSol)
except:
pass
cmd = java_path + ' -cp "' + self.path + '" org.chocosolver.parser.mps.ChocoMPS'
if self.timeLimit is not None:
cmd += f" -tl {self.timeLimit}" * 1000
cmd += " " + " ".join([f"{key} {value}" for key, value in self.options])
cmd += f" {tmpMps}"
if lp.sense == constants.LpMaximize:
cmd += " -max"
if lp.isMIP():
if not self.mip:
warnings.warn("CHOCO_CMD cannot solve the relaxation of a problem")
# we always get the output to a file.
# if not, we cannot read it afterwards
# (we thus ignore the self.msg parameter)
pipe = open(tmpSol, "w")
return_code = subprocess.call(cmd, stdout=pipe, stderr=pipe, shell=True)
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, tmpLp, 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 Choco solution file"""
# TODO: figure out the unbounded status in choco solver
chocoStatus = {
"OPTIMUM FOUND": constants.LpStatusOptimal,
"SATISFIABLE": constants.LpStatusOptimal,
"UNSATISFIABLE": constants.LpStatusInfeasible,
"UNKNOWN": constants.LpStatusNotSolved,
}
chocoSolStatus = {
"OPTIMUM FOUND": constants.LpSolutionOptimal,
"SATISFIABLE": constants.LpSolutionIntegerFeasible,
"UNSATISFIABLE": constants.LpSolutionInfeasible,
"UNKNOWN": constants.LpSolutionNoSolutionFound,
}
status = constants.LpStatusNotSolved
sol_status = constants.LpSolutionNoSolutionFound
values = {}
with open(filename) as f:
content = f.readlines()
content = [l.strip() for l in content if l[:2] not in ["o ", "c "]]
if not len(content):
return status, values, sol_status
if content[0][:2] == "s ":
status_str = content[0][2:]
status = chocoStatus[status_str]
sol_status = chocoSolStatus[status_str]
for line in content[1:]:
name, value = line.split()
values[name] = float(value)
return status, values, sol_status
| (path=None, keepFiles=False, mip=True, msg=True, options=None, timeLimit=None) |
37,989 | pulp.apis.choco_api | __init__ |
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param float timeLimit: maximum time for solver (in seconds)
:param 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
| 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,
)
| (self, path=None, keepFiles=False, mip=True, msg=True, options=None, timeLimit=None) |
37,990 | pulp.apis.core | actualResolve |
uses existing problem information and solves the problem
If it is not implemented in the solver
just solve again
| def actualResolve(self, lp, **kwargs):
"""
uses existing problem information and solves the problem
If it is not implemented in the solver
just solve again
"""
self.actualSolve(lp, **kwargs)
| (self, lp, **kwargs) |
37,991 | pulp.apis.choco_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
java_path = self.executableExtension("java")
if not self.executable(java_path):
raise PulpSolverError(
"PuLP: java needs to be installed and accesible in order to use CHOCO_CMD"
)
if not os.path.exists(self.path):
raise PulpSolverError("PuLP: cannot execute " + self.path)
tmpMps, tmpLp, tmpSol = self.create_tmp_files(lp.name, "mps", "lp", "sol")
# just to report duplicated variables:
lp.checkDuplicateVars()
lp.writeMPS(tmpMps, mpsSense=lp.sense)
try:
os.remove(tmpSol)
except:
pass
cmd = java_path + ' -cp "' + self.path + '" org.chocosolver.parser.mps.ChocoMPS'
if self.timeLimit is not None:
cmd += f" -tl {self.timeLimit}" * 1000
cmd += " " + " ".join([f"{key} {value}" for key, value in self.options])
cmd += f" {tmpMps}"
if lp.sense == constants.LpMaximize:
cmd += " -max"
if lp.isMIP():
if not self.mip:
warnings.warn("CHOCO_CMD cannot solve the relaxation of a problem")
# we always get the output to a file.
# if not, we cannot read it afterwards
# (we thus ignore the self.msg parameter)
pipe = open(tmpSol, "w")
return_code = subprocess.call(cmd, stdout=pipe, stderr=pipe, shell=True)
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, tmpLp, tmpSol)
lp.assignStatus(status, status_sol)
if status not in [constants.LpStatusInfeasible, constants.LpStatusNotSolved]:
lp.assignVarsVals(values)
return status
| (self, lp) |
37,992 | pulp.apis.choco_api | available | True if the solver is available | def available(self):
"""True if the solver is available"""
java_path = self.executableExtension("java")
return self.executable(self.path) and self.executable(java_path)
| (self) |
37,993 | pulp.apis.core | copy | Make a copy of self | def copy(self):
"""Make a copy of self"""
aCopy = LpSolver.copy(self)
aCopy.path = self.path
aCopy.keepFiles = self.keepFiles
aCopy.tmpDir = self.tmpDir
return aCopy
| (self) |
37,994 | pulp.apis.core | create_tmp_files | null | def create_tmp_files(self, name, *args):
if self.keepFiles:
prefix = name
else:
prefix = os.path.join(self.tmpDir, uuid4().hex)
return (f"{prefix}-pulp.{n}" for n in args)
| (self, name, *args) |
37,995 | pulp.apis.choco_api | defaultPath | null | def defaultPath(self):
return self.executableExtension("choco-parsers-with-dependencies.jar")
| (self) |
37,996 | pulp.apis.core | delete_tmp_files | null | def delete_tmp_files(self, *args):
if self.keepFiles:
return
for file in args:
self.silent_remove(file)
| (self, *args) |
37,997 | pulp.apis.core | executable | Checks that the solver command is executable,
And returns the actual path to it. | @staticmethod
def executable(command):
"""Checks that the solver command is executable,
And returns the actual path to it."""
return shutil.which(command)
| (command) |
37,998 | pulp.apis.core | executableExtension | null | @staticmethod
def executableExtension(name):
if os.name != "nt":
return name
else:
return name + ".exe"
| (name) |
37,999 | pulp.apis.core | getCplexStyleArrays | returns the arrays suitable to pass to a cdll Cplex
or other solvers that are similar
Copyright (c) Stuart Mitchell 2007
| def getCplexStyleArrays(
self, lp, senseDict=None, LpVarCategories=None, LpObjSenses=None, infBound=1e20
):
"""returns the arrays suitable to pass to a cdll Cplex
or other solvers that are similar
Copyright (c) Stuart Mitchell 2007
"""
if senseDict is None:
senseDict = {
const.LpConstraintEQ: "E",
const.LpConstraintLE: "L",
const.LpConstraintGE: "G",
}
if LpVarCategories is None:
LpVarCategories = {const.LpContinuous: "C", const.LpInteger: "I"}
if LpObjSenses is None:
LpObjSenses = {const.LpMaximize: -1, const.LpMinimize: 1}
import ctypes
rangeCount = 0
variables = list(lp.variables())
numVars = len(variables)
# associate each variable with a ordinal
self.v2n = {variables[i]: i for i in range(numVars)}
self.vname2n = {variables[i].name: i for i in range(numVars)}
self.n2v = {i: variables[i] for i in range(numVars)}
# objective values
objSense = LpObjSenses[lp.sense]
NumVarDoubleArray = ctypes.c_double * numVars
objectCoeffs = NumVarDoubleArray()
# print "Get objective Values"
for v, val in lp.objective.items():
objectCoeffs[self.v2n[v]] = val
# values for variables
objectConst = ctypes.c_double(0.0)
NumVarStrArray = ctypes.c_char_p * numVars
colNames = NumVarStrArray()
lowerBounds = NumVarDoubleArray()
upperBounds = NumVarDoubleArray()
initValues = NumVarDoubleArray()
for v in lp.variables():
colNames[self.v2n[v]] = to_string(v.name)
initValues[self.v2n[v]] = 0.0
if v.lowBound != None:
lowerBounds[self.v2n[v]] = v.lowBound
else:
lowerBounds[self.v2n[v]] = -infBound
if v.upBound != None:
upperBounds[self.v2n[v]] = v.upBound
else:
upperBounds[self.v2n[v]] = infBound
# values for constraints
numRows = len(lp.constraints)
NumRowDoubleArray = ctypes.c_double * numRows
NumRowStrArray = ctypes.c_char_p * numRows
NumRowCharArray = ctypes.c_char * numRows
rhsValues = NumRowDoubleArray()
rangeValues = NumRowDoubleArray()
rowNames = NumRowStrArray()
rowType = NumRowCharArray()
self.c2n = {}
self.n2c = {}
i = 0
for c in lp.constraints:
rhsValues[i] = -lp.constraints[c].constant
# for ranged constraints a<= constraint >=b
rangeValues[i] = 0.0
rowNames[i] = to_string(c)
rowType[i] = to_string(senseDict[lp.constraints[c].sense])
self.c2n[c] = i
self.n2c[i] = c
i = i + 1
# return the coefficient matrix as a series of vectors
coeffs = lp.coefficients()
sparseMatrix = sparse.Matrix(list(range(numRows)), list(range(numVars)))
for var, row, coeff in coeffs:
sparseMatrix.add(self.c2n[row], self.vname2n[var], coeff)
(
numels,
mystartsBase,
mylenBase,
myindBase,
myelemBase,
) = sparseMatrix.col_based_arrays()
elemBase = ctypesArrayFill(myelemBase, ctypes.c_double)
indBase = ctypesArrayFill(myindBase, ctypes.c_int)
startsBase = ctypesArrayFill(mystartsBase, ctypes.c_int)
lenBase = ctypesArrayFill(mylenBase, ctypes.c_int)
# MIP Variables
NumVarCharArray = ctypes.c_char * numVars
columnType = NumVarCharArray()
if lp.isMIP():
for v in lp.variables():
columnType[self.v2n[v]] = to_string(LpVarCategories[v.cat])
self.addedVars = numVars
self.addedRows = numRows
return (
numVars,
numRows,
numels,
rangeCount,
objSense,
objectCoeffs,
objectConst,
rhsValues,
rangeValues,
rowType,
startsBase,
lenBase,
indBase,
elemBase,
lowerBounds,
upperBounds,
initValues,
colNames,
rowNames,
columnType,
self.n2v,
self.n2c,
)
| (self, lp, senseDict=None, LpVarCategories=None, LpObjSenses=None, infBound=1e+20) |
38,000 | pulp.apis.choco_api | readsol | Read a Choco solution file | @staticmethod
def readsol(filename):
"""Read a Choco solution file"""
# TODO: figure out the unbounded status in choco solver
chocoStatus = {
"OPTIMUM FOUND": constants.LpStatusOptimal,
"SATISFIABLE": constants.LpStatusOptimal,
"UNSATISFIABLE": constants.LpStatusInfeasible,
"UNKNOWN": constants.LpStatusNotSolved,
}
chocoSolStatus = {
"OPTIMUM FOUND": constants.LpSolutionOptimal,
"SATISFIABLE": constants.LpSolutionIntegerFeasible,
"UNSATISFIABLE": constants.LpSolutionInfeasible,
"UNKNOWN": constants.LpSolutionNoSolutionFound,
}
status = constants.LpStatusNotSolved
sol_status = constants.LpSolutionNoSolutionFound
values = {}
with open(filename) as f:
content = f.readlines()
content = [l.strip() for l in content if l[:2] not in ["o ", "c "]]
if not len(content):
return status, values, sol_status
if content[0][:2] == "s ":
status_str = content[0][2:]
status = chocoStatus[status_str]
sol_status = chocoSolStatus[status_str]
for line in content[1:]:
name, value = line.split()
values[name] = float(value)
return status, values, sol_status
| (filename) |
38,001 | pulp.apis.core | setTmpDir | Set the tmpDir attribute to a reasonnable location for a temporary
directory | def setTmpDir(self):
"""Set the tmpDir attribute to a reasonnable location for a temporary
directory"""
if os.name != "nt":
# On unix use /tmp by default
self.tmpDir = os.environ.get("TMPDIR", "/tmp")
self.tmpDir = os.environ.get("TMP", self.tmpDir)
else:
# On Windows use the current directory
self.tmpDir = os.environ.get("TMPDIR", "")
self.tmpDir = os.environ.get("TMP", self.tmpDir)
self.tmpDir = os.environ.get("TEMP", self.tmpDir)
if not os.path.isdir(self.tmpDir):
self.tmpDir = ""
elif not os.access(self.tmpDir, os.F_OK + os.W_OK):
self.tmpDir = ""
| (self) |
38,002 | pulp.apis.core | silent_remove | null | def silent_remove(self, file: Union[str, bytes, os.PathLike]) -> None:
try:
os.remove(file)
except FileNotFoundError:
pass
| (self, file: Union[str, bytes, os.PathLike]) -> NoneType |
38,003 | pulp.apis.core | solve | Solve the problem lp | def solve(self, lp):
"""Solve the problem lp"""
# Always go through the solve method of LpProblem
return lp.solve(self)
| (self, lp) |
38,004 | pulp.apis.core | toDict | null | def toDict(self):
data = dict(solver=self.name)
for k in ["mip", "msg", "keepFiles"]:
try:
data[k] = getattr(self, k)
except AttributeError:
pass
for k in ["timeLimit", "options"]:
# with these ones, we only export if it has some content:
try:
value = getattr(self, k)
if value:
data[k] = value
except AttributeError:
pass
data.update(self.optionsDict)
return data
| (self) |
38,005 | pulp.apis.core | toJson | null | def toJson(self, filename, *args, **kwargs):
with open(filename, "w") as f:
json.dump(self.toDict(), f, *args, **kwargs)
| (self, filename, *args, **kwargs) |
38,008 | pulp.apis.coin_api | COIN_CMD | The COIN CLP/CBC LP solver
now only uses cbc
| class COIN_CMD(LpSolver_CMD):
"""The COIN CLP/CBC LP solver
now only uses cbc
"""
name = "COIN_CMD"
def defaultPath(self):
return self.executableExtension(cbc_path)
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",
maxNodes=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 float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param float gapAbs: absolute gap tolerance for the solver to stop
:param int threads: sets the maximum number of threads
:param list options: list of additional options to pass to solver
:param bool warmStart: if True, the solver will use the current value of variables as a start
:param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
:param str path: path to the solver binary
:param str logPath: path to the log file
:param bool presolve: if True, adds presolve on
:param bool cuts: if True, adds gomory on knapsack on probing on
:param bool strong: if True, adds strong
:param str timeMode: "elapsed": count wall-time to timeLimit; "cpu": count cpu-time
:param int maxNodes: max number of nodes during branching. Stops the solving when reached.
"""
LpSolver_CMD.__init__(
self,
gapRel=gapRel,
mip=mip,
msg=msg,
timeLimit=timeLimit,
presolve=presolve,
cuts=cuts,
strong=strong,
options=options,
warmStart=warmStart,
path=path,
keepFiles=keepFiles,
threads=threads,
gapAbs=gapAbs,
logPath=logPath,
timeMode=timeMode,
maxNodes=maxNodes,
)
def copy(self):
"""Make a copy of self"""
aCopy = LpSolver_CMD.copy(self)
aCopy.optionsDict = self.optionsDict
return aCopy
def actualSolve(self, lp, **kwargs):
"""Solve a well formulated lp problem"""
return self.solve_CBC(lp, **kwargs)
def available(self):
"""True if the solver is available"""
return self.executable(self.path)
def solve_CBC(self, lp, use_mps=True):
"""Solve a MIP problem using CBC"""
if not self.executable(self.path):
raise PulpSolverError(
f"Pulp: cannot execute {self.path} cwd: {os.getcwd()}"
)
tmpLp, tmpMps, tmpSol, tmpMst = self.create_tmp_files(
lp.name, "lp", "mps", "sol", "mst"
)
if use_mps:
vs, variablesNames, constraintsNames, objectiveName = lp.writeMPS(
tmpMps, rename=1
)
cmds = " " + tmpMps + " "
if lp.sense == constants.LpMaximize:
cmds += "-max "
else:
vs = lp.writeLP(tmpLp)
# In the Lp we do not create new variable or constraint names:
variablesNames = {v.name: v.name for v in vs}
constraintsNames = {c: c for c in lp.constraints}
cmds = " " + tmpLp + " "
if self.optionsDict.get("warmStart", False):
self.writesol(tmpMst, lp, vs, variablesNames, constraintsNames)
cmds += f"-mips {tmpMst} "
if self.timeLimit is not None:
cmds += f"-sec {self.timeLimit} "
options = self.options + self.getOptions()
for option in options:
cmds += "-" + option + " "
if self.mip:
cmds += "-branch "
else:
cmds += "-initialSolve "
cmds += "-printingOptions all "
cmds += "-solution " + tmpSol + " "
if self.msg:
pipe = None
else:
pipe = open(os.devnull, "w")
logPath = self.optionsDict.get("logPath")
if logPath:
if self.msg:
warnings.warn(
"`logPath` argument replaces `msg=1`. The output will be redirected to the log file."
)
pipe = open(self.optionsDict["logPath"], "w")
log.debug(self.path + cmds)
args = []
args.append(self.path)
args.extend(cmds[1:].split())
if not self.msg and operating_system == "win":
# Prevent flashing windows if used from a GUI application
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
cbc = subprocess.Popen(
args, stdout=pipe, stderr=pipe, stdin=devnull, startupinfo=startupinfo
)
else:
cbc = subprocess.Popen(args, stdout=pipe, stderr=pipe, stdin=devnull)
if cbc.wait() != 0:
if pipe:
pipe.close()
raise PulpSolverError(
"Pulp: Error while trying to execute, use msg=True for more details"
+ self.path
)
if pipe:
pipe.close()
if not os.path.exists(tmpSol):
raise PulpSolverError("Pulp: Error while executing " + self.path)
(
status,
values,
reducedCosts,
shadowPrices,
slacks,
sol_status,
) = self.readsol_MPS(tmpSol, lp, vs, variablesNames, constraintsNames)
lp.assignVarsVals(values)
lp.assignVarsDj(reducedCosts)
lp.assignConsPi(shadowPrices)
lp.assignConsSlack(slacks, activity=True)
lp.assignStatus(status, sol_status)
self.delete_tmp_files(tmpMps, tmpLp, tmpSol, tmpMst)
return status
def getOptions(self):
params_eq = dict(
gapRel="ratio {}",
gapAbs="allow {}",
threads="threads {}",
presolve="presolve on",
strong="strong {}",
cuts="gomory on knapsack on probing on",
timeMode="timeMode {}",
maxNodes="maxNodes {}",
)
return [
v.format(self.optionsDict[k])
for k, v in params_eq.items()
if self.optionsDict.get(k) is not None
]
def readsol_MPS(
self, filename, lp, vs, variablesNames, constraintsNames, objectiveName=None
):
"""
Read a CBC solution file generated from an mps or lp file (possible different names)
"""
values = {v.name: 0 for v in vs}
reverseVn = {v: k for k, v in variablesNames.items()}
reverseCn = {v: k for k, v in constraintsNames.items()}
reducedCosts = {}
shadowPrices = {}
slacks = {}
status, sol_status = self.get_status(filename)
with open(filename) as f:
for l in f:
if len(l) <= 2:
break
l = l.split()
# incase the solution is infeasible
if l[0] == "**":
l = l[1:]
vn = l[1]
val = l[2]
dj = l[3]
if vn in reverseVn:
values[reverseVn[vn]] = float(val)
reducedCosts[reverseVn[vn]] = float(dj)
if vn in reverseCn:
slacks[reverseCn[vn]] = float(val)
shadowPrices[reverseCn[vn]] = float(dj)
return status, values, reducedCosts, shadowPrices, slacks, sol_status
def writesol(self, filename, lp, vs, variablesNames, constraintsNames):
"""
Writes a CBC solution file generated from an mps / lp file (possible different names)
returns True on success
"""
values = {v.name: v.value() if v.value() is not None else 0 for v in vs}
value_lines = []
value_lines += [
(i, v, values[k], 0) for i, (k, v) in enumerate(variablesNames.items())
]
lines = ["Stopped on time - objective value 0\n"]
lines += ["{:>7} {} {:>15} {:>23}\n".format(*tup) for tup in value_lines]
with open(filename, "w") as f:
f.writelines(lines)
return True
def readsol_LP(self, filename, lp, vs):
"""
Read a CBC solution file generated from an lp (good names)
returns status, values, reducedCosts, shadowPrices, slacks, sol_status
"""
variablesNames = {v.name: v.name for v in vs}
constraintsNames = {c: c for c in lp.constraints}
return self.readsol_MPS(filename, lp, vs, variablesNames, constraintsNames)
def get_status(self, filename):
cbcStatus = {
"Optimal": constants.LpStatusOptimal,
"Infeasible": constants.LpStatusInfeasible,
"Integer": constants.LpStatusInfeasible,
"Unbounded": constants.LpStatusUnbounded,
"Stopped": constants.LpStatusNotSolved,
}
cbcSolStatus = {
"Optimal": constants.LpSolutionOptimal,
"Infeasible": constants.LpSolutionInfeasible,
"Unbounded": constants.LpSolutionUnbounded,
"Stopped": constants.LpSolutionNoSolutionFound,
}
with open(filename) as f:
statusstrs = f.readline().split()
status = cbcStatus.get(statusstrs[0], constants.LpStatusUndefined)
sol_status = cbcSolStatus.get(
statusstrs[0], constants.LpSolutionNoSolutionFound
)
# here we could use some regex expression.
# Not sure what's more desirable
if status == constants.LpStatusNotSolved and len(statusstrs) >= 5:
if statusstrs[4] == "objective":
status = constants.LpStatusOptimal
sol_status = constants.LpSolutionIntegerFeasible
return status, sol_status
| (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', maxNodes=None) |
38,009 | pulp.apis.coin_api | __init__ |
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param float timeLimit: maximum time for solver (in seconds)
:param float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param float gapAbs: absolute gap tolerance for the solver to stop
:param int threads: sets the maximum number of threads
:param list options: list of additional options to pass to solver
:param bool warmStart: if True, the solver will use the current value of variables as a start
:param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
:param str path: path to the solver binary
:param str logPath: path to the log file
:param bool presolve: if True, adds presolve on
:param bool cuts: if True, adds gomory on knapsack on probing on
:param bool strong: if True, adds strong
:param str timeMode: "elapsed": count wall-time to timeLimit; "cpu": count cpu-time
:param int maxNodes: max number of nodes during branching. Stops the solving when reached.
| 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",
maxNodes=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 float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param float gapAbs: absolute gap tolerance for the solver to stop
:param int threads: sets the maximum number of threads
:param list options: list of additional options to pass to solver
:param bool warmStart: if True, the solver will use the current value of variables as a start
:param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
:param str path: path to the solver binary
:param str logPath: path to the log file
:param bool presolve: if True, adds presolve on
:param bool cuts: if True, adds gomory on knapsack on probing on
:param bool strong: if True, adds strong
:param str timeMode: "elapsed": count wall-time to timeLimit; "cpu": count cpu-time
:param int maxNodes: max number of nodes during branching. Stops the solving when reached.
"""
LpSolver_CMD.__init__(
self,
gapRel=gapRel,
mip=mip,
msg=msg,
timeLimit=timeLimit,
presolve=presolve,
cuts=cuts,
strong=strong,
options=options,
warmStart=warmStart,
path=path,
keepFiles=keepFiles,
threads=threads,
gapAbs=gapAbs,
logPath=logPath,
timeMode=timeMode,
maxNodes=maxNodes,
)
| (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', maxNodes=None) |
38,011 | pulp.apis.coin_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp, **kwargs):
"""Solve a well formulated lp problem"""
return self.solve_CBC(lp, **kwargs)
| (self, lp, **kwargs) |
38,012 | pulp.apis.coin_api | available | True if the solver is available | def available(self):
"""True if the solver is available"""
return self.executable(self.path)
| (self) |
38,013 | pulp.apis.coin_api | copy | Make a copy of self | def copy(self):
"""Make a copy of self"""
aCopy = LpSolver_CMD.copy(self)
aCopy.optionsDict = self.optionsDict
return aCopy
| (self) |
38,015 | pulp.apis.coin_api | defaultPath | null | def defaultPath(self):
return self.executableExtension(cbc_path)
| (self) |
38,020 | pulp.apis.coin_api | getOptions | null | def getOptions(self):
params_eq = dict(
gapRel="ratio {}",
gapAbs="allow {}",
threads="threads {}",
presolve="presolve on",
strong="strong {}",
cuts="gomory on knapsack on probing on",
timeMode="timeMode {}",
maxNodes="maxNodes {}",
)
return [
v.format(self.optionsDict[k])
for k, v in params_eq.items()
if self.optionsDict.get(k) is not None
]
| (self) |
38,021 | pulp.apis.coin_api | get_status | null | def get_status(self, filename):
cbcStatus = {
"Optimal": constants.LpStatusOptimal,
"Infeasible": constants.LpStatusInfeasible,
"Integer": constants.LpStatusInfeasible,
"Unbounded": constants.LpStatusUnbounded,
"Stopped": constants.LpStatusNotSolved,
}
cbcSolStatus = {
"Optimal": constants.LpSolutionOptimal,
"Infeasible": constants.LpSolutionInfeasible,
"Unbounded": constants.LpSolutionUnbounded,
"Stopped": constants.LpSolutionNoSolutionFound,
}
with open(filename) as f:
statusstrs = f.readline().split()
status = cbcStatus.get(statusstrs[0], constants.LpStatusUndefined)
sol_status = cbcSolStatus.get(
statusstrs[0], constants.LpSolutionNoSolutionFound
)
# here we could use some regex expression.
# Not sure what's more desirable
if status == constants.LpStatusNotSolved and len(statusstrs) >= 5:
if statusstrs[4] == "objective":
status = constants.LpStatusOptimal
sol_status = constants.LpSolutionIntegerFeasible
return status, sol_status
| (self, filename) |
38,022 | pulp.apis.coin_api | readsol_LP |
Read a CBC solution file generated from an lp (good names)
returns status, values, reducedCosts, shadowPrices, slacks, sol_status
| def readsol_LP(self, filename, lp, vs):
"""
Read a CBC solution file generated from an lp (good names)
returns status, values, reducedCosts, shadowPrices, slacks, sol_status
"""
variablesNames = {v.name: v.name for v in vs}
constraintsNames = {c: c for c in lp.constraints}
return self.readsol_MPS(filename, lp, vs, variablesNames, constraintsNames)
| (self, filename, lp, vs) |
38,023 | pulp.apis.coin_api | readsol_MPS |
Read a CBC solution file generated from an mps or lp file (possible different names)
| def readsol_MPS(
self, filename, lp, vs, variablesNames, constraintsNames, objectiveName=None
):
"""
Read a CBC solution file generated from an mps or lp file (possible different names)
"""
values = {v.name: 0 for v in vs}
reverseVn = {v: k for k, v in variablesNames.items()}
reverseCn = {v: k for k, v in constraintsNames.items()}
reducedCosts = {}
shadowPrices = {}
slacks = {}
status, sol_status = self.get_status(filename)
with open(filename) as f:
for l in f:
if len(l) <= 2:
break
l = l.split()
# incase the solution is infeasible
if l[0] == "**":
l = l[1:]
vn = l[1]
val = l[2]
dj = l[3]
if vn in reverseVn:
values[reverseVn[vn]] = float(val)
reducedCosts[reverseVn[vn]] = float(dj)
if vn in reverseCn:
slacks[reverseCn[vn]] = float(val)
shadowPrices[reverseCn[vn]] = float(dj)
return status, values, reducedCosts, shadowPrices, slacks, sol_status
| (self, filename, lp, vs, variablesNames, constraintsNames, objectiveName=None) |
38,027 | pulp.apis.coin_api | solve_CBC | Solve a MIP problem using CBC | def solve_CBC(self, lp, use_mps=True):
"""Solve a MIP problem using CBC"""
if not self.executable(self.path):
raise PulpSolverError(
f"Pulp: cannot execute {self.path} cwd: {os.getcwd()}"
)
tmpLp, tmpMps, tmpSol, tmpMst = self.create_tmp_files(
lp.name, "lp", "mps", "sol", "mst"
)
if use_mps:
vs, variablesNames, constraintsNames, objectiveName = lp.writeMPS(
tmpMps, rename=1
)
cmds = " " + tmpMps + " "
if lp.sense == constants.LpMaximize:
cmds += "-max "
else:
vs = lp.writeLP(tmpLp)
# In the Lp we do not create new variable or constraint names:
variablesNames = {v.name: v.name for v in vs}
constraintsNames = {c: c for c in lp.constraints}
cmds = " " + tmpLp + " "
if self.optionsDict.get("warmStart", False):
self.writesol(tmpMst, lp, vs, variablesNames, constraintsNames)
cmds += f"-mips {tmpMst} "
if self.timeLimit is not None:
cmds += f"-sec {self.timeLimit} "
options = self.options + self.getOptions()
for option in options:
cmds += "-" + option + " "
if self.mip:
cmds += "-branch "
else:
cmds += "-initialSolve "
cmds += "-printingOptions all "
cmds += "-solution " + tmpSol + " "
if self.msg:
pipe = None
else:
pipe = open(os.devnull, "w")
logPath = self.optionsDict.get("logPath")
if logPath:
if self.msg:
warnings.warn(
"`logPath` argument replaces `msg=1`. The output will be redirected to the log file."
)
pipe = open(self.optionsDict["logPath"], "w")
log.debug(self.path + cmds)
args = []
args.append(self.path)
args.extend(cmds[1:].split())
if not self.msg and operating_system == "win":
# Prevent flashing windows if used from a GUI application
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
cbc = subprocess.Popen(
args, stdout=pipe, stderr=pipe, stdin=devnull, startupinfo=startupinfo
)
else:
cbc = subprocess.Popen(args, stdout=pipe, stderr=pipe, stdin=devnull)
if cbc.wait() != 0:
if pipe:
pipe.close()
raise PulpSolverError(
"Pulp: Error while trying to execute, use msg=True for more details"
+ self.path
)
if pipe:
pipe.close()
if not os.path.exists(tmpSol):
raise PulpSolverError("Pulp: Error while executing " + self.path)
(
status,
values,
reducedCosts,
shadowPrices,
slacks,
sol_status,
) = self.readsol_MPS(tmpSol, lp, vs, variablesNames, constraintsNames)
lp.assignVarsVals(values)
lp.assignVarsDj(reducedCosts)
lp.assignConsPi(shadowPrices)
lp.assignConsSlack(slacks, activity=True)
lp.assignStatus(status, sol_status)
self.delete_tmp_files(tmpMps, tmpLp, tmpSol, tmpMst)
return status
| (self, lp, use_mps=True) |
38,032 | pulp.apis.coin_api | writesol |
Writes a CBC solution file generated from an mps / lp file (possible different names)
returns True on success
| def writesol(self, filename, lp, vs, variablesNames, constraintsNames):
"""
Writes a CBC solution file generated from an mps / lp file (possible different names)
returns True on success
"""
values = {v.name: v.value() if v.value() is not None else 0 for v in vs}
value_lines = []
value_lines += [
(i, v, values[k], 0) for i, (k, v) in enumerate(variablesNames.items())
]
lines = ["Stopped on time - objective value 0\n"]
lines += ["{:>7} {} {:>15} {:>23}\n".format(*tup) for tup in value_lines]
with open(filename, "w") as f:
f.writelines(lines)
return True
| (self, filename, lp, vs, variablesNames, constraintsNames) |
38,033 | pulp.apis.coin_api | COINMP_DLL |
The COIN_MP LP MIP solver (via a DLL or linux so)
:param timeLimit: The number of seconds before forcing the solver to exit
:param epgap: The fractional mip tolerance
| class COINMP_DLL(LpSolver):
"""
The COIN_MP LP MIP solver (via a DLL or linux so)
:param timeLimit: The number of seconds before forcing the solver to exit
:param epgap: The fractional mip tolerance
"""
name = "COINMP_DLL"
try:
lib = COINMP_DLL_load_dll(coinMP_path)
except (ImportError, OSError):
@classmethod
def available(cls):
"""True if the solver is available"""
return False
def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
raise PulpSolverError("COINMP_DLL: Not Available")
else:
COIN_INT_LOGLEVEL = 7
COIN_REAL_MAXSECONDS = 16
COIN_REAL_MIPMAXSEC = 19
COIN_REAL_MIPFRACGAP = 34
lib.CoinGetInfinity.restype = ctypes.c_double
lib.CoinGetVersionStr.restype = ctypes.c_char_p
lib.CoinGetSolutionText.restype = ctypes.c_char_p
lib.CoinGetObjectValue.restype = ctypes.c_double
lib.CoinGetMipBestBound.restype = ctypes.c_double
def __init__(
self,
cuts=1,
presolve=1,
dual=1,
crash=0,
scale=1,
rounding=1,
integerPresolve=1,
strong=5,
*args,
**kwargs,
):
LpSolver.__init__(self, *args, **kwargs)
self.fracGap = None
gapRel = self.optionsDict.get("gapRel")
if gapRel is not None:
self.fracGap = float(gapRel)
if self.timeLimit is not None:
self.timeLimit = float(self.timeLimit)
# Todo: these options are not yet implemented
self.cuts = cuts
self.presolve = presolve
self.dual = dual
self.crash = crash
self.scale = scale
self.rounding = rounding
self.integerPresolve = integerPresolve
self.strong = strong
def copy(self):
"""Make a copy of self"""
aCopy = LpSolver.copy(self)
aCopy.cuts = self.cuts
aCopy.presolve = self.presolve
aCopy.dual = self.dual
aCopy.crash = self.crash
aCopy.scale = self.scale
aCopy.rounding = self.rounding
aCopy.integerPresolve = self.integerPresolve
aCopy.strong = self.strong
return aCopy
@classmethod
def available(cls):
"""True if the solver is available"""
return True
def getSolverVersion(self):
"""
returns a solver version string
example:
>>> COINMP_DLL().getSolverVersion() # doctest: +ELLIPSIS
'...'
"""
return self.lib.CoinGetVersionStr()
def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
# TODO alter so that msg parameter is handled correctly
self.debug = 0
# initialise solver
self.lib.CoinInitSolver("")
# create problem
self.hProb = hProb = self.lib.CoinCreateProblem(lp.name)
# set problem options
self.lib.CoinSetIntOption(
hProb, self.COIN_INT_LOGLEVEL, ctypes.c_int(self.msg)
)
if self.timeLimit:
if self.mip:
self.lib.CoinSetRealOption(
hProb, self.COIN_REAL_MIPMAXSEC, ctypes.c_double(self.timeLimit)
)
else:
self.lib.CoinSetRealOption(
hProb,
self.COIN_REAL_MAXSECONDS,
ctypes.c_double(self.timeLimit),
)
if self.fracGap:
# Hopefully this is the bound gap tolerance
self.lib.CoinSetRealOption(
hProb, self.COIN_REAL_MIPFRACGAP, ctypes.c_double(self.fracGap)
)
# CoinGetInfinity is needed for varibles with no bounds
coinDblMax = self.lib.CoinGetInfinity()
if self.debug:
print("Before getCoinMPArrays")
(
numVars,
numRows,
numels,
rangeCount,
objectSense,
objectCoeffs,
objectConst,
rhsValues,
rangeValues,
rowType,
startsBase,
lenBase,
indBase,
elemBase,
lowerBounds,
upperBounds,
initValues,
colNames,
rowNames,
columnType,
n2v,
n2c,
) = self.getCplexStyleArrays(lp)
self.lib.CoinLoadProblem(
hProb,
numVars,
numRows,
numels,
rangeCount,
objectSense,
objectConst,
objectCoeffs,
lowerBounds,
upperBounds,
rowType,
rhsValues,
rangeValues,
startsBase,
lenBase,
indBase,
elemBase,
colNames,
rowNames,
"Objective",
)
if lp.isMIP() and self.mip:
self.lib.CoinLoadInteger(hProb, columnType)
if self.msg == 0:
self.lib.CoinRegisterMsgLogCallback(
hProb, ctypes.c_char_p(""), ctypes.POINTER(ctypes.c_int)()
)
self.coinTime = -clock()
self.lib.CoinOptimizeProblem(hProb, 0)
self.coinTime += clock()
# TODO: check Integer Feasible status
CoinLpStatus = {
0: constants.LpStatusOptimal,
1: constants.LpStatusInfeasible,
2: constants.LpStatusInfeasible,
3: constants.LpStatusNotSolved,
4: constants.LpStatusNotSolved,
5: constants.LpStatusNotSolved,
-1: constants.LpStatusUndefined,
}
solutionStatus = self.lib.CoinGetSolutionStatus(hProb)
solutionText = self.lib.CoinGetSolutionText(hProb)
objectValue = self.lib.CoinGetObjectValue(hProb)
# get the solution values
NumVarDoubleArray = ctypes.c_double * numVars
NumRowsDoubleArray = ctypes.c_double * numRows
cActivity = NumVarDoubleArray()
cReducedCost = NumVarDoubleArray()
cSlackValues = NumRowsDoubleArray()
cShadowPrices = NumRowsDoubleArray()
self.lib.CoinGetSolutionValues(
hProb,
ctypes.byref(cActivity),
ctypes.byref(cReducedCost),
ctypes.byref(cSlackValues),
ctypes.byref(cShadowPrices),
)
variablevalues = {}
variabledjvalues = {}
constraintpivalues = {}
constraintslackvalues = {}
if lp.isMIP() and self.mip:
lp.bestBound = self.lib.CoinGetMipBestBound(hProb)
for i in range(numVars):
variablevalues[self.n2v[i].name] = cActivity[i]
variabledjvalues[self.n2v[i].name] = cReducedCost[i]
lp.assignVarsVals(variablevalues)
lp.assignVarsDj(variabledjvalues)
# put pi and slack variables against the constraints
for i in range(numRows):
constraintpivalues[self.n2c[i]] = cShadowPrices[i]
constraintslackvalues[self.n2c[i]] = cSlackValues[i]
lp.assignConsPi(constraintpivalues)
lp.assignConsSlack(constraintslackvalues)
self.lib.CoinFreeSolver()
status = CoinLpStatus[self.lib.CoinGetSolutionStatus(hProb)]
lp.assignStatus(status)
return status
| (mip=True, msg=True, options=None, timeLimit=None, *args, **kwargs) |
38,034 | pulp.apis.core | __init__ |
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param list options:
:param float timeLimit: maximum time for solver (in seconds)
:param args:
:param kwargs: optional named options to pass to each solver,
e.g. gapRel=0.1, gapAbs=10, logPath="",
| def __init__(
self, mip=True, msg=True, options=None, timeLimit=None, *args, **kwargs
):
"""
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param list options:
:param float timeLimit: maximum time for solver (in seconds)
:param args:
:param kwargs: optional named options to pass to each solver,
e.g. gapRel=0.1, gapAbs=10, logPath="",
"""
if options is None:
options = []
self.mip = mip
self.msg = msg
self.options = options
self.timeLimit = timeLimit
# here we will store all other relevant information including:
# gapRel, gapAbs, maxMemory, maxNodes, threads, logPath, timeMode
self.optionsDict = {k: v for k, v in kwargs.items() if v is not None}
| (self, mip=True, msg=True, options=None, timeLimit=None, *args, **kwargs) |
38,036 | pulp.apis.coin_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
raise PulpSolverError("COINMP_DLL: Not Available")
| (self, lp) |
38,037 | pulp.apis.core | copy | Make a copy of self | def copy(self):
"""Make a copy of self"""
aCopy = self.__class__()
aCopy.mip = self.mip
aCopy.msg = self.msg
aCopy.options = self.options
return aCopy
| (self) |
38,044 | pulp.apis.coin_api | COINMP_DLL_load_dll |
function that loads the DLL useful for debugging installation problems
| def COINMP_DLL_load_dll(path):
"""
function that loads the DLL useful for debugging installation problems
"""
if os.name == "nt":
lib = ctypes.windll.LoadLibrary(str(path[-1]))
else:
# linux hack to get working
mode = ctypes.RTLD_GLOBAL
for libpath in path[:-1]:
# RTLD_LAZY = 0x00001
ctypes.CDLL(libpath, mode=mode)
lib = ctypes.CDLL(path[-1], mode=mode)
return lib
| (path) |
38,070 | pulp.apis.copt_api | COPT |
The COPT Optimizer via its python interface
The COPT variables are available (after a solve) in var.solverVar
Constraints in constraint.solverConstraint
and the Model is in prob.solverModel
| class COPT(LpSolver):
"""
The COPT Optimizer via its python interface
The COPT variables are available (after a solve) in var.solverVar
Constraints in constraint.solverConstraint
and the Model is in prob.solverModel
"""
name = "COPT"
try:
global coptpy
import coptpy
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("COPT: Not available")
else:
def __init__(
self,
mip=True,
msg=True,
timeLimit=None,
gapRel=None,
warmStart=False,
logPath=None,
**solverParams,
):
"""
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param float timeLimit: maximum time for solver (in seconds)
:param float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param bool warmStart: if True, the solver will use the current value of variables as a start
:param str logPath: path to the log file
"""
LpSolver.__init__(
self,
mip=mip,
msg=msg,
timeLimit=timeLimit,
gapRel=gapRel,
logPath=logPath,
warmStart=warmStart,
)
self.coptenv = coptpy.Envr()
self.coptmdl = self.coptenv.createModel()
if not self.msg:
self.coptmdl.setParam("Logging", 0)
for key, value in solverParams.items():
self.coptmdl.setParam(key, value)
def findSolutionValues(self, lp):
model = lp.solverModel
solutionStatus = model.status
CoptLpStatus = {
coptpy.COPT.UNSTARTED: LpStatusNotSolved,
coptpy.COPT.OPTIMAL: LpStatusOptimal,
coptpy.COPT.INFEASIBLE: LpStatusInfeasible,
coptpy.COPT.UNBOUNDED: LpStatusUnbounded,
coptpy.COPT.INF_OR_UNB: LpStatusInfeasible,
coptpy.COPT.NUMERICAL: LpStatusNotSolved,
coptpy.COPT.NODELIMIT: LpStatusNotSolved,
coptpy.COPT.TIMEOUT: LpStatusNotSolved,
coptpy.COPT.UNFINISHED: LpStatusNotSolved,
coptpy.COPT.INTERRUPTED: LpStatusNotSolved,
}
if self.msg:
print("COPT status=", solutionStatus)
lp.resolveOK = True
for var in lp._variables:
var.isModified = False
status = CoptLpStatus.get(solutionStatus, LpStatusUndefined)
lp.assignStatus(status)
if status != LpStatusOptimal:
return status
values = model.getInfo("Value", model.getVars())
for var, value in zip(lp._variables, values):
var.varValue = value
if not model.ismip:
# NOTE: slacks in COPT are activities of rows
slacks = model.getInfo("Slack", model.getConstrs())
for constr, value in zip(lp.constraints.values(), slacks):
constr.slack = value
redcosts = model.getInfo("RedCost", model.getVars())
for var, value in zip(lp._variables, redcosts):
var.dj = value
duals = model.getInfo("Dual", model.getConstrs())
for constr, value in zip(lp.constraints.values(), duals):
constr.pi = value
return status
def available(self):
"""True if the solver is available"""
return True
def callSolver(self, lp, callback=None):
"""Solves the problem with COPT"""
self.solveTime = -clock()
if callback is not None:
lp.solverModel.setCallback(
callback,
coptpy.COPT.CBCONTEXT_MIPRELAX | coptpy.COPT.CBCONTEXT_MIPSOL,
)
lp.solverModel.solve()
self.solveTime += clock()
def buildSolverModel(self, lp):
"""
Takes the pulp lp model and translates it into a COPT model
"""
lp.solverModel = self.coptmdl
if lp.sense == LpMaximize:
lp.solverModel.objsense = coptpy.COPT.MAXIMIZE
if self.timeLimit:
lp.solverModel.setParam("TimeLimit", self.timeLimit)
gapRel = self.optionsDict.get("gapRel")
logPath = self.optionsDict.get("logPath")
if gapRel:
lp.solverModel.setParam("RelGap", gapRel)
if logPath:
lp.solverModel.setLogFile(logPath)
for var in lp.variables():
lowBound = var.lowBound
if lowBound is None:
lowBound = -coptpy.COPT.INFINITY
upBound = var.upBound
if upBound is None:
upBound = coptpy.COPT.INFINITY
obj = lp.objective.get(var, 0.0)
varType = coptpy.COPT.CONTINUOUS
if var.cat == LpInteger and self.mip:
varType = coptpy.COPT.INTEGER
var.solverVar = lp.solverModel.addVar(
lowBound, upBound, vtype=varType, obj=obj, name=var.name
)
if self.optionsDict.get("warmStart", False):
for var in lp._variables:
if var.varValue is not None:
self.coptmdl.setMipStart(var.solverVar, var.varValue)
self.coptmdl.loadMipStart()
for name, constraint in lp.constraints.items():
expr = coptpy.LinExpr(
[v.solverVar for v in constraint.keys()], list(constraint.values())
)
if constraint.sense == LpConstraintLE:
relation = coptpy.COPT.LESS_EQUAL
elif constraint.sense == LpConstraintGE:
relation = coptpy.COPT.GREATER_EQUAL
elif constraint.sense == LpConstraintEQ:
relation = coptpy.COPT.EQUAL
else:
raise PulpSolverError("Detected an invalid constraint type")
constraint.solverConstraint = lp.solverModel.addConstr(
expr, relation, -constraint.constant, name
)
def actualSolve(self, lp, callback=None):
"""
Solve a well formulated lp problem
creates a COPT model, variables and constraints and attaches
them to the lp model which it then solves
"""
self.buildSolverModel(lp)
self.callSolver(lp, callback=callback)
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
"""
for constraint in lp.constraints.values():
if constraint.modified:
if constraint.sense == LpConstraintLE:
constraint.solverConstraint.ub = -constraint.constant
elif constraint.sense == LpConstraintGE:
constraint.solverConstraint.lb = -constraint.constant
else:
constraint.solverConstraint.lb = -constraint.constant
constraint.solverConstraint.ub = -constraint.constant
self.callSolver(lp, callback=callback)
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,073 | pulp.apis.copt_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp, callback=None):
"""Solve a well formulated lp problem"""
raise PulpSolverError("COPT: Not available")
| (self, lp, callback=None) |
38,074 | pulp.apis.copt_api | available | True if the solver is available | def available(self):
"""True if the solver is available"""
return False
| (self) |
38,082 | pulp.apis.copt_api | COPT_CMD |
The COPT command-line solver
| class COPT_CMD(LpSolver_CMD):
"""
The COPT command-line solver
"""
name = "COPT_CMD"
def __init__(
self,
path=None,
keepFiles=0,
mip=True,
msg=True,
mip_start=False,
warmStart=False,
logfile=None,
**params,
):
"""
Initialize command-line solver
"""
LpSolver_CMD.__init__(self, path, keepFiles, mip, msg, [])
self.mipstart = warmStart
self.logfile = logfile
self.solverparams = params
def defaultPath(self):
"""
The default path of 'copt_cmd'
"""
return self.executableExtension("copt_cmd")
def available(self):
"""
True if 'copt_cmd' is available
"""
return self.executable(self.path)
def actualSolve(self, lp):
"""
Solve a well formulated LP problem
This function borrowed implementation of CPLEX_CMD.actualSolve and
GUROBI_CMD.actualSolve, with some modifications.
"""
if not self.available():
raise PulpSolverError("COPT_PULP: Failed to execute '{}'".format(self.path))
if not self.keepFiles:
uuid = uuid4().hex
tmpLp = os.path.join(self.tmpDir, "{}-pulp.lp".format(uuid))
tmpSol = os.path.join(self.tmpDir, "{}-pulp.sol".format(uuid))
tmpMst = os.path.join(self.tmpDir, "{}-pulp.mst".format(uuid))
else:
# Replace space with underscore to make filepath better
tmpName = lp.name
tmpName = tmpName.replace(" ", "_")
tmpLp = tmpName + "-pulp.lp"
tmpSol = tmpName + "-pulp.sol"
tmpMst = tmpName + "-pulp.mst"
lpvars = lp.writeLP(tmpLp, writeSOS=1)
# Generate solving commands
solvecmds = self.path
solvecmds += " -c "
solvecmds += '"read ' + tmpLp + ";"
if lp.isMIP() and self.mipstart:
self.writemst(tmpMst, lpvars)
solvecmds += "read " + tmpMst + ";"
if self.logfile is not None:
solvecmds += "set logfile {};".format(self.logfile)
if self.solverparams is not None:
for parname, parval in self.solverparams.items():
solvecmds += "set {0} {1};".format(parname, parval)
if lp.isMIP() and not self.mip:
solvecmds += "optimizelp;"
else:
solvecmds += "optimize;"
solvecmds += "write " + tmpSol + ";"
solvecmds += 'exit"'
try:
os.remove(tmpSol)
except:
pass
if self.msg:
msgpipe = None
else:
msgpipe = open(os.devnull, "w")
rc = subprocess.call(solvecmds, shell=True, stdout=msgpipe, stderr=msgpipe)
if msgpipe is not None:
msgpipe.close()
# Get and analyze result
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to execute '{}'".format(self.path))
if not os.path.exists(tmpSol):
status = LpStatusNotSolved
else:
status, values = self.readsol(tmpSol)
if not self.keepFiles:
for oldfile in [tmpLp, tmpSol, tmpMst]:
try:
os.remove(oldfile)
except:
pass
if status == LpStatusOptimal:
lp.assignVarsVals(values)
# lp.assignStatus(status)
lp.status = status
return status
def readsol(self, filename):
"""
Read COPT solution file
"""
with open(filename) as solfile:
try:
next(solfile)
except StopIteration:
warnings.warn("COPT_PULP: No solution was returned")
return LpStatusNotSolved, {}
# TODO: No information about status, assumed to be optimal
status = LpStatusOptimal
values = {}
for line in solfile:
if line[0] != "#":
varname, varval = line.split()
values[varname] = float(varval)
return status, values
def writemst(self, filename, lpvars):
"""
Write COPT MIP start file
"""
mstvals = [(v.name, v.value()) for v in lpvars if v.value() is not None]
mstline = []
for varname, varval in mstvals:
mstline.append("{0} {1}".format(varname, varval))
with open(filename, "w") as mstfile:
mstfile.write("\n".join(mstline))
return True
| (path=None, keepFiles=0, mip=True, msg=True, mip_start=False, warmStart=False, logfile=None, **params) |
38,083 | pulp.apis.copt_api | __init__ |
Initialize command-line solver
| def __init__(
self,
path=None,
keepFiles=0,
mip=True,
msg=True,
mip_start=False,
warmStart=False,
logfile=None,
**params,
):
"""
Initialize command-line solver
"""
LpSolver_CMD.__init__(self, path, keepFiles, mip, msg, [])
self.mipstart = warmStart
self.logfile = logfile
self.solverparams = params
| (self, path=None, keepFiles=0, mip=True, msg=True, mip_start=False, warmStart=False, logfile=None, **params) |
38,085 | pulp.apis.copt_api | actualSolve |
Solve a well formulated LP problem
This function borrowed implementation of CPLEX_CMD.actualSolve and
GUROBI_CMD.actualSolve, with some modifications.
| def actualSolve(self, lp):
"""
Solve a well formulated LP problem
This function borrowed implementation of CPLEX_CMD.actualSolve and
GUROBI_CMD.actualSolve, with some modifications.
"""
if not self.available():
raise PulpSolverError("COPT_PULP: Failed to execute '{}'".format(self.path))
if not self.keepFiles:
uuid = uuid4().hex
tmpLp = os.path.join(self.tmpDir, "{}-pulp.lp".format(uuid))
tmpSol = os.path.join(self.tmpDir, "{}-pulp.sol".format(uuid))
tmpMst = os.path.join(self.tmpDir, "{}-pulp.mst".format(uuid))
else:
# Replace space with underscore to make filepath better
tmpName = lp.name
tmpName = tmpName.replace(" ", "_")
tmpLp = tmpName + "-pulp.lp"
tmpSol = tmpName + "-pulp.sol"
tmpMst = tmpName + "-pulp.mst"
lpvars = lp.writeLP(tmpLp, writeSOS=1)
# Generate solving commands
solvecmds = self.path
solvecmds += " -c "
solvecmds += '"read ' + tmpLp + ";"
if lp.isMIP() and self.mipstart:
self.writemst(tmpMst, lpvars)
solvecmds += "read " + tmpMst + ";"
if self.logfile is not None:
solvecmds += "set logfile {};".format(self.logfile)
if self.solverparams is not None:
for parname, parval in self.solverparams.items():
solvecmds += "set {0} {1};".format(parname, parval)
if lp.isMIP() and not self.mip:
solvecmds += "optimizelp;"
else:
solvecmds += "optimize;"
solvecmds += "write " + tmpSol + ";"
solvecmds += 'exit"'
try:
os.remove(tmpSol)
except:
pass
if self.msg:
msgpipe = None
else:
msgpipe = open(os.devnull, "w")
rc = subprocess.call(solvecmds, shell=True, stdout=msgpipe, stderr=msgpipe)
if msgpipe is not None:
msgpipe.close()
# Get and analyze result
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to execute '{}'".format(self.path))
if not os.path.exists(tmpSol):
status = LpStatusNotSolved
else:
status, values = self.readsol(tmpSol)
if not self.keepFiles:
for oldfile in [tmpLp, tmpSol, tmpMst]:
try:
os.remove(oldfile)
except:
pass
if status == LpStatusOptimal:
lp.assignVarsVals(values)
# lp.assignStatus(status)
lp.status = status
return status
| (self, lp) |
38,086 | pulp.apis.copt_api | available |
True if 'copt_cmd' is available
| def available(self):
"""
True if 'copt_cmd' is available
"""
return self.executable(self.path)
| (self) |
38,089 | pulp.apis.copt_api | defaultPath |
The default path of 'copt_cmd'
| def defaultPath(self):
"""
The default path of 'copt_cmd'
"""
return self.executableExtension("copt_cmd")
| (self) |
38,094 | pulp.apis.copt_api | readsol |
Read COPT solution file
| def readsol(self, filename):
"""
Read COPT solution file
"""
with open(filename) as solfile:
try:
next(solfile)
except StopIteration:
warnings.warn("COPT_PULP: No solution was returned")
return LpStatusNotSolved, {}
# TODO: No information about status, assumed to be optimal
status = LpStatusOptimal
values = {}
for line in solfile:
if line[0] != "#":
varname, varval = line.split()
values[varname] = float(varval)
return status, values
| (self, filename) |
38,102 | pulp.apis.copt_api | writemst |
Write COPT MIP start file
| def writemst(self, filename, lpvars):
"""
Write COPT MIP start file
"""
mstvals = [(v.name, v.value()) for v in lpvars if v.value() is not None]
mstline = []
for varname, varval in mstvals:
mstline.append("{0} {1}".format(varname, varval))
with open(filename, "w") as mstfile:
mstfile.write("\n".join(mstline))
return True
| (self, filename, lpvars) |
38,103 | pulp.apis.copt_api | COPT_DLL |
The COPT dynamic library solver
| class COPT_DLL(LpSolver):
"""
The COPT dynamic library solver
"""
name = "COPT_DLL"
try:
coptlib = COPT_DLL_loadlib()
except Exception as e:
err = e
"""The COPT dynamic library solver (DLL). Something went wrong!!!!"""
def available(self):
"""True if the solver is available"""
return False
def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
raise PulpSolverError(f"COPT_DLL: Not Available:\n{self.err}")
else:
# COPT API name map
CreateEnv = coptlib.COPT_CreateEnv
DeleteEnv = coptlib.COPT_DeleteEnv
CreateProb = coptlib.COPT_CreateProb
DeleteProb = coptlib.COPT_DeleteProb
LoadProb = coptlib.COPT_LoadProb
AddCols = coptlib.COPT_AddCols
WriteMps = coptlib.COPT_WriteMps
WriteLp = coptlib.COPT_WriteLp
WriteBin = coptlib.COPT_WriteBin
WriteSol = coptlib.COPT_WriteSol
WriteBasis = coptlib.COPT_WriteBasis
WriteMst = coptlib.COPT_WriteMst
WriteParam = coptlib.COPT_WriteParam
AddMipStart = coptlib.COPT_AddMipStart
SolveLp = coptlib.COPT_SolveLp
Solve = coptlib.COPT_Solve
GetSolution = coptlib.COPT_GetSolution
GetLpSolution = coptlib.COPT_GetLpSolution
GetIntParam = coptlib.COPT_GetIntParam
SetIntParam = coptlib.COPT_SetIntParam
GetDblParam = coptlib.COPT_GetDblParam
SetDblParam = coptlib.COPT_SetDblParam
GetIntAttr = coptlib.COPT_GetIntAttr
GetDblAttr = coptlib.COPT_GetDblAttr
SearchParamAttr = coptlib.COPT_SearchParamAttr
SetLogFile = coptlib.COPT_SetLogFile
def __init__(
self,
mip=True,
msg=True,
mip_start=False,
warmStart=False,
logfile=None,
**params,
):
"""
Initialize COPT solver
"""
LpSolver.__init__(self, mip, msg)
# Initialize COPT environment and problem
self.coptenv = None
self.coptprob = None
# Use MIP start information
self.mipstart = warmStart
# Create COPT environment and problem
self.create()
# Set log file
if logfile is not None:
rc = self.SetLogFile(self.coptprob, coptstr(logfile))
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to set log file")
# Set parameters to problem
if not self.msg:
self.setParam("Logging", 0)
for parname, parval in params.items():
self.setParam(parname, parval)
def available(self):
"""
True if dynamic library is available
"""
return True
def actualSolve(self, lp):
"""
Solve a well formulated LP/MIP problem
This function borrowed implementation of CPLEX_DLL.actualSolve,
with some modifications.
"""
# Extract problem data and load it into COPT
(
ncol,
nrow,
nnonz,
objsen,
objconst,
colcost,
colbeg,
colcnt,
colind,
colval,
coltype,
collb,
colub,
rowsense,
rowrhs,
colname,
rowname,
) = self.extract(lp)
rc = self.LoadProb(
self.coptprob,
ncol,
nrow,
objsen,
objconst,
colcost,
colbeg,
colcnt,
colind,
colval,
coltype,
collb,
colub,
rowsense,
rowrhs,
None,
colname,
rowname,
)
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to load problem")
if lp.isMIP() and self.mip:
# Load MIP start information
if self.mipstart:
mstdict = {
self.v2n[v]: v.value()
for v in lp.variables()
if v.value() is not None
}
if mstdict:
mstkeys = ctypesArrayFill(list(mstdict.keys()), ctypes.c_int)
mstvals = ctypesArrayFill(
list(mstdict.values()), ctypes.c_double
)
rc = self.AddMipStart(
self.coptprob, len(mstkeys), mstkeys, mstvals
)
if rc != 0:
raise PulpSolverError(
"COPT_PULP: Failed to add MIP start information"
)
# Solve the problem
rc = self.Solve(self.coptprob)
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to solve the MIP problem")
elif lp.isMIP() and not self.mip:
# Solve MIP as LP
rc = self.SolveLp(self.coptprob)
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to solve MIP as LP")
else:
# Solve the LP problem
rc = self.SolveLp(self.coptprob)
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to solve the LP problem")
# Get problem status and solution
status = self.getsolution(lp, ncol, nrow)
# Reset attributes
for var in lp.variables():
var.modified = False
return status
def extract(self, lp):
"""
Extract data from PuLP lp structure
This function borrowed implementation of LpSolver.getCplexStyleArrays,
with some modifications.
"""
cols = list(lp.variables())
ncol = len(cols)
nrow = len(lp.constraints)
collb = (ctypes.c_double * ncol)()
colub = (ctypes.c_double * ncol)()
colcost = (ctypes.c_double * ncol)()
coltype = (ctypes.c_char * ncol)()
colname = (ctypes.c_char_p * ncol)()
rowrhs = (ctypes.c_double * nrow)()
rowsense = (ctypes.c_char * nrow)()
rowname = (ctypes.c_char_p * nrow)()
spmat = sparse.Matrix(list(range(nrow)), list(range(ncol)))
# Objective sense and constant offset
objsen = coptobjsen[lp.sense]
objconst = ctypes.c_double(0.0)
# Associate each variable with a ordinal
self.v2n = dict(((cols[i], i) for i in range(ncol)))
self.vname2n = dict(((cols[i].name, i) for i in range(ncol)))
self.n2v = dict((i, cols[i]) for i in range(ncol))
self.c2n = {}
self.n2c = {}
self.addedVars = ncol
self.addedRows = nrow
# Extract objective cost
for col, val in lp.objective.items():
colcost[self.v2n[col]] = val
# Extract variable types, names and lower/upper bounds
for col in lp.variables():
colname[self.v2n[col]] = coptstr(col.name)
if col.lowBound is not None:
collb[self.v2n[col]] = col.lowBound
else:
collb[self.v2n[col]] = -1e30
if col.upBound is not None:
colub[self.v2n[col]] = col.upBound
else:
colub[self.v2n[col]] = 1e30
# Extract column types
if lp.isMIP():
for var in lp.variables():
coltype[self.v2n[var]] = coptctype[var.cat]
else:
coltype = None
# Extract constraint rhs, senses and names
idx = 0
for row in lp.constraints:
rowrhs[idx] = -lp.constraints[row].constant
rowsense[idx] = coptrsense[lp.constraints[row].sense]
rowname[idx] = coptstr(row)
self.c2n[row] = idx
self.n2c[idx] = row
idx += 1
# Extract coefficient matrix and generate CSC-format matrix
for col, row, coeff in lp.coefficients():
spmat.add(self.c2n[row], self.vname2n[col], coeff)
nnonz, _colbeg, _colcnt, _colind, _colval = spmat.col_based_arrays()
colbeg = ctypesArrayFill(_colbeg, ctypes.c_int)
colcnt = ctypesArrayFill(_colcnt, ctypes.c_int)
colind = ctypesArrayFill(_colind, ctypes.c_int)
colval = ctypesArrayFill(_colval, ctypes.c_double)
return (
ncol,
nrow,
nnonz,
objsen,
objconst,
colcost,
colbeg,
colcnt,
colind,
colval,
coltype,
collb,
colub,
rowsense,
rowrhs,
colname,
rowname,
)
def create(self):
"""
Create COPT environment and problem
This function borrowed implementation of CPLEX_DLL.grabLicense,
with some modifications.
"""
# In case recreate COPT environment and problem
self.delete()
self.coptenv = ctypes.c_void_p()
self.coptprob = ctypes.c_void_p()
# Create COPT environment
rc = self.CreateEnv(byref(self.coptenv))
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to create environment")
# Create COPT problem
rc = self.CreateProb(self.coptenv, byref(self.coptprob))
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to create problem")
def __del__(self):
"""
Destructor of COPT_DLL class
"""
self.delete()
def delete(self):
"""
Release COPT problem and environment
This function borrowed implementation of CPLEX_DLL.releaseLicense,
with some modifications.
"""
# Valid environment and problem exist
if self.coptenv is not None and self.coptprob is not None:
# Delete problem
rc = self.DeleteProb(byref(self.coptprob))
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to delete problem")
# Delete environment
rc = self.DeleteEnv(byref(self.coptenv))
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to delete environment")
# Reset to None
self.coptenv = None
self.coptprob = None
def getsolution(self, lp, ncols, nrows):
"""Get problem solution
This function borrowed implementation of CPLEX_DLL.findSolutionValues,
with some modifications.
"""
status = ctypes.c_int()
x = (ctypes.c_double * ncols)()
dj = (ctypes.c_double * ncols)()
pi = (ctypes.c_double * nrows)()
slack = (ctypes.c_double * nrows)()
var_x = {}
var_dj = {}
con_pi = {}
con_slack = {}
if lp.isMIP() and self.mip:
hasmipsol = ctypes.c_int()
# Get MIP problem satus
rc = self.GetIntAttr(self.coptprob, coptstr("MipStatus"), byref(status))
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to get MIP status")
# Has MIP solution
rc = self.GetIntAttr(
self.coptprob, coptstr("HasMipSol"), byref(hasmipsol)
)
if rc != 0:
raise PulpSolverError(
"COPT_PULP: Failed to check if MIP solution exists"
)
# Optimal/Feasible MIP solution
if status.value == 1 or hasmipsol.value == 1:
rc = self.GetSolution(self.coptprob, byref(x))
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to get MIP solution")
for i in range(ncols):
var_x[self.n2v[i].name] = x[i]
# Assign MIP solution to variables
lp.assignVarsVals(var_x)
else:
# Get LP problem status
rc = self.GetIntAttr(self.coptprob, coptstr("LpStatus"), byref(status))
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to get LP status")
# Optimal LP solution
if status.value == 1:
rc = self.GetLpSolution(
self.coptprob, byref(x), byref(slack), byref(pi), byref(dj)
)
if rc != 0:
raise PulpSolverError("COPT_PULP: Failed to get LP solution")
for i in range(ncols):
var_x[self.n2v[i].name] = x[i]
var_dj[self.n2v[i].name] = dj[i]
# NOTE: slacks in COPT are activities of rows
for i in range(nrows):
con_pi[self.n2c[i]] = pi[i]
con_slack[self.n2c[i]] = slack[i]
# Assign LP solution to variables and constraints
lp.assignVarsVals(var_x)
lp.assignVarsDj(var_dj)
lp.assignConsPi(con_pi)
lp.assignConsSlack(con_slack)
# Reset attributes
lp.resolveOK = True
for var in lp.variables():
var.isModified = False
lp.status = coptlpstat.get(status.value, LpStatusUndefined)
return lp.status
def write(self, filename):
"""
Write problem, basis, parameter or solution to file
"""
file_path = coptstr(filename)
file_name, file_ext = os.path.splitext(file_path)
if not file_ext:
raise PulpSolverError("COPT_PULP: Failed to determine output file type")
elif file_ext == coptstr(".mps"):
rc = self.WriteMps(self.coptprob, file_path)
elif file_ext == coptstr(".lp"):
rc = self.WriteLp(self.coptprob, file_path)
elif file_ext == coptstr(".bin"):
rc = self.WriteBin(self.coptprob, file_path)
elif file_ext == coptstr(".sol"):
rc = self.WriteSol(self.coptprob, file_path)
elif file_ext == coptstr(".bas"):
rc = self.WriteBasis(self.coptprob, file_path)
elif file_ext == coptstr(".mst"):
rc = self.WriteMst(self.coptprob, file_path)
elif file_ext == coptstr(".par"):
rc = self.WriteParam(self.coptprob, file_path)
else:
raise PulpSolverError("COPT_PULP: Unsupported file type")
if rc != 0:
raise PulpSolverError(
"COPT_PULP: Failed to write file '{}'".format(filename)
)
def setParam(self, name, val):
"""
Set parameter to COPT problem
"""
par_type = ctypes.c_int()
par_name = coptstr(name)
rc = self.SearchParamAttr(self.coptprob, par_name, byref(par_type))
if rc != 0:
raise PulpSolverError(
"COPT_PULP: Failed to check type for '{}'".format(par_name)
)
if par_type.value == 0:
rc = self.SetDblParam(self.coptprob, par_name, ctypes.c_double(val))
if rc != 0:
raise PulpSolverError(
"COPT_PULP: Failed to set double parameter '{}'".format(
par_name
)
)
elif par_type.value == 1:
rc = self.SetIntParam(self.coptprob, par_name, ctypes.c_int(val))
if rc != 0:
raise PulpSolverError(
"COPT_PULP: Failed to set integer parameter '{}'".format(
par_name
)
)
else:
raise PulpSolverError(
"COPT_PULP: Invalid parameter '{}'".format(par_name)
)
def getParam(self, name):
"""
Get current value of parameter
"""
par_dblval = ctypes.c_double()
par_intval = ctypes.c_int()
par_type = ctypes.c_int()
par_name = coptstr(name)
rc = self.SearchParamAttr(self.coptprob, par_name, byref(par_type))
if rc != 0:
raise PulpSolverError(
"COPT_PULP: Failed to check type for '{}'".format(par_name)
)
if par_type.value == 0:
rc = self.GetDblParam(self.coptprob, par_name, byref(par_dblval))
if rc != 0:
raise PulpSolverError(
"COPT_PULP: Failed to get double parameter '{}'".format(
par_name
)
)
else:
retval = par_dblval.value
elif par_type.value == 1:
rc = self.GetIntParam(self.coptprob, par_name, byref(par_intval))
if rc != 0:
raise PulpSolverError(
"COPT_PULP: Failed to get integer parameter '{}'".format(
par_name
)
)
else:
retval = par_intval.value
else:
raise PulpSolverError(
"COPT_PULP: Invalid parameter '{}'".format(par_name)
)
return retval
def getAttr(self, name):
"""
Get attribute of the problem
"""
attr_dblval = ctypes.c_double()
attr_intval = ctypes.c_int()
attr_type = ctypes.c_int()
attr_name = coptstr(name)
# Check attribute type by name
rc = self.SearchParamAttr(self.coptprob, attr_name, byref(attr_type))
if rc != 0:
raise PulpSolverError(
"COPT_PULP: Failed to check type for '{}'".format(attr_name)
)
if attr_type.value == 2:
rc = self.GetDblAttr(self.coptprob, attr_name, byref(attr_dblval))
if rc != 0:
raise PulpSolverError(
"COPT_PULP: Failed to get double attribute '{}'".format(
attr_name
)
)
else:
retval = attr_dblval.value
elif attr_type.value == 3:
rc = self.GetIntAttr(self.coptprob, attr_name, byref(attr_intval))
if rc != 0:
raise PulpSolverError(
"COPT_PULP: Failed to get integer attribute '{}'".format(
attr_name
)
)
else:
retval = attr_intval.value
else:
raise PulpSolverError(
"COPT_PULP: Invalid attribute '{}'".format(attr_name)
)
return retval
| (mip=True, msg=True, options=None, timeLimit=None, *args, **kwargs) |
38,106 | pulp.apis.copt_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
raise PulpSolverError(f"COPT_DLL: Not Available:\n{self.err}")
| (self, lp) |
38,115 | pulp.apis.copt_api | COPT_DLL_loadlib |
Load COPT shared library in all supported platforms
| def COPT_DLL_loadlib():
"""
Load COPT shared library in all supported platforms
"""
from glob import glob
libfile = None
libpath = None
libhome = os.getenv("COPT_HOME")
if sys.platform == "win32":
libfile = glob(os.path.join(libhome, "bin", "copt.dll"))
elif sys.platform == "linux":
libfile = glob(os.path.join(libhome, "lib", "libcopt.so"))
elif sys.platform == "darwin":
libfile = glob(os.path.join(libhome, "lib", "libcopt.dylib"))
else:
raise PulpSolverError("COPT_PULP: Unsupported operating system")
# Find desired library in given search path
if libfile:
libpath = libfile[0]
if libpath is None:
raise PulpSolverError(
"COPT_PULP: Failed to locate solver library, "
"please refer to COPT manual for installation guide"
)
else:
if sys.platform == "win32":
coptlib = ctypes.windll.LoadLibrary(libpath)
else:
coptlib = ctypes.cdll.LoadLibrary(libpath)
return coptlib
| () |
38,116 | pulp.apis.cplex_api | CPLEX_CMD | The CPLEX LP solver | class CPLEX_CMD(LpSolver_CMD):
"""The CPLEX LP solver"""
name = "CPLEX_CMD"
def __init__(
self,
mip=True,
msg=True,
timeLimit=None,
gapRel=None,
gapAbs=None,
options=None,
warmStart=False,
keepFiles=False,
path=None,
threads=None,
logPath=None,
maxMemory=None,
maxNodes=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 float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param float gapAbs: absolute gap tolerance for the solver to stop
:param int threads: sets the maximum number of threads
:param list options: list of additional options to pass to solver
:param bool warmStart: if True, the solver will use the current value of variables as a start
:param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
:param str path: path to the solver binary
:param str logPath: path to the log file
:param float maxMemory: max memory to use during the solving. Stops the solving when reached.
:param int maxNodes: max number of nodes during branching. Stops the solving when reached.
"""
LpSolver_CMD.__init__(
self,
gapRel=gapRel,
mip=mip,
msg=msg,
timeLimit=timeLimit,
options=options,
maxMemory=maxMemory,
maxNodes=maxNodes,
warmStart=warmStart,
path=path,
keepFiles=keepFiles,
threads=threads,
gapAbs=gapAbs,
logPath=logPath,
)
def defaultPath(self):
return self.executableExtension("cplex")
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, tmpMst = self.create_tmp_files(lp.name, "lp", "sol", "mst")
vs = lp.writeLP(tmpLp, writeSOS=1)
try:
os.remove(tmpSol)
except:
pass
if not self.msg:
cplex = subprocess.Popen(
self.path,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
else:
cplex = subprocess.Popen(self.path, stdin=subprocess.PIPE)
cplex_cmds = "read " + tmpLp + "\n"
if self.optionsDict.get("warmStart", False):
self.writesol(filename=tmpMst, vs=vs)
cplex_cmds += "read " + tmpMst + "\n"
cplex_cmds += "set advance 1\n"
if self.timeLimit is not None:
cplex_cmds += "set timelimit " + str(self.timeLimit) + "\n"
options = self.options + self.getOptions()
for option in options:
cplex_cmds += option + "\n"
if lp.isMIP():
if self.mip:
cplex_cmds += "mipopt\n"
cplex_cmds += "change problem fixed\n"
else:
cplex_cmds += "change problem lp\n"
cplex_cmds += "optimize\n"
cplex_cmds += "write " + tmpSol + "\n"
cplex_cmds += "quit\n"
cplex_cmds = cplex_cmds.encode("UTF-8")
cplex.communicate(cplex_cmds)
if cplex.returncode != 0:
raise PulpSolverError("PuLP: Error while trying to execute " + self.path)
if not os.path.exists(tmpSol):
status = constants.LpStatusInfeasible
values = reducedCosts = shadowPrices = slacks = solStatus = None
else:
(
status,
values,
reducedCosts,
shadowPrices,
slacks,
solStatus,
) = self.readsol(tmpSol)
self.delete_tmp_files(tmpLp, tmpMst, tmpSol)
if self.optionsDict.get("logPath") != "cplex.log":
self.delete_tmp_files("cplex.log")
if status != constants.LpStatusInfeasible:
lp.assignVarsVals(values)
lp.assignVarsDj(reducedCosts)
lp.assignConsPi(shadowPrices)
lp.assignConsSlack(slacks)
lp.assignStatus(status, solStatus)
return status
def getOptions(self):
# CPLEX parameters: https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.6.0/ilog.odms.cplex.help/CPLEX/GettingStarted/topics/tutorials/InteractiveOptimizer/settingParams.html
# CPLEX status: https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.10.0/ilog.odms.cplex.help/refcallablelibrary/macros/Solution_status_codes.html
params_eq = dict(
logPath="set logFile {}",
gapRel="set mip tolerances mipgap {}",
gapAbs="set mip tolerances absmipgap {}",
maxMemory="set mip limits treememory {}",
threads="set threads {}",
maxNodes="set mip limits nodes {}",
)
return [
v.format(self.optionsDict[k])
for k, v in params_eq.items()
if k in self.optionsDict and self.optionsDict[k] is not None
]
def readsol(self, filename):
"""Read a CPLEX solution file"""
# CPLEX solution codes: http://www-eio.upc.es/lceio/manuals/cplex-11/html/overviewcplex/statuscodes.html
try:
import xml.etree.ElementTree as et
except ImportError:
import elementtree.ElementTree as et
solutionXML = et.parse(filename).getroot()
solutionheader = solutionXML.find("header")
statusString = solutionheader.get("solutionStatusString")
statusValue = solutionheader.get("solutionStatusValue")
cplexStatus = {
"1": constants.LpStatusOptimal, # optimal
"101": constants.LpStatusOptimal, # mip optimal
"102": constants.LpStatusOptimal, # mip optimal tolerance
"104": constants.LpStatusOptimal, # max solution limit
"105": constants.LpStatusOptimal, # node limit feasible
"107": constants.LpStatusOptimal, # time lim feasible
"109": constants.LpStatusOptimal, # fail but feasible
"113": constants.LpStatusOptimal, # abort feasible
}
if statusValue not in cplexStatus:
raise PulpSolverError(
"Unknown status returned by CPLEX: \ncode: '{}', string: '{}'".format(
statusValue, statusString
)
)
status = cplexStatus[statusValue]
# we check for integer feasible status to differentiate from optimal in solution status
cplexSolStatus = {
"104": constants.LpSolutionIntegerFeasible, # max solution limit
"105": constants.LpSolutionIntegerFeasible, # node limit feasible
"107": constants.LpSolutionIntegerFeasible, # time lim feasible
"109": constants.LpSolutionIntegerFeasible, # fail but feasible
"111": constants.LpSolutionIntegerFeasible, # memory limit feasible
"113": constants.LpSolutionIntegerFeasible, # abort feasible
}
solStatus = cplexSolStatus.get(statusValue)
shadowPrices = {}
slacks = {}
constraints = solutionXML.find("linearConstraints")
for constraint in constraints:
name = constraint.get("name")
slack = constraint.get("slack")
shadowPrice = constraint.get("dual")
try:
# See issue #508
shadowPrices[name] = float(shadowPrice)
except TypeError:
shadowPrices[name] = None
slacks[name] = float(slack)
values = {}
reducedCosts = {}
for variable in solutionXML.find("variables"):
name = variable.get("name")
value = variable.get("value")
values[name] = float(value)
reducedCost = variable.get("reducedCost")
try:
# See issue #508
reducedCosts[name] = float(reducedCost)
except TypeError:
reducedCosts[name] = None
return status, values, reducedCosts, shadowPrices, slacks, solStatus
def writesol(self, filename, vs):
"""Writes a CPLEX solution file"""
try:
import xml.etree.ElementTree as et
except ImportError:
import elementtree.ElementTree as et
root = et.Element("CPLEXSolution", version="1.2")
attrib_head = dict()
attrib_quality = dict()
et.SubElement(root, "header", attrib=attrib_head)
et.SubElement(root, "header", attrib=attrib_quality)
variables = et.SubElement(root, "variables")
values = [(v.name, v.value()) for v in vs if v.value() is not None]
for index, (name, value) in enumerate(values):
attrib_vars = dict(name=name, value=str(value), index=str(index))
et.SubElement(variables, "variable", attrib=attrib_vars)
mst = et.ElementTree(root)
mst.write(filename, encoding="utf-8", xml_declaration=True)
return True
| (mip=True, msg=True, timeLimit=None, gapRel=None, gapAbs=None, options=None, warmStart=False, keepFiles=False, path=None, threads=None, logPath=None, maxMemory=None, maxNodes=None) |
38,117 | pulp.apis.cplex_api | __init__ |
:param bool mip: if False, assume LP even if integer variables
:param bool msg: if False, no log is shown
:param float timeLimit: maximum time for solver (in seconds)
:param float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param float gapAbs: absolute gap tolerance for the solver to stop
:param int threads: sets the maximum number of threads
:param list options: list of additional options to pass to solver
:param bool warmStart: if True, the solver will use the current value of variables as a start
:param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
:param str path: path to the solver binary
:param str logPath: path to the log file
:param float maxMemory: max memory to use during the solving. Stops the solving when reached.
:param int maxNodes: max number of nodes during branching. Stops the solving when reached.
| def __init__(
self,
mip=True,
msg=True,
timeLimit=None,
gapRel=None,
gapAbs=None,
options=None,
warmStart=False,
keepFiles=False,
path=None,
threads=None,
logPath=None,
maxMemory=None,
maxNodes=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 float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param float gapAbs: absolute gap tolerance for the solver to stop
:param int threads: sets the maximum number of threads
:param list options: list of additional options to pass to solver
:param bool warmStart: if True, the solver will use the current value of variables as a start
:param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
:param str path: path to the solver binary
:param str logPath: path to the log file
:param float maxMemory: max memory to use during the solving. Stops the solving when reached.
:param int maxNodes: max number of nodes during branching. Stops the solving when reached.
"""
LpSolver_CMD.__init__(
self,
gapRel=gapRel,
mip=mip,
msg=msg,
timeLimit=timeLimit,
options=options,
maxMemory=maxMemory,
maxNodes=maxNodes,
warmStart=warmStart,
path=path,
keepFiles=keepFiles,
threads=threads,
gapAbs=gapAbs,
logPath=logPath,
)
| (self, mip=True, msg=True, timeLimit=None, gapRel=None, gapAbs=None, options=None, warmStart=False, keepFiles=False, path=None, threads=None, logPath=None, maxMemory=None, maxNodes=None) |
38,119 | pulp.apis.cplex_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
if not self.executable(self.path):
raise PulpSolverError("PuLP: cannot execute " + self.path)
tmpLp, tmpSol, tmpMst = self.create_tmp_files(lp.name, "lp", "sol", "mst")
vs = lp.writeLP(tmpLp, writeSOS=1)
try:
os.remove(tmpSol)
except:
pass
if not self.msg:
cplex = subprocess.Popen(
self.path,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
else:
cplex = subprocess.Popen(self.path, stdin=subprocess.PIPE)
cplex_cmds = "read " + tmpLp + "\n"
if self.optionsDict.get("warmStart", False):
self.writesol(filename=tmpMst, vs=vs)
cplex_cmds += "read " + tmpMst + "\n"
cplex_cmds += "set advance 1\n"
if self.timeLimit is not None:
cplex_cmds += "set timelimit " + str(self.timeLimit) + "\n"
options = self.options + self.getOptions()
for option in options:
cplex_cmds += option + "\n"
if lp.isMIP():
if self.mip:
cplex_cmds += "mipopt\n"
cplex_cmds += "change problem fixed\n"
else:
cplex_cmds += "change problem lp\n"
cplex_cmds += "optimize\n"
cplex_cmds += "write " + tmpSol + "\n"
cplex_cmds += "quit\n"
cplex_cmds = cplex_cmds.encode("UTF-8")
cplex.communicate(cplex_cmds)
if cplex.returncode != 0:
raise PulpSolverError("PuLP: Error while trying to execute " + self.path)
if not os.path.exists(tmpSol):
status = constants.LpStatusInfeasible
values = reducedCosts = shadowPrices = slacks = solStatus = None
else:
(
status,
values,
reducedCosts,
shadowPrices,
slacks,
solStatus,
) = self.readsol(tmpSol)
self.delete_tmp_files(tmpLp, tmpMst, tmpSol)
if self.optionsDict.get("logPath") != "cplex.log":
self.delete_tmp_files("cplex.log")
if status != constants.LpStatusInfeasible:
lp.assignVarsVals(values)
lp.assignVarsDj(reducedCosts)
lp.assignConsPi(shadowPrices)
lp.assignConsSlack(slacks)
lp.assignStatus(status, solStatus)
return status
| (self, lp) |
38,123 | pulp.apis.cplex_api | defaultPath | null | def defaultPath(self):
return self.executableExtension("cplex")
| (self) |
38,128 | pulp.apis.cplex_api | getOptions | null | def getOptions(self):
# CPLEX parameters: https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.6.0/ilog.odms.cplex.help/CPLEX/GettingStarted/topics/tutorials/InteractiveOptimizer/settingParams.html
# CPLEX status: https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.10.0/ilog.odms.cplex.help/refcallablelibrary/macros/Solution_status_codes.html
params_eq = dict(
logPath="set logFile {}",
gapRel="set mip tolerances mipgap {}",
gapAbs="set mip tolerances absmipgap {}",
maxMemory="set mip limits treememory {}",
threads="set threads {}",
maxNodes="set mip limits nodes {}",
)
return [
v.format(self.optionsDict[k])
for k, v in params_eq.items()
if k in self.optionsDict and self.optionsDict[k] is not None
]
| (self) |
38,129 | pulp.apis.cplex_api | readsol | Read a CPLEX solution file | def readsol(self, filename):
"""Read a CPLEX solution file"""
# CPLEX solution codes: http://www-eio.upc.es/lceio/manuals/cplex-11/html/overviewcplex/statuscodes.html
try:
import xml.etree.ElementTree as et
except ImportError:
import elementtree.ElementTree as et
solutionXML = et.parse(filename).getroot()
solutionheader = solutionXML.find("header")
statusString = solutionheader.get("solutionStatusString")
statusValue = solutionheader.get("solutionStatusValue")
cplexStatus = {
"1": constants.LpStatusOptimal, # optimal
"101": constants.LpStatusOptimal, # mip optimal
"102": constants.LpStatusOptimal, # mip optimal tolerance
"104": constants.LpStatusOptimal, # max solution limit
"105": constants.LpStatusOptimal, # node limit feasible
"107": constants.LpStatusOptimal, # time lim feasible
"109": constants.LpStatusOptimal, # fail but feasible
"113": constants.LpStatusOptimal, # abort feasible
}
if statusValue not in cplexStatus:
raise PulpSolverError(
"Unknown status returned by CPLEX: \ncode: '{}', string: '{}'".format(
statusValue, statusString
)
)
status = cplexStatus[statusValue]
# we check for integer feasible status to differentiate from optimal in solution status
cplexSolStatus = {
"104": constants.LpSolutionIntegerFeasible, # max solution limit
"105": constants.LpSolutionIntegerFeasible, # node limit feasible
"107": constants.LpSolutionIntegerFeasible, # time lim feasible
"109": constants.LpSolutionIntegerFeasible, # fail but feasible
"111": constants.LpSolutionIntegerFeasible, # memory limit feasible
"113": constants.LpSolutionIntegerFeasible, # abort feasible
}
solStatus = cplexSolStatus.get(statusValue)
shadowPrices = {}
slacks = {}
constraints = solutionXML.find("linearConstraints")
for constraint in constraints:
name = constraint.get("name")
slack = constraint.get("slack")
shadowPrice = constraint.get("dual")
try:
# See issue #508
shadowPrices[name] = float(shadowPrice)
except TypeError:
shadowPrices[name] = None
slacks[name] = float(slack)
values = {}
reducedCosts = {}
for variable in solutionXML.find("variables"):
name = variable.get("name")
value = variable.get("value")
values[name] = float(value)
reducedCost = variable.get("reducedCost")
try:
# See issue #508
reducedCosts[name] = float(reducedCost)
except TypeError:
reducedCosts[name] = None
return status, values, reducedCosts, shadowPrices, slacks, solStatus
| (self, filename) |
38,137 | pulp.apis.cplex_api | writesol | Writes a CPLEX solution file | def writesol(self, filename, vs):
"""Writes a CPLEX solution file"""
try:
import xml.etree.ElementTree as et
except ImportError:
import elementtree.ElementTree as et
root = et.Element("CPLEXSolution", version="1.2")
attrib_head = dict()
attrib_quality = dict()
et.SubElement(root, "header", attrib=attrib_head)
et.SubElement(root, "header", attrib=attrib_quality)
variables = et.SubElement(root, "variables")
values = [(v.name, v.value()) for v in vs if v.value() is not None]
for index, (name, value) in enumerate(values):
attrib_vars = dict(name=name, value=str(value), index=str(index))
et.SubElement(variables, "variable", attrib=attrib_vars)
mst = et.ElementTree(root)
mst.write(filename, encoding="utf-8", xml_declaration=True)
return True
| (self, filename, vs) |
38,160 | pulp.apis.cplex_api | CPLEX_PY |
The CPLEX LP/MIP solver (via a Python Binding)
This solver wraps the python api of cplex.
It has been tested against cplex 12.3.
For api functions that have not been wrapped in this solver please use
the base cplex classes
| class CPLEX_PY(LpSolver):
"""
The CPLEX LP/MIP solver (via a Python Binding)
This solver wraps the python api of cplex.
It has been tested against cplex 12.3.
For api functions that have not been wrapped in this solver please use
the base cplex classes
"""
name = "CPLEX_PY"
try:
global cplex
import cplex
except Exception as e:
err = e
"""The CPLEX LP/MIP solver from python. Something went wrong!!!!"""
def available(self):
"""True if the solver is available"""
return False
def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
raise PulpSolverError(f"CPLEX_PY: Not Available:\n{self.err}")
else:
def __init__(
self,
mip=True,
msg=True,
timeLimit=None,
gapRel=None,
warmStart=False,
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 float timeLimit: maximum time for solver (in seconds)
:param float gapRel: relative gap tolerance for the solver to stop (in fraction)
:param bool warmStart: if True, the solver will use the current value of variables as a start
:param str logPath: path to the log file
:param int threads: number of threads to be used by CPLEX to solve a problem (default None uses all available)
"""
LpSolver.__init__(
self,
gapRel=gapRel,
mip=mip,
msg=msg,
timeLimit=timeLimit,
warmStart=warmStart,
logPath=logPath,
threads=threads,
)
def available(self):
"""True if the solver is available"""
return True
def actualSolve(self, lp, callback=None):
"""
Solve a well formulated lp problem
creates a cplex 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 cplex")
self.callSolver(lp)
# 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 buildSolverModel(self, lp):
"""
Takes the pulp lp model and translates it into a cplex model
"""
model_variables = lp.variables()
self.n2v = {var.name: var for var in model_variables}
if len(self.n2v) != len(model_variables):
raise PulpSolverError(
"Variables must have unique names for cplex solver"
)
log.debug("create the cplex model")
self.solverModel = lp.solverModel = cplex.Cplex()
log.debug("set the name of the problem")
if not self.mip:
self.solverModel.set_problem_name(lp.name)
log.debug("set the sense of the problem")
if lp.sense == constants.LpMaximize:
lp.solverModel.objective.set_sense(
lp.solverModel.objective.sense.maximize
)
obj = [float(lp.objective.get(var, 0.0)) for var in model_variables]
def cplex_var_lb(var):
if var.lowBound is not None:
return float(var.lowBound)
else:
return -cplex.infinity
lb = [cplex_var_lb(var) for var in model_variables]
def cplex_var_ub(var):
if var.upBound is not None:
return float(var.upBound)
else:
return cplex.infinity
ub = [cplex_var_ub(var) for var in model_variables]
colnames = [var.name for var in model_variables]
def cplex_var_types(var):
if var.cat == constants.LpInteger:
return "I"
else:
return "C"
ctype = [cplex_var_types(var) for var in model_variables]
ctype = "".join(ctype)
lp.solverModel.variables.add(
obj=obj, lb=lb, ub=ub, types=ctype, names=colnames
)
rows = []
senses = []
rhs = []
rownames = []
for name, constraint in lp.constraints.items():
# build the expression
expr = [(var.name, float(coeff)) for var, coeff in constraint.items()]
if not expr:
# if the constraint is empty
rows.append(([], []))
else:
rows.append(list(zip(*expr)))
if constraint.sense == constants.LpConstraintLE:
senses.append("L")
elif constraint.sense == constants.LpConstraintGE:
senses.append("G")
elif constraint.sense == constants.LpConstraintEQ:
senses.append("E")
else:
raise PulpSolverError("Detected an invalid constraint type")
rownames.append(name)
rhs.append(float(-constraint.constant))
lp.solverModel.linear_constraints.add(
lin_expr=rows, senses=senses, rhs=rhs, names=rownames
)
log.debug("set the type of the problem")
if not self.mip:
self.solverModel.set_problem_type(cplex.Cplex.problem_type.LP)
log.debug("set the logging")
if not self.msg:
self.setlogfile(None)
logPath = self.optionsDict.get("logPath")
if logPath is not None:
if self.msg:
warnings.warn(
"`logPath` argument replaces `msg=1`. The output will be redirected to the log file."
)
self.setlogfile(open(logPath, "w"))
gapRel = self.optionsDict.get("gapRel")
if gapRel is not None:
self.changeEpgap(gapRel)
if self.timeLimit is not None:
self.setTimeLimit(self.timeLimit)
self.setThreads(self.optionsDict.get("threads", None))
if self.optionsDict.get("warmStart", False):
# We assume "auto" for the effort_level
effort = self.solverModel.MIP_starts.effort_level.auto
start = [
(k, v.value()) for k, v in self.n2v.items() if v.value() is not None
]
if not start:
warnings.warn("No variable with value found: mipStart aborted")
return
ind, val = zip(*start)
self.solverModel.MIP_starts.add(
cplex.SparsePair(ind=ind, val=val), effort, "1"
)
def setlogfile(self, fileobj):
"""
sets the logfile for cplex output
"""
self.solverModel.set_error_stream(fileobj)
self.solverModel.set_log_stream(fileobj)
self.solverModel.set_warning_stream(fileobj)
self.solverModel.set_results_stream(fileobj)
def setThreads(self, threads=None):
"""
Change cplex thread count used (None is default which uses all available resources)
"""
self.solverModel.parameters.threads.set(threads or 0)
def changeEpgap(self, epgap=10**-4):
"""
Change cplex solver integer bound gap tolerence
"""
self.solverModel.parameters.mip.tolerances.mipgap.set(epgap)
def setTimeLimit(self, timeLimit=0.0):
"""
Make cplex limit the time it takes --added CBM 8/28/09
"""
self.solverModel.parameters.timelimit.set(timeLimit)
def callSolver(self, isMIP):
"""Solves the problem with cplex"""
# solve the problem
self.solveTime = -clock()
self.solverModel.solve()
self.solveTime += clock()
def findSolutionValues(self, lp):
CplexLpStatus = {
lp.solverModel.solution.status.MIP_optimal: constants.LpStatusOptimal,
lp.solverModel.solution.status.optimal: constants.LpStatusOptimal,
lp.solverModel.solution.status.optimal_tolerance: constants.LpStatusOptimal,
lp.solverModel.solution.status.infeasible: constants.LpStatusInfeasible,
lp.solverModel.solution.status.infeasible_or_unbounded: constants.LpStatusInfeasible,
lp.solverModel.solution.status.MIP_infeasible: constants.LpStatusInfeasible,
lp.solverModel.solution.status.MIP_infeasible_or_unbounded: constants.LpStatusInfeasible,
lp.solverModel.solution.status.unbounded: constants.LpStatusUnbounded,
lp.solverModel.solution.status.MIP_unbounded: constants.LpStatusUnbounded,
lp.solverModel.solution.status.abort_dual_obj_limit: constants.LpStatusNotSolved,
lp.solverModel.solution.status.abort_iteration_limit: constants.LpStatusNotSolved,
lp.solverModel.solution.status.abort_obj_limit: constants.LpStatusNotSolved,
lp.solverModel.solution.status.abort_relaxed: constants.LpStatusNotSolved,
lp.solverModel.solution.status.abort_time_limit: constants.LpStatusNotSolved,
lp.solverModel.solution.status.abort_user: constants.LpStatusNotSolved,
lp.solverModel.solution.status.MIP_abort_feasible: constants.LpStatusOptimal,
lp.solverModel.solution.status.MIP_time_limit_feasible: constants.LpStatusOptimal,
lp.solverModel.solution.status.MIP_time_limit_infeasible: constants.LpStatusInfeasible,
}
lp.cplex_status = lp.solverModel.solution.get_status()
status = CplexLpStatus.get(lp.cplex_status, constants.LpStatusUndefined)
CplexSolStatus = {
lp.solverModel.solution.status.MIP_time_limit_feasible: constants.LpSolutionIntegerFeasible,
lp.solverModel.solution.status.MIP_abort_feasible: constants.LpSolutionIntegerFeasible,
lp.solverModel.solution.status.MIP_feasible: constants.LpSolutionIntegerFeasible,
}
# TODO: I did not find the following status: CPXMIP_NODE_LIM_FEAS, CPXMIP_MEM_LIM_FEAS
sol_status = CplexSolStatus.get(lp.cplex_status)
lp.assignStatus(status, sol_status)
var_names = [var.name for var in lp._variables]
con_names = [con for con in lp.constraints]
try:
objectiveValue = lp.solverModel.solution.get_objective_value()
variablevalues = dict(
zip(var_names, lp.solverModel.solution.get_values(var_names))
)
lp.assignVarsVals(variablevalues)
constraintslackvalues = dict(
zip(con_names, lp.solverModel.solution.get_linear_slacks(con_names))
)
lp.assignConsSlack(constraintslackvalues)
if lp.solverModel.get_problem_type() == cplex.Cplex.problem_type.LP:
variabledjvalues = dict(
zip(
var_names,
lp.solverModel.solution.get_reduced_costs(var_names),
)
)
lp.assignVarsDj(variabledjvalues)
constraintpivalues = dict(
zip(
con_names,
lp.solverModel.solution.get_dual_values(con_names),
)
)
lp.assignConsPi(constraintpivalues)
except cplex.exceptions.CplexSolverError:
# raises this error when there is no solution
pass
# put pi and slack variables against the constraints
# TODO: clear up the name of self.n2c
if self.msg:
print("Cplex status=", lp.cplex_status)
lp.resolveOK = True
for var in lp._variables:
var.isModified = False
return status
def actualResolve(self, lp, **kwargs):
"""
looks at which variables have been modified and changes them
"""
raise NotImplementedError("Resolves in CPLEX_PY not yet implemented")
| (mip=True, msg=True, options=None, timeLimit=None, *args, **kwargs) |
38,163 | pulp.apis.cplex_api | actualSolve | Solve a well formulated lp problem | def actualSolve(self, lp):
"""Solve a well formulated lp problem"""
raise PulpSolverError(f"CPLEX_PY: Not Available:\n{self.err}")
| (self, lp) |
38,201 | pulp.apis.scip_api | FSCIP_CMD | The multi-threaded FiberSCIP version of the SCIP optimization solver | class FSCIP_CMD(LpSolver_CMD):
"""The multi-threaded FiberSCIP version of the SCIP optimization solver"""
name = "FSCIP_CMD"
def __init__(
self,
path=None,
mip=True,
keepFiles=False,
msg=True,
options=None,
timeLimit=None,
gapRel=None,
gapAbs=None,
maxNodes=None,
threads=None,
logPath=None,
):
"""
:param bool msg: if False, no log is shown
:param bool mip: if False, assume LP even if integer variables
: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,
)
FSCIP_STATUSES = {
"No Solution": constants.LpStatusNotSolved,
"Final Solution": constants.LpStatusOptimal,
}
NO_SOLUTION_STATUSES = {
constants.LpStatusInfeasible,
constants.LpStatusUnbounded,
constants.LpStatusNotSolved,
}
def defaultPath(self):
return self.executableExtension(fscip_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, tmpParams = self.create_tmp_files(
lp.name, "lp", "sol", "set", "prm"
)
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 not self.mip:
warnings.warn(f"{self.name} does not allow a problem to be relaxed")
file_parameters: List[str] = []
# disable presolving in the LoadCoordinator to make sure a solution file is always written
file_parameters.append("NoPreprocessingInLC = TRUE")
command: List[str] = []
command.append(self.path)
command.append(tmpParams)
command.append(tmpLp)
command.extend(["-s", tmpOptions])
command.extend(["-fsol", tmpSol])
if not self.msg:
command.append("-q")
if "logPath" in self.optionsDict:
command.extend(["-l", self.optionsDict["logPath"]])
if "threads" in self.optionsDict:
command.extend(["-sth", f"{self.optionsDict['threads']}"])
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 contain a slash (/)
is_file_options = "/" in option
# assumption: all file options and parameters require an argument which is provided after the equal sign (=)
if "=" not in option:
argument = next(options)
option += f"={argument}"
if is_file_options:
file_options.append(option)
else:
file_parameters.append(option)
# wipe the solution file since FSCIP does not overwrite it if no solution was found which causes parsing errors
self.silent_remove(tmpSol)
with open(tmpOptions, "w") as options_file:
options_file.write("\n".join(file_options))
with open(tmpParams, "w") as parameters_file:
parameters_file.write("\n".join(file_parameters))
subprocess.check_call(
command,
stdout=sys.stdout if self.msg else subprocess.DEVNULL,
stderr=sys.stderr if self.msg else subprocess.DEVNULL,
)
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, tmpParams)
return status
@staticmethod
def parse_status(string: str) -> Optional[int]:
for fscip_status, pulp_status in FSCIP_CMD.FSCIP_STATUSES.items():
if fscip_status in string:
return pulp_status
return None
@staticmethod
def parse_objective(string: str) -> Optional[float]:
fields = string.split(":")
if len(fields) != 2:
return None
label, objective = fields
if label != "objective value":
return None
objective = objective.strip()
try:
objective = float(objective)
except ValueError:
return None
return objective
@staticmethod
def parse_variable(string: str) -> Optional[Tuple[str, float]]:
fields = string.split()
if len(fields) < 2:
return None
name, value = fields[:2]
try:
value = float(value)
except ValueError:
return None
return name, value
@staticmethod
def readsol(filename):
"""Read a FSCIP solution file"""
with open(filename) as file:
# First line must contain a solution status
status_line = file.readline()
status = FSCIP_CMD.parse_status(status_line)
if status is None:
raise PulpSolverError(f"Can't get FSCIP solver status: {status_line!r}")
if status in FSCIP_CMD.NO_SOLUTION_STATUSES:
return status, {}
# Look for an objective value. If we can't find one, stop.
objective_line = file.readline()
objective = FSCIP_CMD.parse_objective(objective_line)
if objective is None:
raise PulpSolverError(
f"Can't get FSCIP solver objective: {objective_line!r}"
)
# Parse the variable values.
variables: Dict[str, float] = {}
for variable_line in file:
variable = FSCIP_CMD.parse_variable(variable_line)
if variable is None:
raise PulpSolverError(
f"Can't read FSCIP solver output: {variable_line!r}"
)
name, value = variable
variables[name] = value
return status, variables
| (path=None, mip=True, keepFiles=False, msg=True, options=None, timeLimit=None, gapRel=None, gapAbs=None, maxNodes=None, threads=None, logPath=None) |
38,202 | pulp.apis.scip_api | __init__ |
:param bool msg: if False, no log is shown
:param bool mip: if False, assume LP even if integer variables
: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,
threads=None,
logPath=None,
):
"""
:param bool msg: if False, no log is shown
:param bool mip: if False, assume LP even if integer variables
: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, threads=None, logPath=None) |
38,204 | 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, tmpParams = self.create_tmp_files(
lp.name, "lp", "sol", "set", "prm"
)
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 not self.mip:
warnings.warn(f"{self.name} does not allow a problem to be relaxed")
file_parameters: List[str] = []
# disable presolving in the LoadCoordinator to make sure a solution file is always written
file_parameters.append("NoPreprocessingInLC = TRUE")
command: List[str] = []
command.append(self.path)
command.append(tmpParams)
command.append(tmpLp)
command.extend(["-s", tmpOptions])
command.extend(["-fsol", tmpSol])
if not self.msg:
command.append("-q")
if "logPath" in self.optionsDict:
command.extend(["-l", self.optionsDict["logPath"]])
if "threads" in self.optionsDict:
command.extend(["-sth", f"{self.optionsDict['threads']}"])
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 contain a slash (/)
is_file_options = "/" in option
# assumption: all file options and parameters require an argument which is provided after the equal sign (=)
if "=" not in option:
argument = next(options)
option += f"={argument}"
if is_file_options:
file_options.append(option)
else:
file_parameters.append(option)
# wipe the solution file since FSCIP does not overwrite it if no solution was found which causes parsing errors
self.silent_remove(tmpSol)
with open(tmpOptions, "w") as options_file:
options_file.write("\n".join(file_options))
with open(tmpParams, "w") as parameters_file:
parameters_file.write("\n".join(file_parameters))
subprocess.check_call(
command,
stdout=sys.stdout if self.msg else subprocess.DEVNULL,
stderr=sys.stderr if self.msg else subprocess.DEVNULL,
)
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, tmpParams)
return status
| (self, lp) |
38,208 | pulp.apis.scip_api | defaultPath | null | def defaultPath(self):
return self.executableExtension(fscip_path)
| (self) |
38,213 | pulp.apis.scip_api | parse_objective | null | @staticmethod
def parse_objective(string: str) -> Optional[float]:
fields = string.split(":")
if len(fields) != 2:
return None
label, objective = fields
if label != "objective value":
return None
objective = objective.strip()
try:
objective = float(objective)
except ValueError:
return None
return objective
| (string: str) -> Optional[float] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.