{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "e9a2d4b7",
      "metadata": {},
      "source": [
        "---\n",
        "title: Get started with SQOA Solver by JIJ\n",
        "description: Load the JIJ SQOA Solver function, choose a function size, and solve MaxCut and constrained optimization problems with qiskit-addon-opt-mapper or OMMX.\n",
        "---\n",
        "\n",
        "{/* cspell:ignore SQOA QUBO JijModeling OMMX ommx jijmodeling MaxCut networkx */}\n",
        "\n",
        "# Get started with SQOA Solver by JIJ\n",
        "\n",
        "*See the [overview](/docs/functions/jij-sqoa-solver) and the [API reference](/docs/functions/jij-sqoa-solver/api-reference).*\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  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.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3f9a6c21",
      "metadata": {
        "tags": [
          "version-info"
        ]
      },
      "source": [
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "daa36c25-e497-435a-8a10-e1e6a1d8f851",
      "metadata": {},
      "source": [
        "## Set up and load the function\n",
        "\n",
        "Find access information for this quantum function in the [Quantum Functions Catalog](/functions).\n",
        "\n",
        "This section shows how to authenticate and load the function, and how to prepare a problem in the dictionary format that SQOA Solver accepts by using `OptimizationProblem` from [qiskit-addon-opt-mapper](https://qiskit.github.io/qiskit-addon-opt-mapper/). The examples that follow run the function and read the result.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "543e50ae-c4f4-4972-afbf-45897c08b940",
      "metadata": {},
      "source": [
        "### Authenticate and load the function\n",
        "\n",
        "First, authenticate with your [IBM Quantum API key](/). (The following code assumes that you already [saved your account](/docs/ibm-quantum-platform/functions-get-started#install-qiskit-functions-catalog-client) to your local environment.) Then, create a catalog client as follows:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "c5e52ed0-0496-44c5-86e2-bdecfd64691a",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[QiskitFunction(jij/sqoa-solver)]"
            ]
          },
          "execution_count": 1,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "from qiskit_ibm_catalog import FunctionsCatalog\n",
        "\n",
        "catalog = FunctionsCatalog(channel=\"ibm_quantum_platform\")\n",
        "\n",
        "# verify that you have access to the function\n",
        "catalog.list()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "c4134d92-e21b-444c-a71f-71d033cdf3f6",
      "metadata": {},
      "outputs": [],
      "source": [
        "solver = catalog.load(\"jij/sqoa-solver\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "20af7979-b17e-4eaf-9627-373a9137e1ea",
      "metadata": {},
      "source": [
        "### Prepare the input with `qiskit-addon-opt-mapper`\n",
        "\n",
        "This guide models problems with the `OptimizationProblem` class of [qiskit-addon-opt-mapper](https://qiskit.github.io/qiskit-addon-opt-mapper/). SQOA Solver accepts a QUBO problem as a coefficient dictionary in the tuple-string format used by IBM optimization functions, so every example in this guide follows the same client-side preparation pattern:\n",
        "\n",
        "1. **Write the model.** Create an `OptimizationProblem`, add binary decision variables, and set the objective and any constraints.\n",
        "2. **Convert to QUBO.** Convert the problem with `OptimizationProblemToQubo`, which adds any constraints to the objective as penalty terms and returns an equivalent unconstrained minimization problem.\n",
        "3. **Convert to a dictionary.** Pass the QUBO to the `to_problem_dict()` helper function defined in the next section, and pass the result to `solver.run()` as `problem`, together with `variable_type=\"binary\"`.\n",
        "\n",
        "SQOA Solver always minimizes a dictionary problem, which matches the minimization problem that `OptimizationProblemToQubo` returns. For a maximization problem, the returned `objective_value` is therefore the negative of the original objective. To read the result in terms of the original problem, evaluate the returned assignment with `OptimizationProblem`, as the examples show. For the dictionary format details, see [Accepted problem formats](/docs/functions/jij-sqoa-solver/api-reference#accepted-problem-formats) in the API reference.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "686f86ed-be2a-492e-8e5a-9e435b73fb7c",
      "metadata": {},
      "outputs": [],
      "source": [
        "# %pip install qiskit-addon-opt-mapper"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "619f306e-0516-4a59-b822-efe7755bd2b0",
      "metadata": {},
      "source": [
        "Define the following helper function once and reuse it in every example. It converts the QUBO returned by `OptimizationProblemToQubo` into the dictionary format. The keys use the variable indices of the QUBO, so the solution keys `x_0`, `x_1`, and so on in the result correspond to those indices. Every variable receives a linear entry, even with a zero coefficient, so that the returned solution covers all variables.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "00b2d104-55df-4682-ab5e-051696858d0f",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit_addon_opt_mapper import OptimizationProblem\n",
        "from qiskit_addon_opt_mapper.converters import OptimizationProblemToQubo\n",
        "\n",
        "\n",
        "def to_problem_dict(qubo: OptimizationProblem) -> dict[str, float]:\n",
        "    \"\"\"Convert a QUBO from OptimizationProblemToQubo to the SQOA Solver dictionary format.\"\"\"\n",
        "    objective = qubo.objective\n",
        "    payload = {\"()\": objective.constant}\n",
        "    # Keep every variable in the problem, even with a zero linear coefficient.\n",
        "    payload.update({f\"({i},)\": 0.0 for i in range(qubo.get_num_vars())})\n",
        "    for i, coefficient in objective.linear.to_dict().items():\n",
        "        payload[f\"({i},)\"] += coefficient\n",
        "    for (i, j), coefficient in objective.quadratic.to_dict().items():\n",
        "        # Fold a binary diagonal term x_i * x_i = x_i into the linear term.\n",
        "        key = f\"({i},)\" if i == j else f\"({i}, {j})\"\n",
        "        payload[key] = payload.get(key, 0.0) + coefficient\n",
        "    return {key: float(value) for key, value in payload.items()}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "40cd6bbc-0fd7-4764-812c-681cc12bc998",
      "metadata": {},
      "source": [
        "## Function sizes\n",
        "\n",
        "Every job runs at one size: `\"S\"`, `\"M\"`, or `\"L\"`. If the size is too small, the job is rejected. If it is larger than needed, the job runs on a bigger compute profile than the work requires. See the [managed workflows topic](/docs/managed-workflows/managed-workflow-compute-profiles#best-practice-match-sizes-to-problem-sizes) for how sizes work in general.\n",
        "\n",
        "The size comes from two properties of the QUBO that you submit: how many variables it has, and how densely they interact, that is, the fraction of all variable pairs that appear together in a quadratic term with a nonzero coefficient.\n",
        "\n",
        "| Size | Smallest size for variables and interaction density | Compute profile | vCPU | RAM    |\n",
        "| ---- | --------------------------------------------------- | --------------- | ---- | ------ |\n",
        "| `S`  | At most 50 variables and density at most 0.1        | `8x32`          | 8    | 32 GB  |\n",
        "| `M`  | At most 100 variables and density at most 0.25      | `16x128`        | 16   | 128 GB |\n",
        "| `L`  | Either above the `M` bound                          | `48x768`        | 48   | 768 GB |\n",
        "\n",
        "A problem must fit **both** bounds of a size, which is why a small but tightly coupled problem can be `L`: ten variables all coupled to each other is a density of 1.0. These are the same bounds for every optimization function, so a size means the same difficulty of problem whichever one you call.\n",
        "\n",
        "Converting a constrained problem to a QUBO raises the density more than it might appear. `OptimizationProblemToQubo` replaces each constraint with a penalty term, and squaring the constraint couples every pair of variables in it, so a one-hot constraint over four variables contributes all six pairs.\n",
        "\n",
        "The default size, used when a job does not request one, is `\"M\"`. You can also read the mapping from the function itself with `solver.sizes_map`, and the default size with `solver.default_size`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3df17006-13c6-4793-a494-20efd03ea620",
      "metadata": {},
      "source": [
        "### Calculate the size before submitting\n",
        "\n",
        "Run the following calculator on your own problem. It reads the problem and nothing else: no job is submitted and nothing is reserved, so you can call it as often as you like while you reduce a problem to a smaller size. It performs the same calculation that the function runs when a job arrives, so a job submitted at the calculated size is not rejected as too small.\n",
        "\n",
        "For a coefficient dictionary, pass `calculate_function_size()` a dictionary with the same `problem` and `variable_type` that you pass to `solver.run()`. For an OMMX instance, pass the `ommx.v1.Instance` itself, not the Base64 string. The calculator uses OMMX in both cases, so install the `ommx` package first:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "dc6fea3e-1823-4371-b535-5af2f2d46224",
      "metadata": {},
      "outputs": [],
      "source": [
        "# %pip install ommx"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "a1444762-2da5-46d3-af41-ff7bb541aa25",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Calculate the function size a problem needs, before submitting it.\n",
        "# calculate_function_size(problem) returns \"S\", \"M\", or \"L\" and submits\n",
        "# nothing. The size comes from the number of variables and how densely\n",
        "# they interact.\n",
        "\n",
        "from collections.abc import Iterator\n",
        "from itertools import combinations\n",
        "from typing import Any, Literal\n",
        "\n",
        "from qiskit_addon_opt_mapper.problems import OptimizationProblem\n",
        "\n",
        "Size = Literal[\"S\", \"M\", \"L\"]\n",
        "_ORDER = {\"S\": 0, \"M\": 1, \"L\": 2}\n",
        "\n",
        "# Limits are provided by IBM\n",
        "_SMALL_NUMVARS, _SMALL_DENSITY = 50, 0.1\n",
        "_MEDIUM_NUMVARS, _MEDIUM_DENSITY = 100, 0.25\n",
        "\n",
        "\n",
        "def calculate_function_size(problem: Any, **kwargs: Any) -> Size:\n",
        "    \"\"\"Return the size (\"S\", \"M\" or \"L\") needed to run ``problem``.\"\"\"\n",
        "    metrics = _measure(problem, **kwargs)\n",
        "    if _is_small(metrics):\n",
        "        return \"S\"\n",
        "    if _is_medium(metrics):\n",
        "        return \"M\"\n",
        "    return \"L\"\n",
        "\n",
        "\n",
        "def to_optimization_problem(problem: Any) -> OptimizationProblem:\n",
        "    \"\"\"Convert SQOA input into an ``OptimizationProblem``.\n",
        "\n",
        "    Accept an OMMX ``Instance`` directly, or a dictionary containing a coefficient\n",
        "    dictionary as ``problem`` and ``\"binary\"`` or ``\"spin\"`` as ``variable_type``.\n",
        "    Convert to a binary minimization problem with consecutive variable IDs from zero.\n",
        "    Leave the input instance unchanged.\n",
        "    Return an existing ``OptimizationProblem`` unchanged.\n",
        "    \"\"\"\n",
        "    if isinstance(problem, OptimizationProblem):\n",
        "        return problem\n",
        "    import ast\n",
        "    import math\n",
        "    import re\n",
        "\n",
        "    from ommx.v1 import DecisionVariable, Instance, Kind\n",
        "\n",
        "    _TERM_ID = r\"(?:0|[1-9][0-9]*)\"\n",
        "    _TERM_SPACE = r\"[ \\t\\r\\n]*\"\n",
        "    _TERM_KEY_PATTERN = (\n",
        "        rf\"^\\({_TERM_SPACE}(?:{_TERM_ID}{_TERM_SPACE},\"\n",
        "        rf\"{_TERM_SPACE}(?:{_TERM_ID}{_TERM_SPACE}(?:,{_TERM_SPACE})?)?)?\\)(?![\\s\\S])\"\n",
        "    )\n",
        "\n",
        "    def _term_ids(key: str) -> tuple[int, ...]:\n",
        "        if (\n",
        "            not isinstance(key, str)\n",
        "            or re.fullmatch(_TERM_KEY_PATTERN, key) is None\n",
        "        ):\n",
        "            raise ValueError(\"invalid term key\")\n",
        "        ids = ast.literal_eval(key)\n",
        "        if len(set(ids)) != len(ids):\n",
        "            raise ValueError(\"repeated variable ID\")\n",
        "        return tuple(sorted(ids))\n",
        "\n",
        "    def _dictionary_to_instance(\n",
        "        problem: dict[str, object], variable_type: str\n",
        "    ) -> Instance:\n",
        "        terms: dict[tuple[int, ...], float] = {}\n",
        "        variable_ids: set[int] = set()\n",
        "        for key, value in problem.items():\n",
        "            ids = _term_ids(key)\n",
        "            if type(value) not in (int, float):\n",
        "                raise ValueError(\"invalid coefficient\")\n",
        "            coefficient = float(value)\n",
        "            if not math.isfinite(coefficient):\n",
        "                raise ValueError(\"invalid coefficient\")\n",
        "            variable_ids.update(ids)\n",
        "            terms[ids] = terms.get(ids, 0.0) + coefficient\n",
        "            if not math.isfinite(terms[ids]):\n",
        "                raise ValueError(\"coefficient overflow\")\n",
        "        variables = {\n",
        "            i: DecisionVariable.binary(i) for i in sorted(variable_ids)\n",
        "        }\n",
        "        expressions = {\n",
        "            i: 1 - 2 * variable if variable_type == \"spin\" else variable\n",
        "            for i, variable in variables.items()\n",
        "        }\n",
        "        objective = 0.0\n",
        "        for ids, coefficient in terms.items():\n",
        "            term = coefficient\n",
        "            for i in ids:\n",
        "                term = term * expressions[i]\n",
        "            objective = objective + term\n",
        "        return Instance.from_components(\n",
        "            decision_variables=list(variables.values()),\n",
        "            objective=objective,\n",
        "            constraints=[],\n",
        "            sense=Instance.MINIMIZE,\n",
        "        )\n",
        "\n",
        "    if isinstance(problem, Instance):\n",
        "        instance = problem\n",
        "    else:\n",
        "        if (\n",
        "            not isinstance(problem, dict)\n",
        "            or not {\"problem\", \"variable_type\"} <= problem.keys()\n",
        "        ):\n",
        "            raise ValueError(\n",
        "                \"SQOA sizing requires an OMMX Instance or a coefficient input envelope \"\n",
        "                \"with 'problem' and 'variable_type'\"\n",
        "            )\n",
        "        variable_type = problem[\"variable_type\"]\n",
        "        if variable_type not in (\"binary\", \"spin\"):\n",
        "            raise ValueError(\"variable_type must be binary or spin\")\n",
        "        if not isinstance(problem[\"problem\"], dict):\n",
        "            raise ValueError(\n",
        "                \"problem must be a coefficient dictionary; pass OMMX Instances directly\"\n",
        "            )\n",
        "        instance = _dictionary_to_instance(problem[\"problem\"], variable_type)\n",
        "\n",
        "    variables = list(instance.decision_variables)\n",
        "    degree = instance.objective.degree()\n",
        "    if not variables:\n",
        "        raise ValueError(\n",
        "            \"problem must contain at least one decision variable\"\n",
        "        )\n",
        "    if any(variable.kind == Kind.Continuous for variable in variables):\n",
        "        raise ValueError(\n",
        "            \"problem must not contain Continuous decision variables\"\n",
        "        )\n",
        "    if degree > 2:\n",
        "        raise ValueError(\"problem objective degree must be at most two\")\n",
        "    # Copy the instance so minimization does not modify the caller's original.\n",
        "    normalized = Instance.from_bytes(instance.to_bytes())\n",
        "    normalized.as_minimization_problem()\n",
        "    qubo, offset = normalized.as_qubo_format()\n",
        "    if not math.isfinite(offset) or any(\n",
        "        not math.isfinite(v) for v in qubo.values()\n",
        "    ):\n",
        "        raise ValueError(\"problem objective coefficients must all be finite\")\n",
        "\n",
        "    ids = [variable.id for variable in variables]\n",
        "    dense_ids = {\n",
        "        variable_id: index for index, variable_id in enumerate(sorted(ids))\n",
        "    }\n",
        "    linear = {}\n",
        "    quadratic = {}\n",
        "    for (first, second), coefficient in qubo.items():\n",
        "        i, j = dense_ids[first], dense_ids[second]\n",
        "        if i == j:\n",
        "            linear[i] = linear.get(i, 0.0) + coefficient\n",
        "        else:\n",
        "            pair = (min(i, j), max(i, j))\n",
        "            quadratic[pair] = quadratic.get(pair, 0.0) + coefficient\n",
        "\n",
        "    model = OptimizationProblem()\n",
        "    model.binary_var_list(len(ids), name=\"x\")\n",
        "    model.minimize(\n",
        "        constant=offset,\n",
        "        linear=linear,\n",
        "        quadratic=quadratic,\n",
        "    )\n",
        "    return model\n",
        "\n",
        "\n",
        "def _measure(problem: Any, **kwargs: Any) -> dict[str, float]:\n",
        "    \"\"\"Return the number of variables and the interaction density.\"\"\"\n",
        "    model = to_optimization_problem(problem)\n",
        "    num_vars = model.get_num_vars()\n",
        "\n",
        "    pairs = set()\n",
        "    for term in _interactions(model):\n",
        "        pairs.update(frozenset(pair) for pair in combinations(set(term), 2))\n",
        "\n",
        "    max_pairs = num_vars * (num_vars - 1) // 2\n",
        "    return {\n",
        "        \"num_vars\": num_vars,\n",
        "        \"density\": len(pairs) / max_pairs if max_pairs else 0.0,\n",
        "    }\n",
        "\n",
        "\n",
        "def _interactions(problem: OptimizationProblem) -> Iterator[tuple[int, ...]]:\n",
        "    \"\"\"Yield the variables of every term that couples two or more of them.\n",
        "\n",
        "    A constraint contributes every variable in it, because on hardware it becomes\n",
        "    a penalty whose square couples them all.\n",
        "    \"\"\"\n",
        "    objective = problem.objective\n",
        "    yield from objective.quadratic.to_dict()\n",
        "    for expression in objective.higher_order.values():\n",
        "        yield from expression.to_dict()\n",
        "\n",
        "    for constraint in problem.linear_constraints:\n",
        "        yield _constraint_support(constraint)\n",
        "    for constraint in problem.quadratic_constraints:\n",
        "        yield _constraint_support(constraint)\n",
        "    for constraint in problem.higher_order_constraints:\n",
        "        yield _constraint_support(constraint)\n",
        "\n",
        "\n",
        "def _constraint_support(constraint: Any) -> tuple[int, ...]:\n",
        "    \"\"\"Return every variable appearing in a constraint's left-hand side.\"\"\"\n",
        "    variables = set(constraint.linear.to_dict())\n",
        "    if hasattr(constraint, \"quadratic\"):\n",
        "        for term in constraint.quadratic.to_dict():\n",
        "            variables.update(term)\n",
        "    if hasattr(constraint, \"higher_order\"):\n",
        "        for expression in constraint.higher_order.values():\n",
        "            for term in expression.to_dict():\n",
        "                variables.update(term)\n",
        "    return tuple(variables)\n",
        "\n",
        "\n",
        "def _is_small(metrics: dict[str, float]) -> bool:\n",
        "    \"\"\"Determine if the metrics fit T-size 'S'.\"\"\"\n",
        "    return (\n",
        "        metrics[\"num_vars\"] <= _SMALL_NUMVARS\n",
        "        and metrics[\"density\"] <= _SMALL_DENSITY\n",
        "    )\n",
        "\n",
        "\n",
        "def _is_medium(metrics: dict[str, float]) -> bool:\n",
        "    \"\"\"Determine if the metrics fit T-size 'M'.\"\"\"\n",
        "    return (\n",
        "        metrics[\"num_vars\"] <= _MEDIUM_NUMVARS\n",
        "        and metrics[\"density\"] <= _MEDIUM_DENSITY\n",
        "    )"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "01012d2f-9af0-4ab8-adcf-25765c6f2879",
      "metadata": {},
      "source": [
        "If the size is too small, the job fails with error `4600`, and the message names the size to use instead. If it is larger than needed, the job runs normally and records a `4601` advisory event. See the [managed workflow documentation](/docs/managed-workflows/managed-workflow-compute-profiles#best-practice-match-sizes-to-problem-sizes) to learn more. The examples that follow calculate the size before every submission.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "6e75d220-d0af-41d7-b74b-ab68220cdcce",
      "metadata": {},
      "source": [
        "## Example 1: MaxCut on a 3-regular graph\n",
        "\n",
        "Many graph problems, such as MaxCut, are NP-hard and are natural candidates for quantum optimization. Install `networkx` as an additional dependency to run this example:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "a72518a6-e6bc-4331-9ce6-47b5cc35e277",
      "metadata": {},
      "outputs": [],
      "source": [
        "# %pip install networkx"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "42a13570-5dca-42fc-8d01-ac585f2d4170",
      "metadata": {},
      "source": [
        "### 1. Write the model\n",
        "\n",
        "Assign a binary variable $x_v \\in \\{0, 1\\}$ to each vertex of a graph $G = (V, E)$ to indicate its side of the cut. An edge is cut when its endpoints are on different sides, so the cut size is:\n",
        "\n",
        "$$\n",
        "\\mathrm{Cut}(x) = \\sum_{(u,v) \\in E} \\left(x_u + x_v - 2 x_u x_v\\right).\n",
        "$$\n",
        "\n",
        "This objective is already a QUBO without constraints, so `OptimizationProblemToQubo` only turns the maximization into the equivalent minimization and keeps the variables unchanged. The `Maxcut` application class in `qiskit_addon_opt_mapper.applications` builds the same model with `Maxcut(G).to_optimization_problem()`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "e01f526b-b26c-4f5d-bee7-de44f439a7dc",
      "metadata": {},
      "outputs": [],
      "source": [
        "import networkx as nx\n",
        "\n",
        "G = nx.random_regular_graph(3, 40, seed=42)\n",
        "\n",
        "linear = {v: 0 for v in G.nodes}\n",
        "quadratic = {}\n",
        "for u, v in G.edges:\n",
        "    linear[u] += 1\n",
        "    linear[v] += 1\n",
        "    quadratic[(u, v)] = -2\n",
        "\n",
        "maxcut = OptimizationProblem(\"MaxCut\")\n",
        "maxcut.binary_var_list(G.number_of_nodes(), name=\"x\")\n",
        "maxcut.maximize(linear=linear, quadratic=quadratic)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1ca69bb3-1e67-4765-9043-e88ba6ec034b",
      "metadata": {},
      "source": [
        "### 2. Run the solver\n",
        "\n",
        "Convert the model to a QUBO and then to a dictionary, and submit it. `problem` and `variable_type` are required. `backend_name` is optional. When it is omitted or `None`, the function selects the least busy operational QPU available to your instance.\n",
        "\n",
        "The `options` dictionary accepts `shots`, `seed`, `session`, `postprocessing_level`, and `job_tags`. For descriptions and defaults, see the [API reference](/docs/functions/jij-sqoa-solver/api-reference).\n",
        "\n",
        "The `function_size` argument selects the computing resources for the job. Pass it directly to `solver.run()`, outside `options`. Calculate it with `calculate_function_size()` from [Function sizes](#function-sizes). The graph has 40 nodes and 60 edges, so the QUBO has 40 variables and a density of about 0.08, which fits `\"S\"`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "0b317428-ff6f-4c7f-9837-da580ba96667",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Function size: S\n"
          ]
        }
      ],
      "source": [
        "qubo = OptimizationProblemToQubo().convert(maxcut)\n",
        "problem = to_problem_dict(qubo)\n",
        "\n",
        "size = calculate_function_size(\n",
        "    {\"problem\": problem, \"variable_type\": \"binary\"}\n",
        ")\n",
        "print(f\"Function size: {size}\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "77712ef1-d5a5-4ad0-9213-188c3970c5be",
      "metadata": {},
      "outputs": [],
      "source": [
        "job = solver.run(\n",
        "    problem=problem,\n",
        "    variable_type=\"binary\",\n",
        "    backend_name=\"ibm_fez\",\n",
        "    options={\n",
        "        \"shots\": 4096,\n",
        "        \"seed\": 42,\n",
        "    },\n",
        "    function_size=size,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "87030ecc-cf06-4f0f-bae5-ff502451a564",
      "metadata": {},
      "source": [
        "### 3. Retrieve the result\n",
        "\n",
        "`job.result()` returns a dictionary with four keys:\n",
        "\n",
        "* `solution` is the complete variable assignment, keyed by `x_i`, where `i` is the variable index (for example, `x_3`).\n",
        "* `objective_value` and `feasible` are the objective and feasibility of that assignment, evaluated on the submitted dictionary.\n",
        "* `metadata` holds `solver_info` and `resource_usage`.\n",
        "\n",
        "Because the QUBO is the minimization form of MaxCut, `objective_value` is the negative of the cut size. Evaluate the assignment on the original `OptimizationProblem` to read the cut size directly.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "5c5c1582-383a-4990-a575-6ace9a7cbd80",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Cut value: 55.0\n",
            "Nodes on side 1: [5, 7, 9, 11, 14, 16, 17, 19, 21, 23, 24, 26, 30, 31, 33, 34, 36, 37, 38]\n"
          ]
        }
      ],
      "source": [
        "result = job.result()\n",
        "\n",
        "x = [result[\"solution\"][f\"x_{i}\"] for i in range(maxcut.get_num_vars())]\n",
        "print(f\"Cut value: {maxcut.objective.evaluate(x)}\")\n",
        "print(f\"Nodes on side 1: {[v for v, value in enumerate(x) if value > 0.5]}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "4ceb2a67-86bd-47d8-9cfd-b0d4554a3dea",
      "metadata": {},
      "source": [
        "### 4. Check the resource usage\n",
        "\n",
        "`result[\"metadata\"][\"resource_usage\"]` reports the time spent in each execution phase. Phases other than `RUNNING: EXECUTING_QPU` report `CPU_TIME`, the wall-clock time of the phase in seconds, when it is available.\n",
        "\n",
        "The `RUNNING: EXECUTING_QPU` phase reports `QPU_TIME`, the QPU usage of all Quantum Compute jobs of the run, if the final usage is available for every job. For details, see the [API reference](/docs/functions/jij-sqoa-solver/api-reference).\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "b3707050-47bd-4b59-afae-e3836d14c818",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "RUNNING: MAPPING                     CPU      3.2 s\n",
            "RUNNING: OPTIMIZING_FOR_HARDWARE     CPU      5.0 s\n",
            "RUNNING: WAITING_FOR_QPU             CPU      1.1 s\n",
            "RUNNING: EXECUTING_QPU               QPU      3.0 s\n",
            "RUNNING: POST_PROCESSING             CPU      0.9 s\n"
          ]
        }
      ],
      "source": [
        "for phase, metrics in result[\"metadata\"][\"resource_usage\"].items():\n",
        "    line = f\"{phase:36s}\"\n",
        "    if \"CPU_TIME\" in metrics:\n",
        "        line += f\" CPU {metrics['CPU_TIME']:8.1f} s\"\n",
        "    if \"QPU_TIME\" in metrics:\n",
        "        line += f\" QPU {metrics['QPU_TIME']:8.1f} s\"\n",
        "    print(line)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "59ea8d4c-945a-46c3-af11-b6f06603fc37",
      "metadata": {},
      "source": [
        "## Example 2: Convert a constrained problem to QUBO\n",
        "\n",
        "SQOA Solver accepts unconstrained problems. This example shows how to convert a constrained problem into a QUBO with `OptimizationProblemToQubo` and map the result back to the variables of the original problem.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "e0530ff3-2d24-41ea-998a-920b9fda0662",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Problem name: ConstrainedExample\n",
            "\n",
            "Maximize\n",
            "  x0 + x1\n",
            "\n",
            "Subject to\n",
            "  Linear constraints (1)\n",
            "    x0 + x1 <= 1  'at_most_one'\n",
            "\n",
            "  Binary variables (2)\n",
            "    x0 x1\n",
            "\n"
          ]
        }
      ],
      "source": [
        "selection = OptimizationProblem(\"ConstrainedExample\")\n",
        "selection.binary_var_list(2, name=\"x\")\n",
        "selection.maximize(linear={\"x0\": 1, \"x1\": 1})\n",
        "selection.linear_constraint({\"x0\": 1, \"x1\": 1}, \"<=\", 1, name=\"at_most_one\")\n",
        "\n",
        "print(selection.prettyprint())"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d04d607d-53ff-49b2-9402-d3be06be04d2",
      "metadata": {},
      "source": [
        "`OptimizationProblemToQubo` adds the constraints to the objective as penalty terms and converts the problem to minimization. The appropriate penalty weight is problem-dependent.\n",
        "\n",
        "After the run, `interpret()` maps the QUBO assignment back to the variables of the original problem.\n",
        "\n",
        "Evaluate the objective and the feasibility on the original problem. For a dictionary problem, the `feasible` field of the result refers only to the variable domain, because the dictionary has no constraints.\n",
        "\n",
        "The two variables of this QUBO interact, so its density is 1, and `calculate_function_size()` returns `\"L\"`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "e2bec511-8335-4ba4-8c55-a5fe49004b00",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Objective: 1.0\n",
            "Feasible: True\n",
            "x values: [1. 0.]\n"
          ]
        }
      ],
      "source": [
        "converter = OptimizationProblemToQubo(penalty=4.0)\n",
        "qubo = converter.convert(selection)\n",
        "problem = to_problem_dict(qubo)\n",
        "size = calculate_function_size(\n",
        "    {\"problem\": problem, \"variable_type\": \"binary\"}\n",
        ")\n",
        "\n",
        "job = solver.run(\n",
        "    problem=problem,\n",
        "    variable_type=\"binary\",\n",
        "    backend_name=\"ibm_fez\",\n",
        "    function_size=size,\n",
        ")\n",
        "result = job.result()\n",
        "\n",
        "x_qubo = [result[\"solution\"][f\"x_{i}\"] for i in range(qubo.get_num_vars())]\n",
        "x = converter.interpret(x_qubo)\n",
        "print(\"Objective:\", selection.objective.evaluate(x))\n",
        "print(\"Feasible:\", selection.is_feasible(x))\n",
        "print(\"x values:\", x)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c5d9aadd-5c83-418e-8fcb-cf797cdd5cb2",
      "metadata": {},
      "source": [
        "## Example 3: Submit an OMMX instance\n",
        "\n",
        "SQOA Solver also accepts an `ommx.v1.Instance` from the [OMMX](https://ommx-en-book.readthedocs.io/en/latest/) SDK, which keeps variable names, subscripts, and conversion metadata together with the problem. Compared with a dictionary, an OMMX input has the following advantages:\n",
        "\n",
        "* The result also contains the canonical `ommx.v1.Solution` in `solver_info[\"ommx_solution\"]`.\n",
        "* `objective_value` is evaluated in the sense of the instance, so the objective of a maximization problem is not negated.\n",
        "* For an instance converted in place with [`Instance.to_qubo()`](https://jij-inc.github.io/ommx/python/ommx/autoapi/ommx/v1/index.html#ommx.v1.Instance.to_qubo), `feasible` is evaluated against the original constraints.\n",
        "\n",
        "This example builds the MaxCut model from Example 1 with [JijModeling](https://jij-inc-jijmodeling-tutorials-en.readthedocs-hosted.com/en/latest/introduction.html), a mathematical optimization modeler that compiles models into OMMX instances. Install JijModeling, which also installs the `ommx` package:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "ffe2113f-006b-4a4f-bbb0-bb93e7abb62e",
      "metadata": {},
      "outputs": [],
      "source": [
        "# %pip install \"jijmodeling~=2.8.0\""
      ]
    },
    {
      "cell_type": "markdown",
      "id": "41e08286-0090-4b90-afa5-a95de7aed6cb",
      "metadata": {},
      "source": [
        "SQOA Solver exchanges OMMX data as standard padded Base64 strings. Define the following helper functions for this conversion:\n",
        "\n",
        "* `to_problem_payload()` serializes an `ommx.v1.Instance` into the string that you pass as `problem`.\n",
        "* `to_ommx_solution()` decodes the canonical `ommx.v1.Solution` from the result.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "c7125825-33d9-42c9-a00f-e3cdd09b4029",
      "metadata": {},
      "outputs": [],
      "source": [
        "import base64\n",
        "\n",
        "from ommx.v1 import Instance, Solution\n",
        "\n",
        "\n",
        "def to_problem_payload(instance: Instance) -> str:\n",
        "    \"\"\"Serialize an OMMX instance into the `problem` string for SQOA Solver.\"\"\"\n",
        "    return base64.b64encode(instance.to_bytes()).decode()\n",
        "\n",
        "\n",
        "def to_ommx_solution(result: dict) -> Solution:\n",
        "    \"\"\"Decode the canonical OMMX solution from a SQOA Solver result.\"\"\"\n",
        "    payload = result[\"metadata\"][\"solver_info\"][\"ommx_solution\"]\n",
        "    return Solution.from_bytes(base64.b64decode(payload, validate=True))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "226dc927-5c37-44c5-82c9-4641d7fd3651",
      "metadata": {},
      "source": [
        "### 1. Write the model with JijModeling\n",
        "\n",
        "The usual spin formulation of MaxCut on a graph $G = (V, E)$ assigns\n",
        "$s_v \\in \\{-1, +1\\}$ to each vertex. An edge is cut when $s_u s_v = -1$, so the cut size is:\n",
        "\n",
        "$$\n",
        "\\operatorname{Cut}(s) = \\sum_{(u,v) \\in E} \\frac{1 - s_u s_v}{2}.\n",
        "$$\n",
        "\n",
        "JijModeling does not provide a native spin decision variable, and SQOA Solver accepts binary QUBO\n",
        "variables. Therefore, declare $b_v \\in \\{0, 1\\}$ and define the spin-valued expression\n",
        "$s_v = 1 - 2b_v$ inside the model. With this expression, the objective stays in the standard spin form, and the\n",
        "compiled instance remains a binary QUBO.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "id": "57a5d91a-56d9-4bd5-ba05-49d0944f46e5",
      "metadata": {},
      "outputs": [],
      "source": [
        "import jijmodeling as jm\n",
        "\n",
        "\n",
        "@jm.Problem.define(\"MaxCut\", sense=jm.ProblemSense.MAXIMIZE)\n",
        "def maxcut_model(problem: jm.DecoratedProblem):\n",
        "    V = problem.Natural()  # number of nodes\n",
        "    E = problem.Graph(dtype=V)  # edge list\n",
        "    b = problem.BinaryVar(shape=(V,))\n",
        "    s = 1 - 2 * b  # spin-valued expression\n",
        "\n",
        "    problem += jm.sum((1 - s[u] * s[v]) / 2 for u, v in E)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "4dd18e8d-e20e-4774-9cd3-13f31c12173d",
      "metadata": {},
      "source": [
        "If you display `maxcut_model` in a notebook, it shows the following formulation:\n",
        "\n",
        "$$\n",
        "\\begin{array}{rl}\n",
        "\\text{Problem}\\colon &\\text{MaxCut}\\\\\n",
        "\\displaystyle \\max &\\displaystyle \\sum _{\\left\\langle u,v\\right\\rangle \\in E}{\\frac{1-{\\left(1-2\\cdot b\\right)}_{u}\\cdot {\\left(1-2\\cdot b\\right)}_{v}}{2}}\\\\\n",
        "&\\\\\n",
        "\\text{where}&\\\\\n",
        "&\\text{Decision Variables:}\\\\\n",
        "&\\qquad \\begin{alignedat}{2}{b}_{i}&\\in \\left\\{0,1\\right\\}&\\qquad &\\text{a }1\\text{-dim array of }\\text{binary}\\text{ decision variables}\\\\\n",
        "&\\forall i\\in \\left\\{0,\\ldots ,V-1\\right\\}&&\\\\\n",
        "\\end{alignedat}\\\\\n",
        "&\\\\\n",
        "&\\text{Placeholders:}\\\\\n",
        "&\\qquad \\begin{alignedat}{2}{E}_{i}&\\in V\\times V&\\qquad &\\text{a }1\\text{-dim array of placeholders with elements in }V\\times V\\\\\n",
        "&\\forall i\\in \\left\\{0,\\ldots ,\\mathop{\\mathtt{len\\_{}at}}\\left(E,0\\right)-1\\right\\}&&\\\\\n",
        "&&&\\\\\n",
        "V&\\in \\mathbb{N}&\\qquad &\\text{a scalar placeholder in }\\mathbb{N}\\\\\n",
        "\\end{alignedat}\\end{array}\n",
        "$$\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ad2d2601-9675-4195-912a-22ef4fdf4ac3",
      "metadata": {},
      "source": [
        "### 2. Compile the instance and run the solver\n",
        "\n",
        "Bind the graph from Example 1 to compile an `ommx.v1.Instance`, and submit it with `variable_type=\"binary\"`. An OMMX instance is always submitted as a binary problem. Pass the instance itself to `calculate_function_size()`, before you encode it as Base64. The instance has the same variables and interactions as the QUBO in Example 1, so it also fits `\"S\"`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "id": "428c62fb-6d1a-4a64-87aa-f9261be10186",
      "metadata": {},
      "outputs": [],
      "source": [
        "instance = maxcut_model.eval(\n",
        "    {\"V\": G.number_of_nodes(), \"E\": [list(edge) for edge in G.edges]}\n",
        ")\n",
        "size = calculate_function_size(instance)\n",
        "\n",
        "job = solver.run(\n",
        "    problem=to_problem_payload(instance),\n",
        "    variable_type=\"binary\",\n",
        "    backend_name=\"ibm_fez\",\n",
        "    function_size=size,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "db078927-0be8-405b-8934-5a923233f48a",
      "metadata": {},
      "source": [
        "### 3. Retrieve the result\n",
        "\n",
        "For an OMMX input, `objective_value` is the cut size, and `to_ommx_solution()` decodes the canonical solution so that you can read the assignment by variable name.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "id": "a020c512-99a9-4dfc-a6db-d5aa072b1e4a",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Cut value: 55.0\n",
            "Nodes on side 1: [5, 7, 9, 11, 14, 16, 17, 19, 21, 23, 24, 26, 30, 31, 33, 34, 36, 37, 38]\n"
          ]
        }
      ],
      "source": [
        "result = job.result()\n",
        "print(f\"Cut value: {result['objective_value']}\")\n",
        "\n",
        "solution = to_ommx_solution(result)\n",
        "b_values = solution.extract_decision_variables(\"b\")\n",
        "print(\n",
        "    f\"Nodes on side 1: {sorted(v for (v,), value in b_values.items() if value > 0.5)}\"\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "4c8f1a36",
      "metadata": {},
      "source": [
        "## Next steps\n",
        "\n",
        "<Admonition type=\"tip\" title=\"Recommendations\">\n",
        "  * Visit the [API reference](/docs/functions/jij-sqoa-solver/api-reference) for this quantum function.\n",
        "  * Try an end-to-end example in the [maximum independent set problem](/docs/tutorials/maximum-independent-set-jij-sqoa) tutorial.\n",
        "  * Learn how to model optimization problems with [qiskit-addon-opt-mapper](https://qiskit.github.io/qiskit-addon-opt-mapper/).\n",
        "  * Learn how to model and exchange optimization problems with [JijModeling](https://jij-inc-jijmodeling-tutorials-en.readthedocs-hosted.com/en/latest/introduction.html) and [OMMX](https://ommx-en-book.readthedocs.io/en/latest/).\n",
        "  * Learn how to choose a [problem size](/docs/managed-workflows/managed-workflow-compute-profiles#match-sizes).\n",
        "  * Read the SQOA-QR paper [\\[1\\]](/docs/functions/jij-sqoa-solver/index#references) to learn more about the SQOA framework.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "id": "a1b8767d",
      "source": "© IBM Corp., 2017-2026"
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}