---
title: Get started with Parity Twine Optimizer by ParityQC
description: Load the Parity Twine Optimizer function, choose a function size, and solve a QUBO problem on IBM Quantum hardware.
source: https://quantum.cloud.ibm.com/docs/en/functions/parity-twine-optimizer/get-started
---

# Get started with Parity Twine Optimizer by ParityQC

*See the [overview](/docs/functions/parity-twine-optimizer) and the [API reference](/docs/functions/parity-twine-optimizer/api-reference)*

> **Note**
>
> 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.

## Set up and load the function

Authenticate using your [IBM Quantum Platform API token](/docs/ibm-quantum-platform/functions-get-started) and select the quantum function as:

```python
from qiskit_ibm_catalog import FunctionsCatalog

# Authenticate and load the quantum function
catalog = FunctionsCatalog(
    channel="ibm_quantum_platform",
)
function = catalog.load("parityqc/parity-twine-optimizer")
```

## Function sizes

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.

The size comes from two properties of your model: how many variables it has, and
how densely they interact, that is, the fraction of all variable pairs that appear together
in a term of the objective or of a constraint.

| Size | Smallest size for variables and interaction density | Compute profile | vCPU | RAM    |
| ---- | --------------------------------------------------- | --------------- | ---- | ------ |
| `S`  | At most 50 variables and density at most 0.1        | `8x32`          | 8    | 32 GB  |
| `M`  | At most 100 variables and density at most 0.25      | `16x128`        | 16   | 128 GB |
| `L`  | Either above the `M` bound                          | `16x128`        | 16   | 128 GB |

A model must fit **both** bounds of a size, which is why a small but tightly coupled
model can be `L`: ten variables all coupled to each other is a density of 1.0. These
are the same bounds for every optimization function, so a size means the same
difficulty of model whichever one you call.

Two things raise the density more than they appear to:

- **A term over more than two variables couples every pair of them.** A term in
  four variables contributes all six pairs.
- **A constraint counts as the penalty that replaces it on hardware.** Squaring the
  constraint couples every pair of variables in it, so a one-hot constraint over
  four variables also contributes all six pairs.

The default is `M`, used when a job does not request a size.

You can also read the mapping from the function itself with `function.sizes_map`, and the default size with `function.default_size`.

For the Parity Twine Optimizer, every variable that appears in `problem` counts once,
and every quadratic term such as `"(0, 1)"` contributes one pair. The model in the
[example](#example) has five variables and one of the ten possible pairs, a density
of 0.1, so it needs `S`. Fully connected models, such as the
[Sherrington-Kirkpatrick model](/docs/tutorials/parity-twine-optimizer-sk) or the QUBO
form of the [market split problem](/docs/tutorials/parity-twine-optimizer-ms), have a
density of 1.0 and always need `L`.

### Calculate the size before submitting

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.

```python
# Calculate the function size a model needs, before submitting it.
# Call ``calculate_function_size(problem)``: it returns "S", "M" or "L" and submits
# nothing. The size comes from the number of variables and how densely they interact.


import ast

from collections.abc import Iterator
from itertools import combinations
from typing import Any, Literal

from qiskit_addon_opt_mapper.problems import OptimizationProblem

Size = Literal["S", "M", "L"]
VariableType = Literal["spin", "binary"]
_ORDER = {"S": 0, "M": 1, "L": 2}

# Limits are provided by IBM
_SMALL_NUMVARS, _SMALL_DENSITY = 50, 0.1
_MEDIUM_NUMVARS, _MEDIUM_DENSITY = 100, 0.25


def calculate_function_size(
    problem: dict[str, float] | OptimizationProblem, **kwargs: Any
) -> Size:
    """Return the size ("S", "M" or "L") needed to run ``problem``."""
    metrics = _measure(problem, **kwargs)
    if _is_small(metrics):
        return "S"
    if _is_medium(metrics):
        return "M"
    return "L"


def to_optimization_problem(
    problem: dict[str, float] | OptimizationProblem,
    problem_type: str = "",
    variable_type: VariableType = "binary",
) -> OptimizationProblem:
    """Convert the Parity Twine Optimizer ``problem`` input into an
    ``OptimizationProblem``.

    Args:
        problem: A dictionary {term: coefficient} where each term is a string
            version of a tuple of variable ids, for example
            {"()": 3, "(0,)": 1, "(0, 1)": 2}. An ``OptimizationProblem`` is
            returned unchanged.
        problem_type: The ``problem_type`` passed to the function, for
            example "mis".
        variable_type: Type of all variables, either "spin" or "binary".

    Returns:
        The parsed problem, as a minimization without constraints.
    """
    if isinstance(problem, OptimizationProblem):
        return problem

    if variable_type not in ("spin", "binary"):
        raise ValueError(
            f"Invalid variable type {variable_type!r}, expected 'spin' or 'binary'."
        )

    constant: float = 0
    linear_terms: dict[str, float] = {}
    quadratic_terms: dict[tuple[str, str], float] = {}
    variables: set[str] = set()

    for raw_term, coefficient in problem.items():
        try:
            parsed = ast.literal_eval(raw_term)
        except (ValueError, SyntaxError) as exc:
            raise ValueError(
                f"Invalid problem term {raw_term!r}: expected a tuple literal like '(0, 1)'."
            ) from exc
        if not isinstance(parsed, tuple):
            raise ValueError(
                f"Invalid problem term {raw_term!r}: expected a tuple literal like '(0, 1)'."
            )
        term = tuple(map(str, parsed))
        if len(term) == 0:
            constant = coefficient
        elif len(term) == 1:
            linear_terms[term[0]] = coefficient
        elif len(term) == 2:
            quadratic_terms[term] = coefficient
        else:
            raise ValueError(
                "Invalid problem term, only quadratic problems are "
                f"supported, higher-order term: {term}"
            )
        variables.update(term)

    model = OptimizationProblem()
    model.name = problem_type
    for variable in sorted(variables):
        if variable_type == "spin":
            model.spin_var(variable)
        else:
            model.binary_var(variable)

    model.minimize(
        constant=constant, linear=linear_terms, quadratic=quadratic_terms
    )
    return model


def _measure(
    problem: dict[str, float] | OptimizationProblem, **kwargs: Any
) -> dict[str, float]:
    """Return the number of variables and the interaction density."""
    model = to_optimization_problem(
        problem,
        problem_type=kwargs.get("problem_type", ""),
        variable_type=kwargs.get("variable_type", "binary"),
    )
    num_vars = model.get_num_vars()

    pairs = set()
    for term in _interactions(model):
        pairs.update(frozenset(pair) for pair in combinations(set(term), 2))

    max_pairs = num_vars * (num_vars - 1) // 2
    return {
        "num_vars": num_vars,
        "density": len(pairs) / max_pairs if max_pairs else 0.0,
    }


def _interactions(problem: OptimizationProblem) -> Iterator[tuple[int, ...]]:
    """Yield the variables of every term that couples two or more of them.

    A constraint contributes every variable in it, because on hardware it becomes
    a penalty whose square couples them all.
    """
    objective = problem.objective
    yield from objective.quadratic.to_dict()
    for expression in objective.higher_order.values():
        yield from expression.to_dict()

    for constraint in problem.linear_constraints:
        yield _constraint_support(constraint)
    for constraint in problem.quadratic_constraints:
        yield _constraint_support(constraint)
    for constraint in problem.higher_order_constraints:
        yield _constraint_support(constraint)


def _constraint_support(constraint: Any) -> tuple[int, ...]:
    """Return every variable appearing in a constraint's left-hand side."""
    variables = set(constraint.linear.to_dict())
    if hasattr(constraint, "quadratic"):
        for term in constraint.quadratic.to_dict():
            variables.update(term)
    if hasattr(constraint, "higher_order"):
        for expression in constraint.higher_order.values():
            for term in expression.to_dict():
                variables.update(term)
    return tuple(variables)


def _is_small(metrics: dict[str, float]) -> bool:
    """Determine if the metrics fit T-size 'S'."""
    return (
        metrics["num_vars"] <= _SMALL_NUMVARS
        and metrics["density"] <= _SMALL_DENSITY
    )


def _is_medium(metrics: dict[str, float]) -> bool:
    """Determine if the metrics fit T-size 'M'."""
    return (
        metrics["num_vars"] <= _MEDIUM_NUMVARS
        and metrics["density"] <= _MEDIUM_DENSITY
    )
```

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.

## Example

The Parity Twine Optimizer can be applied to a simple QUBO example as follows. The problem is first defined by using a dictionary:

```python
problem = {"()": 3.0, "(2,)": -1.0, "(3,)": 1.0, "(4,)": 1.0, "(0, 1)": 2.0}
```

Then, the variable type has to be defined as `binary` or `spin`:

```python
variable_type = "spin"
```

This defines the objective function $3 - s_2 + s_3 + s_4 + 2 s_0s_1$ where $s_i \in \{-1, 1\}$.

Choose a backend. For example:

```python
backend_name = "ibm_phoenix"
```

```python
size = calculate_function_size(problem)
print(size)
```

Use `catalog.backends()` to see a list of available backends from the user account/instance.

If no backend is specified, the least-busy backend (the one with the least number of pending jobs) is automatically selected.

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)):

```python
function_job = function.run(
    problem=problem,
    variable_type=variable_type,
    backend_name=backend_name,
    function_size=size,
)
print(f"Job ID: {function_job.job_id}")
```

Check the job status as follows:

```python
# Monitor the job status
function_job.status()
```

Retrieve results as follows:

```python
# Retrieve the job result if the status is DONE
result = function_job.result()

result
```

Printing the results gives the following:

```
{
    'solution': {'0': -1, '1': 1, '2': 1, '3': -1, '4': -1},
    'objective_value': -2.0,
    'solution_bitstring': '10011',
    'metadata': {
        'circuit_metrics': {
            'depth': 14,
            'gate_count': 161,
            'two_qubit_gate_depth': 2,
            'two_qubit_gate_count': 2,
            'num_qubits': 5,
            'operations': {'delay': 121, 'rz': 18, 'sx': 14, 'measure': 5, 'cz': 2, 'x': 1}
        },
        'solver_info': {
            'variable_mapping': {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4},
            'bitstring_distributions': {
                'before_postprocessing': {'01011': 53621, ... },
                'after_postprocessing': {'01011': 59534, '10011': 40466}
            },
            'best_parameters': {
                'beta': [-0.4428884125402417],
                'gamma': [9.483682763002278]
            }
        },
        'resource_usage': {
            'RUNNING: MAPPING': {'CPU_TIME': 44.128},
            'RUNNING: OPTIMIZING_FOR_HARDWARE': {'CPU_TIME': 0.03},
            'RUNNING: WAITING_FOR_QPU': {'CPU_TIME': 790.623},
            'RUNNING: EXECUTING_QPU': {'QPU_TIME': 6.0},
            'RUNNING: POST_PROCESSING': {'CPU_TIME': 0.738}
        }
    }
}
```

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.

The `objective_value` is the cost or energy of the optimization problem. It quantifies the `solution` quality.

`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.

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.

All bitstrings in the result output can be mapped to the problem variables by using the `variable_mapping`.
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}`.
Since you are solving the problem in terms of spin variables, you need to apply the binary to spin transformation  (`0` -> `1`, `1` -> `-1` ).
You then arrive at the final solution `'solution': {'0': -1, '1': 1, '2': 1, '3': -1, '4': -1}`.

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.

## Next steps

> **Recommendations**
>
> - Learn how to choose a [problem size](/docs/managed-workflows/managed-workflow-compute-profiles#match-sizes).
> - Understand [resource units (RUs)](/docs/ibm-quantum-platform/plans-overview#rus).
> - Review the [IBM Quantum Platform plans](/docs/ibm-quantum-platform/plans-overview).
> - Visit the [API reference](/docs/functions/parity-twine-optimizer/api-reference) for this quantum function.
> - Try the [Solve the market split problem with the ParityQC Parity Twine Optimizer](/docs/tutorials/parity-twine-optimizer-ms) tutorial.
> - Try the [Solve the Sherrington-Kirkpatrick model with the ParityQC Parity Twine Optimizer](/docs/tutorials/parity-twine-optimizer-sk) tutorial.
> - Review the [Connectivity-aware Synthesis of Quantum Algorithms, Drier et al. (2025)](https://arxiv.org/abs/2501.14020) ArXiv preprint.
> - Review the [functions overview](/docs/guides/functions), includes cost per execution.
