discrete_optimization.generic_tools package
Subpackages
- discrete_optimization.generic_tools.callbacks package
- Submodules
- discrete_optimization.generic_tools.callbacks.backup module
- discrete_optimization.generic_tools.callbacks.callback module
- discrete_optimization.generic_tools.callbacks.early_stoppers module
- discrete_optimization.generic_tools.callbacks.loggers module
- discrete_optimization.generic_tools.callbacks.optuna module
- Module contents
- discrete_optimization.generic_tools.ea package
- Submodules
- discrete_optimization.generic_tools.ea.alternating_ga module
- discrete_optimization.generic_tools.ea.deap_wrappers module
- discrete_optimization.generic_tools.ea.ga module
- discrete_optimization.generic_tools.ea.ga_tools module
- discrete_optimization.generic_tools.ea.nsga module
- Module contents
- discrete_optimization.generic_tools.hyperparameters package
- Submodules
- discrete_optimization.generic_tools.hyperparameters.hyperparameter module
- discrete_optimization.generic_tools.hyperparameters.hyperparametrizable module
Hyperparametrizable
Hyperparametrizable.complete_with_default_hyperparameters()
Hyperparametrizable.copy_and_update_hyperparameters()
Hyperparametrizable.get_default_hyperparameters()
Hyperparametrizable.get_hyperparameter()
Hyperparametrizable.get_hyperparameters_by_name()
Hyperparametrizable.get_hyperparameters_names()
Hyperparametrizable.hyperparameters
Hyperparametrizable.suggest_hyperparameter_with_optuna()
Hyperparametrizable.suggest_hyperparameters_with_optuna()
- Module contents
- discrete_optimization.generic_tools.ls package
- discrete_optimization.generic_tools.mip package
- discrete_optimization.generic_tools.mutations package
- Submodules
- discrete_optimization.generic_tools.mutations.mixed_mutation module
- discrete_optimization.generic_tools.mutations.mutation_bool module
- discrete_optimization.generic_tools.mutations.mutation_catalog module
- discrete_optimization.generic_tools.mutations.mutation_integer module
- discrete_optimization.generic_tools.mutations.mutation_util module
- discrete_optimization.generic_tools.mutations.permutation_mutations module
- Module contents
- discrete_optimization.generic_tools.pytools package
- discrete_optimization.generic_tools.result_storage package
- Submodules
- discrete_optimization.generic_tools.result_storage.multiobj_utils module
- discrete_optimization.generic_tools.result_storage.result_storage module
ParetoFront
ResultStorage
ResultStorage.add_solution()
ResultStorage.best_fit
ResultStorage.best_solution
ResultStorage.finalize()
ResultStorage.get_best_solution()
ResultStorage.get_best_solution_fit()
ResultStorage.get_last_best_solution()
ResultStorage.get_n_best_solution()
ResultStorage.get_random_best_solution()
ResultStorage.get_random_solution()
ResultStorage.list_solution_fits
ResultStorage.map_solutions
ResultStorage.remove_duplicate_solutions()
from_solutions_to_result_storage()
merge_results_storage()
plot_fitness()
plot_pareto_2d()
plot_storage_2d()
result_storage_to_pareto_front()
- discrete_optimization.generic_tools.result_storage.resultcomparator module
ResultComparator
ResultComparator.generate_super_pareto()
ResultComparator.get_best_by_objective_by_result_storage()
ResultComparator.plot_all_2d_paretos_single_plot()
ResultComparator.plot_all_2d_paretos_subplots()
ResultComparator.plot_all_best_by_objective()
ResultComparator.plot_distribution_for_objective()
ResultComparator.plot_super_pareto()
ResultComparator.print_test_distribution()
ResultComparator.reevaluate_result_storages()
- Module contents
- discrete_optimization.generic_tools.robustness package
Submodules
discrete_optimization.generic_tools.asp_tools module
- class discrete_optimization.generic_tools.asp_tools.ASPCallback(do_solver: ASPClingoSolver, callback: Callback, dump_model_in_folders: bool = False)[source]
Bases:
object
- class discrete_optimization.generic_tools.asp_tools.ASPClingoSolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]
Bases:
SolverDO
Base class for solver based on Answer Set Programming formulation and clingo solver.
- ctl: Control | None = None
- early_stopping_exception: Exception | None = None
- abstract retrieve_solution(model: Model) Solution [source]
Construct a do solution from a clingo model.
- Parameters:
model – the current constructed clingo model
- Returns:
the intermediate solution, at do format.
- solve(callbacks: List[Callback] | None = None, **kwargs: Any) ResultStorage [source]
Solve the problem with a CPSat solver drom ortools library.
- Parameters:
callbacks – list of callbacks used to hook into the various stage of the solve
**kwargs – keyword arguments passed to self.init_model()
Returns:
A dedicated clingo callback is used to: - update a resultstorage each time a new solution is found by the clingo solver. - call the user (do) callbacks at each new solution, with the possibility of early stopping if the callback return True.
This clingo callback use the method self.retrieve_solution() to reconstruct a do Solution from the current clingo model.
discrete_optimization.generic_tools.cp_tools module
Constraint programming common utilities and class that should be used by any solver using CP
- class discrete_optimization.generic_tools.cp_tools.CPSolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]
Bases:
SolverDO
Additional function to be implemented by a CP Solver.
- get_status_solver() StatusSolver | None [source]
- abstract init_model(**args: Any) None [source]
Instantiate a CP model instance
Afterwards, self.instance should not be None anymore.
- abstract solve(callbacks: List[Callback] | None = None, parameters_cp: ParametersCP | None = None, **args: Any) ResultStorage [source]
Generic solving function.
- Parameters:
callbacks – list of callbacks used to hook into the various stage of the solve
**kwargs – any argument specific to the solver
Solvers deriving from SolverDo should use callbacks methods .on_step_end(), … during solve(). But some solvers are not yet updated and are just ignoring it.
Returns (ResultStorage): a result object containing potentially a pool of solutions to a discrete-optimization problem
- status_solver: StatusSolver | None = None
- class discrete_optimization.generic_tools.cp_tools.CPSolverName(value)[source]
Bases:
Enum
Enum choice of underlying CP/LP solver used by Minizinc typically
- CHUFFED = 0
- CPLEX = 2
- CPOPT = 3
- GECODE = 1
- GUROBI = 4
- HIGHS = 6
- ORTOOLS = 5
- class discrete_optimization.generic_tools.cp_tools.MinizincCPSolution(_output_item: str | None = None, **kwargs: Any)[source]
Bases:
object
Base class used by minizinc when building a new solution.
This is used as an entry point for callbacks. It is actually a child class dynamically created during solve that will be used by minizinc, with appropriate callbacks, resultstorage and reference to the solver.
- static generate_subclass_for_solve(solver: MinizincCPSolver, callback: Callback) Type[MinizincCPSolution] [source]
Generate dynamically a subclass with initialized class attributes.
- Parameters:
solver
callback
Returns:
- res: ResultStorage
ResultStorage in which the solution will be added, class attribute.
- solver: MinizincCPSolver
Instance of the solver using this class as an output_type.
- step: int
Step number, updated as a class attribute.
- class discrete_optimization.generic_tools.cp_tools.MinizincCPSolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]
Bases:
CPSolver
CP solver wrapping a minizinc solver.
- hyperparameters: List[Hyperparameter] = [EnumHyperparameter(name='cp_solver_name', default=<CPSolverName.CHUFFED: 0>, choices=[<CPSolverName.CHUFFED: 0>, <CPSolverName.GECODE: 1>, <CPSolverName.CPLEX: 2>, <CPSolverName.CPOPT: 3>, <CPSolverName.GUROBI: 4>, <CPSolverName.ORTOOLS: 5>, <CPSolverName.HIGHS: 6>])]
Hyperparameters available for this solver.
- These hyperparameters are to be feed to **kwargs found in
__init__()
init_model() (when available)
solve()
- instance: Instance | None = None
- abstract retrieve_solution(_output_item: str | None = None, **kwargs: Any) Solution [source]
Return a d-o solution from the variables computed by minizinc.
- Parameters:
_output_item – string representing the minizinc solver output passed by minizinc to the solution constructor
**kwargs – keyword arguments passed by minzinc to the solution contructor containing the objective value (key “objective”), and the computed variables as defined in minizinc model.
Returns:
- silent_solve_error: bool = False
If True and solve should raise an error, a warning is raised instead and an empty ResultStorage returned.
- solve(callbacks: List[Callback] | None = None, parameters_cp: ParametersCP | None = None, instance: Instance | None = None, **kwargs: Any) ResultStorage [source]
Solve the CP problem with minizinc
- Parameters:
callbacks – list of callbacks used to hook into the various stage of the solve
parameters_cp – parameters specific to CP solvers
instance – if specified, use this minizinc instance (and underlying model) rather than self.instance Useful in iterative solvers like LNS_CP.
**kwargs – any argument specific to the solver
Returns:
- class discrete_optimization.generic_tools.cp_tools.ParametersCP(time_limit: int, intermediate_solution: bool, all_solutions: bool, nr_solutions: int, time_limit_iter0: int | None = None, free_search: bool = False, multiprocess: bool = False, nb_process: int = 1, optimisation_level: int = 1)[source]
Bases:
object
Parameters that can be used by any cp - solver
- all_solutions: bool
- copy() ParametersCP [source]
- static default() ParametersCP [source]
- static default_cpsat() ParametersCP [source]
- static default_fast_lns() ParametersCP [source]
- static default_free() ParametersCP [source]
- free_search: bool
- intermediate_solution: bool
- multiprocess: bool
- nb_process: int
- nr_solutions: int
- optimisation_level: int
- time_limit: int
- time_limit_iter0: int
- class discrete_optimization.generic_tools.cp_tools.SignEnum(value)[source]
Bases:
Enum
An enumeration.
- EQUAL = '=='
- LEQ = '<='
- LESS = '<'
- UEQ = '>='
- UP = '>'
- class discrete_optimization.generic_tools.cp_tools.StatusSolver(value)[source]
Bases:
Enum
An enumeration.
- OPTIMAL = 'OPTIMAL'
- SATISFIED = 'SATISFIED'
- UNKNOWN = 'UNKNOWN'
- UNSATISFIABLE = 'UNSATISFIABLE'
- discrete_optimization.generic_tools.cp_tools.find_right_minizinc_solver_name(cp_solver_name: CPSolverName)[source]
This small utility function is adapting the ortools tag if needed. :param cp_solver_name: desired cp solver backend :return: the tag for minizinc corresponding to the given cpsolver.
discrete_optimization.generic_tools.do_mutation module
- class discrete_optimization.generic_tools.do_mutation.LocalMoveDefault(prev_solution: Solution, new_solution: Solution)[source]
Bases:
LocalMove
Not clever local move If you’re lazy or don’t have the choice, don’t do in place modification of the previous solution, so that you can retrieve it directly. So the backward operator is then obvious.
discrete_optimization.generic_tools.do_problem module
Base module for the problem implementation in discrete-optimization library.
- class discrete_optimization.generic_tools.do_problem.BaseMethodAggregating(value)[source]
Bases:
Enum
Enum class used to specify how an evaluation of a multiscenario problem should be aggregated.
- MAX = 5
Take the max value over the scenarios
- MEAN = 0
averaging over scenarios
- MEDIAN = 1
taking the median over scenarios
- MIN = 4
Take the min value over the scenarios
- PERCENTILE = 2
take a given percentile over scenario (the percentile value is given as additional parameter in MethodAggregating object
- PONDERATION = 3
ponderate the different scenario with different weights. (MEAN would be equivalent with equal ponderation for example)
- class discrete_optimization.generic_tools.do_problem.EncodingRegister(dict_attribute_to_type: Dict[str, Any])[source]
Bases:
object
Placeholder class where the Solution definition is defined.
- dict_attribute_to_type
specifies the encoding of a solution object.
- Type:
Dict[str, Any]
- User may refer to example in the different implemented problem definition.
Examples
in ColoringModel, to specify the colors attribute of the Solution, you will do the following. dict_register = {
- “colors”: {
“name”: “colors”, “type”: [TypeAttribute.LIST_INTEGER], “n”: self.number_of_nodes, “arrity”: self.number_of_nodes,
}
}
- dict_attribute_to_type: Dict[str, Any]
- get_types() List[TypeAttribute] [source]
Returns all the TypeAttribute that are present in our encoding.
- class discrete_optimization.generic_tools.do_problem.MethodAggregating(base_method_aggregating: BaseMethodAggregating, percentile: float = 90.0, ponderation: ndarray | None = None)[source]
Bases:
object
Specifies how the evaluation on a RobustProblem (i.e a multiscenario problem) should be aggregated in an objective criteria.
- base_method_aggregating
the base method for aggregation of evaluation
- Type:
- percentile
if base_method_aggregating==BaseMethodAggregating.PERCENTILE, then the percentile value used will be this one.
- Type:
float
- ponderation
if base_method_aggregating==BaseMethodAggregating.PONDERATION, then the ponderation value used will be this one. It should be the same size as the number of scenario in the RobustProblem
- Type:
np.array
- class discrete_optimization.generic_tools.do_problem.ModeOptim(value)[source]
Bases:
Enum
Enum class to specify minimization or maximization problems.
- MAXIMIZATION = 0
- MINIMIZATION = 1
- class discrete_optimization.generic_tools.do_problem.ObjectiveDoc(type: discrete_optimization.generic_tools.do_problem.TypeObjective, default_weight: float)[source]
Bases:
object
- default_weight: float
- type: TypeObjective
- class discrete_optimization.generic_tools.do_problem.ObjectiveHandling(value)[source]
Bases:
Enum
Enum class specifying how should be built the objective criteria.
When SINGLE, it means the problem only returns one KPI to be minimize/maximize When AGGREGATE, the problems has several KPI to combine with different ponderations. When MULTI_OBJ, pareto optimisation will be done if possible.
- AGGREGATE = 1
- MULTI_OBJ = 2
- SINGLE = 0
- class discrete_optimization.generic_tools.do_problem.ObjectiveRegister(objective_sense: ModeOptim, objective_handling: ObjectiveHandling, dict_objective_to_doc: Dict[str, Any])[source]
Bases:
object
Store all the specification concerning the objective criteria.
To specify the objective criteria, you’re invited to choose the objective_sense (ModeOptim), how the criteria is computed (ObjectiveHandling) and how are defined each KPI that are returned by the problem.evaluate() function.
Even though the dict_objective is not strictly typed, it should contain as key the same key as the problem.evaluate(sol) function as you see in the examples. As value the dictionnary contains a type of the corresponding KPI (one TypeObjective value), and a default weight of the KPI to take into account (for SINGLE, and AGGREGATE ObjectiveHandling). The weight should be coherent with the ModeOptim chosen.
Examples
In ColoringProblem implementation. dict_objective = {
“nb_colors”: ObjectiveDoc(type=TypeObjective.OBJECTIVE, default_weight=-1), “nb_violations”: ObjectiveDoc(type=TypeObjective.PENALTY, default_weight=-100),
}
- Attributes
objective_sense (ModeOptim): min or max problem objective_handling (ObjectiveHandling): specify how the different kpi are transformed into an optimization criteria dict_objective_to_doc: for each kpi, gives their default weight and their TypeObjective.
- dict_objective_to_doc: Dict[str, ObjectiveDoc]
- get_list_objective_and_default_weight() Tuple[List[str], List[float]] [source]
Flatten the list of kpi names and default weight.
Returns: list of kpi names, list of default weight for the aggregated objective function.
- objective_handling: ObjectiveHandling
- class discrete_optimization.generic_tools.do_problem.ParamsObjectiveFunction(objective_handling: ObjectiveHandling, objectives: List[str], weights: List[float], sense_function: ModeOptim)[source]
Bases:
object
Alternative of Objective Register, but with the same idea of storing the objective handling, ponderation and sense of optimization.
This class has been implemented after ObjectiveRegister to be able to call solvers and use user choice optimization.
- objective_handling: ObjectiveHandling
- objectives: List[str]
- weights: List[float]
- class discrete_optimization.generic_tools.do_problem.Problem[source]
Bases:
object
Base class for a discrete optimization problem.
- abstract evaluate(variable: Solution) Dict[str, float] [source]
Evaluate a given solution object for the given problem.
This method should return a dictionnary of KPI, that can be then used for mono or multiobjective optimization.
- Parameters:
variable (Solution) – the Solution object to evaluate.
Returns: Dictionnary of float kpi for the solution.
- evaluate_mobj(variable: Solution) TupleFitness [source]
Default implementation of multiobjective evaluation.
It consists in flattening the evaluate() function and put in an array. User should probably custom this to be more efficient.
- Parameters:
variable (Solution) – the Solution object to evaluate.
Returns (TupleFitness): a flattened tuple fitness object representing the multi-objective criteria.
- evaluate_mobj_from_dict(dict_values: Dict[str, float]) TupleFitness [source]
Return an multiobjective fitness from a dictionnary of kpi (output of evaluate function).
It consists in flattening the evaluate() function and put in an array. User should probably custom this to be more efficient.
- Parameters:
dict_values – output of evaluate() function
Returns (TupleFitness): a flattened tuple fitness object representing the multi-objective criteria.
- abstract get_attribute_register() EncodingRegister [source]
Returns how the Solution should be encoded.
Returns (EncodingRegister): content of the encoding of the solution
- abstract get_objective_register() ObjectiveRegister [source]
Returns the objective definition.
Returns (ObjectiveRegister): object defining the objective criteria.
- get_optuna_study_direction() str [source]
Convert the objective sense into the expected string by Optuna.
- class discrete_optimization.generic_tools.do_problem.RobustProblem(list_problem: Sequence[Problem], method_aggregating: MethodAggregating)[source]
Bases:
Problem
Problem built from a list of other problem (that should be considered as “scenario” optimisation problems).
- list_problem
List of Problems corresponding to different scenarios.
- method_aggregating
specifies how the evaluation on each scenario should be merged
- aggregate_vector() Callable[[_SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]], float] [source]
Returns the aggregation function coherent with the method_aggregating attribute.
Returns: aggregation function
- evaluate(variable: Solution) Dict[str, float] [source]
Aggregated evaluate function.
- Parameters:
variable (Solution) – Solution to evaluate on the different scenarios.
Returns (Dict[str,float]): aggregated kpi on different scenarios.
- get_attribute_register() EncodingRegister [source]
See
`Problem.get_attribute_register`
doc.
- get_objective_register() ObjectiveRegister [source]
See
`Problem.get_objective_register`
doc.
- satisfy(variable: Solution) bool [source]
Computes if a solution satisfies or not the constraints of the problem.
Warning
For RobustProblem, we consider than checking the satisfiability on the first scenario is enough. It is not necessarly correct
- Parameters:
variable – the Solution object to check satisfability
Returns (bool): boolean true if the constraints are fulfilled, false elsewhere.
- class discrete_optimization.generic_tools.do_problem.Solution[source]
Bases:
object
Base class for a solution to a Problem.
- abstract change_problem(new_problem: Problem) None [source]
If relevant to the optimisation problem, change the underlying problem instance for the solution.
This method can be used to evaluate a solution for different instance of problems.
- Parameters:
new_problem (Problem) – another problem instance from which the solution can be evaluated
Returns: None
- abstract copy() Solution [source]
Deep copy of the solution.
The copy() function should return a new object containing the same input as the current object, that respects the following expected behaviour: -y = x.copy() -if do some inplace change of y, the changes are not done in x.
Returns: a new object from which you can manipulate attributes without changing the original object.
- get_attribute_register(problem: Problem) EncodingRegister [source]
Returns how the Solution is encoded for the Problem.
By default it returns the encoding register of the problem itself. However it can make sense that for the same Problem, you have different Solution class with different encoding.
Returns (EncodingRegister): content of the encoding of the Solution.
- lazy_copy() Solution [source]
This function should return a new object but possibly with mutable attributes from the original objects.
A typical use of lazy copy is in evolutionary algorithms or genetic algorithm where the use of local move don’t need to do a possibly costly deepcopy.
Returns (Solution): copy (possibly shallow) of the Solution
- class discrete_optimization.generic_tools.do_problem.TypeAttribute(value)[source]
Bases:
Enum
Enum class to specify how are defined the attributes of a Solution.
This specification will be particularly usefull if you want to give a try to local search algorithms, which will use the information to use the right local moves.
- LIST_BOOLEAN = 1
- LIST_BOOLEAN_KNAP = 6
- LIST_FLOATS = 10
- LIST_INTEGER = 0
- LIST_INTEGER_SPECIFIC_ARITY = 7
- PERMUTATION = 2
- PERMUTATION_RCPSP = 4
- PERMUTATION_TSP = 3
- SET_INTEGER = 5
- SET_TUPLE_INTEGER = 8
- VRP_PATHS = 9
- class discrete_optimization.generic_tools.do_problem.TypeObjective(value)[source]
Bases:
Enum
Enum class to specify what should each KPI be.
- OBJECTIVE = 0
- PENALTY = 1
- discrete_optimization.generic_tools.do_problem.build_aggreg_function_and_params_objective(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None) Tuple[Callable[[Solution], float] | Callable[[Solution], TupleFitness], Callable[[Dict[str, float]], float] | Callable[[Dict[str, float]], TupleFitness], ParamsObjectiveFunction] [source]
Build evaluation function from the problem and the params of objective function.
If params_objective_function is None then we compute inside this function the default ParamsObjectiveFunction.
- Parameters:
problem – problem to build evaluation function from
params_objective_function – params of the objective function.
- Returns: the function returns a 3-uple :
-first element is a function of Solution->Union[float,TupleFitness] -second element is a function of (Dict[str,float])->Union[float, TupleFitness] -third element, return the params_objective_function (either the object passed in argument of the function, or the one created inside the function.)
- discrete_optimization.generic_tools.do_problem.build_evaluate_function_aggregated(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None) Tuple[Callable[[Solution], float], Callable[[Dict[str, float]], float]] | Tuple[Callable[[Solution], TupleFitness], Callable[[Dict[str, float]], TupleFitness]] [source]
Build 2 eval functions based from the problem and params of objective function.
The 2 eval function are callable with a Solution for the first one, and a Dict[str, float] (output of Problem.evaluate function) for the second one. Those two eval function will return either a scalar for monoobjective problem or a TupleFitness for multiobjective. those aggregated function will be the one actually called by an optimisation algorithm at the end.
- Parameters:
problem (Problem) – problem to build the evaluation function s
params_objective_function (ParamsObjectiveFunction) – params of the objective function.
- Returns: the function returns a 2-uple :
-first element is a function of Solution->Union[float,TupleFitness] -second element is a function of (Dict[str,float])->Union[float, TupleFitness]
- discrete_optimization.generic_tools.do_problem.get_default_objective_setup(problem: Problem) ParamsObjectiveFunction [source]
Build ParamsObjectiveFunction from the ObjectiveRegister returned by the problem.
- Parameters:
problem (Problem) – problem to build objective setup
Returns: default ParamsObjectiveFunction of the problem.
- discrete_optimization.generic_tools.do_problem.lower_bound_vector_encoding_from_dict(dict_encoding: Dict[str, Any]) List[int] [source]
- discrete_optimization.generic_tools.do_problem.upper_bound_vector_encoding_from_dict(dict_encoding: Dict[str, Any]) List[int] [source]
Return for an encoding that is of type LIST_INTEGER or associated, the upper bound vector.
Examples: if the vector should contains value higher or equal to 1, the function will return a list full of 1.
discrete_optimization.generic_tools.do_solver module
Minimal API for a discrete-optimization solver.
- class discrete_optimization.generic_tools.do_solver.SolverDO(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]
Bases:
Hyperparametrizable
Base class for a discrete-optimization solver.
- init_model(**kwargs: Any) None [source]
Initialize intern model used to solve.
Can initialize a ortools, milp, gurobi, … model.
- abstract solve(callbacks: List[Callback] | None = None, **kwargs: Any) ResultStorage [source]
Generic solving function.
- Parameters:
callbacks – list of callbacks used to hook into the various stage of the solve
**kwargs – any argument specific to the solver
Solvers deriving from SolverDo should use callbacks methods .on_step_end(), … during solve(). But some solvers are not yet updated and are just ignoring it.
Returns (ResultStorage): a result object containing potentially a pool of solutions to a discrete-optimization problem
discrete_optimization.generic_tools.exceptions module
discrete_optimization.generic_tools.ghh_tools module
- class discrete_optimization.generic_tools.ghh_tools.SupportsDunderGT(*args, **kwargs)[source]
Bases:
Protocol
- class discrete_optimization.generic_tools.ghh_tools.SupportsDunderLT(*args, **kwargs)[source]
Bases:
Protocol
- discrete_optimization.generic_tools.ghh_tools.argsort(list_or_array: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) ndarray[Any, dtype[int64]] [source]
Return the sorted array with indexes
- Parameters:
list_or_array – any list or array
Returns: indexes of array by increasing order.
- discrete_optimization.generic_tools.ghh_tools.index_max(list_or_array: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) int64 [source]
Argmax operator that can be used in gp.
- Parameters:
list_or_array – any list or array
Returns: index of maximum element of the array
- discrete_optimization.generic_tools.ghh_tools.index_min(list_or_array: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) int64 [source]
Argmin operator that can be used in gp.
- Parameters:
list_or_array – any list or array
Returns: index of minimum element of the array
- discrete_optimization.generic_tools.ghh_tools.max_operator(left: SupportsRichComparisonT, right: SupportsRichComparisonT) SupportsRichComparisonT [source]
- discrete_optimization.generic_tools.ghh_tools.max_operator_list(list_: Iterable[SupportsRichComparisonT]) SupportsRichComparisonT [source]
- discrete_optimization.generic_tools.ghh_tools.min_operator(left: SupportsRichComparisonT, right: SupportsRichComparisonT) SupportsRichComparisonT [source]
discrete_optimization.generic_tools.graph_api module
- class discrete_optimization.generic_tools.graph_api.Graph(nodes: List[Tuple[Hashable, Dict[str, Any]]], edges: List[Tuple[Hashable, Hashable, Dict[str, Any]]], undirected: bool = True, compute_predecessors: bool = True)[source]
Bases:
object
- compute_all_shortest_path(attribute_name: str | None = None) Dict[Hashable, Dict[Hashable, Tuple[List[Hashable], float]]] [source]
- discrete_optimization.generic_tools.graph_api.from_networkx(graph_nx: DiGraph | Graph, undirected: bool | None = None, compute_predecessors: bool = False)[source]
- discrete_optimization.generic_tools.graph_api.get_node_attributes(graph: ~networkx.classes.graph.Graph, name: <module 'string' from '/opt/hostedtoolcache/Python/3.9.19/x64/lib/python3.9/string.py'>, default: ~typing.Any)[source]
@param graph: a nx.Graph @param name: name of attribut of intereste @param default: default value if no value for attribute of interest @return: a dictionnary with for each node of graph, the attribute value corresponding
discrete_optimization.generic_tools.lns_cp module
- class discrete_optimization.generic_tools.lns_cp.ConstraintHandler[source]
Bases:
Hyperparametrizable
- abstract adding_constraint_from_results_store(cp_solver: CPSolver, child_instance: Instance, result_storage: ResultStorage, last_result_store: ResultStorage | None = None) Iterable[Any] [source]
- class discrete_optimization.generic_tools.lns_cp.ConstraintHandlerMix(problem: Problem, list_constraints_handler: List[ConstraintHandler], list_proba: List[float], update_proba: bool = True, tag_constraint_handler: List[str] | None = None, sequential: bool = False)[source]
Bases:
ConstraintHandler
- adding_constraint_from_results_store(cp_solver: CPSolver, child_instance: Instance, result_storage: ResultStorage, last_result_store: ResultStorage | None = None) Iterable[Any] [source]
- class discrete_optimization.generic_tools.lns_cp.ConstraintStatus[source]
Bases:
TypedDict
- name: str
- nb_improvement: int
- nb_usage: int
- class discrete_optimization.generic_tools.lns_cp.LNS_CP(problem: Problem, cp_solver: MinizincCPSolver | None = None, initial_solution_provider: InitialSolution | None = None, constraint_handler: ConstraintHandler | None = None, post_process_solution: PostProcessSolution | None = None, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]
Bases:
SolverDO
- hyperparameters: List[Hyperparameter] = [SubBrickHyperparameter(name='cp_solver_cls', default=None, choices=[]), SubBrickKwargsHyperparameter(name='cp_solver_kwargs', default=None), SubBrickHyperparameter(name='initial_solution_provider_cls', default=None, choices=[]), SubBrickKwargsHyperparameter(name='initial_solution_provider_kwargs', default=None), SubBrickHyperparameter(name='constraint_handler_cls', default=None, choices=[]), SubBrickKwargsHyperparameter(name='constraint_handler_kwargs', default=None), SubBrickHyperparameter(name='post_process_solution_cls', default=<class 'discrete_optimization.generic_tools.lns_mip.TrivialPostProcessSolution'>, choices=[]), SubBrickKwargsHyperparameter(name='post_process_solution_kwargs', default=None), CategoricalHyperparameter(name='skip_first_iteration', default=False, choices=[True, False])]
Hyperparameters available for this solver.
- These hyperparameters are to be feed to **kwargs found in
__init__()
init_model() (when available)
solve()
- solve(nb_iteration_lns: int, parameters_cp: ParametersCP | None = None, nb_iteration_no_improvement: int | None = None, skip_first_iteration: bool = False, stop_first_iteration_if_optimal: bool = True, callbacks: List[Callback] | None = None, **kwargs: Any) ResultStorage [source]
Generic solving function.
- Parameters:
callbacks – list of callbacks used to hook into the various stage of the solve
**kwargs – any argument specific to the solver
Solvers deriving from SolverDo should use callbacks methods .on_step_end(), … during solve(). But some solvers are not yet updated and are just ignoring it.
Returns (ResultStorage): a result object containing potentially a pool of solutions to a discrete-optimization problem
- solve_lns(parameters_cp: ParametersCP, nb_iteration_lns: int, nb_iteration_no_improvement: int | None = None, skip_first_iteration: bool = False, stop_first_iteration_if_optimal: bool = True, callbacks: List[Callback] | None = None, **kwargs: Any) ResultStorage [source]
- class discrete_optimization.generic_tools.lns_cp.LNS_CPlex(problem: Problem, cp_solver: CPSolver, initial_solution_provider: InitialSolution, constraint_handler: ConstraintHandler, post_process_solution: PostProcessSolution | None = None, params_objective_function: ParamsObjectiveFunction | None = None)[source]
Bases:
SolverDO
- solve(nb_iteration_lns: int, parameters_cp: ParametersCP | None = None, nb_iteration_no_improvement: int | None = None, skip_first_iteration: bool = False, callbacks: List[Callback] | None = None, **kwargs: Any) ResultStorage [source]
Generic solving function.
- Parameters:
callbacks – list of callbacks used to hook into the various stage of the solve
**kwargs – any argument specific to the solver
Solvers deriving from SolverDo should use callbacks methods .on_step_end(), … during solve(). But some solvers are not yet updated and are just ignoring it.
Returns (ResultStorage): a result object containing potentially a pool of solutions to a discrete-optimization problem
- solve_lns(parameters_cp: ParametersCP, nb_iteration_lns: int, nb_iteration_no_improvement: int | None = None, skip_first_iteration: bool = False, callbacks: List[Callback] | None = None, **kwargs: Any) ResultStorage [source]
discrete_optimization.generic_tools.lns_mip module
- class discrete_optimization.generic_tools.lns_mip.ConstraintHandler[source]
Bases:
Hyperparametrizable
- abstract adding_constraint_from_results_store(milp_solver: MilpSolver, result_storage: ResultStorage) Mapping[Hashable, Any] [source]
- abstract remove_constraints_from_previous_iteration(milp_solver: MilpSolver, previous_constraints: Mapping[Hashable, Any]) None [source]
- class discrete_optimization.generic_tools.lns_mip.InitialSolution[source]
Bases:
Hyperparametrizable
- abstract get_starting_solution() ResultStorage [source]
- class discrete_optimization.generic_tools.lns_mip.InitialSolutionFromSolver(solver: SolverDO, **kwargs: Any)[source]
Bases:
InitialSolution
- abstract get_starting_solution() ResultStorage [source]
- class discrete_optimization.generic_tools.lns_mip.LNS_MILP(problem: Problem, milp_solver: MilpSolver, initial_solution_provider: InitialSolution, constraint_handler: ConstraintHandler, post_process_solution: PostProcessSolution | None = None, params_objective_function: ParamsObjectiveFunction | None = None)[source]
Bases:
SolverDO
- solve(parameters_milp: ParametersMilp, nb_iteration_lns: int, nb_iteration_no_improvement: int | None = None, skip_first_iteration: bool | None = False, callbacks: List[Callback] | None = None, **kwargs: Any) ResultStorage [source]
Generic solving function.
- Parameters:
callbacks – list of callbacks used to hook into the various stage of the solve
**kwargs – any argument specific to the solver
Solvers deriving from SolverDo should use callbacks methods .on_step_end(), … during solve(). But some solvers are not yet updated and are just ignoring it.
Returns (ResultStorage): a result object containing potentially a pool of solutions to a discrete-optimization problem
- solve_lns(parameters_milp: ParametersMilp, nb_iteration_lns: int, nb_iteration_no_improvement: int | None = None, skip_first_iteration: bool | None = False, callbacks: List[Callback] | None = None, **args: Any) ResultStorage [source]
- class discrete_optimization.generic_tools.lns_mip.PostProcessSolution[source]
Bases:
Hyperparametrizable
- abstract build_other_solution(result_storage: ResultStorage) ResultStorage [source]
- class discrete_optimization.generic_tools.lns_mip.TrivialInitialSolution(solution: ResultStorage, **kwargs: Any)[source]
Bases:
InitialSolution
- abstract get_starting_solution() ResultStorage [source]
- class discrete_optimization.generic_tools.lns_mip.TrivialPostProcessSolution(**kwargs)[source]
Bases:
PostProcessSolution
- build_other_solution(result_storage: ResultStorage) ResultStorage [source]
discrete_optimization.generic_tools.lp_tools module
- class discrete_optimization.generic_tools.lp_tools.CplexMilpSolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]
Bases:
MilpSolver
- get_var_value_for_ith_solution(var: Var, i: int) float [source]
Get value for i-th solution of a given variable.
- model: docplex.mp.model.Model | None
- property nb_solutions: int
Number of solutions found by the solver.
- results_solve: List[SolveSolution] | None
- solve(parameters_milp: ParametersMilp | None = None, **kwargs: Any) ResultStorage [source]
Generic solving function.
- Parameters:
callbacks – list of callbacks used to hook into the various stage of the solve
**kwargs – any argument specific to the solver
Solvers deriving from SolverDo should use callbacks methods .on_step_end(), … during solve(). But some solvers are not yet updated and are just ignoring it.
Returns (ResultStorage): a result object containing potentially a pool of solutions to a discrete-optimization problem
- class discrete_optimization.generic_tools.lp_tools.GurobiCallback(do_solver: GurobiMilpSolver, callback: Callback)[source]
Bases:
object
- class discrete_optimization.generic_tools.lp_tools.GurobiMilpSolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]
Bases:
MilpSolver
Milp solver wrapping a solver from gurobi library.
- early_stopping_exception: Exception | None = None
- get_var_value_for_ith_solution(var: gurobipy.Var, i: int)[source]
Get value for i-th solution of a given variable.
- model: gurobipy.Model | None = None
- property nb_solutions: int
Number of solutions found by the solver.
- optimize_model(parameters_milp: ParametersMilp | None = None, **kwargs: Any) None [source]
Optimize the Gurobi Model.
The solutions are yet to be retrieved via self.retrieve_solutions(). No callbacks are passed to the internal solver, and no result_storage is created
- prepare_model(parameters_milp: ParametersMilp | None = None, **kwargs: Any) None [source]
Set Gurobi Model parameters according to parameters_milp
- solve(callbacks: List[Callback] | None = None, parameters_milp: ParametersMilp | None = None, **kwargs: Any) ResultStorage [source]
Generic solving function.
- Parameters:
callbacks – list of callbacks used to hook into the various stage of the solve
**kwargs – any argument specific to the solver
Solvers deriving from SolverDo should use callbacks methods .on_step_end(), … during solve(). But some solvers are not yet updated and are just ignoring it.
Returns (ResultStorage): a result object containing potentially a pool of solutions to a discrete-optimization problem
- class discrete_optimization.generic_tools.lp_tools.MilpSolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]
Bases:
SolverDO
- abstract get_obj_value_for_ith_solution(i: int) float [source]
Get objective value for i-th solution.
- abstract get_var_value_for_ith_solution(var: Any, i: int) float [source]
Get value for i-th solution of a given variable.
- abstract init_model(**kwargs: Any) None [source]
Initialize intern model used to solve.
Can initialize a ortools, milp, gurobi, … model.
- model: Any | None
- abstract property nb_solutions: int
Number of solutions found by the solver.
- abstract retrieve_current_solution(get_var_value_for_current_solution: Callable[[Any], float], get_obj_value_for_current_solution: Callable[[], float]) Solution [source]
Retrieve current solution from internal gurobi solution.
This converts internal gurobi solution into a discrete-optimization Solution. This method can be called after the solve in retrieve_solutions() or during solve within a gurobi/pymilp/cplex callback. The difference will be the get_var_value_for_current_solution and get_obj_value_for_current_solution callables passed.
- Parameters:
get_var_value_for_current_solution – function extracting the value of the given variable for the current solution will be different when inside a callback or after the solve is finished
get_obj_value_for_current_solution – function extracting the value of the objective for the current solution.
- Returns:
the converted solution at d-o format
- retrieve_ith_solution(i: int) Solution [source]
Retrieve i-th solution from internal milp model.
- Parameters:
i
Returns:
- retrieve_solutions(parameters_milp: ParametersMilp, **kwargs) ResultStorage [source]
Retrieve solutions found by internal solver.
- Parameters:
parameters_milp
**kwargs – passed to ResultStorage.__init__()
Returns:
- abstract solve(callbacks: List[Callback] | None = None, parameters_milp: ParametersMilp | None = None, **kwargs: Any) ResultStorage [source]
Generic solving function.
- Parameters:
callbacks – list of callbacks used to hook into the various stage of the solve
**kwargs – any argument specific to the solver
Solvers deriving from SolverDo should use callbacks methods .on_step_end(), … during solve(). But some solvers are not yet updated and are just ignoring it.
Returns (ResultStorage): a result object containing potentially a pool of solutions to a discrete-optimization problem
- class discrete_optimization.generic_tools.lp_tools.MilpSolverName(value)[source]
Bases:
Enum
An enumeration.
- CBC = 0
- GRB = 1
- class discrete_optimization.generic_tools.lp_tools.ParametersMilp(time_limit: int, pool_solutions: int, mip_gap_abs: float, mip_gap: float, retrieve_all_solution: bool, n_solutions_max: int, pool_search_mode: int = 0)[source]
Bases:
object
- static default() ParametersMilp [source]
- class discrete_optimization.generic_tools.lp_tools.PymipMilpSolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]
Bases:
MilpSolver
Milp solver wrapping a solver from pymip library.
- get_var_value_for_ith_solution(var: Var, i: int) float [source]
Get value for i-th solution of a given variable.
- model: Model | None = None
- property nb_solutions: int
Number of solutions found by the solver.
- optimize_model(parameters_milp: ParametersMilp | None = None, **kwargs: Any) None [source]
Optimize the mip Model.
The solutions are yet to be retrieved via self.retrieve_solutions().
- prepare_model(parameters_milp: ParametersMilp | None = None, **kwargs: Any) None [source]
Set Gurobi Model parameters according to parameters_milp
- solve(parameters_milp: ParametersMilp | None = None, **kwargs: Any) ResultStorage [source]
Generic solving function.
- Parameters:
callbacks – list of callbacks used to hook into the various stage of the solve
**kwargs – any argument specific to the solver
Solvers deriving from SolverDo should use callbacks methods .on_step_end(), … during solve(). But some solvers are not yet updated and are just ignoring it.
Returns (ResultStorage): a result object containing potentially a pool of solutions to a discrete-optimization problem
discrete_optimization.generic_tools.ortools_cpsat_tools module
- class discrete_optimization.generic_tools.ortools_cpsat_tools.OrtoolsCPSatSolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]
Bases:
CPSolver
Generic ortools cp-sat solver.
- cp_model: CpModel | None = None
- early_stopping_exception: Exception | None = None
- abstract retrieve_solution(cpsolvercb: CpSolverSolutionCallback) Solution [source]
Construct a do solution from the cpsat solver internal solution.
It will be called each time the cpsat solver find a new solution. At that point, value of internal variables are accessible via cpsolvercb.Value(VARIABLE_NAME).
- Parameters:
cpsolvercb – the ortools callback called when the cpsat solver finds a new solution.
- Returns:
the intermediate solution, at do format.
- solve(callbacks: List[Callback] | None = None, parameters_cp: ParametersCP | None = None, **kwargs: Any) ResultStorage [source]
Solve the problem with a CPSat solver drom ortools library.
- Parameters:
callbacks – list of callbacks used to hook into the various stage of the solve
parameters_cp – parameters specific to cp solvers. We use here only parameters_cp.time_limit and parameters_cp.nb_process.
**kwargs – keyword arguments passed to self.init_model()
Returns:
A dedicated ortools callback is used to: - update a resultstorage each time a new solution is found by the cpsat solver. - call the user (do) callbacks at each new solution, with the possibility of early stopping if the callback return True.
This ortools callback use the method self.retrieve_solution() to reconstruct a do Solution from the cpsat solve internal state.
- class discrete_optimization.generic_tools.ortools_cpsat_tools.OrtoolsCallback(do_solver: OrtoolsCPSatSolver, callback: Callback)[source]
Bases:
CpSolverSolutionCallback
- discrete_optimization.generic_tools.ortools_cpsat_tools.cpstatus_to_dostatus(status_from_cpsat) StatusSolver [source]
- Parameters:
status_from_cpsat – either [UNKNOWN,INFEASIBLE,OPTIMAL,FEASIBLE] from ortools.cp api.
- Returns:
Status
discrete_optimization.generic_tools.path_tools module
discrete_optimization.generic_tools.plot_utils module
Contains common utilities to plot solution, for now it’s mainly to patch API break happening with matplotlib3.9.0 on colors.
discrete_optimization.generic_tools.qiskit_tools module
- class discrete_optimization.generic_tools.qiskit_tools.QiskitQAOASolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]
Bases:
SolverDO
- abstract init_model(**kwargs: Any) None [source]
Initialize intern model used to solve.
Can initialize a ortools, milp, gurobi, … model.
- abstract retrieve_current_solution(result) Solution [source]
Retrieve current solution from qiskit result.
- Parameters:
result – list of value for each binary variable of the problem
- Returns:
the converted solution at d-o format
- solve(callbacks: List[Callback] | None = None, **kwargs: Any) ResultStorage [source]
Generic solving function.
- Parameters:
callbacks – list of callbacks used to hook into the various stage of the solve
**kwargs – any argument specific to the solver
Solvers deriving from SolverDo should use callbacks methods .on_step_end(), … during solve(). But some solvers are not yet updated and are just ignoring it.
Returns (ResultStorage): a result object containing potentially a pool of solutions to a discrete-optimization problem
- class discrete_optimization.generic_tools.qiskit_tools.QiskitVQESolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]
Bases:
SolverDO
- abstract init_model(**kwargs: Any) None [source]
Initialize intern model used to solve.
Can initialize a ortools, milp, gurobi, … model.
- abstract retrieve_current_solution(result) Solution [source]
Retrieve current solution from qiskit result.
- Parameters:
result – list of value for each binary variable of the problem
- Returns:
the converted solution at d-o format
- solve(callbacks: List[Callback] | None = None, **kwargs: Any) ResultStorage [source]
Generic solving function.
- Parameters:
callbacks – list of callbacks used to hook into the various stage of the solve
**kwargs – any argument specific to the solver
Solvers deriving from SolverDo should use callbacks methods .on_step_end(), … during solve(). But some solvers are not yet updated and are just ignoring it.
Returns (ResultStorage): a result object containing potentially a pool of solutions to a discrete-optimization problem