Skip to main contentIBM Quantum Documentation Preview
This is a preview build of IBM Quantum® documentation. Refer to quantum.cloud.ibm.com/docs for the official documentation.

Higher-order binary optimization with Q-CTRL's Optimization Solver

Note

IBM Quantum® Functions are a beta feature available only to IBM Quantum Premium Plan, Flex Plan, and On-Prem (through the IBM Quantum Platform API) Plan users. Beta features are subject to change.

Usage estimate: 24 minutes on a Heron r2 processor. (NOTE: This is an estimate only. Your runtime might vary.)


Background

This tutorial demonstrates how to solve a higher-order binary optimization (HOBO) problem using the Optimization Solver by Q-CTRL Fire Opal. The example demonstrated in this tutorial is an optimization problem designed to find the ground-state energy of a random-bond 156-qubit Ising model possessing cubic terms. The Optimization Solver can be applied to problems formulated as supported binary optimization objectives, including formulations for energy grid load balancing, logistics route optimization, or manufacturing waste minimization.

The Optimization fully automates the hardware-aware implementation steps of solving optimization problems on quantum hardware, and by leveraging Performance Management for the quantum execution, it achieves accurate solutions at utility scale. For a detailed summary of the full Optimization Solver workflow and benchmarking results, refer to the published manuscript.

This tutorial walks through the following steps:

  1. Define the problem as an objective function
  2. Run the hybrid algorithm using the Fire Opal Optimization Solver
  3. Evaluate results

Requirements

Before starting this tutorial, ensure that you have the following installed:

  • Quantum Functions (pip install qiskit-ibm-catalog)
  • SymPy (pip install sympy)

You will also need to get access to the Optimization Solver function. Fill out the form to request access.


Setup

First, import the required packages and tools.

# Quantum Functions Catalog
from qiskit_ibm_catalog import FunctionsCatalog

# SymPy tools for constructing objective function
from sympy import Poly
from sympy import symbols, srepr

# Tools for plotting and evaluating results
import numpy as np
import matplotlib.pyplot as plt
from sympy import lambdify

Define your IBM Quantum Platform credentials, which will be used throughout the tutorial to authenticate to IBM Quantum Compute Service and quantum functions.

# Credentials

# For `token`, use the 44-character API_KEY you created
# and saved from the IBM Quantum Platform Home dashboard
token = "<YOUR-API_KEY>"
instance = "<YOUR_CRN>"

Step 1: Define the problem as an objective function

The Optimization Solver accepts either an objective function or a graph as input. In this tutorial, the Ising spin glass minimization problem is defined as an objective function, and it has been tailored for the heavy-hex topology of IBM® devices.

Because this objective function contains cubic, quadratic, and linear terms, it falls into the HOBO class of problems, known to be considerably more complicated to solve than conventional quadratic unconstrained binary optimization (QUBO) problems.

For detailed discussion of the construction of the problem definition and previous results obtained from the Optimization Solver refer to this technical manuscript. The problem was originally defined and evaluated as part of a paper published by Los Alamos National Laboratory, and it has been adapted to leverage the full device width of the 156-qubit IBM Quantum Heron processors.

qubit_count = 156

# Create symbolic variables to represent qubits
x = symbols([f"x[{i}]" for i in range(qubit_count)])

# # Define a polynomial representing a spin glass model
spin_glass_poly = Poly(
    -4 * x[0] * x[1]
    - 8 * x[1] * x[2] * x[3]
    + 8 * x[1] * x[2]
    + 4 * x[1] * x[3]
    - 4 * x[2]
    + 8 * x[3] * x[4] * x[5]
    - 4 * x[3] * x[5]
    - 8 * x[3] * x[16] * x[23]
    + 4 * x[3] * x[23]
    - 2 * x[3]
    - 4 * x[4]
    - 8 * x[5] * x[6] * x[7]
    + 8 * x[5] * x[6]
    + 4 * x[5] * x[7]
    - 2 * x[5]
    + 8 * x[6] * x[7]
    - 4 * x[6]
    - 8 * x[7] * x[8] * x[9]
    + 4 * x[7] * x[9]
    - 8 * x[7] * x[17] * x[27]
    + 4 * x[7] * x[27]
    - 6 * x[7]
    + 8 * x[8] * x[9]
    + 8 * x[9] * x[10] * x[11]
    - 4 * x[9] * x[11]
    - 2 * x[9]
    - 8 * x[10] * x[11]
    + 4 * x[10]
    - 8 * x[11] * x[12] * x[13]
    + 4 * x[11] * x[13]
    - 8 * x[11] * x[18] * x[31]
    + 8 * x[11] * x[18]
    + 4 * x[11] * x[31]
    - 2 * x[11]
    + 8 * x[12] * x[13]
    + 8 * x[13] * x[14] * x[15]
    - 4 * x[13] * x[15]
    - 2 * x[13]
    - 8 * x[14] * x[15]
    + 4 * x[14]
    - 8 * x[15] * x[19] * x[35]
    + 8 * x[15] * x[19]
    + 4 * x[15] * x[35]
    - 2 * x[15]
    + 8 * x[16] * x[23]
    + 8 * x[17] * x[27]
    - 4 * x[17]
    + 8 * x[18] * x[31]
    - 8 * x[18]
    + 8 * x[19] * x[35]
    - 8 * x[19]
    + 4 * x[20] * x[21]
    - 4 * x[20]
    - 8 * x[21] * x[22] * x[23]
    + 8 * x[21] * x[22]
    + 4 * x[21] * x[23]
    - 8 * x[21] * x[36] * x[41]
    + 4 * x[21] * x[41]
    - 4 * x[21]
    + 8 * x[22] * x[23]
    - 8 * x[22]
    + 8 * x[23] * x[24] * x[25]
    - 4 * x[23] * x[25]
    - 10 * x[23]
    - 8 * x[24] * x[25]
    + 8 * x[25] * x[26] * x[27]
    - 8 * x[25] * x[26]
    - 4 * x[25] * x[27]
    + 8 * x[25] * x[37] * x[45]
    - 8 * x[25] * x[37]
    - 4 * x[25] * x[45]
    + 14 * x[25]
    - 8 * x[26] * x[27]
    + 4 * x[26]
    + 8 * x[27] * x[28] * x[29]
    - 4 * x[27] * x[29]
    - 2 * x[27]
    - 8 * x[28] * x[29]
    - 8 * x[29] * x[30] * x[31]
    + 4 * x[29] * x[31]
    + 8 * x[29] * x[38] * x[49]
    - 8 * x[29] * x[38]
    - 4 * x[29] * x[49]
    + 6 * x[29]
    + 8 * x[30] * x[31]
    - 4 * x[30]
    - 8 * x[31] * x[32] * x[33]
    + 4 * x[31] * x[33]
    - 6 * x[31]
    + 8 * x[33] * x[34] * x[35]
    - 4 * x[33] * x[35]
    - 8 * x[33] * x[39] * x[53]
    + 8 * x[33] * x[39]
    + 4 * x[33] * x[53]
    - 6 * x[33]
    - 8 * x[34] * x[35]
    + 2 * x[35]
    + 8 * x[36] * x[41]
    - 8 * x[37] * x[45]
    + 4 * x[37]
    - 8 * x[38] * x[49]
    + 4 * x[38]
    + 4 * x[40] * x[41]
    - 8 * x[41] * x[42] * x[43]
    + 4 * x[41] * x[43]
    - 8 * x[41]
    + 8 * x[42] * x[43]
    - 4 * x[42]
    - 8 * x[43] * x[44] * x[45]
    + 8 * x[43] * x[44]
    + 4 * x[43] * x[45]
    - 8 * x[43] * x[56] * x[63]
    + 4 * x[43] * x[63]
    - 6 * x[43]
    - 4 * x[44]
    - 8 * x[45] * x[46] * x[47]
    + 4 * x[45] * x[47]
    + 2 * x[45]
    + 4 * x[46]
    - 8 * x[47] * x[48] * x[49]
    + 8 * x[47] * x[48]
    + 4 * x[47] * x[49]
    - 8 * x[47] * x[57] * x[67]
    + 4 * x[47] * x[67]
    - 2 * x[47]
    - 4 * x[48]
    - 8 * x[49] * x[50] * x[51]
    + 8 * x[49] * x[50]
    + 4 * x[49] * x[51]
    - 2 * x[49]
    + 8 * x[50] * x[51]
    - 8 * x[50]
    - 8 * x[51] * x[52] * x[53]
    + 8 * x[51] * x[52]
    + 4 * x[51] * x[53]
    - 8 * x[51] * x[58] * x[71]
    + 4 * x[51] * x[71]
    - 6 * x[51]
    + 8 * x[52] * x[53]
    - 8 * x[52]
    + 8 * x[53] * x[54] * x[55]
    - 8 * x[53] * x[54]
    - 4 * x[53] * x[55]
    - 2 * x[53]
    + 4 * x[54]
    - 8 * x[55] * x[59] * x[75]
    + 4 * x[55] * x[75]
    - 2 * x[55]
    + 8 * x[56] * x[63]
    + 8 * x[57] * x[67]
    - 4 * x[57]
    + 8 * x[58] * x[71]
    + 8 * x[59] * x[75]
    - 4 * x[59]
    + 4 * x[60] * x[61]
    + 8 * x[61] * x[62] * x[63]
    - 4 * x[61] * x[63]
    + 8 * x[61] * x[76] * x[81]
    - 8 * x[61] * x[76]
    - 4 * x[61] * x[81]
    - 8 * x[63] * x[64] * x[65]
    + 8 * x[63] * x[64]
    + 4 * x[63] * x[65]
    - 6 * x[63]
    + 8 * x[65] * x[66] * x[67]
    - 8 * x[65] * x[66]
    - 4 * x[65] * x[67]
    - 8 * x[65] * x[77] * x[85]
    + 4 * x[65] * x[85]
    + 2 * x[65]
    + 4 * x[66]
    - 8 * x[67] * x[68] * x[69]
    + 8 * x[67] * x[68]
    + 4 * x[67] * x[69]
    - 10 * x[67]
    + 8 * x[68] * x[69]
    - 4 * x[68]
    + 8 * x[69] * x[70] * x[71]
    - 4 * x[69] * x[71]
    - 8 * x[69] * x[78] * x[89]
    + 4 * x[69] * x[89]
    - 6 * x[69]
    + 8 * x[71] * x[72] * x[73]
    - 8 * x[71] * x[72]
    - 4 * x[71] * x[73]
    + 2 * x[71]
    - 8 * x[72] * x[73]
    + 8 * x[72]
    - 8 * x[73] * x[74] * x[75]
    + 8 * x[73] * x[74]
    + 4 * x[73] * x[75]
    - 8 * x[73] * x[79] * x[93]
    + 8 * x[73] * x[79]
    + 4 * x[73] * x[93]
    - 6 * x[73]
    + 8 * x[74] * x[75]
    - 4 * x[74]
    - 10 * x[75]
    + 4 * x[76]
    + 8 * x[78] * x[89]
    - 4 * x[78]
    - 4 * x[79]
    - 4 * x[80] * x[81]
    + 4 * x[80]
    - 8 * x[81] * x[82] * x[83]
    + 8 * x[81] * x[82]
    + 4 * x[81] * x[83]
    + 8 * x[82] * x[83]
    - 8 * x[82]
    - 8 * x[83] * x[84] * x[85]
    + 4 * x[83] * x[85]
    - 8 * x[83] * x[96] * x[103]
    + 4 * x[83] * x[103]
    - 2 * x[83]
    - 8 * x[85] * x[86] * x[87]
    + 8 * x[85] * x[86]
    + 4 * x[85] * x[87]
    - 6 * x[85]
    + 8 * x[86] * x[87]
    - 4 * x[86]
    - 8 * x[87] * x[88] * x[89]
    + 4 * x[87] * x[89]
    + 8 * x[87] * x[97] * x[107]
    - 8 * x[87] * x[97]
    - 4 * x[87] * x[107]
    + 2 * x[87]
    + 4 * x[88]
    - 8 * x[89] * x[90] * x[91]
    + 8 * x[89] * x[90]
    + 4 * x[89] * x[91]
    - 10 * x[89]
    + 8 * x[90] * x[91]
    - 8 * x[90]
    - 8 * x[91] * x[92] * x[93]
    + 4 * x[91] * x[93]
    - 8 * x[91] * x[98] * x[111]
    + 8 * x[91] * x[98]
    + 4 * x[91] * x[111]
    - 10 * x[91]
    + 8 * x[92] * x[93]
    - 4 * x[92]
    - 8 * x[93] * x[94] * x[95]
    + 4 * x[93] * x[95]
    - 6 * x[93]
    + 8 * x[95] * x[99] * x[115]
    - 8 * x[95] * x[99]
    - 4 * x[95] * x[115]
    + 2 * x[95]
    + 4 * x[96]
    - 8 * x[97] * x[107]
    + 4 * x[97]
    - 4 * x[98]
    - 8 * x[99] * x[115]
    + 4 * x[99]
    - 4 * x[100] * x[101]
    + 8 * x[101] * x[102] * x[103]
    - 8 * x[101] * x[102]
    - 4 * x[101] * x[103]
    - 8 * x[101] * x[116] * x[121]
    + 8 * x[101] * x[116]
    + 4 * x[101] * x[121]
    + 4 * x[101]
    - 8 * x[103] * x[104] * x[105]
    + 4 * x[103] * x[105]
    + 2 * x[103]
    + 8 * x[105] * x[106] * x[107]
    - 4 * x[105] * x[107]
    - 8 * x[105] * x[117] * x[125]
    + 4 * x[105] * x[125]
    + 2 * x[105]
    - 8 * x[106] * x[107]
    + 4 * x[106]
    + 8 * x[107] * x[108] * x[109]
    - 4 * x[107] * x[109]
    + 6 * x[107]
    - 4 * x[108]
    + 8 * x[109] * x[110] * x[111]
    - 4 * x[109] * x[111]
    - 8 * x[109] * x[118] * x[129]
    + 4 * x[109] * x[129]
    + 2 * x[109]
    - 8 * x[110] * x[111]
    + 4 * x[110]
    - 8 * x[111] * x[112] * x[113]
    + 8 * x[111] * x[112]
    + 4 * x[111] * x[113]
    + 2 * x[111]
    + 8 * x[112] * x[113]
    - 8 * x[112]
    - 8 * x[113] * x[114] * x[115]
    + 4 * x[113] * x[115]
    - 8 * x[113] * x[119] * x[133]
    + 4 * x[113] * x[133]
    - 2 * x[113]
    + 6 * x[115]
    - 4 * x[116]
    + 4 * x[118]
    + 4 * x[119]
    + 4 * x[120] * x[121]
    - 8 * x[121] * x[122] * x[123]
    + 4 * x[121] * x[123]
    - 4 * x[121]
    + 4 * x[122]
    - 8 * x[123] * x[124] * x[125]
    + 4 * x[123] * x[125]
    - 8 * x[123] * x[136] * x[143]
    + 4 * x[123] * x[143]
    - 2 * x[123]
    + 8 * x[124] * x[125]
    - 4 * x[124]
    + 8 * x[125] * x[126] * x[127]
    - 8 * x[125] * x[126]
    - 4 * x[125] * x[127]
    + 2 * x[125]
    - 8 * x[127] * x[128] * x[129]
    + 8 * x[127] * x[128]
    + 4 * x[127] * x[129]
    + 8 * x[127] * x[137] * x[147]
    - 8 * x[127] * x[137]
    - 4 * x[127] * x[147]
    - 2 * x[127]
    + 8 * x[129] * x[130] * x[131]
    - 4 * x[129] * x[131]
    + 2 * x[129]
    - 4 * x[130]
    - 8 * x[131] * x[132] * x[133]
    + 4 * x[131] * x[133]
    - 8 * x[131] * x[138] * x[151]
    + 4 * x[131] * x[151]
    - 2 * x[131]
    + 8 * x[133] * x[134] * x[135]
    - 4 * x[133] * x[135]
    + 2 * x[133]
    - 8 * x[134] * x[135]
    + 4 * x[134]
    - 8 * x[135] * x[139] * x[155]
    + 8 * x[135] * x[139]
    + 4 * x[135] * x[155]
    + 2 * x[135]
    + 8 * x[136] * x[143]
    - 4 * x[136]
    + 4 * x[138]
    + 8 * x[139] * x[155]
    - 4 * x[139]
    - 4 * x[140] * x[141]
    - 8 * x[141] * x[142] * x[143]
    + 8 * x[141] * x[142]
    + 4 * x[141] * x[143]
    + 8 * x[142] * x[143]
    - 8 * x[142]
    - 8 * x[143] * x[144] * x[145]
    + 8 * x[143] * x[144]
    + 4 * x[143] * x[145]
    - 14 * x[143]
    + 8 * x[144] * x[145]
    - 8 * x[144]
    - 8 * x[145] * x[146] * x[147]
    + 8 * x[145] * x[146]
    + 4 * x[145] * x[147]
    - 6 * x[145]
    + 8 * x[146] * x[147]
    - 4 * x[146]
    - 8 * x[147] * x[148] * x[149]
    + 8 * x[147] * x[148]
    + 4 * x[147] * x[149]
    - 6 * x[147]
    - 4 * x[148]
    - 8 * x[149] * x[150] * x[151]
    + 8 * x[149] * x[150]
    + 4 * x[149] * x[151]
    - 6 * x[149]
    + 8 * x[151] * x[152] * x[153]
    - 4 * x[151] * x[153]
    + 2 * x[151]
    + 8 * x[153] * x[154] * x[155]
    - 8 * x[153] * x[154]
    - 4 * x[153] * x[155]
    + 2 * x[153]
    - 8 * x[154] * x[155]
    + 4 * x[154]
    - 2 * x[155]
    + 46,
    x,
    domain="ZZ",
)

Calculate the function size

The function size depends on the number of binary decision variables and the interaction density. For the criteria of each size, see Function sizes in the Optimization Solver guide. Use the following helper to select "S", "M", or "L" without submitting a job. Count each distinct pair of variables that appears together in an objective term. A cubic term contributes three pairs, and pairs that appear in multiple terms are counted only once.

# Size calculator example for an optimization function.
#
# Input:  the model in whatever format your entrypoint accepts, plus the other function
#         inputs as ``**kwargs``.
# Output: ``"S"``, ``"M"`` or ``"L"``, from the number of variables and the interaction
#         density: the fraction of variable pairs that appear together in a term of the
#         objective or of a constraint.
#
# ``to_optimization_problem`` is **the one function to implement**: it turns your input into
# a :class:`~qiskit_addon_opt_mapper.problems.OptimizationProblem`, and the sizing logic
# below it never changes. Once converted, ``get_num_vars()`` gives the variable count; the
# class exposes no density, so it is derived from the objective and constraint expressions,
# each of which reports its terms through ``to_dict()``.
#
# Constraints are sized as the penalties that replace them on hardware -- see
# ``_interactions``. Slack variables for inequality penalties are not counted, so a heavily
# inequality-constrained model is sized slightly low on the variable count.
# https://qiskit.github.io/qiskit-opt-mapper/

import re
import sys
from ast import literal_eval
from collections.abc import Iterator
from itertools import combinations
from typing import Any, Literal

import networkx as nx
from qiskit.quantum_info import SparsePauliOp
from qiskit_addon_opt_mapper.problems import OptimizationProblem
from sympy import Poly, sympify

from qiskit_serverless import (
    ServerlessError,
    get_function_size,
    get_logger,
    send_error,
)

Size = Literal["S", "M", "L"]
_ORDER = {"S": 0, "M": 1, "L": 2}

# Error codes assigned by IBM; see the IBM Quantum error registry.
SIZE_TOO_SMALL_ERROR_CODE = "4600"
SIZE_TOO_LARGE_ERROR_CODE = "4601"

# Limits are provided by IBM
_SMALL_NUMVARS, _SMALL_DENSITY = 50, 0.1
_MEDIUM_NUMVARS, _MEDIUM_DENSITY = 100, 0.25


def calculate_function_size(problem: Any, **kwargs: Any) -> Size:
    """Return the size ("S", "M" or "L") needed to run ``problem``."""
    metrics = _measure(problem, **kwargs)
    if _is_small(metrics):
        return "S"
    if _is_medium(metrics):
        return "M"
    return "L"


def to_optimization_problem(
    problem: Any,
    *,
    problem_type: str | None = None,
    constraint: dict[str, int] | None = None,
    **kwargs: Any,  # pylint: disable=unused-argument
) -> OptimizationProblem:
    """Convert the optimizer's inputs into an ``OptimizationProblem``.

    Only the structure matters for sizing, so variables are binary and each term of the
    cost function is kept by its support (the variables it couples).

    - ``SparsePauliOp``: one variable per qubit, one term per Pauli string, supported on
      its ``Z`` operators.
    - Graph (adjacency data), with ``problem_type`` ``"maxcut"``: one variable per node,
      one coupling per edge. ``"max-<k>-cut"``: ``k`` variables per node, as in
      ``MaxKCutInstance``, with a one-hot constraint per node. User constraints are
      ignored for ``k >= 3``, as the solver ignores them.
    - Sympy expression (``srepr``): one variable per free symbol, one term per monomial.

    ``constraint`` (Hamming weights keyed by variable index or name) becomes equality
    constraints on the sum of the variables, which ``_interactions`` sizes as penalties.
    """
    if isinstance(problem, OptimizationProblem):
        return problem

    hamming = _deserialize_hamming_constraint(constraint)
    decoded = (
        problem
        if isinstance(problem, SparsePauliOp)
        else _decode_problem(problem)
    )

    names: dict[str, int] = {}
    groups: list[tuple[tuple[int | str, ...], int]] = list(hamming.items())
    if isinstance(decoded, SparsePauliOp):
        num_vars, terms = decoded.num_qubits, _pauli_terms(decoded)
    elif isinstance(decoded, nx.Graph):
        k = _parse_max_k_cut_k_value(problem_type)
        if problem_type == "maxcut" or k == 2:
            num_vars, terms = (
                decoded.number_of_nodes(),
                _graph_terms(decoded, 1),
            )
        elif k is not None:
            num_vars, terms = (
                decoded.number_of_nodes() * k,
                _graph_terms(decoded, k),
            )
            groups = [
                (tuple(range(k * node, k * (node + 1))), 1)
                for node in range(decoded.number_of_nodes())
            ]
        else:
            raise ValueError(
                f"cannot size a graph problem of type {problem_type!r}: expected "
                "'maxcut' or 'max-<k>-cut'"
            )
    else:
        poly = decoded if isinstance(decoded, Poly) else Poly(decoded)
        symbols = sorted(
            poly.as_expr().free_symbols, key=lambda symbol: symbol.name
        )
        names = {symbol.name: index for index, symbol in enumerate(symbols)}
        num_vars, terms = len(symbols), _poly_terms(poly, names)

    return _build_problem(num_vars, terms, groups, names)


def _decode_problem(problem: Any) -> Any:
    """Decode a graph (networkx adjacency data) or a sympy ``srepr`` string."""
    try:
        try:
            return nx.readwrite.json_graph.adjacency_graph(problem)
        except AttributeError:
            return sympify(problem)
    except RecursionError:
        sys.setrecursionlimit(5000)
        return _decode_problem(problem)


def _parse_max_k_cut_k_value(problem_type: str | None) -> int | None:
    """Return ``k`` for a ``max-<k>-cut`` problem type, else ``None``."""
    match = re.fullmatch(r"max-(\d+)-cut", problem_type or "")
    if match is None:
        return None
    k = int(match.group(1))
    if k < 2:
        raise ValueError(
            f"k for a Max-k-Cut problem must be at least 2, got {k}."
        )
    return k


def _deserialize_hamming_constraint(
    constraint: dict[str, int] | None,
) -> dict[tuple[int | str, ...], int]:
    """Turn string keys such as ``"(0, 1)"`` into tuples of indices or names."""
    deserialized: dict[tuple[int | str, ...], int] = {}
    for key, weight in (constraint or {}).items():
        try:
            group = literal_eval(key)
        except (ValueError, TypeError, SyntaxError):
            group = None
        if not isinstance(group, tuple) or not all(
            isinstance(entry, (int, str)) for entry in group
        ):
            raise ValueError(
                f"Constraint '{key}' is not a valid tuple of variable indexes or names."
            )
        deserialized[group] = weight
    return deserialized


def _pauli_terms(operator: SparsePauliOp) -> dict[tuple[int, ...], float]:
    terms: dict[tuple[int, ...], float] = {}
    for label, coefficient in zip(
        operator.paulis.to_labels(), operator.coeffs
    ):
        # The rightmost character of a Pauli label is qubit 0.
        support = tuple(
            i for i, char in enumerate(reversed(label)) if char == "Z"
        )
        terms[support] = terms.get(support, 0.0) + float(coefficient.real)
    return terms


def _graph_terms(
    graph: nx.Graph, colors: int
) -> dict[tuple[int, ...], float]:
    terms: dict[tuple[int, ...], float] = {}
    for u, v, weight in graph.edges(data="weight", default=1.0):
        for color in range(colors):
            support = tuple(sorted({colors * u + color, colors * v + color}))
            terms[support] = terms.get(support, 0.0) + weight
    return terms


def _poly_terms(
    poly: Poly, names: dict[str, int]
) -> dict[tuple[int, ...], float]:
    terms: dict[tuple[int, ...], float] = {}
    for exponents, coefficient in poly.terms():
        support = tuple(
            sorted(
                names[generator.name]
                for generator, exponent in zip(poly.gens, exponents)
                if exponent > 0
            )
        )
        terms[support] = terms.get(support, 0.0) + float(coefficient)
    return terms


def _build_problem(
    num_vars: int,
    terms: dict[tuple[int, ...], float],
    groups: list[tuple[tuple[int | str, ...], int]],
    names: dict[str, int],
) -> OptimizationProblem:
    """Build the problem; terms of order 3 and above go in ``higher_order``, by order."""
    model = OptimizationProblem()
    model.binary_var_list(num_vars, name="x")

    linear: dict[int, float] = {}
    quadratic: dict[tuple[int, int], float] = {}
    higher_order: dict[int, dict[tuple[int, ...], float]] = {}
    for support, coefficient in terms.items():
        if len(support) == 1:
            linear[support[0]] = coefficient
        elif len(support) == 2:
            quadratic[(support[0], support[1])] = coefficient
        elif len(support) >= 3:
            higher_order.setdefault(len(support), {})[support] = coefficient
    model.minimize(
        linear=linear, quadratic=quadratic, higher_order=higher_order or None
    )

    for group, weight in groups:
        members = {names[m] if isinstance(m, str) else m: 1.0 for m in group}
        model.linear_constraint(members, "==", weight)
    return model


def _measure(problem: Any, **kwargs: Any) -> dict[str, float]:
    """Return the number of variables and the interaction density."""
    model = to_optimization_problem(problem, **kwargs)
    num_vars = model.get_num_vars()

    pairs = set()
    for term in _interactions(model):
        pairs.update(frozenset(pair) for pair in combinations(set(term), 2))

    max_pairs = num_vars * (num_vars - 1) // 2
    return {
        "num_vars": num_vars,
        "density": len(pairs) / max_pairs if max_pairs else 0.0,
    }


def _interactions(problem: OptimizationProblem) -> Iterator[tuple[int, ...]]:
    """Yield the variable tuple of every term that couples two or more variables.

    Objective terms contribute their own variables; a linear objective term couples
    nothing.

    A constraint contributes the whole support of its left-hand side, because the
    unconstrained form of the model replaces it with a penalty ``w * lhs**2``, and
    squaring a sum couples every pair of variables in it -- a one-hot constraint over four
    variables becomes a clique on those four. Neither the penalty weight nor the
    right-hand side changes which pairs exist, so neither is needed here. This holds
    whether or not your function handles constraints natively, because a size has to mean
    the same thing across every optimization function.
    """
    objective = problem.objective
    yield from objective.quadratic.to_dict()
    for expression in objective.higher_order.values():
        yield from expression.to_dict()

    for constraint in problem.linear_constraints:
        yield _constraint_support(constraint)
    for constraint in problem.quadratic_constraints:
        yield _constraint_support(constraint)
    for constraint in problem.higher_order_constraints:
        yield _constraint_support(constraint)


def _constraint_support(constraint: Any) -> tuple[int, ...]:
    """Return every variable appearing in a constraint's left-hand side."""
    variables = set(constraint.linear.to_dict())
    if hasattr(constraint, "quadratic"):
        for term in constraint.quadratic.to_dict():
            variables.update(term)
    if hasattr(constraint, "higher_order"):
        for expression in constraint.higher_order.values():
            for term in expression.to_dict():
                variables.update(term)
    return tuple(variables)


def _is_small(metrics: dict[str, float]) -> bool:
    """Determine if the metrics fit T-size 'S'."""
    return (
        metrics["num_vars"] <= _SMALL_NUMVARS
        and metrics["density"] <= _SMALL_DENSITY
    )


def _is_medium(metrics: dict[str, float]) -> bool:
    """Determine if the metrics fit T-size 'M'."""
    return (
        metrics["num_vars"] <= _MEDIUM_NUMVARS
        and metrics["density"] <= _MEDIUM_DENSITY
    )


def validate_size(problem: Any, **kwargs: Any) -> None:
    """Call once at the start of your function. Compare the size the job was given with
    the calculated size and log both. Raise if the given size is smaller than the calculation;
    report a non-fatal event and continue if it is larger."""
    logger = get_logger()
    provided = get_function_size()
    if not provided:
        # Empty on non-Fleets (Ray) jobs, where sizes do not apply.
        logger.warning(
            "No function size was given to this job; skipping the size check."
        )
        return
    provided = provided.upper()
    expected = calculate_function_size(problem, **kwargs)
    logger.info(
        "Function size given: '%s'; calculated size: '%s'.",
        provided,
        expected,
    )
    if _ORDER[provided] < _ORDER[expected]:
        logger.error(
            "Size '%s' is too small; the calculated size is '%s'.",
            provided,
            expected,
        )
        raise ServerlessError(
            code=SIZE_TOO_SMALL_ERROR_CODE,
            message=f"Size '{provided}' is too small for this problem; expected '{expected}' or larger.",
        )
    if _ORDER[provided] > _ORDER[expected]:
        logger.warning(
            "Size '%s' is larger than this problem needs; the calculated size is '%s'.",
            provided,
            expected,
        )
        send_error(
            code=SIZE_TOO_LARGE_ERROR_CODE,
            message="The specified function size is larger than this job requires.",
            exception="FunctionSizeTooLarge",
            args={
                "provided_size": provided,
                "calculated_size": expected,
                "solution": (
                    "No action is required and the job completed normally. To reduce "
                    "cost, use a smaller function size for jobs of this kind."
                ),
            },
        )

Step 2: Run the hybrid algorithm using the Fire Opal Optimization Solver

Now use the Optimization Solver quantum function to run the algorithm. Behind the scenes, the Optimization Solver takes care of mapping the problem to a hybrid quantum algorithm, running the quantum circuits with error suppression, and performing the classical optimization.

# Authenticate to the Quantum Functions Catalog
catalog = FunctionsCatalog(
    token=token,
    instance=instance,
)

# Load the function
solver = catalog.load("q-ctrl/optimization-solver")

Check to ensure that the chosen device has at least 156 qubits.

# Specify the target backend name
backend_name = "<CHOOSE_A_BACKEND>"

The Solver accepts a string representation of the objective function.

# Convert the objective function to string format
spin_glass_poly_as_str = srepr(spin_glass_poly)

Calculate the function size from the polynomial's variables and distinct interacting pairs, then pass the returned value to solver.run through function_size.

# Calculate the workload size
function_size = calculate_function_size(
    spin_glass_poly_as_str,
)
print(f"Workload size: {function_size}")

Output:

Workload size: L
# Run the problem
spin_glass_job = solver.run(
    problem=spin_glass_poly_as_str,
    run_options={"backend_name": backend_name},
    function_size=function_size,
)

Check your quantum function workload's status:

# Get job status
spin_glass_job.status()

The Solver returns a dictionary with the solution and associated metadata, such as the solution bitstring, number of iterations, and mapping of variables to bitstring. For a full definition of the Solver's inputs and outputs, check out the documentation.

# Poll for results
result = spin_glass_job.result()
# Get the final bitstring distribution and set the number of shots
distribution = result["final_bitstring_distribution"]

Step 3: Evaluate results

# Get the solution ground state energy
print(f"Minimum ground state energy: {result['solution_bitstring_cost']}")

Output:

Minimum ground state energy: -242.0

The Solver found the correct solution, which was validated using classical optimization software. The complexity of this utility-scale problem requires an advanced optimization software to be solved classically, such as IBM ILOG CPLEX Optimization Studio (CPLEX) or Gurobi Optimization.

As a visual analysis of the quality of results, you can plot the results by calculating the cost values from the bitstrings and their probabilities. For comparison, plot the results alongside a distribution of randomly sampled bitstrings, which is equivalent to a "brute-force" classical solution. If the algorithm consistently finds lower costs, it suggests the quantum algorithm is effectively solving the optimization problem.

def plot_cost_histogram(
    costs, probabilities, distribution, qubit_count, bitstring_cost
):
    """Plots a histogram comparing the cost distributions of
    Q-CTRL Solver and random sampling."""

    # Set figure DPI for higher resolution and font size for labels
    plt.rcParams["figure.dpi"] = 300
    plt.rcParams.update({"font.size": 6})  # Set default font size to 6

    # Define labels and colors for the plot
    labels = ["Q-CTRL Solver", "Random Sampling"]
    colors = ["#680CE9", "#E04542"]

    # Calculate total shots (total number of bitstrings in the distribution)
    shots = sum(distribution.values())

    # Generate random bitstrings for comparison (random sampling)
    rng = np.random.default_rng(seed=0)
    random_array = rng.integers(
        0, 2, size=(shots, qubit_count)
    )  # Generate random bitstrings (0 or 1 for each qubit)
    random_bitstrings = ["".join(row.astype(str)) for row in random_array]

    # Compute the cost for each random bitstring
    random_costs = [bitstring_cost(k) for k in random_bitstrings]

    # Set uniform probabilities for the random sampling
    random_probabilities = (
        np.ones(shape=(shots,)) / shots
    )  # Equal probability for each random bitstring

    # Find the minimum and maximum costs for binning the histogram
    min_cost = np.min(costs)
    max_cost = np.max(random_costs)

    # Create a histogram plot with a smaller figure size (4x2 inches)
    fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(4, 2))

    # Plot histograms for the Q-CTRL solver and random sampling costs
    _, _, _ = ax.hist(
        [costs, random_costs],  # Data for the two histograms
        np.arange(min_cost, max_cost, 2),  # Bins for the histogram
        weights=[
            probabilities,
            random_probabilities,
        ],  # Probabilities for each data set
        label=labels,  # Labels for the legend
        color=colors,  # Colors for each histogram
        histtype="stepfilled",  # Filled step histogram
        align="mid",  # Align bars to the bin center
        alpha=0.8,  # Transparency
    )

    # Set the x and y labels for the plot
    ax.set_xlabel("Cost")
    ax.set_ylabel("Probability")

    # Add the legend to the plot
    ax.legend()

    # Show the plot
    plt.show()
# Convert spin_glass_poly into a NumPy-compatible function
poly_as_numpy_function = lambdify(x, spin_glass_poly.as_expr(), "numpy")


# Function to compute the cost of a given bitstring using spin_glass_poly
def bitstring_cost(bitstring: str) -> float:
    # Convert bitstring to a reversed list of integers (0s and 1s)
    return float(
        poly_as_numpy_function(*[int(b) for b in str(bitstring[::-1])])
    )


# Calculate the cost of each bitstring in the distribution
costs = [bitstring_cost(k) for k, _ in distribution.items()]

# Extract probabilities from the bitstring distribution
probabilities = np.array([v for _, v in distribution.items()])
probabilities = probabilities / sum(
    probabilities
)  # Normalize to get probabilities

plot_cost_histogram(
    costs, probabilities, distribution, qubit_count, bitstring_cost
)

Output:

Output of the previous code cell

Since the goal of this optimization algorithm is to find the minimum ground state of the Ising model, lower values indicate better solutions. Therefore, it's visually apparent that the solutions generated by the Fire Opal Optimization Solver far outperform random selection.