{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "dde95705-gs",
      "metadata": {},
      "source": [
        "---\n",
        "title: Get started with Q-CTRL Optimization Solver\n",
        "description: Load the Q-CTRL Optimization Solver function and solve unconstrained and constrained optimization problems on IBM quantum hardware.\n",
        "---\n",
        "\n",
        "{/* cspell:ignore sympify */}\n",
        "\n",
        "# Get started with Q-CTRL Optimization Solver\n",
        "\n",
        "*See the [overview](/docs/functions/q-ctrl-optimization-solver) and the [API reference](/docs/functions/q-ctrl-optimization-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": "40c2085c",
      "metadata": {
        "tags": [
          "version-info"
        ]
      },
      "source": [
        "{/*\n",
        "  DO NOT EDIT THIS CELL!!!\n",
        "  This cell's content is generated automatically by a script. Anything you add\n",
        "  here will be removed next time the notebook is run. To add new content, create\n",
        "  a new cell before or after this one.\n",
        "  */}\n",
        "\n",
        "<Accordion>\n",
        "  <AccordionItem title=\"Package versions\">\n",
        "    The code on this page was developed using the following requirements.\n",
        "    We recommend using these versions or newer.\n",
        "\n",
        "    ```\n",
        "    qiskit-ibm-runtime~=0.47.0\n",
        "    sympy~=1.14.0\n",
        "    ```\n",
        "  </AccordionItem>\n",
        "</Accordion>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "73390a19",
      "metadata": {},
      "source": [
        "## Set up and load the function\n",
        "\n",
        "First, authenticate using your [IBM Quantum API key](http://quantum.cloud.ibm.com/). Then, select the quantum function as follows. (This snippet assumes you've already [saved your account](/docs/ibm-quantum-platform/functions-get-started#install-qiskit-functions-catalog-client) to your local environment.)\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "95a715d2",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit_ibm_catalog import FunctionsCatalog\n",
        "\n",
        "catalog = FunctionsCatalog(channel=\"ibm_quantum_platform\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "8acf84f6",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Access function\n",
        "solver = catalog.load(\"q-ctrl/optimization-solver\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f0bbccd8",
      "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 workflow documentation](/docs/managed-workflows/managed-workflow-compute-profiles#best-practice-match-sizes-to-problem-sizes) for how sizes work in general.\n",
        "\n",
        "Pass the size to `solver.run()` with the `function_size` argument. For the Optimization Solver, the size depends on the number of binary decision variables and the interaction density of the problem.\n",
        "\n",
        "Interaction density is the fraction of possible variable pairs that appear together in at least one term of the objective function or constraints. Each distinct pair is counted once. For sizing, equality constraints contribute interactions between every pair of variables they contain. Continue to pass hard constraints directly through the `constraint` input, as shown in the constrained optimization example.\n",
        "\n",
        "| Size | Binary decision variables | Interaction density | Rule                                                                                   |\n",
        "| ---- | ------------------------- | ------------------- | -------------------------------------------------------------------------------------- |\n",
        "| `S`  | ≤ 50                      | ≤ 10%               | Both metrics must satisfy the Small limits.                                            |\n",
        "| `M`  | ≤ 100                     | ≤ 25%               | At least one metric exceeds its Small limit, but both remain within the Medium limits. |\n",
        "| `L`  | > 100                     | > 25%               | Either the variable count or interaction density exceeds its Medium limit.             |\n",
        "\n",
        "Both the variable count and the interaction density must satisfy the selected size. For example, a problem with 40 variables and 30% interaction density requires `\"L\"`.\n",
        "\n",
        "For graph problems, count the binary decision variables in the optimization model. Depending on the formulation, a single graph node can require more than one variable.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3055fed4",
      "metadata": {},
      "source": [
        "### Calculate the size before submitting\n",
        "\n",
        "Use the following helper to calculate the size from the number of binary decision variables and the number of distinct interacting variable pairs, including the pairs that hard constraints introduce. It returns `\"S\"`, `\"M\"`, or `\"L\"`, and no job is submitted. The examples that follow show how to count the variables and pairs for a graph problem and for a constrained problem.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "3d6701fd",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Size calculator example for an optimization function.\n",
        "#\n",
        "# Input:  the model in whatever format your entrypoint accepts, plus the other function\n",
        "#         inputs as ``**kwargs``.\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",
        "# ``to_optimization_problem`` is **the one function to implement**: it turns your input into\n",
        "# a :class:`~qiskit_addon_opt_mapper.problems.OptimizationProblem`, and the sizing logic\n",
        "# below it never changes. Once converted, ``get_num_vars()`` gives the variable count; the\n",
        "# class exposes no density, so it is derived from the objective and constraint expressions,\n",
        "# each of which reports its terms through ``to_dict()``.\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-opt-mapper/\n",
        "\n",
        "import re\n",
        "import sys\n",
        "from ast import literal_eval\n",
        "from collections.abc import Iterator\n",
        "from itertools import combinations\n",
        "from typing import Any, Literal\n",
        "\n",
        "import networkx as nx\n",
        "from qiskit.quantum_info import SparsePauliOp\n",
        "from qiskit_addon_opt_mapper.problems import OptimizationProblem\n",
        "from sympy import Poly, sympify\n",
        "\n",
        "from qiskit_serverless import (\n",
        "    ServerlessError,\n",
        "    get_function_size,\n",
        "    get_logger,\n",
        "    send_error,\n",
        ")\n",
        "\n",
        "Size = Literal[\"S\", \"M\", \"L\"]\n",
        "_ORDER = {\"S\": 0, \"M\": 1, \"L\": 2}\n",
        "\n",
        "# Error codes assigned by IBM; see the IBM Quantum error registry.\n",
        "SIZE_TOO_SMALL_ERROR_CODE = \"4600\"\n",
        "SIZE_TOO_LARGE_ERROR_CODE = \"4601\"\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(\n",
        "    problem: Any,\n",
        "    *,\n",
        "    problem_type: str | None = None,\n",
        "    constraint: dict[str, int] | None = None,\n",
        "    **kwargs: Any,  # pylint: disable=unused-argument\n",
        ") -> OptimizationProblem:\n",
        "    \"\"\"Convert the optimizer's inputs into an ``OptimizationProblem``.\n",
        "\n",
        "    Only the structure matters for sizing, so variables are binary and each term of the\n",
        "    cost function is kept by its support (the variables it couples).\n",
        "\n",
        "    - ``SparsePauliOp``: one variable per qubit, one term per Pauli string, supported on\n",
        "      its ``Z`` operators.\n",
        "    - Graph (adjacency data), with ``problem_type`` ``\"maxcut\"``: one variable per node,\n",
        "      one coupling per edge. ``\"max-<k>-cut\"``: ``k`` variables per node, as in\n",
        "      ``MaxKCutInstance``, with a one-hot constraint per node. User constraints are\n",
        "      ignored for ``k >= 3``, as the solver ignores them.\n",
        "    - Sympy expression (``srepr``): one variable per free symbol, one term per monomial.\n",
        "\n",
        "    ``constraint`` (Hamming weights keyed by variable index or name) becomes equality\n",
        "    constraints on the sum of the variables, which ``_interactions`` sizes as penalties.\n",
        "    \"\"\"\n",
        "    if isinstance(problem, OptimizationProblem):\n",
        "        return problem\n",
        "\n",
        "    hamming = _deserialize_hamming_constraint(constraint)\n",
        "    decoded = (\n",
        "        problem\n",
        "        if isinstance(problem, SparsePauliOp)\n",
        "        else _decode_problem(problem)\n",
        "    )\n",
        "\n",
        "    names: dict[str, int] = {}\n",
        "    groups: list[tuple[tuple[int | str, ...], int]] = list(hamming.items())\n",
        "    if isinstance(decoded, SparsePauliOp):\n",
        "        num_vars, terms = decoded.num_qubits, _pauli_terms(decoded)\n",
        "    elif isinstance(decoded, nx.Graph):\n",
        "        k = _parse_max_k_cut_k_value(problem_type)\n",
        "        if problem_type == \"maxcut\" or k == 2:\n",
        "            num_vars, terms = (\n",
        "                decoded.number_of_nodes(),\n",
        "                _graph_terms(decoded, 1),\n",
        "            )\n",
        "        elif k is not None:\n",
        "            num_vars, terms = (\n",
        "                decoded.number_of_nodes() * k,\n",
        "                _graph_terms(decoded, k),\n",
        "            )\n",
        "            groups = [\n",
        "                (tuple(range(k * node, k * (node + 1))), 1)\n",
        "                for node in range(decoded.number_of_nodes())\n",
        "            ]\n",
        "        else:\n",
        "            raise ValueError(\n",
        "                f\"cannot size a graph problem of type {problem_type!r}: expected \"\n",
        "                \"'maxcut' or 'max-<k>-cut'\"\n",
        "            )\n",
        "    else:\n",
        "        poly = decoded if isinstance(decoded, Poly) else Poly(decoded)\n",
        "        symbols = sorted(\n",
        "            poly.as_expr().free_symbols, key=lambda symbol: symbol.name\n",
        "        )\n",
        "        names = {symbol.name: index for index, symbol in enumerate(symbols)}\n",
        "        num_vars, terms = len(symbols), _poly_terms(poly, names)\n",
        "\n",
        "    return _build_problem(num_vars, terms, groups, names)\n",
        "\n",
        "\n",
        "def _decode_problem(problem: Any) -> Any:\n",
        "    \"\"\"Decode a graph (networkx adjacency data) or a sympy ``srepr`` string.\"\"\"\n",
        "    try:\n",
        "        try:\n",
        "            return nx.readwrite.json_graph.adjacency_graph(problem)\n",
        "        except AttributeError:\n",
        "            return sympify(problem)\n",
        "    except RecursionError:\n",
        "        sys.setrecursionlimit(5000)\n",
        "        return _decode_problem(problem)\n",
        "\n",
        "\n",
        "def _parse_max_k_cut_k_value(problem_type: str | None) -> int | None:\n",
        "    \"\"\"Return ``k`` for a ``max-<k>-cut`` problem type, else ``None``.\"\"\"\n",
        "    match = re.fullmatch(r\"max-(\\d+)-cut\", problem_type or \"\")\n",
        "    if match is None:\n",
        "        return None\n",
        "    k = int(match.group(1))\n",
        "    if k < 2:\n",
        "        raise ValueError(\n",
        "            f\"k for a Max-k-Cut problem must be at least 2, got {k}.\"\n",
        "        )\n",
        "    return k\n",
        "\n",
        "\n",
        "def _deserialize_hamming_constraint(\n",
        "    constraint: dict[str, int] | None,\n",
        ") -> dict[tuple[int | str, ...], int]:\n",
        "    \"\"\"Turn string keys such as ``\"(0, 1)\"`` into tuples of indices or names.\"\"\"\n",
        "    deserialized: dict[tuple[int | str, ...], int] = {}\n",
        "    for key, weight in (constraint or {}).items():\n",
        "        try:\n",
        "            group = literal_eval(key)\n",
        "        except (ValueError, TypeError, SyntaxError):\n",
        "            group = None\n",
        "        if not isinstance(group, tuple) or not all(\n",
        "            isinstance(entry, (int, str)) for entry in group\n",
        "        ):\n",
        "            raise ValueError(\n",
        "                f\"Constraint '{key}' is not a valid tuple of variable indexes or names.\"\n",
        "            )\n",
        "        deserialized[group] = weight\n",
        "    return deserialized\n",
        "\n",
        "\n",
        "def _pauli_terms(operator: SparsePauliOp) -> dict[tuple[int, ...], float]:\n",
        "    terms: dict[tuple[int, ...], float] = {}\n",
        "    for label, coefficient in zip(\n",
        "        operator.paulis.to_labels(), operator.coeffs\n",
        "    ):\n",
        "        # The rightmost character of a Pauli label is qubit 0.\n",
        "        support = tuple(\n",
        "            i for i, char in enumerate(reversed(label)) if char == \"Z\"\n",
        "        )\n",
        "        terms[support] = terms.get(support, 0.0) + float(coefficient.real)\n",
        "    return terms\n",
        "\n",
        "\n",
        "def _graph_terms(\n",
        "    graph: nx.Graph, colors: int\n",
        ") -> dict[tuple[int, ...], float]:\n",
        "    terms: dict[tuple[int, ...], float] = {}\n",
        "    for u, v, weight in graph.edges(data=\"weight\", default=1.0):\n",
        "        for color in range(colors):\n",
        "            support = tuple(sorted({colors * u + color, colors * v + color}))\n",
        "            terms[support] = terms.get(support, 0.0) + weight\n",
        "    return terms\n",
        "\n",
        "\n",
        "def _poly_terms(\n",
        "    poly: Poly, names: dict[str, int]\n",
        ") -> dict[tuple[int, ...], float]:\n",
        "    terms: dict[tuple[int, ...], float] = {}\n",
        "    for exponents, coefficient in poly.terms():\n",
        "        support = tuple(\n",
        "            sorted(\n",
        "                names[generator.name]\n",
        "                for generator, exponent in zip(poly.gens, exponents)\n",
        "                if exponent > 0\n",
        "            )\n",
        "        )\n",
        "        terms[support] = terms.get(support, 0.0) + float(coefficient)\n",
        "    return terms\n",
        "\n",
        "\n",
        "def _build_problem(\n",
        "    num_vars: int,\n",
        "    terms: dict[tuple[int, ...], float],\n",
        "    groups: list[tuple[tuple[int | str, ...], int]],\n",
        "    names: dict[str, int],\n",
        ") -> OptimizationProblem:\n",
        "    \"\"\"Build the problem; terms of order 3 and above go in ``higher_order``, by order.\"\"\"\n",
        "    model = OptimizationProblem()\n",
        "    model.binary_var_list(num_vars, name=\"x\")\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",
        "        if len(support) == 1:\n",
        "            linear[support[0]] = coefficient\n",
        "        elif len(support) == 2:\n",
        "            quadratic[(support[0], support[1])] = coefficient\n",
        "        elif len(support) >= 3:\n",
        "            higher_order.setdefault(len(support), {})[support] = coefficient\n",
        "    model.minimize(\n",
        "        linear=linear, quadratic=quadratic, higher_order=higher_order or None\n",
        "    )\n",
        "\n",
        "    for group, weight in groups:\n",
        "        members = {names[m] if isinstance(m, str) else m: 1.0 for m in group}\n",
        "        model.linear_constraint(members, \"==\", weight)\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, **kwargs)\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 your 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",
        "    )\n",
        "\n",
        "\n",
        "def validate_size(problem: Any, **kwargs: Any) -> None:\n",
        "    \"\"\"Call once at the start of your function. Compare the size the job was given with\n",
        "    the calculated size and log both. Raise if the given size is smaller than the calculation;\n",
        "    report a non-fatal event and continue if it is larger.\"\"\"\n",
        "    logger = get_logger()\n",
        "    provided = get_function_size()\n",
        "    if not provided:\n",
        "        # Empty on non-Fleets (Ray) jobs, where sizes do not apply.\n",
        "        logger.warning(\n",
        "            \"No function size was given to this job; skipping the size check.\"\n",
        "        )\n",
        "        return\n",
        "    provided = provided.upper()\n",
        "    expected = calculate_function_size(problem, **kwargs)\n",
        "    logger.info(\n",
        "        \"Function size given: '%s'; calculated size: '%s'.\",\n",
        "        provided,\n",
        "        expected,\n",
        "    )\n",
        "    if _ORDER[provided] < _ORDER[expected]:\n",
        "        logger.error(\n",
        "            \"Size '%s' is too small; the calculated size is '%s'.\",\n",
        "            provided,\n",
        "            expected,\n",
        "        )\n",
        "        raise ServerlessError(\n",
        "            code=SIZE_TOO_SMALL_ERROR_CODE,\n",
        "            message=f\"Size '{provided}' is too small for this problem; expected '{expected}' or larger.\",\n",
        "        )\n",
        "    if _ORDER[provided] > _ORDER[expected]:\n",
        "        logger.warning(\n",
        "            \"Size '%s' is larger than this problem needs; the calculated size is '%s'.\",\n",
        "            provided,\n",
        "            expected,\n",
        "        )\n",
        "        send_error(\n",
        "            code=SIZE_TOO_LARGE_ERROR_CODE,\n",
        "            message=\"The specified function size is larger than this job requires.\",\n",
        "            exception=\"FunctionSizeTooLarge\",\n",
        "            args={\n",
        "                \"provided_size\": provided,\n",
        "                \"calculated_size\": expected,\n",
        "                \"solution\": (\n",
        "                    \"No action is required and the job completed normally. To reduce \"\n",
        "                    \"cost, use a smaller function size for jobs of this kind.\"\n",
        "                ),\n",
        "            },\n",
        "        )"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "qctrl-os-sizes-outro",
      "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.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e8837f5f",
      "metadata": {},
      "source": [
        "## Example: Unconstrained optimization\n",
        "\n",
        "Run the [maximum cut](https://en.wikipedia.org/wiki/Maximum_cut) (max-cut) problem. The following example demonstrates the Solver's capabilities on a 100-node, 3-regular unweighted graph max-cut problem, but you can also solve weighted graph problems.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a699235b",
      "metadata": {},
      "source": [
        "In addition to `qiskit-ibm-catalog`, you will also use the following packages to run this example: `networkx` and `numpy`. You can install these packages by uncommenting the following cell if you are running this example in a notebook using the IPython kernel.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "a74fe6a9",
      "metadata": {},
      "outputs": [],
      "source": [
        "# %pip install networkx numpy"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a41c4a0d",
      "metadata": {},
      "source": [
        "### 1. Define the problem\n",
        "\n",
        "You can run a max-cut problem by defining a graph problem and specifying `problem_type='maxcut'`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "d56e1440",
      "metadata": {},
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "\n",
        "# Generate a random graph with 100 nodes\n",
        "maxcut_graph = nx.random_regular_graph(d=3, n=100, seed=8)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "0a7255e1",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/functions/q-ctrl-optimization-solver/get-started/extracted-outputs/0a7255e1-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "# Optionally, visualize the graph\n",
        "nx.draw_networkx(\n",
        "    maxcut_graph, nx.kamada_kawai_layout(maxcut_graph), node_size=100\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e42a8d55",
      "metadata": {},
      "source": [
        "The Solver accepts a string as the problem definition input.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "2546e3e5",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Convert graph to string\n",
        "problem_as_str = nx.readwrite.json_graph.adjacency_data(maxcut_graph)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0ab6f24f",
      "metadata": {},
      "source": [
        "### 2. Run the problem\n",
        "\n",
        "When using the graph-based input method, specify the problem type. Calculate the function size from `maxcut_graph`, then pass the returned value to `solver.run` through `function_size`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "fb4b0dfb",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Workload size: M\n"
          ]
        }
      ],
      "source": [
        "# Calculate the workload size\n",
        "maxcut_size = calculate_function_size(problem_as_str, problem_type=\"maxcut\")\n",
        "\n",
        "print(f\"Workload size: {maxcut_size}\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "cf53550c",
      "metadata": {},
      "outputs": [],
      "source": [
        "backend_name = catalog.least_busy().name"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "16c66d64",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Solve the problem\n",
        "maxcut_job = solver.run(\n",
        "    problem=problem_as_str,\n",
        "    problem_type=\"maxcut\",\n",
        "    backend_name=backend_name,  # E.g. \"ibm_fez\"\n",
        "    function_size=maxcut_size,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "48069093",
      "metadata": {},
      "source": [
        "Check your quantum function workload's [status](/docs/ibm-quantum-platform/functions-get-started#check-job-status) or return [results](/docs/ibm-quantum-platform/functions-get-started#retrieve-results) as follows:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 17,
      "id": "856fe992",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "eb364ea7-b69d-48f4-a1ce-1b22f2290534\n",
            "RUNNING\n"
          ]
        }
      ],
      "source": [
        "# Print the ID so you can use it later, if necessary\n",
        "print(maxcut_job.job_id)\n",
        "\n",
        "# Get job status\n",
        "print(maxcut_job.status())"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "74f48eab",
      "metadata": {},
      "source": [
        "### 3. Retrieve the result\n",
        "\n",
        "Retrieve the optimal cut value from the results dictionary.\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  The mapping of the variables to the bitstring may have changed. The output dictionary contains a `variables_to_bitstring_index_map` sub-dictionary, which helps to verify the ordering.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "id": "6b571411",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Optimal cut value: 137.0\n"
          ]
        }
      ],
      "source": [
        "# Poll for results\n",
        "maxcut_result = maxcut_job.result()\n",
        "\n",
        "# Take the absolute value of the solution since the cost function is minimized\n",
        "qctrl_maxcut = abs(maxcut_result[\"solution_bitstring_cost\"])\n",
        "\n",
        "# Print the optimal cut value found by the Optimization Solver\n",
        "print(f\"Optimal cut value: {qctrl_maxcut}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "508e29b0",
      "metadata": {},
      "source": [
        "You can verify the accuracy of the result by solving the problem classically with open-source solvers like [PuLP](https://coin-or.github.io/pulp/) if the graph is not densely connected. High density problems may require advanced classical solvers to validate the solution.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e2817b13",
      "metadata": {},
      "source": [
        "## Example: Constrained optimization\n",
        "\n",
        "The prior max-cut example is a common quadratic unconstrained binary optimization problem. Q-CTRL's Optimization Solver can also solve constrained optimization problems by passing hard constraints directly to the Solver through the `constraint` input, instead of encoding them as penalty terms in the objective function. The Solver currently supports Hamming-weight-1 constraints: each constraint specifies a group of variables where exactly one variable must equal 1 and the rest must equal 0.\n",
        "\n",
        "The following example demonstrates how to construct a cost function and a set of hard constraints for a constrained optimization problem, [graph partitioning](https://en.wikipedia.org/wiki/Graph_partition), by assigning every node in a graph to exactly one of several groups while minimizing the total weight of edges whose endpoints land in the same group.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a9fbc0e9",
      "metadata": {},
      "source": [
        "In addition to the `qiskit-ibm-catalog` and `qiskit` packages, you will also use the following packages to run this example: `numpy`, `networkx`, and `sympy`. You can install these packages by uncommenting the following cell if you are running this example in a notebook using the IPython kernel.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "c6428fd0",
      "metadata": {},
      "outputs": [],
      "source": [
        "# %pip install numpy networkx sympy"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "98d3bfd3",
      "metadata": {},
      "source": [
        "### 1. Define the problem\n",
        "\n",
        "Define a random graph partitioning problem by generating a graph with randomly weighted nodes.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "c2ce65e3",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/docs/images/functions/q-ctrl-optimization-solver/get-started/extracted-outputs/c2ce65e3-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "import networkx as nx\n",
        "from sympy import Symbol, srepr\n",
        "\n",
        "# To change the weights, change the seed to any integer.\n",
        "rng_seed = 18\n",
        "_rng = np.random.default_rng(rng_seed)\n",
        "node_count = 50\n",
        "edge_probability = 0.08\n",
        "graph = nx.erdos_renyi_graph(\n",
        "    node_count, edge_probability, seed=rng_seed, directed=False\n",
        ")\n",
        "\n",
        "# add node weights\n",
        "min_weight = -1.0\n",
        "max_weight = 1.0\n",
        "for i in graph.nodes:\n",
        "    weight = (max_weight - min_weight) * _rng.random() + min_weight\n",
        "    graph.add_node(i, weight=weight)\n",
        "\n",
        "# Optionally, visualize the graph\n",
        "nx.draw_networkx(graph, nx.kamada_kawai_layout(graph), node_size=200)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "89c91472",
      "metadata": {},
      "source": [
        "A standard optimization model for weighted graph partitioning can be formulated as follows. Split the nodes of the graph into three groups $g \\in \\{0, 1, 2\\}$, and let $n_{i,g} = 1$ if node $i$ is assigned to group $g$, and $n_{i,g} = 0$ otherwise. The goal is to minimize the total weight of edges whose endpoints are assigned to the same group, where the weight of an edge $(i,j)$ is the combined weight of its two endpoints, $\\omega_{i,j} = \\omega_i + \\omega_j$:\n",
        "\n",
        "$\\textbf{Minimize}\\qquad y = \\sum_{(i,j)\\in E} \\omega_{i,j} \\sum_{g} n_{i,g}\\, n_{j,g}$\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "91586ee9",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Construct the cost function.\n",
        "group_count = 3\n",
        "variables = [\n",
        "    Symbol(f\"n[{i},{g}]\")\n",
        "    for i in range(node_count)\n",
        "    for g in range(group_count)\n",
        "]\n",
        "node_group_var = {\n",
        "    (i, g): variables[i * group_count + g]\n",
        "    for i in range(node_count)\n",
        "    for g in range(group_count)\n",
        "}\n",
        "cost_function = Poly(0, *variables)\n",
        "\n",
        "for i, j in graph.edges():\n",
        "    edge_weight = graph.nodes[i][\"weight\"] + graph.nodes[j][\"weight\"]\n",
        "    for g in range(group_count):\n",
        "        cost_function += (\n",
        "            edge_weight * node_group_var[(i, g)] * node_group_var[(j, g)]\n",
        "        )"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "9d01684b",
      "metadata": {},
      "source": [
        "Every node must be assigned to exactly one of the three groups. This is a Hamming-weight-1 constraint: for every node $i$, exactly one of $n_{i,0}, n_{i,1}, n_{i,2}$ must equal 1, and the rest must equal 0:\n",
        "\n",
        "$n_{i,0} + n_{i,1} + n_{i,2} = 1 \\texttt{ for all } i \\in V$\n",
        "\n",
        "Rather than encoding this requirement as a penalty term in the cost function, pass it directly to the Solver as a hard constraint using the `constraint` input.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "1ff1ffcc",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Problem constraints: {\"('n[0,0]', 'n[0,1]', 'n[0,2]')\": 1, \"('n[1,0]', 'n[1,1]', 'n[1,2]')\": 1, \"('n[2,0]', 'n[2,1]', 'n[2,2]')\": 1, \"('n[3,0]', 'n[3,1]', 'n[3,2]')\": 1, \"('n[4,0]', 'n[4,1]', 'n[4,2]')\": 1, \"('n[5,0]', 'n[5,1]', 'n[5,2]')\": 1, \"('n[6,0]', 'n[6,1]', 'n[6,2]')\": 1, \"('n[7,0]', 'n[7,1]', 'n[7,2]')\": 1, \"('n[8,0]', 'n[8,1]', 'n[8,2]')\": 1, \"('n[9,0]', 'n[9,1]', 'n[9,2]')\": 1, \"('n[10,0]', 'n[10,1]', 'n[10,2]')\": 1, \"('n[11,0]', 'n[11,1]', 'n[11,2]')\": 1, \"('n[12,0]', 'n[12,1]', 'n[12,2]')\": 1, \"('n[13,0]', 'n[13,1]', 'n[13,2]')\": 1, \"('n[14,0]', 'n[14,1]', 'n[14,2]')\": 1, \"('n[15,0]', 'n[15,1]', 'n[15,2]')\": 1, \"('n[16,0]', 'n[16,1]', 'n[16,2]')\": 1, \"('n[17,0]', 'n[17,1]', 'n[17,2]')\": 1, \"('n[18,0]', 'n[18,1]', 'n[18,2]')\": 1, \"('n[19,0]', 'n[19,1]', 'n[19,2]')\": 1, \"('n[20,0]', 'n[20,1]', 'n[20,2]')\": 1, \"('n[21,0]', 'n[21,1]', 'n[21,2]')\": 1, \"('n[22,0]', 'n[22,1]', 'n[22,2]')\": 1, \"('n[23,0]', 'n[23,1]', 'n[23,2]')\": 1, \"('n[24,0]', 'n[24,1]', 'n[24,2]')\": 1, \"('n[25,0]', 'n[25,1]', 'n[25,2]')\": 1, \"('n[26,0]', 'n[26,1]', 'n[26,2]')\": 1, \"('n[27,0]', 'n[27,1]', 'n[27,2]')\": 1, \"('n[28,0]', 'n[28,1]', 'n[28,2]')\": 1, \"('n[29,0]', 'n[29,1]', 'n[29,2]')\": 1, \"('n[30,0]', 'n[30,1]', 'n[30,2]')\": 1, \"('n[31,0]', 'n[31,1]', 'n[31,2]')\": 1, \"('n[32,0]', 'n[32,1]', 'n[32,2]')\": 1, \"('n[33,0]', 'n[33,1]', 'n[33,2]')\": 1, \"('n[34,0]', 'n[34,1]', 'n[34,2]')\": 1, \"('n[35,0]', 'n[35,1]', 'n[35,2]')\": 1, \"('n[36,0]', 'n[36,1]', 'n[36,2]')\": 1, \"('n[37,0]', 'n[37,1]', 'n[37,2]')\": 1, \"('n[38,0]', 'n[38,1]', 'n[38,2]')\": 1, \"('n[39,0]', 'n[39,1]', 'n[39,2]')\": 1, \"('n[40,0]', 'n[40,1]', 'n[40,2]')\": 1, \"('n[41,0]', 'n[41,1]', 'n[41,2]')\": 1, \"('n[42,0]', 'n[42,1]', 'n[42,2]')\": 1, \"('n[43,0]', 'n[43,1]', 'n[43,2]')\": 1, \"('n[44,0]', 'n[44,1]', 'n[44,2]')\": 1, \"('n[45,0]', 'n[45,1]', 'n[45,2]')\": 1, \"('n[46,0]', 'n[46,1]', 'n[46,2]')\": 1, \"('n[47,0]', 'n[47,1]', 'n[47,2]')\": 1, \"('n[48,0]', 'n[48,1]', 'n[48,2]')\": 1, \"('n[49,0]', 'n[49,1]', 'n[49,2]')\": 1}\n"
          ]
        }
      ],
      "source": [
        "# Build the hard constraint: exactly one group per node.\n",
        "constraint_dict = {\n",
        "    str(tuple(f\"n[{i},{g}]\" for g in range(group_count))): 1\n",
        "    for i in range(node_count)\n",
        "}\n",
        "print(f\"Problem constraints: {constraint_dict}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "753e5514",
      "metadata": {},
      "source": [
        "<Admonition type=\"note\" title=\"Partially constrained problems\">\n",
        "  You do not need to add every variable to `constraint`. Any variable left out of the dictionary remains unconstrained, so you can mix hard-constrained groups of variables with free variables in the same problem.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "9fd0ba9e",
      "metadata": {},
      "source": [
        "### 2. Run the problem\n",
        "\n",
        "Calculate the function size using the binary decision variables and interactions from the objective function and constraints. This formulation uses one variable per node and group. Pass the calculated size to `solver.run` through `function_size`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "id": "0080c2cf",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Workload size: L\n"
          ]
        }
      ],
      "source": [
        "partition_size = calculate_function_size(\n",
        "    problem=srepr(cost_function),\n",
        "    constraint=constraint_dict,\n",
        ")\n",
        "\n",
        "print(f\"Workload size: {partition_size}\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "f380b56d",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Solve the problem\n",
        "partition_job = solver.run(\n",
        "    problem=srepr(cost_function),\n",
        "    constraint=constraint_dict,\n",
        "    backend_name=\"ibm_marrakesh\",  # E.g. \"ibm_marrakesh\"\n",
        "    function_size=partition_size,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d154c226",
      "metadata": {},
      "source": [
        "Check your quantum function workload's [status](/docs/ibm-quantum-platform/functions-get-started#check-job-status) or return [results](/docs/ibm-quantum-platform/functions-get-started#retrieve-results) as follows:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 21,
      "id": "6de77b14",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "b8085944-f313-444e-be39-ea61b1b47ebd\n",
            "QUEUED\n"
          ]
        }
      ],
      "source": [
        "# Print the ID so you can use it later, if necessary\n",
        "print(partition_job.job_id)\n",
        "\n",
        "# Get job status\n",
        "print(partition_job.status())"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8a95618e",
      "metadata": {},
      "source": [
        "### 3. Get the result\n",
        "\n",
        "Retrieve the solution and analyze the results. The solution cost represents the total weight of edges whose endpoints ended up in the same group, so a lower cost indicates a better partitioning of the graph.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "a924bf93",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Total weight of same-group edges: -36.5539\n",
            "Solution bitstring: 100100100100100001100100100100100100100100100100100001010100010100100100100010001001100100100001100001100001010001001010100100100100100010100100100100\n"
          ]
        }
      ],
      "source": [
        "partition_result = partition_job.result()\n",
        "qctrl_cost = partition_result[\"solution_bitstring_cost\"]\n",
        "solution_bitstring = partition_result[\"solution_bitstring\"]\n",
        "\n",
        "# Print results\n",
        "print(f\"Total weight of same-group edges: {qctrl_cost}\")\n",
        "print(f\"Solution bitstring: {solution_bitstring}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "solver-gs-next-steps",
      "metadata": {},
      "source": [
        "## Next steps\n",
        "\n",
        "<Admonition type=\"tip\" title=\"Recommendations\">\n",
        "  * Tune your workloads with [advanced techniques for Q-CTRL Optimization Solver](/docs/functions/q-ctrl-optimization-solver/performance-tuning).\n",
        "  * Learn how to choose a [problem size](/docs/managed-workflows/managed-workflow-compute-profiles#match-sizes).\n",
        "  * Visit the [API reference](/docs/functions/q-ctrl-optimization-solver/api-reference) for this quantum function.\n",
        "  * Try the [Solve higher-order binary optimization problems with Q-CTRL's Optimization Solver](/docs/tutorials/solve-higher-order-binary-optimization-problems-with-q-ctrls-optimization-solver) tutorial.\n",
        "  * Review [Sachdeva, N., et al. (2024).  Quantum optimization using a 127-qubit gate-model IBM quantum computer can outperform quantum annealers for nontrivial binary optimization problems. arXiv preprint arXiv:2406.01743](https://arxiv.org/abs/2406.01743).\n",
        "  * Review [Loco, D., et al. (2026).  Practical protein-pocket hydration-site prediction for drug discovery on a quantum computer. arXiv preprint arXiv:2512.08390](https://arxiv.org/abs/2512.08390).\n",
        "  * Review the [Mazda](https://q-ctrl.com/case-study/tackling-a-costly-bottleneck-in-automotive-design) case study.\n",
        "  * Review the [Network Rail](https://q-ctrl.com/case-study/accelerating-the-schedule-for-quantum-enhanced-rail) case study.\n",
        "  * Review the [Australian Army](https://q-ctrl.com/case-study/improving-army-logistics-with-quantum-computing) case study.\n",
        "  * Review the [Transport for New South Wales](https://q-ctrl.com/case-study/delivering-quantum-computing-for-faster-commuting) case study.\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
}