API Reference#
In this section we describe relevant classes and methods of the quantagonia
package.
Submitting tasks#
The heart of the package is a HybridSolver
class to conveniently submit optimization tasks and batches of tasks.
- class quantagonia.HybridSolver(api_key: str)#
The main interface to solve and manage optimization tasks with the HybridSolver.
- Parameters:
api_key (str) – The API key to be used to authenticate with the HybridSolver.
- cancel(jobid: str) None #
Sends an interrupt signal to stop the execution of the specified job.
- Parameters:
jobid (str) – The id of the job to be canceled.
- logs(jobid: str) list[str] #
Retrieves a list of logs for the given job.
- Parameters:
jobid (str) – The ID of the job to retrieve logs for.
- Returns:
A list of strings with the log for each item of the job.
- Return type:
list
- progress(jobid: str) list[dict[str, Any]] #
Retrieves a list of progress information for each item of the given job.
- The progress is a dictionary with keys for current
‘job_status’, ‘solver_status’, ‘bound’, ‘objective’, ‘abs_gap’, ‘rel_gap’, ‘solution’, ‘wall_time’, ‘nodes’, and ‘num_incumbents’.
- Parameters:
jobid (str) – The ID of the job to retrieve progress for.
- Returns:
A list of dictionaries with progress for each item of the job.
- Return type:
list
- solve(input_files: str | list, params: HybridSolverParameters | list[HybridSolverParameters] = None, tag: str = '', suppress_output: bool = False, **kwargs) tuple[list[dict[str, Any]], int] #
Solves the given input file(s) and prints the progress to the console. Note that this is a blocking method.
If you want to solve problems non-blocking or need finer control on what to do depending on the progress of the solve, use lower-level methods like
submit()
andprogress()
.- Parameters:
input_files (str or List[str]) – String or list of strings with path(st) to the input file(s).
params (HybridSolverParameters or List[HybridSolverParameters]) – (optional) HybridSolverParameters or list of HybridSolverParameters.
tag (str) – (optional) Attaches a tag to the compute job.
suppress_output (bool) – (optional) If true, all output is suppressed.
kwargs (dict) – (optional) Keyword arguments, see below.
- Keyword Arguments:
submit_callback – (optional) Custom callback function that is called when a job is submitted. Defaults to None.
new_incumbent_callback – (optional) A callback function to call if a new incumbent is found in the batch item. Defaults to None.
poll_frequency (float) – (optional) The frequency (as float, in seconds) at which the function should poll for job status. Defaults to 1.
timeout (float) – (optional) The maximum amount of time (as float, in seconds) to wait for the job to finish before timing out. Defaults to 14400.
- Returns:
- A tuple for which the first item is a list and the second item is an integer.
The list consists of dictionaries containing results of the solve. The integer specifies the minutes billed for the job.
- Return type:
tuple(list, int)
- status(jobid: str) JobStatus #
Retrieves the status of the given job.
The status is one of CREATED, RUNNING, FINISHED, TERMINATED, or TIMEOUT. Note that this only tells the processing status of the job, but nothing about the status of the items of the job. To give an example, a job is also considered finished, if all items exited with an error. Please use the
progress
method to retrieve results for the job items.- Parameters:
jobid (str) – The ID of the job.
- Returns:
The status of the job.
- Return type:
JobStatus
- submit(input_files: str | list[str], params: HybridSolverParameters | list[HybridSolverParameters] = None, tag: str = '', **kwargs) str #
Submits the given instance file(s) to the HybridSolver and returns the corresponding job id.
- Parameters:
input_files (str or List[str]) – String or list of strings with path(st) to the input file(s).
params (HybridSolverParameters or List[HybridSolverParameters]) – (optional) HybridSolverParameters or
HybridSolverParameters. (list of)
tag (str) – (optional) Attaches a tag to the compute job.
kwargs (dict) – (optional) Keyword arguments, see below.
- Keyword Arguments:
submit_callback – (optional) Custom callback function that is called when a job is submitted. Defaults to None.
- Returns:
The job id.
- Return type:
str
Solver Parameters#
You can parameterize the HybridSolver by passing a HybridSolverParameters
object. Parameters are set through dedicated setter methods.
- class quantagonia.HybridSolverParameters#
Class with setter options that allows to pass parameters to the solver.
- set_relative_gap(rel_gap: float) None #
Set the relative gap.
The relative gap corresponds to the improvement potential of the objective value relative to the best-known objective value. It is defined as \(|f^* - f^-| / |f^*|\), where \(f^*\) is the best-known objective value and \(f^-\) is the best-known bound on the objective value. The solver terminates once the relative gap falls below the specified value for
rel_gap
. The default value is set to 1e-4 (0.01%).- Parameters:
rel_gap (float) – A float representing the relative gap for termination.
- Returns:
None.
- Raises:
ValueError – If
rel_gap
is not a float or integer.
Example:
rel_gap = 1e-2 params.set_relative_gap(rel_gap)
- set_absolute_gap(abs_gap: float) None #
Set the absolute gap.
The absolute gap is the difference between the objective value \(f^*\) of the best solution found and the best bound \(f^-\) on the objective value. Hence, the absolute gap tells by how much the objective value could potentially still be improved. The solver terminates if the absolute gap falls below the specified value for
abs_gap
. The default value is set to 1e-9.- Parameters:
abs_gap (float) – A float representing the absolute gap for termination.
- Returns:
None.
- Raises:
ValueError – If
abs_gap
is not a float or integer.
Example:
abs_gap = 1e-6 params.set_absolute_gap(abs_gap)
- set_feasibility_tolerance(feas_tolerance: float) None #
Set the feasibility tolerance.
The feasibility tolerance represents the acceptable deviation from feasibility for constraints. It is defined as the maximum allowable constraint violation. Specifically, the solver ensures that all constraints are satisfied within this tolerance. The solver accepts a solution as feasible if all constraint violations are within the specified tolerance. The default value is typically set to 1e-6.
- Parameters:
feas_tolerance (float) – A float representing the feasibility tolerance for constraints.
- Returns:
None.
- Raises:
ValueError – If
feas_tolerance
is not a float or integer.
Example:
feas_tolerance = 1e-8 params.set_feasibility_tolerance(feas_tolerance)
- set_integrality_tolerance(int_tolerance: float) None #
Set the integrality tolerance.
The integrality tolerance represents the acceptable deviation from feasibility for integrality conditions. It is defined as the maximum allowable integrality violation. Specifically, the solver ensures that all integer variables deviate no more than this tolerance from their nearest integer value. The solver accepts a solution as feasible if all integrality conditions are within the specified tolerance. The default value is typically set to 1e-5.
- Parameters:
int_tolerance (float) – A float representing the integrality tolerance for integrality.
- Returns:
None.
- Raises:
ValueError – If
int_tolerance
is not a float or integer.
Example:
int_tolerance = 1e-7 params.set_integrality_tolerance(int_tolerance)
- set_time_limit(time_limit: float) None #
Sets time limit.
The solver runs at most for ‘time_limit’ seconds and returns the best found solution along with the optimality gap. The optimality gap tells you by how much the solution could possibly be improved, if the solver continues to run.
- Returns:
None
Example:
time_limit = 10 # seconds params.set_time_limit(time_limit)
- set_performance_code(performance_code: str) None #
Sets a performance code for a specific solver version.
The performance code parameter enables optimizations tailored to a specific solver version, enhancing performance for instances that are similar or belong to a defined class. When applied, the solver may find solutions and prove optimality faster by leveraging these targeted adjustments.
- Returns:
None
Example:
performance_code = "Quantagonia-42" params.set_performance_code(performance_code)
- set_as_qubo(as_qubo: bool) None #
Set the as_qubo option (IP only).
If true, the HybridSolver attempts to reformulate the given IP to a QUBO. If successful, the problem is solved as such.
Note that this is an experimental feature which is expected to solve the problem (significantly) slower compared to the default (without reformulation to QUBO).
- Parameters:
as_qubo (bool) – A bool that enables or disables the as_qubo option.
- Returns:
None.
- Raises:
ValueError – If
as_qubo
is not a bool.
- set_qubo_decomposition(qubo_decomposition: bool) None #
Set the qubo_decomposition option (MIP only).
If true, the HybridSolver attempts to decompose the MIP into MIP and QUBO subproblems. If successful, the original problem is solved to global optimality by solving a series of smaller MIPs and QUBOs.
Note that this is an experimental feature which is expected to solve the problem (significantly) slower compared to the default (without decomposition).
- Parameters:
qubo_decomposition (bool) – A bool that enables or disables the qubo_decomposition option.
- Returns:
None.
- Raises:
ValueError – If
qubo_decomposition
is not a bool.
- set_presolve(presolve: bool) None #
Enable or disable presolve.
- Parameters:
presolve (bool) – A boolean indicating whether to enable or disable presolve.
- Returns:
None.
- Raises:
ValueError – If
presolve
is not a boolean.
Example:
params.set_presolve(False)
- set_seed(seed: float) None #
Set the random number seed.
This acts as a small perturbation to some subroutines of the solver and may lead to different solution paths.
- Parameters:
seed (float) – The random number seed.
- Returns:
None.
- set_heuristics_only(heuristics_only: bool) None #
Only apply the root node primal heuristics and then terminate (QUBO only).
This waits until all primal heuristics are finished and displays a table with objective value and runtime per heuristic.
- Parameters:
heuristics_only (bool) – Flag to enable or disable heuristics_only mode.
- Returns:
None
- set_objective_limit(objective_value: float) None #
Sets a limit on the objective value to terminate optimization.
The solver terminates as soon as it finds a feasible solution with an objective value at least as good as the specified
objective_value
.- Parameters:
objective_value (float) – A float representing the termination value for the objective.
- Returns:
None.
- Raises:
ValueError – If
objective_value
is not a float or integer.
Modeling MIPs#
The quantagonia
package comes with a quantagonia.mip
module to simplify modeling and solving MIPs.
Modeling API#
You can use the Model
class to initialize a model, add variables and constraints programmatically to it,
and finally solve the model with the HybridSolver.
After the solve you can access the best-found solution and the associated objective value as well as additional statistics and
solving information using the corresponding members of the class.
The package also contains a Variable
class. Adding a variable to a model via the Model.add_variable
returns an instance of the Variable
class.
The variable can also be used to modify the model by changing its attributes (lower/upper bound,
variable coefficient in the objective function, etc.).
Note that all of this functionality builds on open-source PyScipOpt.
- class quantagonia.mip.model.Model(name: str = 'Model')#
A class representing a Mixed Integer Programming (MIP) problem instance.
- Parameters:
name (str) – (optional) The name of the MIP model. Defaults to “model”.
- property type: str#
The type of the model.
- Returns:
The type of the model.
- Return type:
str
- property name: str#
The name of the model.
- Returns:
The name of the model.
- Return type:
str
- property sense: HybridSolverOptSenses#
The optimization sense of the model.
- Returns:
The current optimization sense of the model.
- Return type:
HybridSolverOptSenses
- Raises:
ModelError – If the current sense is unsupported.
- property objective_value: float#
The objective value of the model’s best solution.
- Returns:
The objective value of the best solution found.
- Return type:
float
- property solution_status: HybridSolverStatus#
The solution status of the model.
- Returns:
The current solution status of the model.
- Return type:
HybridSolverStatus
- property solution: dict[str, float]#
The solution of the model.
- Returns:
A dictionary mapping variable names to their values in the solution.
- Return type:
dict[str, float]
- property best_bound: float#
The best bound of the model.
- Returns:
The best bound found during optimization.
- Return type:
float
- property best_time: float#
The runtime (in seconds) after which the best solution was found.
- Returns:
The runtime (in seconds) after which the best solution was found.
- Return type:
float
- property total_time: float#
The total runtime of the optimization process.
- Returns:
The total runtime (in seconds) of the optimization process.
- Return type:
float
- property objective_offset: float#
The offset of the objective function.
- Returns:
The constant offset value of the objective function.
- Return type:
float
- property n_vars: int#
The number of variables in the model.
- Returns:
The number of variables in the model.
- Return type:
int
- property n_bin_vars: int#
The number of binary variables in the model.
- Returns:
The number of binary variables in the model.
- Return type:
int
- property n_int_vars: int#
The number of integer variables in the model.
- Returns:
The number of integer variables in the model.
- Return type:
int
- property n_cont_vars: int#
The number of continuous variables in the model.
- Returns:
The number of continuous variables in the model.
- Return type:
int
- property parameters: dict#
The parameters of the model.
- Returns:
A dictionary containing the parameters of the model.
- Return type:
dict
- add_variable(lb: float = 0, ub: float = inf, name: str = '', coeff: float = 0, var_type: VarType = VarType.CONTINUOUS) Variable #
Adds a new variable to the model.
- Parameters:
lb (float) – The lower bound of the variable. Defaults to 0.
ub (float) – The upper bound of the variable. Defaults to positive infinity.
name (str) – The name of the variable. Defaults to an empty string.
coeff (float) – The coefficient of the variable in the objective function. Defaults to 0.
var_type (VarType) – The type of the variable. Defaults to VarType.CONTINUOUS.
- Returns:
The Variable instance that was added to the MIP model.
- Return type:
- Raises:
ModelError – If the variable type is unsupported or if the variable addition fails.
- get_variables() list[Variable] #
Returns a list of all variables in the model.
- Returns:
A list of all variables in the model.
- Return type:
list[Variable]
- add_constraint(expr: Expr, name: str = '') None #
Adds a constraint to the model.
- Parameters:
expr (Expression) – The expression representing the constraint.
name (str) – (optional) The name of the constraint.
- Raises:
ModelError – If the constraint addition fails.
- add_constraints(constraints: list[tuple[Expr, str]]) None #
Adds multiple constraints to the model.
- Parameters:
constraints (List[Tuple[Expression, str]]) – A list of tuples, each containing an expression and a name for a constraint.
- set_objective(expr: Expr = None, sense: HybridSolverOptSenses = HybridSolverOptSenses.MINIMIZE) None #
Sets the objective function for the model.
- Parameters:
expr (Expression) – The expression representing the objective function.
sense (HybridSolverOptSenses) – The optimization sense (minimize or maximize). Defaults to HybridSolverOptSenses.MINIMIZE.
- Raises:
ModelError – If the sense is unsupported or if setting the objective fails.
- add_objective_offset(offset: float) None #
Adds an offset to the objective function of the model.
- Parameters:
offset (float) – The offset value to be added to the objective function.
- write(filename: str) None #
Writes the model to a file in the format specified by the filename suffix.
- Parameters:
filename (str) – The name of the file to be written.
- optimize() HybridSolverStatus #
Sends the model to the HybridSolver and solves it on the cloud.
- Returns:
The solution status after optimization.
- Return type:
HybridSolverStatus
- Raises:
ValueError – If the solution status cannot be cast to HybridSolverStatus.
- set_absolute_gap(gap: float) None #
Sets the absolute gap for the model.
- Parameters:
gap (float) – The absolute gap to be set.
- set_relative_gap(gap: float) None #
Sets the relative gap for the model.
- Parameters:
gap (float) – The relative gap to be set.
- set_time_limit(time_limit: float) None #
Sets the time limit for the model.
- Parameters:
time_limit (float) – The time limit to be set.
- set_feasibility_tolerance(tolerance: float) None #
Sets the feasibility tolerance for the model.
- Parameters:
tolerance (float) – The feasibility tolerance to be set.
- set_integrality_tolerance(tolerance: float) None #
Sets the integrality tolerance for the model.
- Parameters:
tolerance (float) – The integrality tolerance to be set.
- set_objective_limit(limit: float) None #
Sets the objective limit for the model.
- Parameters:
limit (float) – The objective limit to be set.
- set_presolve(presolve: bool) None #
Sets the presolve flag for the model.
- Parameters:
presolve (bool) – The presolve flag to be set.
- class quantagonia.mip.variable.Variable(variable: _Variable = None, model: Model = None)#
A class representing a variable in a Mixed Integer Programming (MIP) problem.
- property name: str#
The name of the variable.
- Returns:
The name of the variable.
- Return type:
str
- Raises:
ModelError – If the variable is not set or if the variable data are not set.
- property lb: float#
The lower bound of the variable.
This property allows getting and setting the lower bound of the variable.
- Returns:
The lower bound of the variable.
- Return type:
float
- Sets:
float: The new lower bound value for the variable.
- Raises:
ModelError – If setting the lower bound fails or if the variable data are not set.
- property ub: float#
The upper bound of the variable.
This property allows getting and setting the upper bound of the variable.
- Returns:
The upper bound of the variable.
- Return type:
float
- Sets:
float: The new upper bound value for the variable.
- Raises:
ModelError – If setting the upper bound fails or if the variable data are not set.
- property obj: float#
The coefficient of the variable in the objective function.
This property allows getting and setting the coefficient of the variable in the objective function.
- Returns:
The coefficient of the variable in the objective function.
- Return type:
float
- Sets:
float: The new coefficient value for the variable in the objective function.
- Raises:
ModelError – If setting the objective coefficient fails or if the variable data are not set.
- property sol_value: float#
The value of the variable in the current solution.
- Returns:
The value of the variable in the current solution.
- Return type:
float
- Raises:
ModelError – If the model is not set.
- property x: float#
A wrapper for sol_value.
- Returns:
The value of the variable in the current solution.
- Return type:
float
- Raises:
ModelError – If the model is not set.
- property var_type: VarType#
The type of the variable.
This property allows getting and setting the type of the variable.
- Returns:
The type of the variable (BINARY, INTEGER, or CONTINUOUS).
- Return type:
VarType
- Sets:
VarType: The new type for the variable.
- Raises:
ModelError – If the variable type is unsupported or if setting the type
fails or if the variable data are not set. –
- property index: int#
The index of the variable.
- Returns:
The index of the variable.
- Return type:
int
- Raises:
ModelError – If the variable is not set or if the variable data are not set.
Wrapper Classes#
The quantagonia.mip.wrappers
module contains wrapper classes for the packages
GurobiPy
, DOcplex
, and Python-MIP
.
Each wrapper extends the Model
and Variable
classes by attributes
and methods in the namespace of the target package.
GurobiPy#
- class quantagonia.mip.wrappers.gurobipy.Model(name: str = 'Model')#
Wrapper for gurobipy.Model.
- property Params: Params#
The parameters of the model.
- Returns:
The parameters of the model.
- Return type:
Params
- property ObjVal: float#
The objective value of the model’s best solution.
- Returns:
The objective value of the best solution found.
- Return type:
float
- property ModelSense: GRB#
The optimization sense of the model.
- Returns:
The current optimization sense of the model.
- Return type:
GRB
- Raises:
ModelError – If the current sense is unsupported.
- property ObjConst: float#
The offset of the objective function.
- Returns:
The constant offset value of the objective function.
- Return type:
float
- property NumVars: int#
The number of variables in the model.
- Returns:
The number of variables in the model.
- Return type:
int
- property NumBinVars: int#
The number of binary variables in the model.
- Returns:
The number of binary variables in the model.
- Return type:
int
- property NumIntVars: int#
The number of integer variables in the model.
- Returns:
The number of integer variables in the model.
- Return type:
int
- property Status: GRB#
The solution status of the model.
- Returns:
The current solution status of the model.
- Return type:
GRB
- getAttr(attr: str, var_list: tupledict | Var) dict | float | str #
Retrieves the specified attribute for a tupledict of variables or a single variable.
- Parameters:
attr (str) – The name of the attribute to retrieve (e.g., “X” for solution values).
var_list (tupledict | Var) – A tupledict of variables or a single variable.
- Returns:
- If var_list is a tupledict, returns a dictionary mapping keys to
attribute values. If var_list is a single variable, returns the attribute value for that variable.
- Return type:
dict | Any
- Raises:
ValueError – If var_list is neither a tupledict nor a Variable.
AttributeError – If the attribute is not valid for the variables.
- addVar(lb: float = 0, ub: float = inf, obj: float = 0, vtype: GRB = GRB.CONTINUOUS, name: str = '') Var #
Adds a new variable to the model.
- Parameters:
lb (float) – The lower bound of the variable. Defaults to 0.
ub (float) – The upper bound of the variable. Defaults to positive infinity.
obj (float) – The coefficient of the variable in the objective function. Defaults to 0.
name (str) – The name of the variable. Defaults to an empty string.
vtype (GRB) – The type of the variable. Defaults to GRB.CONTINUOUS.
- Returns:
The Variable instance that was added to the MIP model.
- Return type:
- Raises:
ModelError – If the variable type is unsupported or if the variable addition fails.
- addVars(*indices: str | int | range | list[int], lb: float = 0.0, ub: float = inf, obj: float = 0.0, vtype: GRB = GRB.CONTINUOUS, name: str = '') tupledict #
Adds multiple variables to the model in a multi-dimensional array format.
- Parameters:
*indices – Dimensions for the variable array, or a single list of index tuples.
lb (float or list) – Lower bound for variables, or list of bounds for each variable.
ub (float or list) – Upper bound for variables, or list of bounds for each variable.
obj (float or list) – Objective coefficient for variables, or list of coefficients for each variable.
vtype (GRB or list) – Variable type, or list of types for each variable.
name (str or list) – Base name for each variable, or list of names for each variable.
- Returns:
Dictionary-like structure with keys as index tuples and values as Variable instances.
- Return type:
tupledict
- Raises:
ValueError – If indices contain invalid entries or if list lengths of
lb, ub, obj, vtype, and name don't match. –
- getVars() list[Var] #
Returns a list of all variables in the model.
- Returns:
A list of all variables in the model.
- Return type:
list[Var]
- addConstr(expr: Expression, name: str = '') None #
Adds a constraint to the model.
- Parameters:
expr (Expression) – The expression representing the constraint.
name (str) – (optional) The name of the constraint.
- Raises:
ModelError – If the constraint addition fails.
- addConstrs(generator: Iterable[Expression], name: str = '') None #
Adds multiple constraints to the model using a generator.
- Parameters:
generator (Generator[Expression, None, None]) – A generator yielding constraint expressions.
name (str) – (optional) A prefix for the constraint names.
- setObjective(expr: Expression, sense: GRB = GRB.MINIMIZE) None #
Sets the objective function for the model.
- Parameters:
expr (Expression) – The expression representing the objective function.
sense (GRB) – The optimization sense (minimize or maximize). Defaults to GRB.MINIMIZE.
- Raises:
ModelError – If the sense is unsupported or if setting the objective fails.
- optimize() GRB #
Sends the model to the HybridSolver and solves it on the cloud.
- Returns:
The solution status after optimization.
- Return type:
GRB
- Raises:
ValueError – If the solution status cannot be cast to HybridSolverStatus.
- class quantagonia.mip.wrappers.gurobipy.Var(variable: Variable)#
Wrapper for gurobipy.Var.
- property VarName: str#
The name of the variable.
- Returns:
The name of the variable.
- Return type:
str
- property LB: float#
The lower bound of the variable.
- Returns:
The lower bound of the variable.
- Return type:
float
- property UB: float#
The upper bound of the variable.
- Returns:
The upper bound of the variable.
- Return type:
float
- property Obj: float#
The coefficient of the variable in the objective function.
- Returns:
The coefficient of the variable in the objective function.
- Return type:
float
- property X: float#
The value of the variable in the current solution.
- Returns:
The value of the variable in the current solution.
- Return type:
float
- Raises:
ModelError – If the model is not set.
- property VType: GRB#
The type of the variable.
- Returns:
The type of the variable.
- Return type:
GRB
- property Start: float#
The starting value of the variable.
- Returns:
The starting value of the variable.
- Return type:
float
DOcplex#
- class quantagonia.mip.wrappers.cplex.Model(name: str = 'Model')#
Wrapper for a CPLEX model.
- class Parameters#
A class for storing the parameters of the model.
- class Mip#
A class for storing the MIP parameters of the model.
- class Tolerances#
A class for storing the tolerances of the MIP parameters.
- class Limits#
A class for storing the limits of the MIP parameters.
- class Feasopt#
A class for storing the Feasopt parameters of the model.
- class Preprocessing#
A class for storing the preprocessing parameters of the model.
- property parameters: Parameters#
The parameters of the model.
- property objective_sense: CplexEnum#
The optimization sense of the model.
- Returns:
The current optimization sense of the model.
- Return type:
HybridSolverOptSenses
- Raises:
ModelError – If the current sense is unsupported.
- property number_of_variables: int#
The number of variables in the model.
- Returns:
The number of variables in the model.
- Return type:
int
- property number_of_binary_variables: int#
The number of binary variables in the model.
- Returns:
The number of binary variables in the model.
- Return type:
int
- property number_of_integer_variables: int#
The number of integer variables in the model.
- Returns:
The number of integer variables in the model.
- Return type:
int
- property number_of_continuous_variables: int#
The number of continuous variables in the model.
- Returns:
The number of continuous variables in the model.
- Return type:
int
- property binary_vartype: CplexEnum#
Returns the binary variable type.
- Returns:
The binary variable type.
- Return type:
CplexEnum
- property continuous_vartype: CplexEnum#
Returns the continuous variable type.
- Returns:
The continuous variable type.
- Return type:
CplexEnum
- property integer_vartype: CplexEnum#
Returns the integer variable type.
- Returns:
The integer variable type.
- Return type:
CplexEnum
- property problem_type: str#
The type of the problem.
- Returns:
The type of the problem.
- Return type:
str
- property infinity: float#
The positive infinity value.
- Returns:
The positive infinity value.
- Return type:
float
- continuous_var(lb: float = 0, ub: float = inf, name: str = '', coeff: float = 0) Variable #
Adds a new continuous variable to the model.
- Parameters:
lb (float) – The lower bound of the variable. Defaults to 0.
ub (float) – The upper bound of the variable. Defaults to positive infinity.
name (str) – The name of the variable. Defaults to an empty string.
coeff (float) – The coefficient of the variable in the objective function. Defaults to 0.
- Returns:
The Variable instance that was added to the MIP model.
- Return type:
- Raises:
ModelError – If the variable addition fails.
- integer_var(lb: float = 0, ub: float = inf, name: str = '', coeff: float = 0) Variable #
Adds a new integer variable to the model.
- Parameters:
lb (float) – The lower bound of the variable. Defaults to 0.
ub (float) – The upper bound of the variable. Defaults to positive infinity.
name (str) – The name of the variable. Defaults to an empty string.
coeff (float) – The coefficient of the variable in the objective function. Defaults to 0.
- Returns:
The Variable instance that was added to the MIP model.
- Return type:
- Raises:
ModelError – If the variable addition fails.
- binary_var(name: str = '', coeff: float = 0) Variable #
Adds a new binary variable to the model.
- Parameters:
name (str) – The name of the variable. Defaults to an empty string.
coeff (float) – The coefficient of the variable in the objective function. Defaults to 0.
- Returns:
The Variable instance that was added to the MIP model.
- Return type:
- Raises:
ModelError – If the variable addition fails.
- binary_var_dict(keys: list | tuple | range | int, name: str | None = None, key_format: str | None = None) dict[str, Variable] #
Creates a dictionary of binary decision variables, indexed by key objects.
- Parameters:
keys – Either a sequence of objects, an iterator, or a positive integer. If passed an integer, it is interpreted as the number of variables to create.
name (str) – A string used to name variables. The variable name is formed by appending the string to the string representation of the key object. Defaults to None.
key_format (str) – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, … then variables will be named “x_k1”, “x_k2”,…
- Returns:
A dictionary of binary decision variables indexed by key objects.
- Return type:
dict[str, Variable]
- binary_var_list(keys: list | tuple | range | int, name: str | None = None, key_format: str | None = None) list[Variable] #
Creates a list of binary decision variables, indexed by key objects.
- Parameters:
keys – Either a sequence of objects, an iterator, or a positive integer. If passed an integer, it is interpreted as the number of variables to create.
name (str) – A string used to name variables. The variable name is formed by appending the string to the string representation of the key object. Defaults to None.
key_format (str) – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, … then variables will be named “x_k1”, “x_k2”,…
- Returns:
A list of binary decision variables indexed by key objects.
- Return type:
list[Variable]
- continuous_var_dict(keys: list | tuple | range | int, lb: float | list[float] | None = None, ub: float | list[float] | None = None, name: str | None = None, key_format: str | None = None) dict[str, Variable] #
Creates a dictionary of continuous decision variables, indexed by key objects.
- Parameters:
keys – Either a sequence of objects, an iterator, or a positive integer. If passed an integer, it is interpreted as the number of variables to create.
lb (float) – The lower bound of the variables. Defaults to None.
ub (float) – The upper bound of the variables. Defaults to None.
name (str) – A string used to name variables. The variable name is formed by appending the string to the string representation of the key object. Defaults to None.
key_format (str) – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, … then variables will be named “x_k1”, “x_k2”,…
- Returns:
A dictionary of continuous decision variables indexed by key objects.
- Return type:
dict[str, Variable]
- continuous_var_list(keys: list | tuple | range | int, lb: float | list[float] | None = None, ub: float | list[float] | None = None, name: str | None = None, key_format: str | None = None) list[Variable] #
Creates a list of continuous decision variables, indexed by key objects.
- Parameters:
keys – Either a sequence of objects, an iterator, or a positive integer. If passed an integer, it is interpreted as the number of variables to create.
lb (float) – The lower bound of the variables. Defaults to None.
ub (float) – The upper bound of the variables. Defaults to None.
name (str) – A string used to name variables. The variable name is formed by appending the string to the string representation of the key object. Defaults to None.
key_format (str) – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, … then variables will be named “x_k1”, “x_k2”,…
- Returns:
A list of continuous decision variables indexed by key objects.
- Return type:
list[Variable]
- integer_var_dict(keys: list | tuple | range | int, lb: float | list[float] | None = None, ub: float | list[float] | None = None, name: str | None = None, key_format: str | None = None) dict[str, Variable] #
Creates a dictionary of integer decision variables, indexed by key objects.
- Parameters:
keys – Either a sequence of objects, an iterator, or a positive integer. If passed an integer, it is interpreted as the number of variables to create.
lb (float) – The lower bound of the variables. Defaults to None.
ub (float) – The upper bound of the variables. Defaults to None.
name (str) – A string used to name variables. The variable name is formed by appending the string to the string representation of the key object. Defaults to None.
key_format (str) – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, … then variables will be named “x_k1”, “x_k2”,…
- Returns:
A dictionary of integer decision variables indexed by key objects.
- Return type:
dict[str, Variable]
- integer_var_list(keys: list | tuple | range | int, lb: float | list[float] | None = None, ub: float | list[float] | None = None, name: str | None = None, key_format: str | None = None) list[Variable] #
Creates a list of integer decision variables, indexed by key objects.
- Parameters:
keys – Either a sequence of objects, an iterator, or a positive integer. If passed an integer, it is interpreted as the number of variables to create.
lb (float) – The lower bound of the variables. Defaults to None.
ub (float) – The upper bound of the variables. Defaults to None.
name (str) – A string used to name variables. The variable name is formed by appending the string to the string representation of the key object. Defaults to None.
key_format (str) – A format string or None. This format string describes how keys contribute to variable names. The default is “_%s”. For example if name is “x” and each key object is represented by a string like “k1”, “k2”, … then variables will be named “x_k1”, “x_k2”,…
- Returns:
A list of integer decision variables indexed by key objects.
- Return type:
list[Variable]
- change_var_upper_bounds(dvars: list[Variable], ubs: float | list[float] | None, check_bounds: bool = True) None #
Changes the upper bounds of variables.
- Parameters:
dvars (list[Variable]) – A list of variables to change the upper
ubs (float | list[float] | None) – The new upper bounds for the variables.
check_bounds (bool) – If True, the function checks that the new upper bounds are valid.
- change_var_lower_bounds(dvars: list[Variable], lbs: float | list[float] | None, check_bounds: bool = True) None #
Changes the lower bounds of variables.
- Parameters:
dvars (list[Variable]) – A list of variables to change the lower
lbs (float | list[float] | None) – The new lower bounds for the variables.
check_bounds (bool) – If True, the function checks that the new lower bounds are valid.
- objective_coef(var: Variable) float #
Returns the coefficient of a variable in the objective function.
- Parameters:
var (Variable) – The variable whose coefficient is to be retrieved.
- Returns:
The coefficient of the variable in the objective function.
- Return type:
float
- get_var_by_name(name: str) Variable #
Returns the variable with the given name.
- Parameters:
name (str) – The name of the variable to be retrieved.
- Returns:
Returns a variable if it finds one with exactly this name, or None.
- add_constraint_(expr: Expression, name: str = '') None #
Adds a constraint to the model.
- Parameters:
expr (Expression) – The expression representing the constraint.
name (str) – (optional) The name of the constraint.
- Raises:
ModelError – If the constraint addition fails.
- linear_constraint(lhs: Expression, ctsense: str, rhs: float, name: str = '') None #
Adds a linear constraint to the model.
- Parameters:
lhs (Expression) – The left-hand side of the constraint.
ctsense (str) – The sense of the constraint (e.g., “<=”, “==”, or “>=”).
rhs (float) – The right-hand side of the constraint.
name (str) – (optional) The name of the constraint.
- Raises:
ModelError – If the constraint addition fails.
- eq_constraint(lhs: Expression, rhs: float, name: str = '') None #
Adds an equality constraint to the model.
- Parameters:
lhs (Expression) – The left-hand side of the constraint.
rhs (float) – The right-hand side of the constraint.
name (str) – (optional) The name of the constraint.
- Raises:
ModelError – If the constraint addition fails.
- le_constraint(lhs: Expression, rhs: float, name: str = '') None #
Adds a less-than-or-equal constraint to the model.
- Parameters:
lhs (Expression) – The left-hand side of the constraint.
rhs (float) – The right-hand side of the constraint.
name (str) – (optional) The name of the constraint.
- Raises:
ModelError – If the constraint addition fails.
- ge_constraint(lhs: Expression, rhs: float, name: str = '') None #
Adds a greater-than-or-equal constraint to the model.
- Parameters:
lhs (Expression) – The left-hand side of the constraint.
rhs (float) – The right-hand side of the constraint.
name (str) – (optional) The name of the constraint.
- Raises:
ModelError – If the constraint addition fails.
- is_maximized() bool #
Checks if the model is maximized.
- Returns:
True if the model is maximized, False otherwise.
- Return type:
bool
- is_minimized() bool #
Checks if the model is minimized.
- Returns:
True if the model is minimized, False otherwise.
- Return type:
bool
- solve(log_output: bool = False) CplexEnum #
Solves the model.
- Returns:
The solution status after optimization.
- Return type:
HybridSolverStatus
- set_objective(expr: Expression, sense: CplexEnum = CplexEnum.Minimize) None #
Sets the objective function for the model.
- Parameters:
expr (Expression) – The expression representing the objective function.
sense (CplexEnum) – The optimization sense (minimize or maximize). Defaults to CplexEnum.Minimize.
- Raises:
ModelError – If the sense is unsupported or if setting the objective fails.
- minimize(expr: Expression) CplexEnum #
Solves the model by minimizing the objective function.
- Parameters:
expr (Expression) – The expression representing the objective function.
- Returns:
The solution status after optimization.
- Return type:
HybridSolverStatus
- maximize(expr: Expression) CplexEnum #
Solves the model by maximizing the objective function.
- Parameters:
expr (Expression) – The expression representing the objective function.
- Returns:
The solution status after optimization.
- Return type:
HybridSolverStatus
- get_solve_status() CplexEnum #
Returns the solution status after optimization.
- Returns:
The solution status after optimization.
- Return type:
HybridSolverStatus
- sum(args: list[Expression]) Expression #
Sum of a list of expressions.
- Parameters:
args (list[Expression]) – The list of expressions to sum.
- Returns:
The sum of the expressions.
- Return type:
Expression
- sum_vars(dvars: list[Variable]) Expression #
Creates a linear expression that sums variables.
- Parameters:
dvars (list[Variable]) – The list of variables to sum.
- Returns:
The linear expression that sums the variables.
- Return type:
Expression
- optimize() CplexEnum #
Sends the model to the HybridSolver and solves it on the cloud.
- Returns:
The solution status after optimization.
- Return type:
CplexEnum
- Raises:
ValueError – If the solution status cannot be cast to HybridSolverStatus.
- print_solution() None #
Prints the values of the model variables after a solve.
Only valid after a successful solve. If the model has not been solved successfully, an exception is raised.
- class quantagonia.mip.wrappers.cplex.Variable(variable: Variable)#
Wrapper for a CPLEX variable.
- property var_type: CplexEnum#
The type of the variable.
This property allows getting and setting the type of the variable.
- Returns:
The type of the variable (CplexEnum.BINARY, CplexEnum.INTEGER, or CplexEnum.CONTINUOUS).
- Return type:
CplexEnum
- Raises:
ModelError – If the variable type is unsupported or if setting the type
fails or if the variable data are not set. –
Python-MIP#
- class quantagonia.mip.wrappers.python_mip.Model(name: str = 'Model', sense: PythonMipEnum | None = None)#
- property sense: PythonMipEnum#
The optimization sense of the model.
- Returns:
The optimization sense of the model.
- Return type:
PythonMipEnum
- property objective: tuple[Expr, PythonMipEnum]#
The objective function of the model.
- Returns:
A tuple containing the objective expression and sense.
- Return type:
tuple[Expression, HybridSolverOptSenses]
- property status: PythonMipStatus#
The solution status of the model.
- Returns:
The current solution status of the model.
- Return type:
HybridSolverStatus
- property num_solutions: int#
The number of solutions found during optimization.
- Returns:
The number of solutions found during the MIP search.
- Return type:
int
- property objective_const: float#
The offset of the objective function.
- Returns:
The constant offset value of the objective function.
- Return type:
float
- property num_cols: int#
The number of variables in the model.
- Returns:
The number of variables in the model.
- Return type:
int
- property num_int: int#
The number of integer variables in the model.
- Returns:
The number of integer variables in the model.
- Return type:
int
- property vars: list[Var]#
The list of variables in the model.
- Returns:
A list of Variable instances in the model.
- Return type:
list[Variable]
- property max_mip_gap: float#
The maximum MIP gap for the model.
- Returns:
The maximum MIP gap for the model.
- Return type:
float
- property max_mip_gap_abs: float#
The maximum absolute MIP gap for the model.
- Returns:
The maximum absolute MIP gap for the model.
- Return type:
float
- property infeas_tol: float#
The feasibility tolerance for the model.
- Returns:
The feasibility tolerance for the model.
- Return type:
float
- property integer_tol: float#
The integer tolerance for the model.
- Returns:
The integer tolerance for the model.
- Return type:
float
- property max_seconds: float#
The maximum time limit for the model.
- Returns:
The maximum time limit for the model.
- Return type:
float
- add_var(name: str = '', lb: float = 0, ub: float = inf, obj: float = 0, var_type: PythonMipEnum = PythonMipEnum.CONTINUOUS, column: int | None = None) Var #
Adds a new variable to the model.
- Parameters:
lb (float) – The lower bound of the variable. Defaults to 0.
ub (float) – The upper bound of the variable. Defaults to positive infinity.
obj (float) – The coefficient of the variable in the objective function. Defaults to 0.
name (str) – The name of the variable. Defaults to an empty string.
var_type (PythonMipEnum) – The type of the variable. Defaults to PythonMipEnum.CONTINUOUS.
column (int) – (optional) Not supported. Defaults to None.
- Returns:
The Variable instance that was added to the MIP model.
- Return type:
- Raises:
ModelError – If the variable type is unsupported or if the variable addition fails.
- var_by_name(name: str) Var #
Returns the variable with the given name.
- Parameters:
name (str) – The name of the variable to be retrieved.
- Returns:
Returns a variable if it finds one with exactly this name, or None.
- add_constr(lin_expr: Expr, name: str = '', priority: int | None = None) None #
Adds a constraint to the model.
- Parameters:
lin_expr (Expression) – The expression representing the constraint.
name (str) – (optional) The name of the constraint.
priority (int) – (optional) The priority of the constraint. Not supported.
- Raises:
ModelError – If the constraint addition fails.
- optimize() PythonMipStatus #
Sends the model to the HybridSolver and solves it on the cloud.
- Returns:
The solution status after optimization.
- Return type:
OptimizationStatus
- Raises:
ValueError – If the solution status cannot be cast to HybridSolverStatus.
PuLP Adapter#
The quantagonia.mip
module contains a HybridSolver_CMD
command, which can be passed to PuLP’s solve
method. This allows to model problems with PuLP and solve them with the HybridSolver.
After the solve, you can access solution values directly from the PuLP model.
- class quantagonia.mip.pulp_adapter.HybridSolver_CMD(api_key: str, params: dict | None = None, keepFiles: bool = False, obfuscate: bool = True)#
The HybridSolver command to be passed to the
solve
method of PuLP.- Parameters:
api_key (str) – A string containing the API key.
params (HybridSolverParameters) – (optional) The parameters for the solver.
keepFiles (bool) – (optional) If True, files are saved in the current directory and not deleted after solving.
obfuscate (bool) – (optional) If True, constraints and variable names are obfuscated.
Modeling QUBOs#
The quantagonia[qubo]
package comes with a QuboModel
class to model and solve QUBOs programmatically. Have a look at our .qubo format for QUBOs to learn more. You can also retrieve solution values of variables to process and use the optimal solution in your application.
- class quantagonia.qubo.model.QuboModel(sense: HybridSolverOptSenses = HybridSolverOptSenses.MAXIMIZE, name: str = 'pyclient')#
A class representing a Quadratic Unconstrained Binary Optimization (QUBO) problem instance.
- Parameters:
sense (HybridSolverOptSenses) – (optional )An enum representing the optimization sense of the QUBO. Defaults to HybridSolverOptSenses.MAXIMIZE.
name (str) – (optional) The name of the QUBO model.
- property sense: HybridSolverOptSenses#
The optimization sense of the QUBO of type
HybridSolverOptSenses
.- Returns:
The optimization sense of the QUBO model.
- Return type:
HybridSolverOptSenses
- property name: str#
The name of the QUBO model.
- Returns:
The name of the QUBO model.
- Return type:
str
- add_variable(name: str, initial: Literal[0, 1] | None = None, fixing: Literal[0, 1] | None = None, disable_warnings: bool = False) QuboVariable #
Adds a new variable to the QUBO.
Note
QUBO Variables are binary and can take a value in {0, 1, None}.
- Parameters:
name (str) – The name of the variable.
initial (0 or 1) – The initial value of the variable. Defaults to None.
fixing (0 or 1) – The value to which the variable should be fixed. Defaults to None.
disable_warnings (bool) – If True, disables the warning message that is displayed when a variable
False. (with the same name is already in the QUBO. Defaults to)
- Returns:
The
QuboVariable
that was added to the QUBO.- Return type:
QuboVariable
- Raises:
Warning – If initial not in {0, 1, None}.
- variable(name: str) QuboVariable #
Returns the
QuboVariable
with the specified name.- Parameters:
name (str) – A string of the name of the
QuboVariable
to retrieve.- Returns:
The
QuboVariable
with the specified name.- Return type:
QuboVariable
- Raises:
KeyError – If no
QuboVariable
with the specified name exists in the QUBO.
- eval() float #
Returns the objective function value for the current variable assignment.
After solving, it provides the optimal value.
- Returns:
The value of the QUBO’s objective function.
- Return type:
float
- is_valid() bool #
Checks that all terms are in the upper triangle and that they have been reduced in the right way.
- Returns:
Indicating whether conditions are all true.
- Return type:
bool
- write_qubo(path: str) None #
Writes QUBO to file in the Quantagonia QUBO format.
- Parameters:
path (str) – Path as string to the destined file.
- Raises:
Exception – If the QUBO is not valid.
FileNotFoundError – If the path or file cannot be found.
PermissionError – If program does not have sufficient permissions to access the file.
TypeError – If path is not a string.
- get_number_of_nonzeros_of_upper_triangle() int #
Get the number of nonzero entries for the upper triangle matrix.
This corresponds to the number of terms in the objective function, excluding the shift.
- Returns:
Integer representing the number of nonzero entries for the upper triangle matrix.
- Return type:
int
- get_number_of_nonzeros_of_full_matrix() int #
Compute number of nonzero entries of the full matrix on demand.
- Returns:
Integer representing the number of nonzero entries of the full matrix.
- Return type:
int
- classmethod read_qubo(path: str) QuboModel #
Reads a QUBO from file.
- Parameters:
path (str) – String containing the path to the QUBO file.
- Returns:
The QUBO.
- Return type:
- classmethod from_qiskit_qubo(qp: QiskitQP) QuboModel #
Converts a QUBO in Qiskits QuadraticProgram format to a
QuboModel
.
- classmethod from_dwave_bqm(bqm: BinaryQuadraticModel, name: str = 'fromdwaveqbm') QuboModel #
Converts a D-Wave BQM to a
QuboModel
.
- classmethod from_pyqubo(pqm: pqModel, constants: dict | None = None, name: str = 'frompyqubo') QuboModel #
Reads a PyQUBO quadratic model into a
QuboModel
that can be solved by Quantagonia solvers.
- solve(hybrid_solver: HybridSolver, params: HybridSolverParameters | None = None) dict[str, Any] #
Solves the QUBO using the given HybridSolver.
- Parameters:
hybrid_solver (HybridSolver) – HybridSolver instance used to solve the QUBO.
params (HybridSolverParameters) – Solver parameters. If no parameters are passed the default parameters are used.
- Returns:
- List of solver results. It contains a dictionary containing the keys ‘status’,
’solver_log’, ‘sol_status’, ‘timing’, ‘objective’, ‘bound’, ‘absolute_gap’, ‘relative_gap’, ‘iterations’, ‘nodes’, ‘nodes_per_sec’, ‘best_node’, ‘best_time’, ‘num_quantum_solutions’, ‘solver_mix’, and ‘solution’.
- Return type:
Dict[str, Any]