discrete_optimization.generic_tools package

Subpackages

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

on_model(model: Model) bool[source]
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, time_limit: float | None = 100.0, **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

  • time_limit – the solve process stops after this time limit (in seconds). If None, no time limit is applied.

  • **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.

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

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.

callback: Callback

User-definied callback to be called at each step.

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.

solution: Solution

Solution wrapped.

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>, depends_on=None, name_in_kwargs='cp_solver_name')]

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, time_limit: float | None = 100.0, **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 LnsCpMzn.

  • time_limit – the solve process stops after this time limit (in seconds). If None, no time limit is applied.

  • **kwargs – any argument specific to the solver

Returns:

class discrete_optimization.generic_tools.cp_tools.ParametersCp(intermediate_solution: bool, 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

copy() ParametersCp[source]
static default() ParametersCp[source]
static default_cpsat() ParametersCp[source]
static default_fast_lns() ParametersCp[source]
static default_free() ParametersCp[source]
intermediate_solution: bool
multiprocess: bool
nb_process: int
optimisation_level: int
class discrete_optimization.generic_tools.cp_tools.SignEnum(value)[source]

Bases: Enum

An enumeration.

EQUAL = '=='
LEQ = '<='
LESS = '<'
UEQ = '>='
UP = '>'
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.LocalMove[source]

Bases: object

abstract apply_local_move(solution: Solution) Solution[source]
abstract backtrack_local_move(solution: Solution) Solution[source]
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.

apply_local_move(solution: Solution) Solution[source]
backtrack_local_move(solution: Solution) Solution[source]
class discrete_optimization.generic_tools.do_mutation.Mutation[source]

Bases: object

static build(problem: Problem, solution: Solution, **kwargs: Any) Mutation[source]
abstract mutate(solution: Solution) tuple[Solution, LocalMove][source]
abstract mutate_and_compute_obj(solution: Solution) tuple[Solution, LocalMove, dict[str, float]][source]

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.

lower_bound_vector_encoding(encoding_name: str) list[int][source]

Return for an encoding that is of type LIST_INTEGER or associated, the lower bound vector. Examples: if the vector should contains value higher or equal to 1, the function will return a list full of 1.

upper_bound_vector_encoding(encoding_name: str) 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.

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:

BaseMethodAggregating

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.

get_objective_names() list[str][source]
objective_handling: ObjectiveHandling
objective_sense: ModeOptim
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]
sense_function: ModeOptim
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

get_objective_names() list[str][source]
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.

abstract get_solution_type() type[Solution][source]

Returns the class implementation of a Solution.

Returns (class): class object of the given Problem.

abstract satisfy(variable: Solution) bool[source]

Computes if a solution satisfies or not the constraints of the problem.

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.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.

get_solution_type() type[Solution][source]

See `Problem.get_solution_type` 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, ABC

Base class for a discrete-optimization solver.

add_lexico_constraint(obj: str, value: float) Iterable[Any][source]

Add a constraint on a computed sub-objective

Parameters:
  • obj – a string representing the desired objective. Should be one of self.get_lexico_objectives_available().

  • value – the limiting value. If the optimization direction is maximizing, this is a lower bound, else this is an upper bound.

Returns:

the created constraints.

create_result_storage(list_solution_fits: list[tuple[Solution, float | TupleFitness]] | None = None) ResultStorage[source]

Create a result storage with the proper mode_optim.

Parameters:

list_solution_fits

Returns:

get_lexico_objective_value(obj: str, res: ResultStorage) float[source]

Get best internal model objective value found by last call to solve().

The default implementation consists in using the fit of the last solution in result_storage. This assumes: - that the last solution is the best one for the objective considered - that no aggregation was performed but rather that the fitness is a TupleFitness

with values in the same order as self.problem.get_objective_names().

Parameters:
  • obj – a string representing the desired objective. Should be one of self.get_lexico_objectives_available().

  • res – result storage returned by last call to solve().

Returns:

get_lexico_objectives_available() list[str][source]

List objectives available for lexico optimization

It corresponds to the labels accepted for obj argument for - set_lexico_objective() - add_lexico_constraint() - get_lexico_objective_value()

Default to self.problem.get_objective_names().

Returns:

static implements_lexico_api() bool[source]

Tell whether this solver is implementing the api for lexicographic optimization.

Should return True only if

  • set_lexico_objective()

  • add_lexico_constraint()

  • get_lexico_objective_value()

have been really implemented, i.e. - calling set_lexico_objective() and add_lexico_constraint()

should actually change the next call to solve(),

  • get_lexico_objective_value() should correspond to the internal model objective

init_model(**kwargs: Any) None[source]

Initialize internal model used to solve.

Can initialize a ortools, milp, gurobi, … model.

is_optimal() bool | None[source]

Tell if found solution is supposed to be optimal.

To be called after a solve.

Returns:

optimality of the solution. If information missing, returns None instead.

problem: Problem
remove_constraints(constraints: Iterable[Any]) None[source]

Remove the internal model constraints.

Parameters:

constraints – constraints created for instance with add_lexico_constraint()

Returns:

set_lexico_objective(obj: str) None[source]

Update internal model objective.

Parameters:

obj – a string representing the desired objective. Should be one of self.get_lexico_objectives_available().

Returns:

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

status_solver: StatusSolver = 'UNKNOWN'
class discrete_optimization.generic_tools.do_solver.StatusSolver(value)[source]

Bases: Enum

An enumeration.

OPTIMAL = 'OPTIMAL'
SATISFIED = 'SATISFIED'
UNKNOWN = 'UNKNOWN'
UNSATISFIABLE = 'UNSATISFIABLE'
class discrete_optimization.generic_tools.do_solver.TrivialSolverFromResultStorage(problem: Problem, result_storage: ResultStorage, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]

Bases: SolverDO, WarmstartMixin

Trivial solver created from an already computed result storage.

set_warm_start(solution: Solution) None[source]

Add solution add result_storage’s start.

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.do_solver.TrivialSolverFromSolution(problem: Problem, solution: Solution, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]

Bases: SolverDO

Trivial solver created from an already computed solution.

set_warm_start(solution: Solution) None[source]

Replace the stored solution.

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.do_solver.WarmstartMixin[source]

Bases: ABC

Mixin class for warmstart-ready solvers.

abstract set_warm_start(solution: Solution) None[source]

Make the solver warm start from the given solution.

discrete_optimization.generic_tools.dyn_prog_tools module

class discrete_optimization.generic_tools.dyn_prog_tools.DpCallback(do_solver: DpSolver, callback: Callback)[source]

Bases: object

on_solution_callback(sol: Solution) bool[source]
store_current_solution(sol: Solution)[source]
class discrete_optimization.generic_tools.dyn_prog_tools.DpSolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]

Bases: SolverDO

early_stopping_exception: Exception | None = None
hyperparameters: list[Hyperparameter] = [CategoricalHyperparameter(name='solver', default=<class 'builtins.CABS'>, depends_on=None, name_in_kwargs='solver')]

Hyperparameters available for this solver.

These hyperparameters are to be feed to **kwargs found in
  • __init__()

  • init_model() (when available)

  • solve()

abstract init_model(**kwargs: Any) None[source]

Initialize internal model used to solve.

Can initialize a ortools, milp, gurobi, … model.

initial_solution: list[Transition] | None = None
model: Model = None
abstract retrieve_solution(sol: Solution) Solution[source]
solve(callbacks: List[Callback] | None = None, time_limit: float | None = 100.0, retrieve_intermediate_solutions: bool = True, **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

exception discrete_optimization.generic_tools.exceptions.SolveEarlyStop[source]

Bases: Exception

Exception used to stop some solvers

See for instance discrete_optimization.gpdp.solver.ortools_solver.OrtoolsGpdpSolver.

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.ghh_tools.min_operator_list(list_: Iterable[SupportsRichComparisonT]) SupportsRichComparisonT[source]
discrete_optimization.generic_tools.ghh_tools.protected_div(left: float, right: float) float[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

ancestors_map() dict[Hashable, set[Hashable]][source]
build_edges() None[source]
build_nodes_infos_dict() None[source]
check_loop() list[tuple[Hashable, Hashable, str]] | None[source]
compute_all_shortest_path(attribute_name: str | None = None) dict[Hashable, dict[Hashable, tuple[list[Hashable], float]]][source]
compute_length(path: list[Hashable], attribute_name: str | None = None)[source]
compute_shortest_path(source: Hashable, target: Hashable, attribute_name: str | None = None)[source]
descendants_map() dict[Hashable, set[Hashable]][source]
get_attr_edge(node1: Hashable, node2: Hashable, attr: str) Any[source]
get_attr_node(node: Hashable, attr: str) Any[source]
get_edges() KeysView[tuple[Hashable, Hashable]][source]
get_neighbors(node: Hashable) set[Hashable][source]
get_nodes() list[Hashable][source]
get_predecessors(node: Hashable) set[Hashable][source]
precedessors_nodes(n: Hashable) set[Hashable][source]
predecessors_map() dict[Hashable, list[Hashable]][source]
successors_map() dict[Hashable, list[Hashable]][source]
to_networkx() DiGraph[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.20/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.lexico_tools module

Tools for lexicographic optimization.

class discrete_optimization.generic_tools.lexico_tools.LexicoSolver(subsolver: SolverDO | None, problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]

Bases: SolverDO

init_model(**kwargs: Any) None[source]

Initialize internal model used to solve.

Can initialize a ortools, milp, gurobi, … model.

solve(callbacks: list[Callback] | None = None, objectives: Iterable[str] | 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

subsolver: SolverDO

discrete_optimization.generic_tools.lns_cp module

class discrete_optimization.generic_tools.lns_cp.BaseLnsCp(problem: Problem, subsolver: CpSolver | 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: BaseLns

Large Neighborhood Search solver using a cp solver at each iteration.

solve(nb_iteration_lns: int, parameters_cp: ParametersCp | None = None, time_limit_subsolver: float | None = 100.0, time_limit_subsolver_iter0: float | None = None, nb_iteration_no_improvement: int | None = None, skip_initial_solution_provider: bool = False, stop_first_iteration_if_optimal: bool = True, callbacks: list[Callback] | None = None, **kwargs: Any) ResultStorage[source]

Solve the problem with an LNS loop

Parameters:
  • nb_iteration_lns – number of lns iteration

  • parameters_cp – parameters needed by the cp solver

  • time_limit_subsolver – time limit (in seconds) for a subsolver solve() call If None, no time limit is applied.

  • time_limit_subsolver_iter0 – time limit (in seconds) for the first subsolver solve() call, in the case we are skipping the initial solution provider (skip_initial_solution_provider is True) If None, we use the regular time_limit parameter even for this first solve.

  • nb_iteration_no_improvement – maximal number of consecutive iteration without improvement allowed before stopping the solve process.

  • skip_initial_solution_provider – if True, we do not use self.initial_solution_provider but instead launch a first self.subsolver.solve()

  • stop_first_iteration_if_optimal – if True, if skip_initial_solution_provider, and if subsolver tells its result is optimal after the first `self.subsolver.solve() (so before any constraint tempering), we stop the solve process.

  • callbacks – list of callbacks used to hook into the various stage of the solve

  • **kwargs – passed to the subsolver

Returns:

subsolver: CpSolver

Sub-solver used by this lns solver at each iteration.

class discrete_optimization.generic_tools.lns_cp.LnsCpMzn(problem: Problem, subsolver: MinizincCpSolver | None = None, initial_solution_provider: InitialSolution | None = None, constraint_handler: MznConstraintHandler | None = None, post_process_solution: PostProcessSolution | None = None, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]

Bases: BaseLnsCp

constraint_handler: MznConstraintHandler
create_submodel() AbstractContextManager[source]

Create a branch of the current instance, wrapped in a context manager.

init_model(**kwargs: Any) None[source]

Initialize internal model used to solve.

Can initialize a ortools, milp, gurobi, … model.

subsolver: MinizincCpSolver

Sub-solver used by this lns solver at each iteration.

class discrete_optimization.generic_tools.lns_cp.LnsOrtoolsCpSat(problem: Problem, subsolver: OrtoolsCpSatSolver | 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: BaseLnsCp

init_model(**kwargs: Any) None[source]

Initialize internal model used to solve.

Can initialize a ortools, milp, gurobi, … model.

subsolver: OrtoolsCpSatSolver

Sub-solver used by this lns solver at each iteration.

class discrete_optimization.generic_tools.lns_cp.MznConstraintHandler[source]

Bases: ConstraintHandler

abstract adding_constraint_from_results_store(solver: MinizincCpSolver, child_instance: Instance, result_storage: ResultStorage, last_result_store: ResultStorage | None = None, **kwargs: Any) Iterable[Any][source]
remove_constraints_from_previous_iteration(solver: SolverDO, previous_constraints: Iterable[Any], **kwargs: Any) None[source]

Remove previous constraints.

Nothing to do for minizinc solvers as the constraints were added only to the child instance.

class discrete_optimization.generic_tools.lns_cp.OrtoolsCpSatConstraintHandler[source]

Bases: ConstraintHandler

Base class for constraint handler for solvers based on ortools

abstract adding_constraint_from_results_store(solver: OrtoolsCpSatSolver, result_storage: ResultStorage, **kwargs: Any) Iterable[Constraint][source]
remove_constraints_from_previous_iteration(solver: OrtoolsCpSatSolver, previous_constraints: Iterable[Constraint], **kwargs: Any) None[source]

Clear specified cpsat constraints.

discrete_optimization.generic_tools.lns_mip module

class discrete_optimization.generic_tools.lns_mip.GurobiConstraintHandler[source]

Bases: ConstraintHandler

remove_constraints_from_previous_iteration(solver: GurobiMilpSolver, previous_constraints: Iterable[Any], **kwargs: Any) None[source]
class discrete_optimization.generic_tools.lns_mip.LnsMilp(problem: Problem, subsolver: MilpSolver | 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: BaseLns

Large Neighborhood Search solver using a milp solver at each iteration.

init_model(**kwargs: Any) None[source]

Initialize internal model used to solve.

Can initialize a ortools, milp, gurobi, … model.

solve(nb_iteration_lns: int, parameters_milp: ParametersMilp | None = None, time_limit_subsolver: float | None = 30.0, time_limit_subsolver_iter0: float | None = None, nb_iteration_no_improvement: int | None = None, skip_initial_solution_provider: bool = False, stop_first_iteration_if_optimal: bool = True, callbacks: list[Callback] | None = None, **kwargs: Any) ResultStorage[source]

Solve the problem with an LNS loop

Parameters:
  • nb_iteration_lns – number of lns iteration

  • parameters_milp – parameters needed by the milp solver

  • time_limit_subsolver – time limit (in seconds) for a subsolver solve() call If None, no time limit is applied.

  • time_limit_subsolver_iter0 – time limit (in seconds) for the first subsolver solve() call, in the case we are skipping the initial solution provider (skip_initial_solution_provider is True) If None, we use the regular time_limit parameter even for this first solve.

  • nb_iteration_no_improvement – maximal number of consecutive iteration without improvement allowed before stopping the solve process.

  • skip_initial_solution_provider – if True, we do not use self.initial_solution_provider but instead launch a first self.subsolver.solve()

  • stop_first_iteration_if_optimal – if True, if skip_initial_solution_provider, and if subsolver tells its result is optimal after the first `self.subsolver.solve() (so before any constraint tempering), we stop the solve process.

  • callbacks – list of callbacks used to hook into the various stage of the solve

  • **kwargs – passed to the subsolver

Returns:

subsolver: MilpSolver

Sub-solver used by this lns solver at each iteration.

class discrete_optimization.generic_tools.lns_mip.OrtoolsMathOptConstraintHandler[source]

Bases: ConstraintHandler

remove_constraints_from_previous_iteration(solver: OrtoolsMathOptMilpSolver, previous_constraints: Iterable[Any], **kwargs: Any) None[source]

discrete_optimization.generic_tools.lns_tools module

class discrete_optimization.generic_tools.lns_tools.BaseLns(problem: Problem, subsolver: SolverDO | 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, WarmstartMixin

Base class for Large Neighborhood Search solvers.

constraint_handler: ConstraintHandler
create_submodel() AbstractContextManager[source]
hyperparameters: list[Hyperparameter] = [SubBrickHyperparameter(name='subsolver', default=None, depends_on=None, name_in_kwargs='subsolver_subbrick'), SubBrickHyperparameter(name='initial_solution_provider', default=None, depends_on=('skip_initial_solution_provider', [False]), name_in_kwargs='initial_solution_provider_subbrick'), SubBrickHyperparameter(name='constraint_handler', default=None, depends_on=None, name_in_kwargs='constraint_handler_subbrick'), SubBrickHyperparameter(name='post_process_solution', default=None, depends_on=None, name_in_kwargs='post_process_solution_subbrick'), CategoricalHyperparameter(name='skip_initial_solution_provider', default=False, depends_on=None, name_in_kwargs='skip_initial_solution_provider')]

Hyperparameters available for this solver.

These hyperparameters are to be feed to **kwargs found in
  • __init__()

  • init_model() (when available)

  • solve()

initial_solution_provider: InitialSolution | None
post_process_solution: PostProcessSolution | None
set_warm_start(solution: Solution) None[source]

Make the solver warm start from the given solution.

Be careful, if you set in skip_initial_solution_provider=True in self.solve(), the initial solution will be ignored.

solve(nb_iteration_lns: int, time_limit_subsolver: float | None = 100.0, time_limit_subsolver_iter0: float | None = None, nb_iteration_no_improvement: int | None = None, skip_initial_solution_provider: bool = False, stop_first_iteration_if_optimal: bool = True, callbacks: list[Callback] | None = None, **kwargs: Any) ResultStorage[source]

Solve the problem with an LNS loop

Parameters:
  • nb_iteration_lns – number of lns iteration

  • time_limit_subsolver – time limit (in seconds) for a subsolver solve() call If None, no time limit is applied.

  • time_limit_subsolver_iter0 – time limit (in seconds) for the first subsolver solve() call, in the case we are skipping the initial solution provider (skip_initial_solution_provider is True) If None, we use the regular time_limit parameter even for this first solve.

  • nb_iteration_no_improvement – maximal number of consecutive iteration without improvement allowed before stopping the solve process.

  • skip_initial_solution_provider – if True, we do not use self.initial_solution_provider but instead launch a first self.subsolver.solve()

  • stop_first_iteration_if_optimal – if True, if skip_initial_solution_provider, and if subsolver tells its result is optimal after the first `self.subsolver.solve() (so before any constraint tempering), we stop the solve process.

  • callbacks – list of callbacks used to hook into the various stage of the solve

  • **kwargs – passed to the subsolver

Returns:

subsolver: SolverDO

Sub-solver used by this lns solver at each iteration.

class discrete_optimization.generic_tools.lns_tools.ConstraintHandler[source]

Bases: Hyperparametrizable

abstract adding_constraint_from_results_store(solver: SolverDO, result_storage: ResultStorage, **kwargs: Any) Iterable[Any][source]
abstract remove_constraints_from_previous_iteration(solver: SolverDO, previous_constraints: Iterable[Any], **kwargs: Any) None[source]
class discrete_optimization.generic_tools.lns_tools.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(solver: SolverDO, result_storage: ResultStorage, **kwargs: Any) Iterable[Any][source]
remove_constraints_from_previous_iteration(solver: SolverDO, previous_constraints: Iterable[Any], **kwargs: Any) None[source]
class discrete_optimization.generic_tools.lns_tools.ConstraintStatus[source]

Bases: TypedDict

name: str
nb_improvement: int
nb_usage: int
class discrete_optimization.generic_tools.lns_tools.InitialSolution[source]

Bases: Hyperparametrizable

abstract get_starting_solution() ResultStorage[source]
class discrete_optimization.generic_tools.lns_tools.InitialSolutionFromSolver(solver: SolverDO, **kwargs: Any)[source]

Bases: InitialSolution

abstract get_starting_solution() ResultStorage[source]
class discrete_optimization.generic_tools.lns_tools.PostProcessSolution[source]

Bases: Hyperparametrizable

abstract build_other_solution(result_storage: ResultStorage) ResultStorage[source]
class discrete_optimization.generic_tools.lns_tools.TrivialInitialSolution(solution: ResultStorage, **kwargs: Any)[source]

Bases: InitialSolution

abstract get_starting_solution() ResultStorage[source]
class discrete_optimization.generic_tools.lns_tools.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

add_binary_variable(name: str = '') Any[source]

Add a binary variable to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

add_continuous_variable(lb: float = 0.0, ub: float = inf, name: str = '') Any[source]

Add a continuous variable to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

Parameters:
  • lb – lower bound

  • ub – upper bound

add_integer_variable(lb: float = 0.0, ub: float = inf, name: str = '') Any[source]

Add an integer variable to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

Parameters:
  • lb – lower bound

  • ub – upper bound

add_linear_constraint(expr: Any, name: str = '') Any[source]

Add a linear constraint to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

static construct_linear_sum(expr: Iterable) Any[source]

Generate a linear sum (with variables) ready for the internal model.

static create_empty_model(name: str = '') Any[source]

Generate an empty milp model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

get_obj_value_for_ith_solution(i: int) float[source]

Get objective value for i-th solution.

get_var_value_for_ith_solution(var: docplex.mp.dvar.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
set_model_objective(expr: Any, minimize: bool) None[source]

Define the model objective.

Useful to write an init_model() common to gurobi and ortools/mathopt.

Parameters:
  • expr

  • minimize – if True, objective will be minimized, else maximized

Returns:

solve(parameters_milp: ParametersMilp | None = None, time_limit: float | None = 30.0, **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, WarmstartMixin

Milp solver wrapping a solver from gurobi library.

add_binary_variable(name: str = '') gurobipy.Var[source]

Add a binary variable to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

add_continuous_variable(lb: float = 0.0, ub: float = inf, name: str = '') gurobipy.Var[source]

Add a continuous variable to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

Parameters:
  • lb – lower bound

  • ub – upper bound

add_integer_variable(lb: float = 0.0, ub: float = inf, name: str = '') gurobipy.Var[source]

Add an integer variable to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

Parameters:
  • lb – lower bound

  • ub – upper bound

add_linear_constraint(expr: Any, name: str = '') gurobipy.Constr[source]

Add a linear constraint to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

add_linear_constraint_with_indicator(binvar: Variable, binval: int, lhs: Any, sense: InequalitySense, rhs: Any, penalty_coeff=100000, name: str = '') list[LinearConstraint][source]

Add a linear constraint dependending on the value of an indicator (boolean var)

This wraps `gurobipy.Model.addGenConstrIndicator().

Parameters:
  • binvar

  • binval

  • lhs

  • sense

  • rhs

  • penalty_coeff

  • name

Returns:

static construct_linear_sum(expr: Iterable) Any[source]

Generate a linear sum (with variables) ready for the internal model.

abstract convert_to_variable_values(solution: Solution) dict[gurobipy.Var, float][source]

Convert a solution to a mapping between model variables and their values.

Will be used by set_warm_start().

Override it in subclasses to have a proper warm start. You can also override set_warm_start() if default behaviour is not sufficient.

static create_empty_model(name: str = '') gurobipy.Model[source]

Generate an empty milp model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

early_stopping_exception: Exception | None = None
get_obj_value_for_ith_solution(i: int) float[source]

Get objective value for i-th solution.

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, time_limit: float | None = 30.0, gurobi_callback: GurobiCallback | 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, time_limit: float | None = 30.0, **kwargs: Any) None[source]

Set Gurobi Model parameters according to parameters_milp

remove_constraints(constraints: Iterable[Any]) None[source]

Remove the internal model constraints.

Parameters:

constraints – constraints created for instance with add_lexico_constraint()

Returns:

set_model_objective(expr: Any, minimize: bool) None[source]

Define the model objective.

Useful to write an init_model() common to gurobi and ortools/mathopt.

Parameters:
  • expr

  • minimize – if True, objective will be minimized, else maximized

Returns:

set_random_seed(random_seed: int) None[source]
set_warm_start(solution: Solution) None[source]

Make the solver warm start from the given solution.

By default, this is using convert_to_variable_values(). If not sufficient, you can override it. (And for instance make implementation of convert_to_variable_values() raise a NotImplementedError.)

set_warm_start_from_values(variable_values: dict[gurobipy.Var, float]) None[source]

Make the model variables warm start from the given values.

solve(callbacks: list[Callback] | None = None, parameters_milp: ParametersMilp | None = None, time_limit: float | None = 30.0, **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.InequalitySense(value)[source]

Bases: Enum

Sense of an inequality/equality.

EQUAL = '=='
GREATER_OR_EQUAL = '>='
LOWER_OR_EQUAL = '<='
class discrete_optimization.generic_tools.lp_tools.MathOptCallback(do_solver: OrtoolsMathOptMilpSolver, callback: Callback)[source]

Bases: object

class discrete_optimization.generic_tools.lp_tools.MilpSolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]

Bases: SolverDO

abstract add_binary_variable(name: str = '') Any[source]

Add a binary variable to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

abstract add_continuous_variable(lb: float = 0.0, ub: float = inf, name: str = '') Any[source]

Add a continuous variable to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

Parameters:
  • lb – lower bound

  • ub – upper bound

abstract add_integer_variable(lb: float = 0.0, ub: float = inf, name: str = '') Any[source]

Add an integer variable to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

Parameters:
  • lb – lower bound

  • ub – upper bound

abstract add_linear_constraint(expr: Any, name: str = '') Any[source]

Add a linear constraint to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

add_linear_constraint_with_indicator(binvar: Variable, binval: int, lhs: Any, sense: InequalitySense, rhs: Any, penalty_coeff=100000, name: str = '') list[LinearConstraint][source]

Add a linear constraint depending on the value of an indicator (boolean var)

This mirrors `gurobipy.Model.addGenConstrIndicator().

Parameters:
  • binvar

  • binval

  • lhs

  • sense

  • rhs

  • penalty_coeff

  • name

Returns:

abstract static construct_linear_sum(expr: Iterable) Any[source]

Generate a linear sum (with variables) ready for the internal model.

abstract static create_empty_model(name: str = '') Any[source]

Generate an empty milp model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

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 internal 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) ResultStorage[source]

Retrieve solutions found by internal solver.

Parameters:

parameters_milp

Returns:

abstract set_model_objective(expr: Any, minimize: bool) None[source]

Define the model objective.

Useful to write an init_model() common to gurobi and ortools/mathopt.

Parameters:
  • expr

  • minimize – if True, objective will be minimized, else maximized

Returns:

set_warm_start_from_values(variable_values: dict[Variable, float]) None[source]

Make the model variables warm start from the given values.

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.OrtoolsMathOptMilpSolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs: Any)[source]

Bases: MilpSolver, WarmstartMixin

Milp solver wrapping a solver from pymip library.

add_binary_variable(name: str = '') Variable[source]

Add a binary variable to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

add_continuous_variable(lb: float = 0.0, ub: float = inf, name: str = '') Variable[source]

Add a continuous variable to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

Parameters:
  • lb – lower bound

  • ub – upper bound

add_integer_variable(lb: float = 0.0, ub: float = inf, name: str = '') Variable[source]

Add an integer variable to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

Parameters:
  • lb – lower bound

  • ub – upper bound

add_linear_constraint(expr: Any, name: str = '') LinearConstraint[source]

Add a linear constraint to the model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

static construct_linear_sum(expr: Iterable) Any[source]

Generate a linear sum (with variables) ready for the internal model.

convert_to_dual_values(solution: Solution) dict[LinearConstraint, float][source]

Convert a solution to a mapping between model contraints and their values.

Will be used by set_warm_start() to provide a suitable SolutionHint.dual_values. See https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/model_parameters.html#SolutionHint for more information. Generally MIP solvers do not need this part, but LP solvers do.

abstract convert_to_variable_values(solution: Solution) dict[Variable, float][source]

Convert a solution to a mapping between model variables and their values.

Will be used by set_warm_start() to provide a suitable SolutionHint.variable_values. See https://or-tools.github.io/docs/pdoc/ortools/math_opt/python/model_parameters.html#SolutionHint for more information.

Override it in subclasses to have a proper warm start.

static create_empty_model(name: str = '') Model[source]

Generate an empty milp model.

Useful to write an init_model() common to gurobi and ortools/mathopt.

early_stopping_exception: Exception | None = None
get_obj_value_for_ith_solution(i: int) float[source]

Get objective value for i-th solution.

get_var_value_for_ith_solution(var: Any, i: int) float[source]

Get value for i-th solution of a given variable.

has_quadratic_objective: bool = False

Flag telling that the objective is a quadratic expression.

This is use to pass the proper function to retrieve_current_solution for the objective. Should be overriden to True in solvers with quadratic objectives.

hyperparameters: list[Hyperparameter] = [EnumHyperparameter(name='mathopt_solver_type', default=None, depends_on=None, name_in_kwargs='mathopt_solver_type')]

Hyperparameters available for this solver.

These hyperparameters are to be feed to **kwargs found in
  • __init__()

  • init_model() (when available)

  • solve()

model: mathopt.Model | None = None
property nb_solutions: int

Number of solutions found by the solver.

optimize_model(parameters_milp: ParametersMilp | None = None, mathopt_solver_type: SolverType = SolverType.CP_SAT, time_limit: float | None = 30.0, mathopt_cb: Callable[[CallbackData], CallbackResult] | None = None, mathopt_enable_output: bool = False, mathopt_model_parameters: ModelSolveParameters | None = None, mathopt_additional_solve_parameters: SolveParameters | None = None, **kwargs: Any) SolveResult[source]
Parameters:
  • parameters_milp – parameters for the milp solver

  • mathopt_solver_type – underlying solver type to use. Passed as solver_type to mathopt.solve()

  • time_limit – the solve process stops after this time limit (in seconds). If None, no time limit is applied.

  • mathopt_cb – a mathopt callback passed to mathopt.solve() called at each new solution found

  • mathopt_enable_output – turn on mathopt logging

  • mathopt_model_parameters – passed to mathopt.solve() as model_params

  • mathopt_additional_solve_parameters – passed to mathopt.solve() as params, except that parameters defined by above time_limit, parameters_milp, and mathopt_enable_output will be overriden by them.

  • **kwargs – passed to init_model() if model not yet existing

Returns:

random_seed: int | None = None
remove_constraints(constraints: Iterable[Any]) None[source]

Remove the internal model constraints.

Parameters:

constraints – constraints created for instance with add_lexico_constraint()

Returns:

set_model_objective(expr: Any, minimize: bool) None[source]

Define the model objective.

Useful to write an init_model() common to gurobi and ortools/mathopt.

Parameters:
  • expr

  • minimize – if True, objective will be minimized, else maximized

Returns:

set_random_seed(random_seed: int) None[source]
set_warm_start(solution: Solution) None[source]

Make the solver warm start from the given solution.

set_warm_start_from_values(variable_values: dict[Variable, float], dual_values: dict[LinearConstraint, float] | None = None) None[source]

Make the model variables warm start from the given values.

solution_hint: mathopt.SolutionHint | None = None
solve(callbacks: list[Callback] | None = None, parameters_milp: ParametersMilp | None = None, mathopt_solver_type: SolverType = SolverType.CP_SAT, time_limit: float | None = 30.0, mathopt_enable_output: bool = False, mathopt_model_parameters: ModelSolveParameters | None = None, mathopt_additional_solve_parameters: SolveParameters | None = None, **kwargs: Any) ResultStorage[source]

Solve with OR-Tools MathOpt API

Parameters:
  • callbacks – list of callbacks used to hook into the various stage of the solve

  • parameters_milp – parameters passed to the MILP solver

  • mathopt_solver_type – underlying solver type to use. Passed as solver_type to mathopt.solve()

  • time_limit – the solve process stops after this time limit (in seconds). If None, no time limit is applied.

  • mathopt_enable_output – turn on mathopt logging

  • mathopt_model_parameters – passed to mathopt.solve() as model_params

  • mathopt_additional_solve_parameters – passed to mathopt.solve() as params, except that parameters defined by above time_limit and parameters_milp will be overriden by them.

  • **kwargs – passed to init_model() if model not yet existing

Returns:

termination: mathopt.Termination
class discrete_optimization.generic_tools.lp_tools.ParametersMilp(pool_solutions: int, mip_gap_abs: float, mip_gap: float, retrieve_all_solution: bool, pool_search_mode: int = 0)[source]

Bases: object

static default() ParametersMilp[source]

discrete_optimization.generic_tools.ortools_cpsat_tools module

class discrete_optimization.generic_tools.ortools_cpsat_tools.OrtoolsCpSatCallback(do_solver: OrtoolsCpSatSolver, callback: Callback, retrieve_stats: bool = False)[source]

Bases: CpSolverSolutionCallback

on_solution_callback() None[source]
store_current_solution()[source]
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.

clb: CpSolverSolutionCallback | None = None
cp_model: CpModel | None = None
early_stopping_exception: Exception | None = None
remove_constraints(constraints: Iterable[Any]) None[source]

Remove the internal model constraints.

Parameters:

constraints – constraints created for instance with add_lexico_constraint()

Returns:

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, time_limit: float | None = 100.0, ortools_cpsat_solver_kwargs: dict[str, Any] | None = None, retrieve_stats: bool = False, **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

  • time_limit – the solve process stops after this time limit (in seconds). If None, no time limit is applied.

  • parameters_cp – parameters specific to cp solvers. We use here only parameters_cp.nb_process.

  • ortools_cpsat_solver_kwargs – used to customize the underlying ortools solver. Each key/value will update the corresponding attribute from the ortools.sat.python.cp_model.CpSolver

  • retrieve_stats – retrieve detailed stats of cpsat solving in the cpsat callback

  • object. (and store it in the res)

  • **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.

solver: CpSolver | None = None
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.path_tools.abspath_from_file(file: str, relative_path: str) str[source]
discrete_optimization.generic_tools.path_tools.get_directory(file: str) str[source]

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.plot_utils.get_cmap(color_map_str: str)[source]
discrete_optimization.generic_tools.plot_utils.get_cmap_with_nb_colors(color_map_str: str, nb_colors: int = 2)[source]

discrete_optimization.generic_tools.qiskit_tools module

class discrete_optimization.generic_tools.qiskit_tools.GeneralQaoaSolver(problem: Problem, model: object | GurobiMilpSolver, retrieve_solution: Callable, params_objective_function: ParamsObjectiveFunction | None = None, backend: Optional = None, **kwargs)[source]

Bases: QiskitQaoaSolver

init_model(**kwargs: Any) None[source]

Initialize internal model used to solve.

Can initialize a ortools, milp, gurobi, … model.

retrieve_current_solution(result: ndarray) 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

class discrete_optimization.generic_tools.qiskit_tools.GeneralVqeSolver(problem: Problem, model: object | GurobiMilpSolver, retrieve_solution: Callable, params_objective_function: ParamsObjectiveFunction | None = None, backend: Optional = None, **kwargs)[source]

Bases: QiskitVqeSolver

init_model(**kwargs: Any) None[source]

Initialize internal model used to solve.

Can initialize a ortools, milp, gurobi, … model.

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

class discrete_optimization.generic_tools.qiskit_tools.QiskitQaoaSolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, backend: Optional = None, **kwargs)[source]

Bases: QiskitSolver, Hyperparametrizable

hyperparameters: list[Hyperparameter] = [IntegerHyperparameter(name='reps', default=2, depends_on=None, name_in_kwargs='reps', low=1, high=6, step=1, log=False), IntegerHyperparameter(name='optimization_level', default=1, depends_on=None, name_in_kwargs='optimization_level', low=0, high=3, step=1, log=False), CategoricalHyperparameter(name='method', default='COBYLA', depends_on=None, name_in_kwargs='method'), IntegerHyperparameter(name='nb_shots', default=10000, depends_on=None, name_in_kwargs='nb_shots', low=10000, high=100000, step=10000, log=False), IntegerHyperparameter(name='maxiter', default=300, depends_on=None, name_in_kwargs='maxiter', low=100, high=1000, step=50, log=False), FloatHyperparameter(name='rhobeg', default=1.0, depends_on=None, name_in_kwargs='rhobeg', low=0.5, high=1.5, suggest_low=False, suggest_high=False, step=None, log=False), CategoricalHyperparameter(name='tol', default=0.01, depends_on=None, name_in_kwargs='tol')]

Hyperparameters available for this solver.

These hyperparameters are to be feed to **kwargs found in
  • __init__()

  • init_model() (when available)

  • solve()

abstract init_model(**kwargs: any) None[source]

Initialize internal 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, backend: Optional = None, use_session: bool | None = False, **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.QiskitSolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, **kwargs)[source]

Bases: SolverDO

set_executed_ansatz(ansatz)[source]
set_final_ansatz(ansatz)[source]
class discrete_optimization.generic_tools.qiskit_tools.QiskitVqeSolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, backend: Optional = None, **kwargs)[source]

Bases: QiskitSolver

hyperparameters: list[Hyperparameter] = [IntegerHyperparameter(name='reps', default=3, depends_on=None, name_in_kwargs='reps', low=1, high=6, step=1, log=False), IntegerHyperparameter(name='optimization_level', default=1, depends_on=None, name_in_kwargs='optimization_level', low=0, high=3, step=1, log=False), CategoricalHyperparameter(name='method', default='COBYLA', depends_on=None, name_in_kwargs='method'), IntegerHyperparameter(name='nb_shots', default=10000, depends_on=None, name_in_kwargs='nb_shots', low=10000, high=100000, step=10000, log=False), IntegerHyperparameter(name='maxiter', default=300, depends_on=None, name_in_kwargs='maxiter', low=100, high=2000, step=50, log=False), FloatHyperparameter(name='rhobeg', default=1.0, depends_on=None, name_in_kwargs='rhobeg', low=0.5, high=1.5, suggest_low=False, suggest_high=False, step=None, log=False), CategoricalHyperparameter(name='tol', default=0.01, depends_on=None, name_in_kwargs='tol')]

Hyperparameters available for this solver.

These hyperparameters are to be feed to **kwargs found in
  • __init__()

  • init_model() (when available)

  • solve()

abstract init_model(**kwargs: Any) None[source]

Initialize internal 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, backend: Optional = None, use_session: bool | None = False, **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.qiskit_tools.compute_energy(matrix, x)[source]

@param matrix: a matrix of a QUBO formulation @param x: a binary vector @return: the value of the matrix for the giving vector

discrete_optimization.generic_tools.qiskit_tools.cost_func(params, ansatz, hamiltonian, estimator, callback_dict)[source]

Return estimate of energy from estimator

Parameters:
  • params (ndarray) – Array of ansatz parameters

  • ansatz (QuantumCircuit) – Parameterized ansatz circuit

  • hamiltonian (SparsePauliOp) – Operator representation of Hamiltonian

  • estimator (EstimatorV2) – Estimator primitive instance

  • callback_dict – dictionary for storing intermediate results

Returns:

Energy estimate

Return type:

float

discrete_optimization.generic_tools.qiskit_tools.execute_ansatz_with_Hamiltonian(solver, backend, ansatz, hamiltonian, use_session: bool | None = False, **kwargs) ndarray[source]

@param solver: the solver who solve the problem, must be a QiskitSolver @param backend: the backend use to run the circuit (simulator or real device) @param ansatz: the quantum circuit @param hamiltonian: the hamiltonian corresponding to the problem @param use_session: boolean to set to True for use a session @param kwargs: a list of hyperparameters who can be specified @return: the qubit’s value the must often chose

discrete_optimization.generic_tools.qiskit_tools.get_result_from_dict_result(dict_result: dict[str, int]) ndarray[source]

@param dict_result: dictionnary where keys are qubit’s value and values are the number of time where this qubit’s value have been chosen @return: the qubit’s value the must often chose

discrete_optimization.generic_tools.qiskit_tools.gurobi_to_qubo(model)[source]
discrete_optimization.generic_tools.qiskit_tools.matrix(quad: object)[source]

@param quad: a quadratic programm, must be in QUBO form @return: the QUBO matrix

discrete_optimization.generic_tools.quantum_solvers module

Utility module to launch different solvers on the coloring problem.

discrete_optimization.generic_tools.quantum_solvers.solve(method: type[QiskitSolver], problem: MisProblem | Point2DTspProblem | KnapsackProblem | Facility2DProblem, **kwargs: Any) ResultStorage[source]

Solve a problem instance with a given class of solver.

Parameters:
  • method – class of the solver to use

  • problem – problem instance

  • **args – specific options of the solver

Returns: a ResultsStorage objecting obtained by the solver.

discrete_optimization.generic_tools.quantum_solvers.solve_coloring(method: type[QiskitSolver], problem: ColoringProblem, nb_color, **kwargs: Any) ResultStorage[source]

Solve a problem instance with a given class of solver.

Parameters:
  • method – class of the solver to use

  • problem – problem instance

  • nb_color – the number of colors or the max number of colors

  • **args – specific options of the solver

Returns: a ResultsStorage objecting obtained by the solver.

discrete_optimization.generic_tools.sequential_metasolver module

class discrete_optimization.generic_tools.sequential_metasolver.SequentialMetasolver(problem: Problem, params_objective_function: ParamsObjectiveFunction | None = None, list_subbricks: list[SubBrick] | None = None, **kwargs)[source]

Bases: SolverDO

Sequential metasolver.

The problem will be solved sequentially, each subsolver being warm started by the previous one. Therefore each subsolver must inherit from WarmstartMixin, except the first one.

hyperparameters: list[Hyperparameter] = [SubBrickHyperparameter(name='subsolver_0', default=None, depends_on=None, name_in_kwargs='subsolver_0'), ListHyperparameter(name='next_subsolvers', default=None, depends_on=None, name_in_kwargs='next_subsolvers')]

Hyperparameters available for this solver.

These hyperparameters are to be feed to **kwargs found in
  • __init__()

  • init_model() (when available)

  • solve()

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

Module contents