mirror of
https://github.com/ANL-CEEESA/MIPLearn.git
synced 2025-12-06 17:38:51 -06:00
Add first model feature (constraint RHS)
This commit is contained in:
26
miplearn/features.py
Normal file
26
miplearn/features.py
Normal file
@@ -0,0 +1,26 @@
|
||||
# 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.
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from miplearn.types import ModelFeatures
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from miplearn import InternalSolver
|
||||
|
||||
|
||||
class ModelFeaturesExtractor:
|
||||
def __init__(
|
||||
self,
|
||||
internal_solver: "InternalSolver",
|
||||
) -> None:
|
||||
self.internal_solver = internal_solver
|
||||
|
||||
def extract(self) -> ModelFeatures:
|
||||
rhs = {}
|
||||
for cid in self.internal_solver.get_constraint_ids():
|
||||
rhs[cid] = self.internal_solver.get_constraint_rhs(cid)
|
||||
return {
|
||||
"ConstraintRHS": rhs,
|
||||
}
|
||||
@@ -9,7 +9,7 @@ from typing import Any, List, Optional, Hashable
|
||||
|
||||
import numpy as np
|
||||
|
||||
from miplearn.types import TrainingSample, VarIndex
|
||||
from miplearn.types import TrainingSample, VarIndex, ModelFeatures
|
||||
|
||||
|
||||
class Instance(ABC):
|
||||
@@ -24,8 +24,9 @@ class Instance(ABC):
|
||||
features, which can be provided as inputs to machine learning models.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
self.training_data: List[TrainingSample] = []
|
||||
self.model_features: ModelFeatures = {}
|
||||
|
||||
@abstractmethod
|
||||
def to_model(self) -> Any:
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# 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.
|
||||
from typing import List
|
||||
|
||||
import numpy as np
|
||||
import pyomo.environ as pe
|
||||
@@ -24,7 +25,6 @@ class ChallengeA:
|
||||
n_training_instances=500,
|
||||
n_test_instances=50,
|
||||
):
|
||||
|
||||
np.random.seed(seed)
|
||||
self.gen = MultiKnapsackGenerator(
|
||||
n=randint(low=250, high=251),
|
||||
@@ -241,7 +241,12 @@ class KnapsackInstance(Instance):
|
||||
Simpler (one-dimensional) Knapsack Problem, used for testing.
|
||||
"""
|
||||
|
||||
def __init__(self, weights, prices, capacity):
|
||||
def __init__(
|
||||
self,
|
||||
weights: List[float],
|
||||
prices: List[float],
|
||||
capacity: float,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.weights = weights
|
||||
self.prices = prices
|
||||
@@ -282,7 +287,12 @@ class GurobiKnapsackInstance(KnapsackInstance):
|
||||
instead of Pyomo, used for testing.
|
||||
"""
|
||||
|
||||
def __init__(self, weights, prices, capacity):
|
||||
def __init__(
|
||||
self,
|
||||
weights: List[float],
|
||||
prices: List[float],
|
||||
capacity: float,
|
||||
) -> None:
|
||||
super().__init__(weights, prices, capacity)
|
||||
|
||||
def to_model(self):
|
||||
|
||||
@@ -335,6 +335,10 @@ class GurobiSolver(InternalSolver):
|
||||
self.model.update()
|
||||
return [c.ConstrName for c in self.model.getConstrs()]
|
||||
|
||||
def get_constraint_rhs(self, cid: str) -> float:
|
||||
assert self.model is not None
|
||||
return self.model.getConstrByName(cid).rhs
|
||||
|
||||
def extract_constraint(self, cid):
|
||||
self._raise_if_callback()
|
||||
constr = self.model.getConstrByName(cid)
|
||||
|
||||
@@ -155,6 +155,13 @@ class InternalSolver(ABC):
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_constraint_rhs(self, cid: str) -> float:
|
||||
"""
|
||||
Returns the right-hand side of a given constraint.
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def add_constraint(self, cobj: Constraint) -> None:
|
||||
"""
|
||||
|
||||
@@ -16,11 +16,12 @@ from miplearn.components.cuts import UserCutsComponent
|
||||
from miplearn.components.lazy_dynamic import DynamicLazyConstraintsComponent
|
||||
from miplearn.components.objective import ObjectiveValueComponent
|
||||
from miplearn.components.primal import PrimalSolutionComponent
|
||||
from miplearn.features import ModelFeaturesExtractor
|
||||
from miplearn.instance import Instance
|
||||
from miplearn.solvers import _RedirectOutput
|
||||
from miplearn.solvers.internal import InternalSolver
|
||||
from miplearn.solvers.pyomo.gurobi import GurobiPyomoSolver
|
||||
from miplearn.types import MIPSolveStats, TrainingSample, LearningSolveStats
|
||||
from miplearn.types import TrainingSample, LearningSolveStats
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -164,6 +165,10 @@ class LearningSolver:
|
||||
assert isinstance(self.internal_solver, InternalSolver)
|
||||
self.internal_solver.set_instance(instance, model)
|
||||
|
||||
# Extract model features
|
||||
extractor = ModelFeaturesExtractor(self.internal_solver)
|
||||
instance.model_features = extractor.extract()
|
||||
|
||||
# Solve linear relaxation
|
||||
if self.solve_lp_first:
|
||||
logger.info("Solving LP relaxation...")
|
||||
|
||||
@@ -212,7 +212,11 @@ class BasePyomoSolver(InternalSolver):
|
||||
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
|
||||
if isinstance(constr, pe.ConstraintList):
|
||||
for idx in constr:
|
||||
self._cname_to_constr[f"{constr.name}[{idx}]"] = constr[idx]
|
||||
else:
|
||||
self._cname_to_constr[constr.name] = constr
|
||||
|
||||
def fix(self, solution):
|
||||
count_total, count_fixed = 0, 0
|
||||
@@ -302,6 +306,13 @@ class BasePyomoSolver(InternalSolver):
|
||||
else:
|
||||
return "="
|
||||
|
||||
def get_constraint_rhs(self, cid: str) -> float:
|
||||
cobj = self._cname_to_constr[cid]
|
||||
if cobj.has_ub:
|
||||
return cobj.upper()
|
||||
else:
|
||||
return cobj.lower()
|
||||
|
||||
def set_constraint_sense(self, cid: str, sense: str) -> None:
|
||||
raise Exception("Not implemented")
|
||||
|
||||
|
||||
@@ -71,6 +71,14 @@ LearningSolveStats = TypedDict(
|
||||
total=False,
|
||||
)
|
||||
|
||||
ModelFeatures = TypedDict(
|
||||
"ModelFeatures",
|
||||
{
|
||||
"ConstraintRHS": Dict[str, float],
|
||||
},
|
||||
total=False,
|
||||
)
|
||||
|
||||
IterationCallback = Callable[[], bool]
|
||||
|
||||
LazyCallback = Callable[[Any, Any], None]
|
||||
|
||||
Reference in New Issue
Block a user