{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "dde95705",
      "metadata": {},
      "source": [
        "---\n",
        "title: Get started with Constrained Quantum Optimizer by Aqarios\n",
        "description: Load the Constrained Quantum Optimizer function, choose a function size, and solve constrained problems from LP files and Luna models.\n",
        "---\n",
        "\n",
        "{/* cspell:ignore Aqarios docplex forall Zachary quicksum QOBLIB */}\n",
        "\n",
        "# Get started with Constrained Quantum Optimizer by Aqarios\n",
        "\n",
        "*See the [overview](/docs/functions/aqarios-constrained-quantum-optimizer) and the [API reference](/docs/functions/aqarios-constrained-quantum-optimizer/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": "e9f4110b",
      "metadata": {
        "tags": [
          "version-info"
        ]
      },
      "source": [
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "73390a19",
      "metadata": {},
      "source": [
        "## Set up and load the function\n",
        "\n",
        "This guide demonstrates basic usage of the Constrained Quantum Optimizer by showing how to load the function and execute simple problems. For a more involved tutorial, see [Find the Maximum Independent Set with the Aqarios Constrained Quantum Optimizer](/docs/tutorials/find-the-maximum-independent-set-with-aqarios-constrained-quantum-optimizer).\n",
        "\n",
        "Authenticate with your IBM Quantum API key and instance CRN, then load the function from the catalog.\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  The following code assumes you have saved your credentials. To set them up, follow the instructions in [Save your IBM Cloud account credentials](/docs/ibm-quantum-platform/functions-get-started#install-qiskit-functions-catalog-client).\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "95a715d2",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:32.374333Z",
          "iopub.status.busy": "2026-11-06T14:41:32.374096Z",
          "iopub.status.idle": "2026-11-06T14:41:41.380959Z",
          "shell.execute_reply": "2026-11-06T14:41:41.379535Z"
        }
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[QiskitFunction(aqarios/constrained-quantum-optimizer)]"
            ]
          },
          "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": 2,
      "id": "fe865158",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:41.383532Z",
          "iopub.status.busy": "2026-11-06T14:41:41.383340Z",
          "iopub.status.idle": "2026-11-06T14:41:41.829779Z",
          "shell.execute_reply": "2026-11-06T14:41:41.828348Z"
        }
      },
      "outputs": [],
      "source": [
        "# Load the function\n",
        "optimizer = catalog.load(\"aqarios/constrained-quantum-optimizer\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "d976e101",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:41.832567Z",
          "iopub.status.busy": "2026-11-06T14:41:41.832375Z",
          "iopub.status.idle": "2026-11-06T14:41:44.041553Z",
          "shell.execute_reply": "2026-11-06T14:41:44.040615Z"
        }
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[<IBMBackend('ibm_boston')>,\n",
              " <IBMBackend('ibm_chicago')>,\n",
              " <IBMBackend('ibm_fez')>,\n",
              " <IBMBackend('ibm_kingston')>,\n",
              " <IBMBackend('ibm_marrakesh')>,\n",
              " <IBMBackend('ibm_phoenix')>,\n",
              " <IBMBackend('ibm_pittsburgh')>]"
            ]
          },
          "execution_count": 3,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Check the list of backends you have access to\n",
        "catalog.backends()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "6b0f5c79",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:44.043936Z",
          "iopub.status.busy": "2026-11-06T14:41:44.043766Z",
          "iopub.status.idle": "2026-11-06T14:41:44.443135Z",
          "shell.execute_reply": "2026-11-06T14:41:44.441841Z"
        }
      },
      "outputs": [],
      "source": [
        "# Select the backend you want to use\n",
        "backend = catalog.backend(\"ibm_phoenix\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c67bcea1",
      "metadata": {},
      "source": [
        "## Function sizes\n",
        "\n",
        "Every job runs at one size — `S`, `M` or `L`. If you select a size that's too small, the job is rejected.  If you select a size that's larger\n",
        "than needed and it runs on a bigger compute profile than the work requires. See\n",
        "[Function sizes](/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 your model: how many variables it has, and\n",
        "how densely they interact — the fraction of all variable pairs that appear together\n",
        "in a term of the objective or of a constraint.\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                          | `16x128`        | 16   | 128 GB |\n",
        "\n",
        "A model must fit **both** bounds of a size, which is why a small but tightly coupled\n",
        "model can be `L`: ten variables all coupled to each other is a density of 1.0. These\n",
        "are the same bounds for every optimization function, so a size means the same\n",
        "difficulty of model whichever one you call.\n",
        "\n",
        "Two things raise the density more than they appear to:\n",
        "\n",
        "* **A term over more than two variables couples every pair of them.** A term in\n",
        "  four variables contributes all six pairs.\n",
        "* **A constraint counts as the penalty that replaces it on hardware.** Squaring the\n",
        "  constraint couples every pair of variables in it, so a one-hot constraint over\n",
        "  four variables also contributes all six pairs.\n",
        "\n",
        "The default is `M`, used when a job does not request a size.\n",
        "\n",
        "Users can also read the mapping off the function itself with `optimizer.sizes_map`, and\n",
        "the size used when a job does not ask for one with `optimizer.default_size`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2654342d",
      "metadata": {},
      "source": [
        "### Calculate the size before submitting\n",
        "\n",
        "Run this on your own model. It reads it and does nothing else: no job is submitted and\n",
        "nothing is reserved, so you can call it as often as you like while you tune a model\n",
        "down to a smaller size.\n",
        "\n",
        "It accepts the same `problem` input as the function: an LP string, an MPS string, or\n",
        "a base64-encoded Luna Model. It needs `luna-model` and `qiskit-addon-opt-mapper`\n",
        "installed.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "ffea1a52",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:44.446417Z",
          "iopub.status.busy": "2026-11-06T14:41:44.446177Z",
          "iopub.status.idle": "2026-11-06T14:41:44.449398Z",
          "shell.execute_reply": "2026-11-06T14:41:44.448655Z"
        }
      },
      "outputs": [],
      "source": [
        "# %pip install luna-model qiskit-addon-opt-mapper"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "9b68b9c6",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:44.451384Z",
          "iopub.status.busy": "2026-11-06T14:41:44.451252Z",
          "iopub.status.idle": "2026-11-06T14:41:44.510030Z",
          "shell.execute_reply": "2026-11-06T14:41:44.509548Z"
        }
      },
      "outputs": [],
      "source": [
        "# Calculate the function size a model needs, before submitting it.\n",
        "#\n",
        "# Call ``calculate_function_size(problem)``: it returns \"S\", \"M\" or \"L\" and submits\n",
        "# nothing. The size comes from the number of variables and how densely they interact.\n",
        "\n",
        "from collections.abc import Iterator\n",
        "from itertools import combinations\n",
        "from typing import Any, Literal\n",
        "\n",
        "import luna_model\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 an LP string, MPS string or base64-encoded Luna Model into an\n",
        "    ``OptimizationProblem``.\"\"\"\n",
        "    model = (\n",
        "        luna_model.Model.decode_b64(problem)\n",
        "        if luna_model.Model.is_b64_encoded(problem)\n",
        "        else luna_model.Model.from_(problem)\n",
        "    )\n",
        "    problem = model.to(luna_model.TranslationTarget.OPT_MAPPER)\n",
        "    if isinstance(problem, OptimizationProblem):\n",
        "        return problem\n",
        "    raise NotImplementedError(\n",
        "        f\"cannot size a {type(problem).__name__}: pass an LP string, an MPS string \"\n",
        "        \"or a base64-encoded Luna Model\"\n",
        "    )\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": "8010bac5",
      "metadata": {},
      "source": [
        "If the specified size is too small, the job fails with error `4600` and the message names the\n",
        "correct size to use. If the specified size is larger than needed, the job runs normally and records a\n",
        "`4601` advisory event. See the [managed workflow documentation](/docs/managed-workflows/managed-workflow-compute-profiles#best-practice-match-sizes-to-problem-sizes) for details.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e4445979",
      "metadata": {},
      "source": [
        "## Example 1: A simple constrained problem\n",
        "\n",
        "The first example shows how to use the function with [LP-files](https://www.ibm.com/docs/icos/22.1.1?topic=cplex-lp-file-format-algebraic-representation), a common optimization problem specification used in operations research. You will formulate the following arbitrary optimization problem of ten binary variables $x_i \\in \\{0,1\\}$ subject to four constraints:\n",
        "\n",
        "$$\n",
        "    \\min \\tfrac{3}{2} x_6 x_7 + \\tfrac{3}{2} x_7 x_8 + 2 x_8 x_9 - \\sum_{i=0}^{9} x_i \\\\\n",
        "    \\text{s.t.}\\quad x_0 + x_1 + x_2 = 1 \\\\\n",
        "    \\quad -x_2 + x_3 \\leq 0 \\\\\n",
        "    \\quad x_3 + x_4 \\leq 1 \\\\\n",
        "    \\quad x_4 + x_5 + x_6 = 1\n",
        "$$\n",
        "\n",
        "### 1. Formulate the problem\n",
        "\n",
        "Directly state the mathematical expression as the following LP-string format:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "7c3af25d",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:44.511419Z",
          "iopub.status.busy": "2026-11-06T14:41:44.511348Z",
          "iopub.status.idle": "2026-11-06T14:41:44.513193Z",
          "shell.execute_reply": "2026-11-06T14:41:44.512679Z"
        },
        "lines_to_next_cell": 0
      },
      "outputs": [],
      "source": [
        "lp_str = \"\"\"\\\\Problem name: Example\n",
        "Minimize\n",
        " [ 3 x6 * x7 + 3 x7 * x8 + 4 x8 * x9 ] / 2 - x0 - x1 - x2 - x3 - x4 - x5 - x6 - x7 - x8 - x9\n",
        "Subject To\n",
        " c0: x0 + x1 + x2 = 1\n",
        " c1: - x2 + x3 <= 0\n",
        " c2: x3 + x4 <= 1\n",
        " c3: x4 + x5 + x6 = 1\n",
        "Binaries\n",
        " x0 x1 x2 x3 x4 x5 x6 x7 x8 x9\n",
        "End\n",
        "\"\"\""
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f6c75f9d",
      "metadata": {},
      "source": [
        "Note that `[ ... ] / 2` is a required notation for quadratic objectives from the LP standard.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "adb8f60d",
      "metadata": {},
      "source": [
        "### 2. Run the optimizer\n",
        "\n",
        "Calculate the function size with `calculate_function_size` from the [Function sizes](#function-sizes) section. This problem needs `M`: its ten variables are well within the `S` bound of 50, but its four constraints couple eight of the 45 variable pairs and the objective couples three more. That is a density of about 0.24, above the `S` bound of 0.1 but within the `M` bound of 0.25.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "a24f8fe9",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:44.513974Z",
          "iopub.status.busy": "2026-11-06T14:41:44.513922Z",
          "iopub.status.idle": "2026-11-06T14:41:44.519629Z",
          "shell.execute_reply": "2026-11-06T14:41:44.519207Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "M\n"
          ]
        }
      ],
      "source": [
        "size = calculate_function_size(lp_str)  # \"S\", \"M\" or \"L\"\n",
        "print(size)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "242f1f89",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:44.520360Z",
          "iopub.status.busy": "2026-11-06T14:41:44.520314Z",
          "iopub.status.idle": "2026-11-06T14:41:44.974337Z",
          "shell.execute_reply": "2026-11-06T14:41:44.973041Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Job ID: d442a35f-11c4-4ac4-aa5c-2bb43cfe21fb\n"
          ]
        }
      ],
      "source": [
        "# Set up low-resource options for the simple problem\n",
        "options = {\"total_shots\": 2000, \"num_parallel\": 5, \"use_session\": True}\n",
        "\n",
        "# Dispatch the job\n",
        "job_1 = optimizer.run(\n",
        "    problem=lp_str,\n",
        "    backend_name=backend.name,\n",
        "    options=options,\n",
        "    function_size=size,\n",
        ")\n",
        "\n",
        "print(f\"Job ID: {job_1.job_id}\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "4bd4790a",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:44.978053Z",
          "iopub.status.busy": "2026-11-06T14:41:44.977787Z",
          "iopub.status.idle": "2026-11-06T14:41:47.845759Z",
          "shell.execute_reply": "2026-11-06T14:41:47.844401Z"
        }
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "'QUEUED'"
            ]
          },
          "execution_count": 10,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Monitor the job status\n",
        "job_1.status()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "acff0671",
      "metadata": {
        "lines_to_next_cell": 0
      },
      "source": [
        "### 3. Retrieve the result\n",
        "\n",
        "The solution, mapping the variable names to the associated assignments, is provided by the result.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "6a121188",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:47.848557Z",
          "iopub.status.busy": "2026-11-06T14:41:47.848320Z",
          "iopub.status.idle": "2026-11-06T14:41:50.648608Z",
          "shell.execute_reply": "2026-11-06T14:41:50.647795Z"
        },
        "lines_to_next_cell": 0
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "{'solutions': [{'x0': 0,\n",
              "   'x1': 0,\n",
              "   'x2': 1,\n",
              "   'x3': 1,\n",
              "   'x4': 0,\n",
              "   'x5': 1,\n",
              "   'x6': 0,\n",
              "   'x7': 1,\n",
              "   'x8': 0,\n",
              "   'x9': 1}],\n",
              " 'solution_bitstrings': ['0011010101'],\n",
              " 'raw_energy': -5.0,\n",
              " 'objective_value': -5.0,\n",
              " 'feasible': True,\n",
              " 'metadata': {'resource_usage': {'RUNNING: MAPPING': {'CPU': 4.829},\n",
              "   'RUNNING: OPTIMIZING_FOR_HARDWARE': {'CPU': 10.322},\n",
              "   'RUNNING: WAITING_FOR_QPU': {'CPU': 2735.119},\n",
              "   'RUNNING: EXECUTING_QPU': {'CPU': 21.959},\n",
              "   'RUNNING: POST_PROCESSING': {'CPU': 5.258}},\n",
              "  'circuit_metrics': {'before_transpilation': {'num_qubits': 10,\n",
              "    'gate_count': 68,\n",
              "    'depth': 15,\n",
              "    'two_qubit_gate_count': 15,\n",
              "    'two_qubit_gate_depth': 7,\n",
              "    'operations': {'rz': 21,\n",
              "     'ry': 14,\n",
              "     'p': 12,\n",
              "     'rzz': 5,\n",
              "     'global_phase': 4,\n",
              "     'cx': 4,\n",
              "     'xx_plus_yy': 4,\n",
              "     'x': 2,\n",
              "     'cry': 2}},\n",
              "   'after_transpilation': {'num_qubits': 10,\n",
              "    'gate_count': 330,\n",
              "    'depth': 87,\n",
              "    'two_qubit_gate_count': 55,\n",
              "    'two_qubit_gate_depth': 29,\n",
              "    'operations': {'sx': 150, 'rz': 112, 'cz': 55, 'measure': 10}}},\n",
              "  'solver_info': {'variable_mapping': {'x0': 0,\n",
              "    'x1': 1,\n",
              "    'x2': 2,\n",
              "    'x3': 3,\n",
              "    'x4': 4,\n",
              "    'x5': 5,\n",
              "    'x6': 6,\n",
              "    'x7': 7,\n",
              "    'x8': 8,\n",
              "    'x9': 9}}}}"
            ]
          },
          "execution_count": 11,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "result = job_1.result()\n",
        "\n",
        "result"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e8837f5f",
      "metadata": {},
      "source": [
        "The `solutions` field in the return dictionary contains all degenerate best solutions found, as dictionaries that map each variable name to its assignment. The same solutions are also returned as bitstrings in `solution_bitstrings`; `metadata.solver_info.variable_mapping` tells you which character position of a bitstring belongs to which variable. Alongside the solution data, the `objective_value`, a `feasible` flag, and additional `metadata` are provided.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b43e01b1",
      "metadata": {},
      "source": [
        "## Example 2: Maximum Independent Set\n",
        "\n",
        "The Maximum Independent Set (MIS) problem asks for the largest subset of vertices in a graph such that no two vertices in the subset share an edge. This example solves MIS on a 30-node ring with five chords across it. For more information on the problem and a larger example, refer to the [tutorial](/docs/tutorials/find-the-maximum-independent-set-with-aqarios-constrained-quantum-optimizer).\n",
        "\n",
        "The problem is built with [qiskit-addon-opt-mapper](https://github.com/qiskit/qiskit-addon-opt-mapper).\n",
        "Install the required packages if needed:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "id": "a1e2f301",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:50.650542Z",
          "iopub.status.busy": "2026-11-06T14:41:50.650389Z",
          "iopub.status.idle": "2026-11-06T14:41:50.652809Z",
          "shell.execute_reply": "2026-11-06T14:41:50.652098Z"
        }
      },
      "outputs": [],
      "source": [
        "# %pip install networkx qiskit-addon-opt-mapper"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d56e1440",
      "metadata": {},
      "source": [
        "### Step 1: Define the problem\n",
        "\n",
        "Build a 30-node ring, connect every third node in the first half to the node opposite it, and create the MIS optimization problem. Each graph node becomes a binary variable, and each edge introduces a constraint ensuring that at most one endpoint is selected.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "id": "03998691",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:50.654431Z",
          "iopub.status.busy": "2026-11-06T14:41:50.654300Z",
          "iopub.status.idle": "2026-11-06T14:41:50.968897Z",
          "shell.execute_reply": "2026-11-06T14:41:50.968576Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\\ This file has been generated by DOcplex\n",
            "\\ ENCODING=ISO-8859-1\n",
            "\\Problem name: Independent set\n",
            "\n",
            "Maximize\n",
            " obj: x_0 + x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8 + x_9 + x_10 + x_11\n",
            "      + x_12 + x_13 + x_14 + x_15 + x_16 + x_17 + x_18 + x_19 + x_20 + x_21\n",
            "      + x_22 + x_23 + x_24 + x_25 + x_26 + x_27 + x_28 + x_29\n",
            "Subject To\n",
            " c0: x_0 + x_1 <= 1\n",
            " c1: x_0 + x_29 <= 1\n",
            " c2: x_0 + x_15 <= 1\n",
            " c3: x_1 + x_2 <= 1\n",
            " c4: x_2 + x_3 <= 1\n",
            " c5: x_3 + x_4 <= 1\n",
            " c6: x_3 + x_18 <= 1\n",
            " c7: x_4 + x_5 <= 1\n",
            " c8: x_5 + x_6 <= 1\n",
            " c9: x_6 + x_7 <= 1\n",
            " c10: x_6 + x_21 <= 1\n",
            " c11: x_7 + x_8 <= 1\n",
            " c12: x_8 + x_9 <= 1\n",
            " c13: x_9 + x_10 <= 1\n",
            " c14: x_9 + x_24 <= 1\n",
            " c15: x_10 + x_11 <= 1\n",
            " c16: x_11 + x_12 <= 1\n",
            " c17: x_12 + x_13 <= 1\n",
            " c18: x_12 + x_27 <= 1\n",
            " c19: x_13 + x_14 <= 1\n",
            " c20: x_14 + x_15 <= 1\n",
            " c21: x_15 + x_16 <= 1\n",
            " c22: x_16 + x_17 <= 1\n",
            " c23: x_17 + x_18 <= 1\n",
            " c24: x_18 + x_19 <= 1\n",
            " c25: x_19 + x_20 <= 1\n",
            " c26: x_20 + x_21 <= 1\n",
            " c27: x_21 + x_22 <= 1\n",
            " c28: x_22 + x_23 <= 1\n",
            " c29: x_23 + x_24 <= 1\n",
            " c30: x_24 + x_25 <= 1\n",
            " c31: x_25 + x_26 <= 1\n",
            " c32: x_26 + x_27 <= 1\n",
            " c33: x_27 + x_28 <= 1\n",
            " c34: x_28 + x_29 <= 1\n",
            "\n",
            "Bounds\n",
            " 0 <= x_0 <= 1\n",
            " 0 <= x_1 <= 1\n",
            " 0 <= x_2 <= 1\n",
            " 0 <= x_3 <= 1\n",
            " 0 <= x_4 <= 1\n",
            " 0 <= x_5 <= 1\n",
            " 0 <= x_6 <= 1\n",
            " 0 <= x_7 <= 1\n",
            " 0 <= x_8 <= 1\n",
            " 0 <= x_9 <= 1\n",
            " 0 <= x_10 <= 1\n",
            " 0 <= x_11 <= 1\n",
            " 0 <= x_12 <= 1\n",
            " 0 <= x_13 <= 1\n",
            " 0 <= x_14 <= 1\n",
            " 0 <= x_15 <= 1\n",
            " 0 <= x_16 <= 1\n",
            " 0 <= x_17 <= 1\n",
            " 0 <= x_18 <= 1\n",
            " 0 <= x_19 <= 1\n",
            " 0 <= x_20 <= 1\n",
            " 0 <= x_21 <= 1\n",
            " 0 <= x_22 <= 1\n",
            " 0 <= x_23 <= 1\n",
            " 0 <= x_24 <= 1\n",
            " 0 <= x_25 <= 1\n",
            " 0 <= x_26 <= 1\n",
            " 0 <= x_27 <= 1\n",
            " 0 <= x_28 <= 1\n",
            " 0 <= x_29 <= 1\n",
            "\n",
            "Binaries\n",
            " x_0 x_1 x_2 x_3 x_4 x_5 x_6 x_7 x_8 x_9 x_10 x_11 x_12 x_13 x_14 x_15 x_16 x_17\n",
            " x_18 x_19 x_20 x_21 x_22 x_23 x_24 x_25 x_26 x_27 x_28 x_29\n",
            "End\n",
            "\n"
          ]
        }
      ],
      "source": [
        "import networkx as nx\n",
        "from qiskit_addon_opt_mapper.applications import IndependentSet\n",
        "from qiskit_addon_opt_mapper.translators import to_docplex_mp\n",
        "\n",
        "# 30-node ring with five chords to the opposite node\n",
        "G = nx.cycle_graph(30)\n",
        "G.add_edges_from((i, i + 15) for i in range(0, 15, 3))\n",
        "\n",
        "# Build MIS problem and export as LP string\n",
        "mis = IndependentSet(G)\n",
        "mis_problem = mis.to_optimization_problem()\n",
        "lp_str = to_docplex_mp(mis_problem).export_as_lp_string()\n",
        "\n",
        "print(lp_str)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "666ce2b4",
      "metadata": {},
      "source": [
        "### Step 2: Run the optimizer\n",
        "\n",
        "Calculate the function size. The 35 edge constraints couple 35 of the 435 variable pairs, a density of about 0.08. With 30 variables and a density within the `S` bound of 0.1, the problem needs `S`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "id": "693a1fc0",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:50.970019Z",
          "iopub.status.busy": "2026-11-06T14:41:50.969855Z",
          "iopub.status.idle": "2026-11-06T14:41:50.972461Z",
          "shell.execute_reply": "2026-11-06T14:41:50.972162Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "S\n"
          ]
        }
      ],
      "source": [
        "size = calculate_function_size(lp_str)  # \"S\", \"M\" or \"L\"\n",
        "print(size)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "id": "04236c83",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:50.973210Z",
          "iopub.status.busy": "2026-11-06T14:41:50.973169Z",
          "iopub.status.idle": "2026-11-06T14:41:53.515530Z",
          "shell.execute_reply": "2026-11-06T14:41:53.515130Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Job ID: fc3fee79-eef2-4ded-8a55-98fb17608fe1\n"
          ]
        }
      ],
      "source": [
        "options = {\"total_shots\": 2000, \"use_session\": True}\n",
        "\n",
        "# Dispatch the job\n",
        "job_2 = optimizer.run(\n",
        "    problem=lp_str,\n",
        "    backend_name=backend.name,\n",
        "    options=options,\n",
        "    function_size=size,\n",
        ")\n",
        "\n",
        "print(f\"Job ID: {job_2.job_id}\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "id": "079ebc2f",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:53.516799Z",
          "iopub.status.busy": "2026-11-06T14:41:53.516734Z",
          "iopub.status.idle": "2026-11-06T14:41:53.775748Z",
          "shell.execute_reply": "2026-11-06T14:41:53.774724Z"
        }
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "'QUEUED'"
            ]
          },
          "execution_count": 16,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Monitor the job status\n",
        "job_2.status()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "90c6de7c",
      "metadata": {},
      "source": [
        "### Step 3: Retrieve and interpret results\n",
        "\n",
        "Finally we retrieve the solution and verify for correctness.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 17,
      "id": "f1a2b3c4",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:53.778424Z",
          "iopub.status.busy": "2026-11-06T14:41:53.778238Z",
          "iopub.status.idle": "2026-11-06T14:41:58.708991Z",
          "shell.execute_reply": "2026-11-06T14:41:58.707615Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Feasible: True\n",
            "Independent set size: 15\n",
            "Selected nodes: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]\n",
            "Edge conflicts: []\n"
          ]
        }
      ],
      "source": [
        "result = job_2.result()\n",
        "\n",
        "print(f\"Feasible: {result['feasible']}\")\n",
        "print(f\"Independent set size: {int(result['objective_value'])}\")\n",
        "\n",
        "# Extract the selected nodes\n",
        "solution = result[\"solutions\"][0]\n",
        "independent_set = [\n",
        "    int(k.split(\"_\")[1]) for k, v in solution.items() if v == 1\n",
        "]\n",
        "print(f\"Selected nodes: {sorted(independent_set)}\")\n",
        "\n",
        "# Verify no two selected nodes share an edge\n",
        "conflicts = [\n",
        "    (u, v)\n",
        "    for u, v in G.edges()\n",
        "    if u in independent_set and v in independent_set\n",
        "]\n",
        "print(f\"Edge conflicts: {conflicts}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a2b3c4d5",
      "metadata": {},
      "source": [
        "## Example 3: Graph 3-coloring (Max-3-Cut)\n",
        "\n",
        "The Max-$k$-Cut problem partitions the vertices of a graph into $k$ groups to maximize the number of edges whose endpoints belong to different groups. For $k = 3$ this is equivalent to finding a 3-coloring that maximizes cross-color edges.\n",
        "\n",
        "Formally, assign each node $i \\in V$ to one of $k$ groups with binary variables $x_{i,c}$ for color $c \\in \\{1, \\ldots, k\\}$. The one-hot constraint $\\sum_c x_{i,c} = 1$ for each node enforces a unique assignment. The objective maximizes cross-group edges:\n",
        "\n",
        "$$\n",
        "\\min \\sum_{(u,v) \\in E} \\sum_c x_{u,c} \\, x_{v,c}\\\\\n",
        "\\text{s.t.} \\sum_{c} x_{i,c} = 1 \\quad \\forall i \\in  V\n",
        "$$\n",
        "\n",
        "The one-hot constraints are ideal for XY-mixers, which the optimizer handles natively.\n",
        "\n",
        "This example uses the [Zachary Karate Club graph](https://en.wikipedia.org/wiki/Zachary%27s_karate_club) (34 nodes, 78 edges) and builds the model with the [Luna Model](https://docs.aqarios.com/luna-model/).\n",
        "Install the required packages if needed:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "id": "b3c4d5e6",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:58.711100Z",
          "iopub.status.busy": "2026-11-06T14:41:58.710933Z",
          "iopub.status.idle": "2026-11-06T14:41:58.713874Z",
          "shell.execute_reply": "2026-11-06T14:41:58.713097Z"
        }
      },
      "outputs": [],
      "source": [
        "# %pip install networkx matplotlib luna-model"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c4d5e6f7",
      "metadata": {},
      "source": [
        "### Step 1: Define the problem\n",
        "\n",
        "First, generate the binary variables with the `luna-model` package. Then, define the objective and add the constraints to the model.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 19,
      "id": "d5e6f7a8",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:58.715618Z",
          "iopub.status.busy": "2026-11-06T14:41:58.715454Z",
          "iopub.status.idle": "2026-11-06T14:41:58.729011Z",
          "shell.execute_reply": "2026-11-06T14:41:58.728501Z"
        }
      },
      "outputs": [],
      "source": [
        "import networkx as nx\n",
        "from luna_model import Model, quicksum\n",
        "\n",
        "k = 3\n",
        "G = nx.karate_club_graph()\n",
        "\n",
        "# Instantiate the Model object\n",
        "model = Model(name=\"Max-3-Cut\")\n",
        "\n",
        "# Add binary variables\n",
        "x = model.add_variables(\"x\", shape=(G.number_of_nodes(), k))\n",
        "\n",
        "# Add the objective by using the numpy dot abstraction\n",
        "model.objective = quicksum(x[i].dot(x[j]) for i, j in G.edges)\n",
        "\n",
        "# Bulk-add the one-hot constraints\n",
        "model.add_constraints(x.sum(axis=1) == 1)\n",
        "\n",
        "# Encode the model to send via API\n",
        "model_enc = model.encode_b64()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8631a092",
      "metadata": {},
      "source": [
        "### Step 2: Run the optimizer\n",
        "\n",
        "Calculate the function size. The model has 34 × 3 = 102 variables, which is above the `M` bound of 100, so it needs `L`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 20,
      "id": "791bcb47",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:58.730530Z",
          "iopub.status.busy": "2026-11-06T14:41:58.730437Z",
          "iopub.status.idle": "2026-11-06T14:41:58.739731Z",
          "shell.execute_reply": "2026-11-06T14:41:58.738971Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "L\n"
          ]
        }
      ],
      "source": [
        "size = calculate_function_size(model_enc)  # \"S\", \"M\" or \"L\"\n",
        "print(size)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 21,
      "id": "f7a8b9c0",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:41:58.741145Z",
          "iopub.status.busy": "2026-11-06T14:41:58.741027Z",
          "iopub.status.idle": "2026-11-06T14:42:02.090558Z",
          "shell.execute_reply": "2026-11-06T14:42:02.089261Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Job ID: df911d83-9df7-44a1-bfad-5d66e08676c3\n"
          ]
        }
      ],
      "source": [
        "options = {\"use_session\": True}\n",
        "\n",
        "# Dispatch the job\n",
        "job_3 = optimizer.run(\n",
        "    problem=model_enc,\n",
        "    backend_name=backend.name,\n",
        "    options=options,\n",
        "    function_size=size,\n",
        ")\n",
        "\n",
        "print(f\"Job ID: {job_3.job_id}\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 22,
      "id": "e2ff9b51",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:42:02.093102Z",
          "iopub.status.busy": "2026-11-06T14:42:02.092930Z",
          "iopub.status.idle": "2026-11-06T14:42:03.626414Z",
          "shell.execute_reply": "2026-11-06T14:42:03.625779Z"
        }
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "'RUNNING: WAITING_FOR_QPU'"
            ]
          },
          "execution_count": 22,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Monitor the job status\n",
        "job_3.status()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a8b9c0d1",
      "metadata": {},
      "source": [
        "### Step 3: Retrieve and visualize results\n",
        "\n",
        "Retrieve and visualize the results.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 23,
      "id": "b9c0d1e2",
      "metadata": {
        "execution": {
          "iopub.execute_input": "2026-11-06T14:42:03.627765Z",
          "iopub.status.busy": "2026-11-06T14:42:03.627667Z",
          "iopub.status.idle": "2026-11-06T14:55:49.275443Z",
          "shell.execute_reply": "2026-11-06T14:55:49.275017Z"
        }
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Feasible: True\n",
            "Violations: 4\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/guides/aqarios-constrained-quantum-optimizer/extracted-outputs/b9c0d1e2-1.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "result = job_3.result()\n",
        "solution = result[\"solutions\"][0]\n",
        "\n",
        "# Map each node to its assigned color group\n",
        "node_group = {}\n",
        "for i in G.nodes:\n",
        "    for c in range(k):\n",
        "        if solution[f\"x{i},{c}\"] == 1:\n",
        "            node_group[i] = c\n",
        "\n",
        "print(f\"Feasible: {result['feasible']}\")\n",
        "print(f\"Violations: {int(result['objective_value'])}\")\n",
        "\n",
        "# Visualize the partition\n",
        "colors = [\"tab:blue\", \"tab:orange\", \"tab:green\"]\n",
        "node_colors = [colors[node_group[i]] for i in G.nodes()]\n",
        "nx.draw(G, nx.kamada_kawai_layout(G), node_color=node_colors, node_size=200)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "gs-next-steps",
      "metadata": {
        "jp-MarkdownHeadingCollapsed": true
      },
      "source": [
        "## Next steps\n",
        "\n",
        "<Admonition type=\"tip\" title=\"Recommendations\">\n",
        "  * Visit the [API reference](/docs/functions/aqarios-constrained-quantum-optimizer/api-reference) for the complete parameter and output documentation.\n",
        "  * Try the [Find the Maximum Independent Set with the Aqarios Constrained Quantum Optimizer](/docs/tutorials/find-the-maximum-independent-set-with-aqarios-constrained-quantum-optimizer) tutorial for a deep-dive into a real QOBLIB benchmark instance.\n",
        "  * Learn how to choose a [problem size](/docs/managed-workflows/managed-workflow-compute-profiles#match-sizes).\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
}