Skip to content

Solution

BaseModelSolution(model_solver)

Bases: ABC

Source code in src/bilevelpy/solution/core.py
def __init__(self, model_solver: ModelSolver):
    self._solver = model_solver
    self._gurobi_model = model_solver.model.get_model()
    self._model = model_solver.model

    self._solution_metadata = SolutionMetadata.from_model(self._gurobi_model)

    self._name_to_var_obj: Dict[str, VariableMetaData] = {}
    for var_cls in self._model.vars:
        if isinstance(var_cls, type) and issubclass(var_cls, Variable):
            meta = var_cls.var_metadata
            self._name_to_var_obj[meta.value] = meta

    self._dict_solution, self._solution_data = self.__extract_solution()

    self.variables = list(self._dict_solution.keys())

    self._register_custom_entities()

dispose()

Release heavy references (Gurobi model / solver) to free memory.

This attempts to call the gurobipy Model.dispose() if available and removes references to the solver and Gurobi model so the Python garbage collector can reclaim memory. Call this after all required data has been extracted from the solution.

Source code in src/bilevelpy/solution/core.py
def dispose(self) -> None:
    """Release heavy references (Gurobi model / solver) to free memory.

    This attempts to call the gurobipy Model.dispose() if available and
    removes references to the solver and Gurobi model so the Python
    garbage collector can reclaim memory. Call this after all required
    data has been extracted from the solution.
    """
    self._gurobi_model.dispose()  # Attempt to dispose the Gurobi model (best-effort)
    self._gurobi_model = None
    self._solver = None

    gc.collect()

SolutionRegistry

Map model classes to their solution classes.

When ModelSolver finishes solving, it uses the registry to find the correct solution class for the model. Models are registered via the :meth:register_for decorator.

Example
@SolutionRegistry.register_for(MySolution)
class MyModel(BaseModel):
    ...

get_solution_class(model_instance_or_class) classmethod

Look up the registered solution class for a model.

Walks up the MRO so that subclasses inherit their parent's solution if none is registered directly.

Parameters:

Name Type Description Default
model_instance_or_class

A model instance or class.

required

Returns:

Type Description
type

The registered BaseModelSolution

type

subclass.

Raises:

Type Description
NotImplementedError

If no solution is registered for the model or any of its base classes.

Source code in src/bilevelpy/solution/solution_registry.py
@classmethod
def get_solution_class(cls, model_instance_or_class) -> type:
    """Look up the registered solution class for a model.

    Walks up the MRO so that subclasses inherit their parent's
    solution if none is registered directly.

    Args:
        model_instance_or_class: A model instance or class.

    Returns:
        The registered [BaseModelSolution][bilevelpy.solution.BaseModelSolution]
        subclass.

    Raises:
        NotImplementedError: If no solution is registered for the
            model or any of its base classes.
    """

    model_type = model_instance_or_class if isinstance(model_instance_or_class, type) else type(
        model_instance_or_class)


    for base in model_type.__mro__:
        if base in cls._registry:
            return cls._registry[base]
    raise NotImplementedError(f"No solution registered for {model_type.__name__} or its bases.")

register_for(solution_class) classmethod

Decorator that registers a solution class for a model class.

Parameters:

Name Type Description Default
solution_class type

The BaseModelSolution subclass to use for the decorated model.

required

Returns:

Type Description

A decorator that adds the model→solution mapping.

Source code in src/bilevelpy/solution/solution_registry.py
@classmethod
def register_for(cls, solution_class: type):
    """Decorator that registers a solution class for a model class.

    Args:
        solution_class: The [BaseModelSolution][bilevelpy.solution.BaseModelSolution]
            subclass to use for the decorated model.

    Returns:
        A decorator that adds the model→solution mapping.
    """
    def decorator(model_class: type):
        cls._registry[model_class] = solution_class
        return model_class
    return decorator