{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "c3a91f20",
      "metadata": {},
      "source": [
        "---\n",
        "title: Get started with Parity Twine Optimizer by ParityQC\n",
        "description: Load the Parity Twine Optimizer function, choose a function size, and solve a QUBO problem on IBM Quantum hardware.\n",
        "---\n",
        "\n",
        "{/* cspell:ignore parityqc */}\n",
        "\n",
        "# Get started with Parity Twine Optimizer by ParityQC\n",
        "\n",
        "*See the [overview](/docs/functions/parity-twine-optimizer) and the [API reference](/docs/functions/parity-twine-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": "02f8e130",
      "metadata": {
        "tags": [
          "version-info"
        ]
      },
      "source": [
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "73390a19",
      "metadata": {},
      "source": [
        "## Set up and load the function\n",
        "\n",
        "Authenticate using your [IBM Quantum Platform API token](/docs/ibm-quantum-platform/functions-get-started) and select the quantum function as:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "95a715d2",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit_ibm_catalog import FunctionsCatalog\n",
        "\n",
        "# Authenticate and load the quantum function\n",
        "catalog = FunctionsCatalog(\n",
        "    channel=\"ibm_quantum_platform\",\n",
        ")\n",
        "function = catalog.load(\"parityqc/parity-twine-optimizer\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "186f7ca2",
      "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",
        "The size comes from two properties of your model: how many variables it has, and\n",
        "how densely they interact, that is, 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",
        "You can also read the mapping from the function itself with `function.sizes_map`, and the default size with `function.default_size`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "37b155ba",
      "metadata": {},
      "source": [
        "For the Parity Twine Optimizer, every variable that appears in `problem` counts once,\n",
        "and every quadratic term such as `\"(0, 1)\"` contributes one pair. The model in the\n",
        "[example](#example) has five variables and one of the ten possible pairs, a density\n",
        "of 0.1, so it needs `S`. Fully connected models, such as the\n",
        "[Sherrington-Kirkpatrick model](/docs/tutorials/parity-twine-optimizer-sk) or the QUBO\n",
        "form of the [market split problem](/docs/tutorials/parity-twine-optimizer-ms), have a\n",
        "density of 1.0 and always need `L`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "989f34f8",
      "metadata": {},
      "source": [
        "### Calculate the size before submitting\n",
        "\n",
        "Run the following calculator on your own model. It reads the model and nothing else: no job is submitted and nothing is reserved, so you can call it as often as you like while you reduce a model to a smaller size.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "9c9a0225",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Calculate the function size a model needs, before submitting it.\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",
        "\n",
        "import ast\n",
        "\n",
        "from collections.abc import Iterator\n",
        "from itertools import combinations\n",
        "from typing import Any, Literal\n",
        "\n",
        "from qiskit_addon_opt_mapper.problems import OptimizationProblem\n",
        "\n",
        "Size = Literal[\"S\", \"M\", \"L\"]\n",
        "VariableType = Literal[\"spin\", \"binary\"]\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(\n",
        "    problem: dict[str, float] | OptimizationProblem, **kwargs: Any\n",
        ") -> 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: dict[str, float] | OptimizationProblem,\n",
        "    problem_type: str = \"\",\n",
        "    variable_type: VariableType = \"binary\",\n",
        ") -> OptimizationProblem:\n",
        "    \"\"\"Convert the Parity Twine Optimizer ``problem`` input into an\n",
        "    ``OptimizationProblem``.\n",
        "\n",
        "    Args:\n",
        "        problem: A dictionary {term: coefficient} where each term is a string\n",
        "            version of a tuple of variable ids, for example\n",
        "            {\"()\": 3, \"(0,)\": 1, \"(0, 1)\": 2}. An ``OptimizationProblem`` is\n",
        "            returned unchanged.\n",
        "        problem_type: The ``problem_type`` passed to the function, for\n",
        "            example \"mis\".\n",
        "        variable_type: Type of all variables, either \"spin\" or \"binary\".\n",
        "\n",
        "    Returns:\n",
        "        The parsed problem, as a minimization without constraints.\n",
        "    \"\"\"\n",
        "    if isinstance(problem, OptimizationProblem):\n",
        "        return problem\n",
        "\n",
        "    if variable_type not in (\"spin\", \"binary\"):\n",
        "        raise ValueError(\n",
        "            f\"Invalid variable type {variable_type!r}, expected 'spin' or 'binary'.\"\n",
        "        )\n",
        "\n",
        "    constant: float = 0\n",
        "    linear_terms: dict[str, float] = {}\n",
        "    quadratic_terms: dict[tuple[str, str], float] = {}\n",
        "    variables: set[str] = set()\n",
        "\n",
        "    for raw_term, coefficient in problem.items():\n",
        "        try:\n",
        "            parsed = ast.literal_eval(raw_term)\n",
        "        except (ValueError, SyntaxError) as exc:\n",
        "            raise ValueError(\n",
        "                f\"Invalid problem term {raw_term!r}: expected a tuple literal like '(0, 1)'.\"\n",
        "            ) from exc\n",
        "        if not isinstance(parsed, tuple):\n",
        "            raise ValueError(\n",
        "                f\"Invalid problem term {raw_term!r}: expected a tuple literal like '(0, 1)'.\"\n",
        "            )\n",
        "        term = tuple(map(str, parsed))\n",
        "        if len(term) == 0:\n",
        "            constant = coefficient\n",
        "        elif len(term) == 1:\n",
        "            linear_terms[term[0]] = coefficient\n",
        "        elif len(term) == 2:\n",
        "            quadratic_terms[term] = coefficient\n",
        "        else:\n",
        "            raise ValueError(\n",
        "                \"Invalid problem term, only quadratic problems are \"\n",
        "                f\"supported, higher-order term: {term}\"\n",
        "            )\n",
        "        variables.update(term)\n",
        "\n",
        "    model = OptimizationProblem()\n",
        "    model.name = problem_type\n",
        "    for variable in sorted(variables):\n",
        "        if variable_type == \"spin\":\n",
        "            model.spin_var(variable)\n",
        "        else:\n",
        "            model.binary_var(variable)\n",
        "\n",
        "    model.minimize(\n",
        "        constant=constant, linear=linear_terms, quadratic=quadratic_terms\n",
        "    )\n",
        "    return model\n",
        "\n",
        "\n",
        "def _measure(\n",
        "    problem: dict[str, float] | OptimizationProblem, **kwargs: Any\n",
        ") -> dict[str, float]:\n",
        "    \"\"\"Return the number of variables and the interaction density.\"\"\"\n",
        "    model = to_optimization_problem(\n",
        "        problem,\n",
        "        problem_type=kwargs.get(\"problem_type\", \"\"),\n",
        "        variable_type=kwargs.get(\"variable_type\", \"binary\"),\n",
        "    )\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": "54740991",
      "metadata": {},
      "source": [
        "If the size is too small, the job fails with error `4600` and the message names the\n",
        "size to use instead. If it 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) to learn more.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e8837f5f",
      "metadata": {},
      "source": [
        "## Example\n",
        "\n",
        "The Parity Twine Optimizer can be applied to a simple QUBO example as follows. The problem is first defined by using a dictionary:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "d56e1440",
      "metadata": {},
      "outputs": [],
      "source": [
        "problem = {\"()\": 3.0, \"(2,)\": -1.0, \"(3,)\": 1.0, \"(4,)\": 1.0, \"(0, 1)\": 2.0}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "69ea92c9",
      "metadata": {},
      "source": [
        "Then, the variable type has to be defined as `binary` or `spin`:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "06fc4134",
      "metadata": {},
      "outputs": [],
      "source": [
        "variable_type = \"spin\""
      ]
    },
    {
      "cell_type": "markdown",
      "id": "03998691",
      "metadata": {},
      "source": [
        "This defines the objective function $3 - s_2 + s_3 + s_4 + 2 s_0s_1$ where $s_i \\in \\{-1, 1\\}$.\n",
        "\n",
        "Choose a backend. For example:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "856fe992",
      "metadata": {},
      "outputs": [],
      "source": [
        "backend_name = \"ibm_phoenix\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "aae75d8a",
      "metadata": {},
      "outputs": [],
      "source": [
        "size = calculate_function_size(problem)\n",
        "print(size)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "6f88b8ee-47a8-4c93-b25c-f4eceaf3dbf8",
      "metadata": {},
      "source": [
        "Use `catalog.backends()` to see a list of available backends from the user account/instance.\n",
        "\n",
        "If no backend is specified, the least-busy backend (the one with the least number of pending jobs) is automatically selected.\n",
        "\n",
        "Once the optimizer is loaded (see the previous section), you can run it on the problem using default options. This model needs function size `S` (see [Function sizes](#function-sizes)):\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "27558d79-01c1-4616-aec0-2a9623e0e9e1",
      "metadata": {},
      "outputs": [],
      "source": [
        "function_job = function.run(\n",
        "    problem=problem,\n",
        "    variable_type=variable_type,\n",
        "    backend_name=backend_name,\n",
        "    function_size=size,\n",
        ")\n",
        "print(f\"Job ID: {function_job.job_id}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c036d9c6a386323",
      "metadata": {},
      "source": [
        "Check the job status as follows:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "5c71411c8ac8271d",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Monitor the job status\n",
        "function_job.status()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "646bd940-80ad-4e79-b4e2-0db447edf41b",
      "metadata": {},
      "source": [
        "Retrieve results as follows:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "197d53b9-2b5e-44e5-99e3-0c285db903a9",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Retrieve the job result if the status is DONE\n",
        "result = function_job.result()\n",
        "\n",
        "result"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "bb1bba96-4689-4ddf-b72f-6c6e5cf2c3ba",
      "metadata": {},
      "source": [
        "Printing the results gives the following:\n",
        "\n",
        "```\n",
        "{\n",
        "    'solution': {'0': -1, '1': 1, '2': 1, '3': -1, '4': -1},\n",
        "    'objective_value': -2.0,\n",
        "    'solution_bitstring': '10011',\n",
        "    'metadata': {\n",
        "        'circuit_metrics': {\n",
        "            'depth': 14,\n",
        "            'gate_count': 161,\n",
        "            'two_qubit_gate_depth': 2,\n",
        "            'two_qubit_gate_count': 2,\n",
        "            'num_qubits': 5,\n",
        "            'operations': {'delay': 121, 'rz': 18, 'sx': 14, 'measure': 5, 'cz': 2, 'x': 1}\n",
        "        },\n",
        "        'solver_info': {\n",
        "            'variable_mapping': {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4},\n",
        "            'bitstring_distributions': {\n",
        "                'before_postprocessing': {'01011': 53621, ... },\n",
        "                'after_postprocessing': {'01011': 59534, '10011': 40466}\n",
        "            },\n",
        "            'best_parameters': {\n",
        "                'beta': [-0.4428884125402417],\n",
        "                'gamma': [9.483682763002278]\n",
        "            }\n",
        "        },\n",
        "        'resource_usage': {\n",
        "            'RUNNING: MAPPING': {'CPU_TIME': 44.128},\n",
        "            'RUNNING: OPTIMIZING_FOR_HARDWARE': {'CPU_TIME': 0.03},\n",
        "            'RUNNING: WAITING_FOR_QPU': {'CPU_TIME': 790.623},\n",
        "            'RUNNING: EXECUTING_QPU': {'QPU_TIME': 6.0},\n",
        "            'RUNNING: POST_PROCESSING': {'CPU_TIME': 0.738}\n",
        "        }\n",
        "    }\n",
        "}\n",
        "```\n",
        "\n",
        "The `solution` dictionary corresponds to the qubits defined in the problem ($s_0, s_1$, $s_2$, $s_3$ and $s_4$) and gives their optimized spin values.\n",
        "\n",
        "The `objective_value` is the cost or energy of the optimization problem. It quantifies the `solution` quality.\n",
        "\n",
        "`metadata` gives information on the transpilation (two-qubit gate counts/depth, gates used, active qubits) and various runtimes for both quantum and classical compute time.\n",
        "\n",
        "Additionally, `metadata` provides a glimpse into the internal workings of the algorithm. You can see the optimized variational parameters (beta and gamma) and review how the distribution of measured bitstrings improved after classical post-processing was applied to the raw quantum results.\n",
        "\n",
        "All bitstrings in the result output can be mapped to the problem variables by using the `variable_mapping`.\n",
        "For example, you can map the `'solution_bitstring': '10011'` with the `'variable_mapping': {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4}` to the binary solution: `{'0': 1, '1': 0, '2': 0, '3': 1, '4': 1}`.\n",
        "Since you are solving the problem in terms of spin variables, you need to apply the binary to spin transformation  (`0` -> `1`, `1` -> `-1` ).\n",
        "You then arrive at the final solution `'solution': {'0': -1, '1': 1, '2': 1, '3': -1, '4': -1}`.\n",
        "\n",
        "Refer to the [API reference](/docs/functions/parity-twine-optimizer/api-reference) for full details of the input to and output from the Parity Twine Optimizer function.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d7e2b64a",
      "metadata": {},
      "source": [
        "## Next steps\n",
        "\n",
        "<Admonition type=\"tip\" title=\"Recommendations\">\n",
        "  * Learn how to choose a [problem size](/docs/managed-workflows/managed-workflow-compute-profiles#match-sizes).\n",
        "  * Understand [resource units (RUs)](/docs/ibm-quantum-platform/plans-overview#rus).\n",
        "  * Review the [IBM Quantum Platform plans](/docs/ibm-quantum-platform/plans-overview).\n",
        "  * Visit the [API reference](/docs/functions/parity-twine-optimizer/api-reference) for this quantum function.\n",
        "  * Try the [Solve the market split problem with the ParityQC Parity Twine Optimizer](/docs/tutorials/parity-twine-optimizer-ms) tutorial.\n",
        "  * Try the [Solve the Sherrington-Kirkpatrick model with the ParityQC Parity Twine Optimizer](/docs/tutorials/parity-twine-optimizer-sk) tutorial.\n",
        "  * Review the [Connectivity-aware Synthesis of Quantum Algorithms, Drier et al. (2025)](https://arxiv.org/abs/2501.14020) ArXiv preprint.\n",
        "  * Review the [functions overview](/docs/guides/functions), includes cost per execution.\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
}