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, server: HybridSolverServers = None)#

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.

  • server (HybridSolverServers) – (optional) Allows to specify a server different to the default production server. Defaults to None.

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() and progress().

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_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 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 Quantagonia QUBO File Format 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:

QuboModel

classmethod from_qiskit_qubo(qp: QiskitQP) QuboModel#

Converts a QUBO in Qiskits QuadraticProgram format to a QuboModel.

Parameters:

qp (qiskit_optimization.problems.quadratic_program.QuadraticProgram) – The Quiskit QP to be converted.

Returns:

The resulting QuboModel.

Return type:

QuboModel

classmethod from_dwave_bqm(bqm: BinaryQuadraticModel, name: str = 'fromdwaveqbm') QuboModel#

Converts a D-Wave BQM to a QuboModel.

Parameters:
  • bqm (dimod.BinaryQuadraticModel) – The dimod.BinaryQuadraticModel to be converted.

  • name (str) – The name of the QUBO model.

Returns:

The resulting QuboModel.

Return type:

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.

Parameters:
  • pqm (pyqubo.Model) – A pyqubo.Model to be converted.

  • constants (dict) – A dictionary of constant values that can be used in the conversion.

  • name (str) – The name of the QUBO model.

Returns:

The resulting QuboModel.

Return type:

QuboModel

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]