{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "d3f6a1c8",
      "metadata": {},
      "source": [
        "---\n",
        "title: Get started with Iskay Quantum Optimizer by Kipu Quantum\n",
        "description: Load the Kipu Quantum Iskay Quantum Optimizer, choose a function size, and solve a simple cost function, a MaxCut problem, and benchmark instances.\n",
        "---\n",
        "\n",
        "{/* cspell:ignore Kipu, HUBO, Iskay, Weidenfeller, vCPU, Cadavid, Chandarana */}\n",
        "\n",
        "# Get started with Iskay Quantum Optimizer by Kipu Quantum\n",
        "\n",
        "*See the [overview](/docs/functions/kipu-optimization) and the [API reference](/docs/functions/kipu-optimization/api-reference)*\n",
        "\n",
        "<Admonition type=\"note\" title=\"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": "61da1dd5",
      "metadata": {
        "tags": [
          "version-info"
        ]
      },
      "source": [
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "73390a19",
      "metadata": {},
      "source": [
        "## Set up and load the function\n",
        "\n",
        "In this documentation, we will go through the steps of using the Iskay Quantum Optimizer. In the process we will quickly show how to load the function from the catalog and how to convert your problem to a valid input, all while showing how you can experiment with different optional parameters.\n",
        "\n",
        "For a more detailed example, please check out the tutorial [Solve the Market Split problem with Kipu Quantum's Iskay Quantum Optimizer](/docs/tutorials/solve-market-split-problem-with-iskay-quantum-optimizer), where we work through the whole process of using Iskay Solver to address the Market Split problem, which represents a real-world resource allocation challenge where markets must be partitioned into balanced sales regions to meet exact demand targets.\n",
        "\n",
        "Authenticate using your API key, found on the [IBM Quantum Platform dashboard](http://quantum.cloud.ibm.com/), and select the quantum function as follows:\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e5cd4ac8",
      "metadata": {},
      "source": [
        "<Admonition type=\"note\">\n",
        "  The following code assumes that you have saved your credentials. If you have not, follow the instructions in [save your IBM Cloud® account](/docs/ibm-quantum-platform/functions-get-started#install-qiskit-functions-catalog-client) to authenticate with your API key.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "68d3ecea-f7e3-4b4b-b299-1670abc72415",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[QiskitFunction(qunova/hivqe-chemistry),\n",
              " QiskitFunction(global-data-quantum/quantum-portfolio-optimizer),\n",
              " QiskitFunction(algorithmiq/tem),\n",
              " QiskitFunction(qedma/qesem),\n",
              " QiskitFunction(multiverse/singularity),\n",
              " QiskitFunction(ibm/circuit-function),\n",
              " QiskitFunction(q-ctrl/optimization-solver),\n",
              " QiskitFunction(colibritd/quick-pde),\n",
              " QiskitFunction(q-ctrl/performance-management),\n",
              " QiskitFunction(kipu-quantum/iskay-quantum-optimizer)]"
            ]
          },
          "execution_count": 3,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "from qiskit_ibm_catalog import FunctionsCatalog\n",
        "\n",
        "catalog = FunctionsCatalog(\n",
        "    channel=\"ibm_quantum_platform\",\n",
        "    instance=\"INSTANCE_CRN\",\n",
        "    # For `token`, use the 44-character API_KEY you created\n",
        "    # and saved from the IBM Quantum Platform Home dashboard\n",
        "    token=\"YOUR_API_KEY\",\n",
        ")\n",
        "\n",
        "# verify that you have access to the function\n",
        "catalog.list()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "95a715d2",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Access function\n",
        "optimizer = catalog.load(\"kipu-quantum/iskay-quantum-optimizer\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "4a8e24f7",
      "metadata": {},
      "source": [
        "## Custom configuration example\n",
        "\n",
        "Here's how you might configure Iskay with different settings:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "712dbae3",
      "metadata": {},
      "outputs": [],
      "source": [
        "custom_options = {\n",
        "    \"shots\": 15_000,  # Higher shot count for better statistics\n",
        "    \"num_iterations\": 12,  # More iterations for solution refinement\n",
        "    \"preprocessing_level\": 1,  # Light preprocessing for problem simplification\n",
        "    \"postprocessing_level\": 2,  # Maximum postprocessing for solution quality\n",
        "    \"transpilation_level\": 2,  # Improved transpiler (default)\n",
        "    \"seed_transpiler\": 42,  # Fixed seed for reproducible results, which skips the seed search\n",
        "    \"job_tags\": [\"custom_config\"],  # Custom tracking tags\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "50690350",
      "metadata": {},
      "source": [
        "**Seed optimization**: By default, `seed_transpiler` is `None`, and transpilation level 2 searches over transpiler seeds to find the circuit with the best depth. If you set a seed, the function skips that search and the transpilation is reproducible.\n",
        "\n",
        "**Transpilation levels (1-3)**: The `transpilation_level` option selects the transpilation method.\n",
        "\n",
        "* **Level 1**: Standard Qiskit transpiler.\n",
        "* **Level 2** (default): Improved transpiler that searches over 15 transpiler seeds and keeps the best circuit. If you set `seed_transpiler`, the function skips the search.\n",
        "* **Level 3**: Line routing with the swap strategy for a linear coupling map that is described in Section 2.2.1 of [Weidenfeller et al.](https://arxiv.org/abs/2202.03459) Line routing follows a fixed swap schedule, so its circuit depth grows linearly with the number of variables. For densely connected problems, line routing typically produces shallower circuits than levels 1 and 2 and transpiles faster. Level 3 supports at most 127 variables on Heron r2 and r3 processors, 112 variables on Heron r1, and 120 variables on Nighthawk.\n",
        "\n",
        "Version 3.0.0 removed levels 0, 4, and 5. A job that requests one of them fails with error `1221`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3e9de85c",
      "metadata": {},
      "source": [
        "## Function sizes\n",
        "\n",
        "Every job runs at one size, `S`, `M`, or `L`. If the size is too small, the platform rejects the job. If the size is larger than the job needs, the job runs on a bigger compute profile than the work requires. See the [managed workflow documentation](/docs/managed-workflows/managed-workflow-compute-profiles#best-practice-match-sizes-to-problem-sizes) for how sizes work in general.\n",
        "\n",
        "The size depends on two properties of your model, the number of variables and the interaction density. The interaction density is the fraction of all variable pairs that appear together in a term of the objective or of a constraint.\n",
        "\n",
        "| Size | Variables and interaction density                   | Compute profile | vCPU | RAM    |\n",
        "| ---- | --------------------------------------------------- | --------------- | ---- | ------ |\n",
        "| `S`  | At most 50 variables and a density of at most 0.1   | `8x32`          | 8    | 32 GB  |\n",
        "| `M`  | At most 100 variables and a density of at most 0.25 | `16x128`        | 16   | 128 GB |\n",
        "| `L`  | Any model above either `M` bound                    | `48x768`        | 48   | 768 GB |\n",
        "\n",
        "A model must fit both bounds of a size. For this reason, a small model with many interactions might need `L`. For example, 10 variables that are all coupled to each other have a density of 1.0. Every optimization function uses the same bounds, so a size means the same model difficulty in every function.\n",
        "\n",
        "Two features of a model raise the density more than you might expect.\n",
        "\n",
        "* A term over more than two variables couples every pair of them. For example, a term in four variables contributes all six pairs.\n",
        "* A constraint counts as the penalty that replaces it on hardware. The squared constraint couples every pair of variables in it, so a one-hot constraint over four variables also contributes all six pairs.\n",
        "\n",
        "If a job does not request a size, it runs at the default size, `M`.\n",
        "\n",
        "To read the sizes from the function itself, call `optimizer.sizes()`. To read the default size, call `optimizer.get_default_size()`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "14169c49",
      "metadata": {},
      "source": [
        "### Calculate the size before you submit a job\n",
        "\n",
        "The calculator reads your model and nothing else. It submits no job and reserves nothing, so you can call it as often as you need while you reduce a model to a smaller size.\n",
        "\n",
        "The calculator requires the `qiskit-addon-opt-mapper` package. To install it, run the following command.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "60f355d3",
      "metadata": {},
      "outputs": [],
      "source": [
        "# %pip install qiskit-addon-opt-mapper"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "f256fd73",
      "metadata": {},
      "outputs": [],
      "source": [
        "\"\"\"\n",
        "Size calculator for the Kipu Quantum ``iskay-quantum-optimizer`` quantum function.\n",
        "\n",
        "IBM's reference ``optimization_size_calculator.py``, with ``to_optimization_problem``\n",
        "implemented for the ``problem`` dict the function accepts. Everything below that function\n",
        "is IBM's sizing logic and limits, unchanged, so a size means the same thing across\n",
        "vendors.\n",
        "\n",
        "Input:  the ``problem`` dict -- string-encoded index tuples to coefficients, exactly as\n",
        "        ``validate_problem`` in the function parses them -- plus the other function inputs\n",
        "        as ``**kwargs``::\n",
        "\n",
        "            {\"()\": 1.0, \"(0,)\": 1.5, \"(0, 3)\": 2.5, \"(0, 1, 2)\": 4.0}\n",
        "\n",
        "Output: ``\"S\"``, ``\"M\"`` or ``\"L\"``, from the number of variables and the interaction\n",
        "        density: the fraction of variable pairs that appear together in a term of the\n",
        "        objective or of a constraint.\n",
        "\n",
        "``problem_type`` (\"spin\" or \"binary\") does not change which variables interact, so the\n",
        "sizing is the same for both.\n",
        "\n",
        "Constraints are sized as the penalties that replace them on hardware -- see\n",
        "``_interactions``. Slack variables for inequality penalties are not counted, so a heavily\n",
        "inequality-constrained model is sized slightly low on the variable count.\n",
        "https://qiskit.github.io/qiskit-addon-opt-mapper/\n",
        "\"\"\"\n",
        "from __future__ import annotations\n",
        "\n",
        "import ast\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",
        "\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 the function's ``problem`` dict into an ``OptimizationProblem``.\n",
        "\n",
        "    Keys are parsed with ``ast.literal_eval``, the same parse the function itself applies,\n",
        "    so anything the function would reject raises here too rather than being sized on a\n",
        "    guess. A term is classified by its distinct indices: none is the constant, one linear,\n",
        "    two quadratic, three or more a higher-order term of that order.\n",
        "\n",
        "    Indices are remapped to a dense ``0..k-1`` range, because an index that never appears\n",
        "    is not a variable and gaps in the numbering must not dilute the interaction density.\n",
        "    \"\"\"\n",
        "    if isinstance(problem, OptimizationProblem):\n",
        "        return problem\n",
        "    if not isinstance(problem, dict):\n",
        "        raise NotImplementedError(\n",
        "            f\"cannot size a {type(problem).__name__}: iskay-quantum-optimizer takes a \"\n",
        "            \"dict of string-encoded index tuples to coefficients\"\n",
        "        )\n",
        "\n",
        "    terms = _parse_terms(problem)\n",
        "    indices = sorted({i for support in terms for i in support})\n",
        "    index_of = {index: position for position, index in enumerate(indices)}\n",
        "\n",
        "    linear: dict[int, float] = {}\n",
        "    quadratic: dict[tuple[int, int], float] = {}\n",
        "    higher_order: dict[int, dict[tuple[int, ...], float]] = {}\n",
        "    for support, coefficient in terms.items():\n",
        "        mapped = tuple(index_of[i] for i in support)\n",
        "        if len(mapped) == 1:\n",
        "            linear[mapped[0]] = coefficient\n",
        "        elif len(mapped) == 2:\n",
        "            quadratic[mapped] = coefficient\n",
        "        elif len(mapped) >= 3:\n",
        "            higher_order.setdefault(len(mapped), {})[mapped] = coefficient\n",
        "\n",
        "    converted = OptimizationProblem()\n",
        "    converted.binary_var_list(len(indices), name=\"x\")\n",
        "    converted.minimize(\n",
        "        constant=terms.get((), 0.0),\n",
        "        linear=linear or None,\n",
        "        quadratic=quadratic or None,\n",
        "        higher_order=higher_order or None,\n",
        "    )\n",
        "    return converted\n",
        "\n",
        "\n",
        "def _parse_terms(problem: dict) -> dict[tuple[int, ...], float]:\n",
        "    \"\"\"Map each term's sorted, distinct indices to its coefficient.\n",
        "\n",
        "    Repeated supports (for example, \"(0, 1)\" and \"(1, 0)\") are summed; for sizing only the\n",
        "    presence of the term matters.\n",
        "    \"\"\"\n",
        "    terms: dict[tuple[int, ...], float] = {}\n",
        "    for key, coefficient in problem.items():\n",
        "        parsed = ast.literal_eval(key) if isinstance(key, str) else key\n",
        "        if not isinstance(parsed, tuple):\n",
        "            raise ValueError(f\"problem key {key!r} is not a tuple\")\n",
        "        support = tuple(sorted(set(parsed)))\n",
        "        if any(not isinstance(i, int) for i in support):\n",
        "            raise ValueError(f\"problem key {key!r} holds non-integer indices\")\n",
        "        terms[support] = terms.get(support, 0.0) + float(coefficient)\n",
        "    return terms\n",
        "\n",
        "\n",
        "def _measure(problem: Any, **kwargs: Any) -> dict[str, float]:  # pylint: disable=unused-argument\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 variable tuple of every term that couples two or more variables.\n",
        "\n",
        "    Objective terms contribute their own variables; a linear objective term couples\n",
        "    nothing.\n",
        "\n",
        "    A constraint contributes the whole support of its left-hand side, because the\n",
        "    unconstrained form of the model replaces it with a penalty ``w * lhs**2``, and\n",
        "    squaring a sum couples every pair of variables in it -- a one-hot constraint over four\n",
        "    variables becomes a clique on those four. Neither the penalty weight nor the\n",
        "    right-hand side changes which pairs exist, so neither is needed here. This holds\n",
        "    whether or not the function handles constraints natively, because a size has to mean\n",
        "    the same thing across every optimization function.\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": "69d9dd60",
      "metadata": {},
      "source": [
        "### Size a sparse problem\n",
        "\n",
        "Consider a ring of 40 spins, where each spin interacts only with its two neighbors. The ring has 40 interacting pairs out of 780, which is a density of about 0.05, so it fits both bounds of `S`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "495d146f",
      "metadata": {},
      "outputs": [],
      "source": [
        "ring = {f\"({i}, {(i + 1) % 40})\": 1.0 for i in range(40)}\n",
        "\n",
        "size = calculate_function_size(ring)\n",
        "print(size)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e79b790b",
      "metadata": {},
      "source": [
        "The output is `S`. Pass the result to `run`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "229e5b5b",
      "metadata": {},
      "outputs": [],
      "source": [
        "job = optimizer.run(\n",
        "    problem=ring,\n",
        "    problem_type=\"spin\",\n",
        "    backend_name=backend_name,  # such as \"ibm_fez\"\n",
        "    options={\"shots\": 5000, \"num_iterations\": 5},\n",
        "    function_size=size,\n",
        ")\n",
        "print(job.job_id)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "04d72161",
      "metadata": {},
      "source": [
        "If the size is too small, the job fails with error `4600`, and the error message names the size to use. If the size is larger than the job needs, 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.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d4ca2590",
      "metadata": {},
      "source": [
        "## Example 1: Simple cost function\n",
        "\n",
        "Consider the cost function in spin formulation:\n",
        "\n",
        "$$\n",
        "C(x_0, ..., x_6) = 3 + x_0 - x_1 + 2x_2 + x_3 - 2x_4 + x_5 - x_6 + 2x_0x_1 - x_1x_2\n",
        "$$\n",
        "\n",
        "where $(x_0, ..., x_6) \\in \\{-1, 1\\}^7$.\n",
        "\n",
        "The solution to this simple cost function is\n",
        "\n",
        "$$\n",
        "(x_0, x_1, x_2, x_3, x_4, x_5, x_6) = (-1, 1, -1, -1, 1, -1, 1)\n",
        "$$\n",
        "\n",
        "with minimum value $C^{*} = -7$\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a98e8232",
      "metadata": {},
      "source": [
        "### 1. Create the objective function\n",
        "\n",
        "We start by creating a dictionary with the coefficients of the objective function as follows:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "3b4a58b1",
      "metadata": {},
      "outputs": [],
      "source": [
        "objective_func = {\n",
        "    \"()\": 3,\n",
        "    \"(0,)\": 1,\n",
        "    \"(1,)\": -1,\n",
        "    \"(2,)\": 2,\n",
        "    \"(3,)\": 1,\n",
        "    \"(4,)\": -2,\n",
        "    \"(5,)\": 1,\n",
        "    \"(6,)\": -1,\n",
        "    \"(0, 1)\": 2,\n",
        "    \"(1, 2)\": -1,\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f19a772d",
      "metadata": {},
      "source": [
        "Calculate the function size for this problem.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "586ac552",
      "metadata": {},
      "outputs": [],
      "source": [
        "size = calculate_function_size(objective_func)\n",
        "print(size)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "79fc4dcb",
      "metadata": {},
      "source": [
        "The output is `S`. The problem has seven variables, and only 2 of its 21 variable pairs interact. This density of about 0.095 is within the `S` bound of 0.1.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ab63b08f",
      "metadata": {},
      "source": [
        "### 2. Run the Optimizer\n",
        "\n",
        "We solve the problem by running the optimizer. Since $(x_0, ..., x_6) \\in \\{-1, 1\\}^7$ we must set `problem_type=spin`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "469ae361",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Setup options to run the optimizer\n",
        "options = {\"shots\": 5000, \"num_iterations\": 5, \"use_session\": True}\n",
        "\n",
        "arguments = {\n",
        "    \"problem\": objective_func,\n",
        "    \"problem_type\": \"spin\",\n",
        "    \"backend_name\": backend_name,  # such as \"ibm_fez\"\n",
        "    \"options\": options,\n",
        "    \"function_size\": size,\n",
        "}\n",
        "\n",
        "job = optimizer.run(**arguments)\n",
        "\n",
        "# Print the ID so you can use it later, if necessary\n",
        "print(job.job_id)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1e3a8542",
      "metadata": {},
      "source": [
        "### 3. Retrieve the result\n",
        "\n",
        "The solution of the optimization problem is provided directly from the optimizer.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "2f74d7e2",
      "metadata": {},
      "outputs": [],
      "source": [
        "print(job.result())"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c4d0a0f8",
      "metadata": {},
      "source": [
        "This will show a dictionary of the form:\n",
        "\n",
        "```\n",
        "{'solution': {'0': -1, '1': 1, '2': -1, '3': -1, '4': 1, '5': -1, '6': 1},\n",
        " 'solution_info': {'bitstring': '1011010',\n",
        "  'cost': -7,\n",
        "  'seed_transpiler': 0,\n",
        "  'mapping': {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6},\n",
        "  'qpu_time': 15.0},\n",
        " 'prob_type': 'spin'}\n",
        "```\n",
        "\n",
        "Notice that the dictionary `solution` displays the result vector $(x_0, x_1, x_2, x_3, x_4, x_5, x_6) = (-1, 1, -1, -1, 1, -1, 1)$.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "7eaa5cac",
      "metadata": {},
      "source": [
        "## Example 2: MaxCut\n",
        "\n",
        "Many graph problems like MaxCut or Maximum independent set are NP-hard problems and ideal candidates for testing quantum algorithms and hardware. This example demonstrates solving the MaxCut problem of a 3-regular graph with the Quantum Optimizer.\n",
        "\n",
        "To run this example you must install the `networkx` package in addition to the `qiskit-ibm-catalog`. To install it, run the following command:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "9ea6d138",
      "metadata": {},
      "outputs": [],
      "source": [
        "# %pip install networkx numpy"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0c63487f",
      "metadata": {},
      "source": [
        "### 1. Create the objective function\n",
        "\n",
        "Start by generating a random 3-regular graph. For this graph, we define the objective function of the MaxCut problem.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "d1d4017f",
      "metadata": {},
      "outputs": [],
      "source": [
        "import networkx as nx\n",
        "\n",
        "# Create a random 3-regular graph\n",
        "G = nx.random_regular_graph(3, 10, seed=42)\n",
        "\n",
        "\n",
        "# Create the objective function for MaxCut in Ising formulation\n",
        "def graph_to_ising_maxcut(G):\n",
        "    \"\"\"\n",
        "    Convert a NetworkX graph to an Ising Hamiltonian for the max-cut problem.\n",
        "    Args:\n",
        "        G (networkx.Graph): The input graph.\n",
        "    Returns:\n",
        "        dict: The objective function of the Ising model\n",
        "    \"\"\"\n",
        "    # Initialize the linear and quadratic coefficients\n",
        "    objective_func = {}\n",
        "    # Populate the coefficients\n",
        "    for i, j in G.edges:\n",
        "        objective_func[f\"({i}, {j})\"] = 0.5\n",
        "    return objective_func\n",
        "\n",
        "\n",
        "objective_func = graph_to_ising_maxcut(G)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "7e1a6eb1",
      "metadata": {},
      "source": [
        "Calculate the function size for this problem.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "1bd8b272",
      "metadata": {},
      "outputs": [],
      "source": [
        "size = calculate_function_size(objective_func)\n",
        "print(size)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1ec3a4fa",
      "metadata": {},
      "source": [
        "The output is `L`. The graph has 10 nodes and 15 edges, so 15 of the 45 variable pairs interact. This density of about 0.33 is higher than the `M` bound.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3be09664",
      "metadata": {},
      "source": [
        "### 2. Run the Optimizer\n",
        "\n",
        "Solve the problem by running the optimizer.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "2499ab67",
      "metadata": {},
      "outputs": [],
      "source": [
        "options = {\"shots\": 5000, \"num_iterations\": 5, \"use_session\": True}\n",
        "\n",
        "arguments = {\n",
        "    \"problem\": objective_func,\n",
        "    \"problem_type\": \"spin\",\n",
        "    \"backend_name\": backend_name,  # such as \"ibm_fez\"\n",
        "    \"options\": options,\n",
        "    \"function_size\": size,\n",
        "}\n",
        "\n",
        "job = optimizer.run(**arguments)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3548f6dc",
      "metadata": {},
      "source": [
        "### 3. Retrieve the result\n",
        "\n",
        "Retrieve the result and map the solution bitstring back to the original graph nodes.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "169cbd6e",
      "metadata": {},
      "outputs": [],
      "source": [
        "print(job.result())"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "7f22d66a",
      "metadata": {},
      "source": [
        "The solution to the Maxcut problem is directly contained in the `solution` sub-dictionary of the result object\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "38309554",
      "metadata": {},
      "outputs": [],
      "source": [
        "maxcut_solution = job.result()[\"solution\"]"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "19a664c4",
      "metadata": {},
      "source": [
        "## Example 3: Benchmark instances\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "98545ce3",
      "metadata": {},
      "source": [
        "The benchmark instances are available on GitHub: [Kipu benchmark instances](https://github.com/Kipu-Quantum-GmbH/benchmark-instances).\n",
        "\n",
        "The instances can be loaded using the `pygithub` library. To install it, run the following command:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "1d8777e4",
      "metadata": {},
      "outputs": [],
      "source": [
        "# %pip install pygithub"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e3a03447",
      "metadata": {},
      "source": [
        "The paths for the benchmark instances are:\n",
        "\n",
        "**Maxcut:**\n",
        "\n",
        "* `'maxcut/maxcut_regular_3_100_nodes_weighted.json'`\n",
        "* `'maxcut/maxcut_regular_3_140_nodes_weighted.json'`\n",
        "* `'maxcut/maxcut_regular_3_150_nodes_weighted.json'`\n",
        "* `'maxcut/maxcut_regular_4_130_nodes_weighted.json'`\n",
        "\n",
        "**HUBO:**\n",
        "\n",
        "* `'HUBO/hubo1_marrakesh.json'`\n",
        "* `'HUBO/hubo2_marrakesh.json'`\n",
        "\n",
        "To reproduce the performance of the benchmark for the HUBO instances, select the backend `ibm_marrakesh` and set `direct_qubit_mapping` to `True` in the `options` sub-dictionary.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "adbed9be",
      "metadata": {},
      "source": [
        "The following example runs the Maxcut instance with 150 nodes.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "da681a18",
      "metadata": {},
      "outputs": [],
      "source": [
        "from github import Github\n",
        "import urllib\n",
        "import json\n",
        "\n",
        "repo = \"Kipu-Quantum-GmbH/benchmark-instances\"\n",
        "path = \"maxcut/maxcut_regular_3_150_nodes_weighted.json\"\n",
        "gh = Github()\n",
        "repo = gh.get_repo(repo)\n",
        "branch = \"main\"\n",
        "file = repo.get_contents(urllib.parse.quote(path), ref=branch)\n",
        "\n",
        "# load json file with benchmark problem\n",
        "problem_json = json.loads(file.decoded_content)\n",
        "\n",
        "# convert objective function to compatible format\n",
        "objective_func = {\n",
        "    key: ast.literal_eval(value) for key, value in problem_json.items()\n",
        "}\n",
        "\n",
        "# Calculate the function size. The problem has 150 variables,\n",
        "# more than the M bound allows, so the size is \"L\".\n",
        "size = calculate_function_size(objective_func)\n",
        "\n",
        "# Setup configuration to run the optimizer\n",
        "options = {\n",
        "    \"shots\": 5_000,\n",
        "    \"num_iterations\": 5,\n",
        "    \"use_session\": True,\n",
        "    \"direct_qubit_mapping\": False,\n",
        "}\n",
        "\n",
        "arguments = {\n",
        "    \"problem\": objective_func,\n",
        "    \"problem_type\": \"spin\",\n",
        "    \"backend_name\": \"<BACKEND-NAME>\",\n",
        "    \"options\": options,\n",
        "    \"function_size\": size,\n",
        "}\n",
        "\n",
        "job = optimizer.run(**arguments)\n",
        "\n",
        "result = job.result()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "7b3e9c52",
      "metadata": {},
      "source": [
        "## Next steps\n",
        "\n",
        "* Visit the [API reference](/docs/functions/kipu-optimization/api-reference) for this quantum function.\n",
        "* Try the [Solve the Market Split problem with Kipu Quantum's Iskay Quantum Optimizer](/docs/tutorials/solve-market-split-problem-with-iskay-quantum-optimizer) tutorial.\n",
        "* Learn how to choose a [problem size](/docs/managed-workflows/managed-workflow-compute-profiles#match-sizes).\n",
        "* Review [Romero, S. V., et al. (2025).  Bias-Field Digitized Counterdiabatic Quantum Algorithm for Higher-Order Binary Optimization. arXiv preprint arXiv:2409.04477](https://arxiv.org/abs/2409.04477).\n",
        "* Review [Cadavid, A. G., et al. (2024).  Bias-field digitized counterdiabatic quantum optimization. arXiv preprint arXiv:2405.13898](https://arxiv.org/abs/2405.13898).\n",
        "* Review [Chandarana, P., et al. (2025).  Runtime Quantum Advantage with Digital Quantum Optimization. arXiv preprint arXiv:2505.08663](https://arxiv.org/abs/2505.08663).\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
}