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_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#
First, 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 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
- 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.
- 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, 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.
- set_sense(sense: HybridSolverOptSenses) None #
Sets the optimization sense of the model.
- Parameters:
sense (HybridSolverOptSenses) – The optimization sense to be set.
- Raises:
ModelError – If the provided sense is unsupported.
- 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.
- 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
- 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.
- 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.
- 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.
- 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.
PuLP Adapter#
Second, 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]