You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
730 lines
31 KiB
730 lines
31 KiB
<!doctype html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
|
|
<meta name="generator" content="pdoc 0.7.0" />
|
|
<title>miplearn.solvers.pyomo.base API documentation</title>
|
|
<meta name="description" content="" />
|
|
<link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css' rel='stylesheet'>
|
|
<link href='https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/8.0.0/sanitize.min.css' rel='stylesheet'>
|
|
<link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css" rel="stylesheet">
|
|
<style>.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{font-weight:bold}#index h4 + ul{margin-bottom:.6em}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
|
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
|
|
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
|
</head>
|
|
<body>
|
|
<main>
|
|
<article id="content">
|
|
<header>
|
|
<h1 class="title">Module <code>miplearn.solvers.pyomo.base</code></h1>
|
|
</header>
|
|
<section id="section-intro">
|
|
<details class="source">
|
|
<summary>
|
|
<span>Expand source code</span>
|
|
</summary>
|
|
<pre><code class="python"># MIPLearn: Extensible Framework for Learning-Enhanced Mixed-Integer Optimization
|
|
# Copyright (C) 2020, UChicago Argonne, LLC. All rights reserved.
|
|
# Released under the modified BSD license. See COPYING.md for more details.
|
|
|
|
import logging
|
|
import re
|
|
import sys
|
|
from io import StringIO
|
|
from typing import Any, List, Dict, Optional
|
|
|
|
import pyomo
|
|
from pyomo import environ as pe
|
|
from pyomo.core import Var, Constraint
|
|
from pyomo.opt import TerminationCondition
|
|
from pyomo.opt.base.solvers import SolverFactory
|
|
|
|
from miplearn.instance import Instance
|
|
from miplearn.solvers import _RedirectOutput
|
|
from miplearn.solvers.internal import (
|
|
InternalSolver,
|
|
LPSolveStats,
|
|
IterationCallback,
|
|
LazyCallback,
|
|
MIPSolveStats,
|
|
)
|
|
from miplearn.types import VarIndex, SolverParams, Solution
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class BasePyomoSolver(InternalSolver):
|
|
"""
|
|
Base class for all Pyomo solvers.
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
solver_factory: SolverFactory,
|
|
params: SolverParams,
|
|
) -> None:
|
|
self.instance: Optional[Instance] = None
|
|
self.model: Optional[pe.ConcreteModel] = None
|
|
self._all_vars: List[pe.Var] = []
|
|
self._bin_vars: List[pe.Var] = []
|
|
self._is_warm_start_available: bool = False
|
|
self._pyomo_solver: SolverFactory = solver_factory
|
|
self._obj_sense: str = "min"
|
|
self._varname_to_var: Dict[str, pe.Var] = {}
|
|
self._cname_to_constr: Dict[str, pe.Constraint] = {}
|
|
self._termination_condition: str = ""
|
|
|
|
for (key, value) in params.items():
|
|
self._pyomo_solver.options[key] = value
|
|
|
|
def solve_lp(
|
|
self,
|
|
tee: bool = False,
|
|
) -> LPSolveStats:
|
|
self.relax()
|
|
streams: List[Any] = [StringIO()]
|
|
if tee:
|
|
streams += [sys.stdout]
|
|
with _RedirectOutput(streams):
|
|
results = self._pyomo_solver.solve(tee=True)
|
|
self._restore_integrality()
|
|
opt_value = None
|
|
if not self.is_infeasible():
|
|
opt_value = results["Problem"][0]["Lower bound"]
|
|
return {
|
|
"Optimal value": opt_value,
|
|
"Log": streams[0].getvalue(),
|
|
}
|
|
|
|
def _restore_integrality(self) -> None:
|
|
for var in self._bin_vars:
|
|
var.domain = pyomo.core.base.set_types.Binary
|
|
self._pyomo_solver.update_var(var)
|
|
|
|
def solve(
|
|
self,
|
|
tee: bool = False,
|
|
iteration_cb: IterationCallback = None,
|
|
lazy_cb: LazyCallback = None,
|
|
) -> MIPSolveStats:
|
|
if lazy_cb is not None:
|
|
raise Exception("lazy callback not supported")
|
|
total_wallclock_time = 0
|
|
streams: List[Any] = [StringIO()]
|
|
if tee:
|
|
streams += [sys.stdout]
|
|
if iteration_cb is None:
|
|
iteration_cb = lambda: False
|
|
while True:
|
|
logger.debug("Solving MIP...")
|
|
with _RedirectOutput(streams):
|
|
results = self._pyomo_solver.solve(
|
|
tee=True,
|
|
warmstart=self._is_warm_start_available,
|
|
)
|
|
total_wallclock_time += results["Solver"][0]["Wallclock time"]
|
|
should_repeat = iteration_cb()
|
|
if not should_repeat:
|
|
break
|
|
log = streams[0].getvalue()
|
|
node_count = self._extract_node_count(log)
|
|
ws_value = self._extract_warm_start_value(log)
|
|
self._termination_condition = results["Solver"][0]["Termination condition"]
|
|
lb, ub = None, None
|
|
if not self.is_infeasible():
|
|
lb = results["Problem"][0]["Lower bound"]
|
|
ub = results["Problem"][0]["Upper bound"]
|
|
stats: MIPSolveStats = {
|
|
"Lower bound": lb,
|
|
"Upper bound": ub,
|
|
"Wallclock time": total_wallclock_time,
|
|
"Sense": self._obj_sense,
|
|
"Log": log,
|
|
"Nodes": node_count,
|
|
"Warm start value": ws_value,
|
|
"LP value": None,
|
|
}
|
|
return stats
|
|
|
|
def get_solution(self) -> Optional[Solution]:
|
|
assert self.model is not None
|
|
if self.is_infeasible():
|
|
return None
|
|
solution: Solution = {}
|
|
for var in self.model.component_objects(Var):
|
|
solution[str(var)] = {}
|
|
for index in var:
|
|
if var[index].fixed:
|
|
continue
|
|
solution[str(var)][index] = var[index].value
|
|
return solution
|
|
|
|
def set_warm_start(self, solution: Solution) -> None:
|
|
self._clear_warm_start()
|
|
count_total, count_fixed = 0, 0
|
|
for var_name in solution:
|
|
var = self._varname_to_var[var_name]
|
|
for index in solution[var_name]:
|
|
count_total += 1
|
|
var[index].value = solution[var_name][index]
|
|
if solution[var_name][index] is not None:
|
|
count_fixed += 1
|
|
if count_fixed > 0:
|
|
self._is_warm_start_available = True
|
|
logger.info(
|
|
"Setting start values for %d variables (out of %d)"
|
|
% (count_fixed, count_total)
|
|
)
|
|
|
|
def set_instance(
|
|
self,
|
|
instance: Instance,
|
|
model: Any = None,
|
|
) -> None:
|
|
if model is None:
|
|
model = instance.to_model()
|
|
assert isinstance(model, pe.ConcreteModel)
|
|
self.instance = instance
|
|
self.model = model
|
|
self._pyomo_solver.set_instance(model)
|
|
self._update_obj()
|
|
self._update_vars()
|
|
self._update_constrs()
|
|
|
|
def get_value(self, var_name: str, index: VarIndex) -> Optional[float]:
|
|
if self.is_infeasible():
|
|
return None
|
|
else:
|
|
var = self._varname_to_var[var_name]
|
|
return var[index].value
|
|
|
|
def get_empty_solution(self) -> Solution:
|
|
assert self.model is not None
|
|
solution: Solution = {}
|
|
for var in self.model.component_objects(Var):
|
|
svar = str(var)
|
|
solution[svar] = {}
|
|
for index in var:
|
|
if var[index].fixed:
|
|
continue
|
|
solution[svar][index] = None
|
|
return solution
|
|
|
|
def _clear_warm_start(self) -> None:
|
|
for var in self._all_vars:
|
|
if not var.fixed:
|
|
var.value = None
|
|
self._is_warm_start_available = False
|
|
|
|
def _update_obj(self) -> None:
|
|
self._obj_sense = "max"
|
|
if self._pyomo_solver._objective.sense == pyomo.core.kernel.objective.minimize:
|
|
self._obj_sense = "min"
|
|
|
|
def _update_vars(self) -> None:
|
|
assert self.model is not None
|
|
self._all_vars = []
|
|
self._bin_vars = []
|
|
self._varname_to_var = {}
|
|
for var in self.model.component_objects(Var):
|
|
self._varname_to_var[var.name] = var
|
|
for idx in var:
|
|
self._all_vars += [var[idx]]
|
|
if var[idx].domain == pyomo.core.base.set_types.Binary:
|
|
self._bin_vars += [var[idx]]
|
|
|
|
def _update_constrs(self) -> None:
|
|
assert self.model is not None
|
|
self._cname_to_constr = {}
|
|
for constr in self.model.component_objects(Constraint):
|
|
self._cname_to_constr[constr.name] = constr
|
|
|
|
def fix(self, solution):
|
|
count_total, count_fixed = 0, 0
|
|
for varname in solution:
|
|
for index in solution[varname]:
|
|
var = self._varname_to_var[varname]
|
|
count_total += 1
|
|
if solution[varname][index] is None:
|
|
continue
|
|
count_fixed += 1
|
|
var[index].fix(solution[varname][index])
|
|
self._pyomo_solver.update_var(var[index])
|
|
logger.info(
|
|
"Fixing values for %d variables (out of %d)"
|
|
% (
|
|
count_fixed,
|
|
count_total,
|
|
)
|
|
)
|
|
|
|
def add_constraint(self, constraint):
|
|
self._pyomo_solver.add_constraint(constraint)
|
|
self._update_constrs()
|
|
|
|
@staticmethod
|
|
def __extract(
|
|
log: str,
|
|
regexp: Optional[str],
|
|
default: Optional[str] = None,
|
|
) -> Optional[str]:
|
|
if regexp is None:
|
|
return default
|
|
value = default
|
|
for line in log.splitlines():
|
|
matches = re.findall(regexp, line)
|
|
if len(matches) == 0:
|
|
continue
|
|
value = matches[0]
|
|
return value
|
|
|
|
def _extract_warm_start_value(self, log: str) -> Optional[float]:
|
|
value = self.__extract(log, self._get_warm_start_regexp())
|
|
if value is None:
|
|
return None
|
|
return float(value)
|
|
|
|
def _extract_node_count(self, log: str) -> Optional[int]:
|
|
value = self.__extract(log, self._get_node_count_regexp())
|
|
if value is None:
|
|
return None
|
|
return int(value)
|
|
|
|
def get_constraint_ids(self):
|
|
return list(self._cname_to_constr.keys())
|
|
|
|
def _get_warm_start_regexp(self) -> Optional[str]:
|
|
return None
|
|
|
|
def _get_node_count_regexp(self) -> Optional[str]:
|
|
return None
|
|
|
|
def relax(self) -> None:
|
|
for var in self._bin_vars:
|
|
lb, ub = var.bounds
|
|
var.setlb(lb)
|
|
var.setub(ub)
|
|
var.domain = pyomo.core.base.set_types.Reals
|
|
self._pyomo_solver.update_var(var)
|
|
|
|
def get_inequality_slacks(self) -> Dict[str, float]:
|
|
result: Dict[str, float] = {}
|
|
for (cname, cobj) in self._cname_to_constr.items():
|
|
if cobj.equality:
|
|
continue
|
|
result[cname] = cobj.slack()
|
|
return result
|
|
|
|
def get_constraint_sense(self, cid: str) -> str:
|
|
cobj = self._cname_to_constr[cid]
|
|
has_ub = cobj.has_ub()
|
|
has_lb = cobj.has_lb()
|
|
assert (not has_lb) or (not has_ub), "range constraints not supported"
|
|
if has_lb:
|
|
return ">"
|
|
elif has_ub:
|
|
return "<"
|
|
else:
|
|
return "="
|
|
|
|
def set_constraint_sense(self, cid: str, sense: str) -> None:
|
|
raise Exception("Not implemented")
|
|
|
|
def extract_constraint(self, cid: str) -> Constraint:
|
|
raise Exception("Not implemented")
|
|
|
|
def is_constraint_satisfied(self, cobj: Constraint) -> bool:
|
|
raise Exception("Not implemented")
|
|
|
|
def is_infeasible(self) -> bool:
|
|
return self._termination_condition == TerminationCondition.infeasible
|
|
|
|
def get_dual(self, cid):
|
|
raise Exception("Not implemented")
|
|
|
|
def get_sense(self) -> str:
|
|
return self._obj_sense</code></pre>
|
|
</details>
|
|
</section>
|
|
<section>
|
|
</section>
|
|
<section>
|
|
</section>
|
|
<section>
|
|
</section>
|
|
<section>
|
|
<h2 class="section-title" id="header-classes">Classes</h2>
|
|
<dl>
|
|
<dt id="miplearn.solvers.pyomo.base.BasePyomoSolver"><code class="flex name class">
|
|
<span>class <span class="ident">BasePyomoSolver</span></span>
|
|
<span>(</span><span>solver_factory, params)</span>
|
|
</code></dt>
|
|
<dd>
|
|
<section class="desc"><p>Base class for all Pyomo solvers.</p></section>
|
|
<details class="source">
|
|
<summary>
|
|
<span>Expand source code</span>
|
|
</summary>
|
|
<pre><code class="python">class BasePyomoSolver(InternalSolver):
|
|
"""
|
|
Base class for all Pyomo solvers.
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
solver_factory: SolverFactory,
|
|
params: SolverParams,
|
|
) -> None:
|
|
self.instance: Optional[Instance] = None
|
|
self.model: Optional[pe.ConcreteModel] = None
|
|
self._all_vars: List[pe.Var] = []
|
|
self._bin_vars: List[pe.Var] = []
|
|
self._is_warm_start_available: bool = False
|
|
self._pyomo_solver: SolverFactory = solver_factory
|
|
self._obj_sense: str = "min"
|
|
self._varname_to_var: Dict[str, pe.Var] = {}
|
|
self._cname_to_constr: Dict[str, pe.Constraint] = {}
|
|
self._termination_condition: str = ""
|
|
|
|
for (key, value) in params.items():
|
|
self._pyomo_solver.options[key] = value
|
|
|
|
def solve_lp(
|
|
self,
|
|
tee: bool = False,
|
|
) -> LPSolveStats:
|
|
self.relax()
|
|
streams: List[Any] = [StringIO()]
|
|
if tee:
|
|
streams += [sys.stdout]
|
|
with _RedirectOutput(streams):
|
|
results = self._pyomo_solver.solve(tee=True)
|
|
self._restore_integrality()
|
|
opt_value = None
|
|
if not self.is_infeasible():
|
|
opt_value = results["Problem"][0]["Lower bound"]
|
|
return {
|
|
"Optimal value": opt_value,
|
|
"Log": streams[0].getvalue(),
|
|
}
|
|
|
|
def _restore_integrality(self) -> None:
|
|
for var in self._bin_vars:
|
|
var.domain = pyomo.core.base.set_types.Binary
|
|
self._pyomo_solver.update_var(var)
|
|
|
|
def solve(
|
|
self,
|
|
tee: bool = False,
|
|
iteration_cb: IterationCallback = None,
|
|
lazy_cb: LazyCallback = None,
|
|
) -> MIPSolveStats:
|
|
if lazy_cb is not None:
|
|
raise Exception("lazy callback not supported")
|
|
total_wallclock_time = 0
|
|
streams: List[Any] = [StringIO()]
|
|
if tee:
|
|
streams += [sys.stdout]
|
|
if iteration_cb is None:
|
|
iteration_cb = lambda: False
|
|
while True:
|
|
logger.debug("Solving MIP...")
|
|
with _RedirectOutput(streams):
|
|
results = self._pyomo_solver.solve(
|
|
tee=True,
|
|
warmstart=self._is_warm_start_available,
|
|
)
|
|
total_wallclock_time += results["Solver"][0]["Wallclock time"]
|
|
should_repeat = iteration_cb()
|
|
if not should_repeat:
|
|
break
|
|
log = streams[0].getvalue()
|
|
node_count = self._extract_node_count(log)
|
|
ws_value = self._extract_warm_start_value(log)
|
|
self._termination_condition = results["Solver"][0]["Termination condition"]
|
|
lb, ub = None, None
|
|
if not self.is_infeasible():
|
|
lb = results["Problem"][0]["Lower bound"]
|
|
ub = results["Problem"][0]["Upper bound"]
|
|
stats: MIPSolveStats = {
|
|
"Lower bound": lb,
|
|
"Upper bound": ub,
|
|
"Wallclock time": total_wallclock_time,
|
|
"Sense": self._obj_sense,
|
|
"Log": log,
|
|
"Nodes": node_count,
|
|
"Warm start value": ws_value,
|
|
"LP value": None,
|
|
}
|
|
return stats
|
|
|
|
def get_solution(self) -> Optional[Solution]:
|
|
assert self.model is not None
|
|
if self.is_infeasible():
|
|
return None
|
|
solution: Solution = {}
|
|
for var in self.model.component_objects(Var):
|
|
solution[str(var)] = {}
|
|
for index in var:
|
|
if var[index].fixed:
|
|
continue
|
|
solution[str(var)][index] = var[index].value
|
|
return solution
|
|
|
|
def set_warm_start(self, solution: Solution) -> None:
|
|
self._clear_warm_start()
|
|
count_total, count_fixed = 0, 0
|
|
for var_name in solution:
|
|
var = self._varname_to_var[var_name]
|
|
for index in solution[var_name]:
|
|
count_total += 1
|
|
var[index].value = solution[var_name][index]
|
|
if solution[var_name][index] is not None:
|
|
count_fixed += 1
|
|
if count_fixed > 0:
|
|
self._is_warm_start_available = True
|
|
logger.info(
|
|
"Setting start values for %d variables (out of %d)"
|
|
% (count_fixed, count_total)
|
|
)
|
|
|
|
def set_instance(
|
|
self,
|
|
instance: Instance,
|
|
model: Any = None,
|
|
) -> None:
|
|
if model is None:
|
|
model = instance.to_model()
|
|
assert isinstance(model, pe.ConcreteModel)
|
|
self.instance = instance
|
|
self.model = model
|
|
self._pyomo_solver.set_instance(model)
|
|
self._update_obj()
|
|
self._update_vars()
|
|
self._update_constrs()
|
|
|
|
def get_value(self, var_name: str, index: VarIndex) -> Optional[float]:
|
|
if self.is_infeasible():
|
|
return None
|
|
else:
|
|
var = self._varname_to_var[var_name]
|
|
return var[index].value
|
|
|
|
def get_empty_solution(self) -> Solution:
|
|
assert self.model is not None
|
|
solution: Solution = {}
|
|
for var in self.model.component_objects(Var):
|
|
svar = str(var)
|
|
solution[svar] = {}
|
|
for index in var:
|
|
if var[index].fixed:
|
|
continue
|
|
solution[svar][index] = None
|
|
return solution
|
|
|
|
def _clear_warm_start(self) -> None:
|
|
for var in self._all_vars:
|
|
if not var.fixed:
|
|
var.value = None
|
|
self._is_warm_start_available = False
|
|
|
|
def _update_obj(self) -> None:
|
|
self._obj_sense = "max"
|
|
if self._pyomo_solver._objective.sense == pyomo.core.kernel.objective.minimize:
|
|
self._obj_sense = "min"
|
|
|
|
def _update_vars(self) -> None:
|
|
assert self.model is not None
|
|
self._all_vars = []
|
|
self._bin_vars = []
|
|
self._varname_to_var = {}
|
|
for var in self.model.component_objects(Var):
|
|
self._varname_to_var[var.name] = var
|
|
for idx in var:
|
|
self._all_vars += [var[idx]]
|
|
if var[idx].domain == pyomo.core.base.set_types.Binary:
|
|
self._bin_vars += [var[idx]]
|
|
|
|
def _update_constrs(self) -> None:
|
|
assert self.model is not None
|
|
self._cname_to_constr = {}
|
|
for constr in self.model.component_objects(Constraint):
|
|
self._cname_to_constr[constr.name] = constr
|
|
|
|
def fix(self, solution):
|
|
count_total, count_fixed = 0, 0
|
|
for varname in solution:
|
|
for index in solution[varname]:
|
|
var = self._varname_to_var[varname]
|
|
count_total += 1
|
|
if solution[varname][index] is None:
|
|
continue
|
|
count_fixed += 1
|
|
var[index].fix(solution[varname][index])
|
|
self._pyomo_solver.update_var(var[index])
|
|
logger.info(
|
|
"Fixing values for %d variables (out of %d)"
|
|
% (
|
|
count_fixed,
|
|
count_total,
|
|
)
|
|
)
|
|
|
|
def add_constraint(self, constraint):
|
|
self._pyomo_solver.add_constraint(constraint)
|
|
self._update_constrs()
|
|
|
|
@staticmethod
|
|
def __extract(
|
|
log: str,
|
|
regexp: Optional[str],
|
|
default: Optional[str] = None,
|
|
) -> Optional[str]:
|
|
if regexp is None:
|
|
return default
|
|
value = default
|
|
for line in log.splitlines():
|
|
matches = re.findall(regexp, line)
|
|
if len(matches) == 0:
|
|
continue
|
|
value = matches[0]
|
|
return value
|
|
|
|
def _extract_warm_start_value(self, log: str) -> Optional[float]:
|
|
value = self.__extract(log, self._get_warm_start_regexp())
|
|
if value is None:
|
|
return None
|
|
return float(value)
|
|
|
|
def _extract_node_count(self, log: str) -> Optional[int]:
|
|
value = self.__extract(log, self._get_node_count_regexp())
|
|
if value is None:
|
|
return None
|
|
return int(value)
|
|
|
|
def get_constraint_ids(self):
|
|
return list(self._cname_to_constr.keys())
|
|
|
|
def _get_warm_start_regexp(self) -> Optional[str]:
|
|
return None
|
|
|
|
def _get_node_count_regexp(self) -> Optional[str]:
|
|
return None
|
|
|
|
def relax(self) -> None:
|
|
for var in self._bin_vars:
|
|
lb, ub = var.bounds
|
|
var.setlb(lb)
|
|
var.setub(ub)
|
|
var.domain = pyomo.core.base.set_types.Reals
|
|
self._pyomo_solver.update_var(var)
|
|
|
|
def get_inequality_slacks(self) -> Dict[str, float]:
|
|
result: Dict[str, float] = {}
|
|
for (cname, cobj) in self._cname_to_constr.items():
|
|
if cobj.equality:
|
|
continue
|
|
result[cname] = cobj.slack()
|
|
return result
|
|
|
|
def get_constraint_sense(self, cid: str) -> str:
|
|
cobj = self._cname_to_constr[cid]
|
|
has_ub = cobj.has_ub()
|
|
has_lb = cobj.has_lb()
|
|
assert (not has_lb) or (not has_ub), "range constraints not supported"
|
|
if has_lb:
|
|
return ">"
|
|
elif has_ub:
|
|
return "<"
|
|
else:
|
|
return "="
|
|
|
|
def set_constraint_sense(self, cid: str, sense: str) -> None:
|
|
raise Exception("Not implemented")
|
|
|
|
def extract_constraint(self, cid: str) -> Constraint:
|
|
raise Exception("Not implemented")
|
|
|
|
def is_constraint_satisfied(self, cobj: Constraint) -> bool:
|
|
raise Exception("Not implemented")
|
|
|
|
def is_infeasible(self) -> bool:
|
|
return self._termination_condition == TerminationCondition.infeasible
|
|
|
|
def get_dual(self, cid):
|
|
raise Exception("Not implemented")
|
|
|
|
def get_sense(self) -> str:
|
|
return self._obj_sense</code></pre>
|
|
</details>
|
|
<h3>Ancestors</h3>
|
|
<ul class="hlist">
|
|
<li><a title="miplearn.solvers.internal.InternalSolver" href="../internal.html#miplearn.solvers.internal.InternalSolver">InternalSolver</a></li>
|
|
<li>abc.ABC</li>
|
|
</ul>
|
|
<h3>Subclasses</h3>
|
|
<ul class="hlist">
|
|
<li><a title="miplearn.solvers.pyomo.gurobi.GurobiPyomoSolver" href="gurobi.html#miplearn.solvers.pyomo.gurobi.GurobiPyomoSolver">GurobiPyomoSolver</a></li>
|
|
<li><a title="miplearn.solvers.pyomo.cplex.CplexPyomoSolver" href="cplex.html#miplearn.solvers.pyomo.cplex.CplexPyomoSolver">CplexPyomoSolver</a></li>
|
|
<li><a title="miplearn.solvers.pyomo.xpress.XpressPyomoSolver" href="xpress.html#miplearn.solvers.pyomo.xpress.XpressPyomoSolver">XpressPyomoSolver</a></li>
|
|
</ul>
|
|
<h3>Inherited members</h3>
|
|
<ul class="hlist">
|
|
<li><code><b><a title="miplearn.solvers.internal.InternalSolver" href="../internal.html#miplearn.solvers.internal.InternalSolver">InternalSolver</a></b></code>:
|
|
<ul class="hlist">
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.add_constraint" href="../internal.html#miplearn.solvers.internal.InternalSolver.add_constraint">add_constraint</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.extract_constraint" href="../internal.html#miplearn.solvers.internal.InternalSolver.extract_constraint">extract_constraint</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.fix" href="../internal.html#miplearn.solvers.internal.InternalSolver.fix">fix</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.get_constraint_ids" href="../internal.html#miplearn.solvers.internal.InternalSolver.get_constraint_ids">get_constraint_ids</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.get_constraint_sense" href="../internal.html#miplearn.solvers.internal.InternalSolver.get_constraint_sense">get_constraint_sense</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.get_dual" href="../internal.html#miplearn.solvers.internal.InternalSolver.get_dual">get_dual</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.get_empty_solution" href="../internal.html#miplearn.solvers.internal.InternalSolver.get_empty_solution">get_empty_solution</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.get_inequality_slacks" href="../internal.html#miplearn.solvers.internal.InternalSolver.get_inequality_slacks">get_inequality_slacks</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.get_sense" href="../internal.html#miplearn.solvers.internal.InternalSolver.get_sense">get_sense</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.get_solution" href="../internal.html#miplearn.solvers.internal.InternalSolver.get_solution">get_solution</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.get_value" href="../internal.html#miplearn.solvers.internal.InternalSolver.get_value">get_value</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.is_constraint_satisfied" href="../internal.html#miplearn.solvers.internal.InternalSolver.is_constraint_satisfied">is_constraint_satisfied</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.is_infeasible" href="../internal.html#miplearn.solvers.internal.InternalSolver.is_infeasible">is_infeasible</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.relax" href="../internal.html#miplearn.solvers.internal.InternalSolver.relax">relax</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.set_branching_priorities" href="../internal.html#miplearn.solvers.internal.InternalSolver.set_branching_priorities">set_branching_priorities</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.set_constraint_sense" href="../internal.html#miplearn.solvers.internal.InternalSolver.set_constraint_sense">set_constraint_sense</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.set_instance" href="../internal.html#miplearn.solvers.internal.InternalSolver.set_instance">set_instance</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.set_warm_start" href="../internal.html#miplearn.solvers.internal.InternalSolver.set_warm_start">set_warm_start</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.solve" href="../internal.html#miplearn.solvers.internal.InternalSolver.solve">solve</a></code></li>
|
|
<li><code><a title="miplearn.solvers.internal.InternalSolver.solve_lp" href="../internal.html#miplearn.solvers.internal.InternalSolver.solve_lp">solve_lp</a></code></li>
|
|
</ul>
|
|
</li>
|
|
</ul>
|
|
</dd>
|
|
</dl>
|
|
</section>
|
|
</article>
|
|
<nav id="sidebar">
|
|
<h1>Index</h1>
|
|
<div class="toc">
|
|
<ul></ul>
|
|
</div>
|
|
<ul id="index">
|
|
<li><h3>Super-module</h3>
|
|
<ul>
|
|
<li><code><a title="miplearn.solvers.pyomo" href="index.html">miplearn.solvers.pyomo</a></code></li>
|
|
</ul>
|
|
</li>
|
|
<li><h3><a href="#header-classes">Classes</a></h3>
|
|
<ul>
|
|
<li>
|
|
<h4><code><a title="miplearn.solvers.pyomo.base.BasePyomoSolver" href="#miplearn.solvers.pyomo.base.BasePyomoSolver">BasePyomoSolver</a></code></h4>
|
|
</li>
|
|
</ul>
|
|
</li>
|
|
</ul>
|
|
</nav>
|
|
</main>
|
|
<footer id="footer">
|
|
<p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.7.0</a>.</p>
|
|
</footer>
|
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
|
|
<script>hljs.initHighlightingOnLoad()</script>
|
|
</body>
|
|
</html> |