Skip to main contentIBM Quantum Documentation Preview
This is a preview build of IBM Quantum® documentation. Refer to quantum.cloud.ibm.com/docs for the official documentation.

Get started with QUICK-PDE by ColibriTD

See the overview and the 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

Fill out the form to request access to the QUICK-PDE function. Then, assuming you've already saved your account to your local environment, select the function as follows. For login instructions, use the getting started guide.

from qiskit_ibm_catalog import FunctionsCatalog

catalog = FunctionsCatalog(
    channel="ibm_cloud / ibm_quantum_platform",
)

# Verify that you have access to the function
catalog.list()
quick = catalog.load("colibritd/quick-pde")

Plan sizes

The QUICK-PDE function is available in three plan sizes: Small, Medium, and Large. The following table gives the limits and the services of each size.

Size
Mode
Iterations max (all stages)
Shots max per job
Max qubits
Compute profile (vCPU x RAM Go)
SJob mode2510,000158x32
MJob mode5050,0003516x128
LSession modeUnlimited (up to session limit)100,000Unlimited (up to QPU limits)48x768

The maximum number of iterations applies to the sum of the iterations of all the stages of the optimizer chain.


Function sizes

The function runs with a compute size, "S", "M", or "L", which you set with the function_size argument of run. The size that your problem needs follows the limits of the plans:

  • The mode (the session mode requires the size "L")
  • The total number of iterations, which is the sum of the max_iter of all the stages of the optimizers chain
  • The maximum number of shots per job, which is the largest shot of the stages (more than 100,000 shots per job is not supported)
  • The maximum number of qubits, which is the number of qubits of the largest function

The size is the smallest one for which all these values stay within its limits. The onboarding and the support depend on your plan and are not part of the calculation. A problem above the limits of the size "M" is sized "L".

If the size you pass is smaller than the size that the problem needs, the job fails with the error code 4600. If it is larger, the job runs and reports an event with the error code 4601 to tell you that a smaller size can be used.

The following function calculates the size of a problem from the same arguments as run, without submitting anything. When optimizers or nb_qubits are omitted, the default values of the use case are used, as in run.

from typing import Any, Literal

Size = Literal["S", "M", "L"]


_SMALL = {"iterations": 25, "shots": 10_000, "qubits": 15}
_MEDIUM = {"iterations": 50, "shots": 50_000, "qubits": 35}
_MAX_SHOTS = 100_000

_MODES = ("job", "batch", "session")

_DEFAULT = {
    "CFD_EULER": {
        "nb_qubits": {"u": {"t": 2, "x": 2}, "g": {"t": 2, "x": 2}},
        "optimizers": [
            ("CMA", {"shot": 2500, "max_iter": 12}),
            ("CMA", {"shot": 4000, "max_iter": 18}),
            ("LS_TRF", {"shot": 10000, "max_iter": 30}),
        ],
    },
    "CFD_BURGER": {
        "nb_qubits": {"u": {"t": 2, "x": 2}},
        "optimizers": [
            ("CMA", {"shot": 3000, "max_iter": 40}),
            ("CMA", {"shot": 15000, "max_iter": 15}),
            ("CMA", {"shot": 50000, "max_iter": 10}),
        ],
    },
    "MD": {
        "nb_qubits": {"u": {"x": 3}, "sigma": {"x": 3}},
        "optimizers": [
            ("CMA", {"shot": 2500, "max_iter": 12}),
            ("CMA", {"shot": 4000, "max_iter": 18}),
            ("CMA", {"shot": 6000, "max_iter": 12}),
            ("LS_TRF", {"shot": 10000, "max_iter": 55}),
        ],
    },
    "BS_1A": {
        "nb_qubits": {"F_0": {"x_0": 3, "x_1": 3}},
        "optimizers": [
            ("CMA", {"shot": 5000, "max_iter": 12}),
            ("CMA", {"shot": 5000, "max_iter": 12}),
            ("LS_TRF", {"shot": 10000, "max_iter": 26}),
        ],
    },
    "BS_2A": {
        "nb_qubits": {"F_0": {"x_0": 3, "x_1": 2, "x_2": 2}},
        "optimizers": [
            ("CMA", {"shot": 5000, "max_iter": 12}),
            ("CMA", {"shot": 5000, "max_iter": 12}),
            ("LS_TRF", {"shot": 10000, "max_iter": 19}),
        ],
    },
    "BS_3A": {
        "nb_qubits": {"F_0": {"x_0": 3, "x_1": 2, "x_2": 2, "x_3": 2}},
        "optimizers": [
            ("CMA", {"shot": 5000, "max_iter": 18}),
            ("CMA", {"shot": 40000, "max_iter": 18}),
            ("LS_TRF", {"shot": 10000, "max_iter": 12}),
        ],
    },
}


def calculate_function_size(problem: Any, **kwargs: Any) -> Size:
    """Return the size ("S", "M" or "L") required to run the function."""
    metrics = _measure(problem, **kwargs)
    if _is_small(metrics):
        return "S"
    if _is_medium(metrics):
        return "M"
    return "L"


def _measure(problem: Any, **kwargs: Any) -> dict:
    """Reduce the problem to a dict of numbers that drives your resource usage."""
    args = (
        {**problem, **kwargs}
        if isinstance(problem, dict)
        else {**kwargs, "use_case": problem}
    )

    use_case = str(args.get("use_case") or "").upper()
    if use_case not in _DEFAULT:
        raise ValueError(
            f"cannot size use_case {args.get('use_case')!r}: expected one of {list(_DEFAULT)}"
        )

    mode = (
        "job"
        if args.get("run_local")
        else str(args.get("mode") or "job").lower()
    )
    if mode not in _MODES:
        raise ValueError(
            f"cannot size mode {args.get('mode')!r}: expected one of {list(_MODES)}"
        )

    optimizers = args.get("optimizers")
    if optimizers is None:
        optimizers = _DEFAULT[use_case]["optimizers"]
    if not isinstance(optimizers, (list, tuple)) or not optimizers:
        raise ValueError(
            "optimizers must be a non-empty list of (name, parameters) pairs"
        )
    iterations, shots = 0, 0
    for i, stage in enumerate(optimizers):
        if (
            not isinstance(stage, (list, tuple))
            or len(stage) != 2
            or not isinstance(stage[1], dict)
        ):
            raise ValueError(
                f"optimizers[{i}] must be a (name, parameters) pair"
            )
        options = {str(k).lower(): v for k, v in stage[1].items()}
        shot, max_iter = options.get("shot"), options.get("max_iter")
        if not shot or not max_iter:
            raise ValueError(
                f"optimizers[{i}] must give 'shot' and 'max_iter'"
            )
        iterations += int(max_iter)
        shots = max(shots, int(shot))
    if shots > _MAX_SHOTS:
        raise ValueError(
            f"shots per job ({shots}) exceeds the maximum of {_MAX_SHOTS}"
        )

    nb_qubits = args.get("nb_qubits")
    if nb_qubits is None:
        nb_qubits = _DEFAULT[use_case]["nb_qubits"]
    qubits = max(
        sum(int(q) for q in per_var.values())
        for per_var in nb_qubits.values()
    )

    return {
        "mode": mode,
        "iterations": iterations,
        "shots": shots,
        "qubits": qubits,
    }


def _is_small(metrics: dict) -> bool:
    """Determine if the metrics fit T-size 'S'."""
    return (
        metrics["mode"] != "session"
        and metrics["iterations"] <= _SMALL["iterations"]
        and metrics["shots"] <= _SMALL["shots"]
        and metrics["qubits"] <= _SMALL["qubits"]
    )


def _is_medium(metrics: dict) -> bool:
    """Determine if the metrics fit T-size 'M'."""
    return (
        metrics["mode"] != "session"
        and metrics["iterations"] <= _MEDIUM["iterations"]
        and metrics["shots"] <= _MEDIUM["shots"]
        and metrics["qubits"] <= _MEDIUM["qubits"]
    )

For example, a basket of three assets with a chain of three stages needs a total of 40 iterations and up to 20,000 shots, so it fits size "M":

optimizers = [
    ("CMA", {"shot": 5000, "max_iter": 20, "sigma": 0.3}),
    ("CMA", {"shot": 20000, "max_iter": 10, "sigma": 0.1}),
    ("LS_TRF", {"shot": 10000, "max_iter": 10, "psr": True}),
]

size = calculate_function_size("BS_3A", optimizers=optimizers)
print(size)

Then pass the size to run:

job = quick.run(
    use_case="BS_3A",
    physical_parameters={...},
    optimizers=optimizers,
    function_size=size,
)

Examples

To get started, try one of the following examples:

Inviscid Burgers' equation (CFD)

For Burgers' equation, when initial conditions are set to u(0,x)=xu(0,x) = x, the results are as follows:

use_case = "CFD_BURGER"
optimizers = [("CMA", {"shot": 5000, "max_iter": 20, "sigma": 0.3})]

size = calculate_function_size(use_case, optimizers=optimizers)
print(size)

# launch the simulation with initial conditions u(0,x) = a*x + b

job = quick.run(
    use_case=use_case,
    optimizers=optimizers,
    physical_parameters={"a": 1.0, "b": 0.0},
    function_size=size,
)

Check your quantum function workload's status or return results as follows:

# Print the ID so you can use it later, if necessary
print(job.job_id)
solution = job.result()
import numpy as np
import matplotlib.pyplot as plt


def plot_result_3d(result):
    fig = plt.figure()
    ax = fig.add_subplot(projection="3d")

    t, x = np.meshgrid(result["samples"]["t"], result["samples"]["x"])

    ax.plot_surface(
        t,
        x,
        result["functions"]["u"],
        edgecolor="royalblue",
        lw=0.25,
        rstride=26,
        cstride=26,
        alpha=0.3,
    )
    ax.scatter(t, x, result["functions"]["u"], marker=".")
    ax.set(xlabel="t", ylabel="x", zlabel="u(t,x)")

    plt.show()


# Call
plot_result_3d(solution)

Pressureless Euler's equation (CFD)

For Euler's equation, when initial conditions are set to g(0,x)=e−xg(0, x) = e^{-x} and u(0,x)=xu(0, x) = x, for a given μ\mu (here, μ=0.1\mu = 0.1) and λ=1\lambda = 1, the results are as follows:

use_case = "CFD_EULER"
optimizers = [("CMA", {"shot": 5000, "max_iter": 20, "sigma": 0.3})]

size = calculate_function_size(use_case, optimizers=optimizers)
print(size)

# Launches the solving for an arbitrary mu

job = quick.run(
    use_case=use_case,
    optimizers=optimizers,
    physical_parameters={"mu": 0.1},
    function_size=size,
)
solution = job.result()
# Colorplot function
def plot_result_2d(result):
    fig, axes = plt.subplots(1, 2, figsize=(14, 5))

    configs = {
        "g": {"cmap": "viridis", "title": "g(t, x)"},
        "u": {"cmap": "plasma", "title": "u(t, x)"},
    }

    t = result["samples"]["t"]
    x = result["samples"]["x"]

    for ax, (field, cfg) in zip(axes, configs.items()):
        v = result["functions"][field]

        im = ax.contourf(t, x, v, levels=50, cmap=cfg["cmap"])
        fig.colorbar(im, ax=ax, label=cfg["title"])

        ax.set_xlabel("t")
        ax.set_ylabel("x")
        ax.set_title(cfg["title"], fontsize=13, fontweight="bold")

    plt.tight_layout()
    plt.show()


plot_result_2d(solution)

Material deformation

The material deformation use case requires the physical parameters of your material and the applied force, as follows:

use_case = "MD"
optimizers = [("CMA", {"shot": 5000, "max_iter": 20, "sigma": 0.3})]

size = calculate_function_size(use_case, optimizers=optimizers)
print(size)

# Select the properties of your material
job = quick.run(
    use_case=use_case,
    optimizers=optimizers,
    physical_parameters={
        "t": 12.0,
        "K": 100.0,
        "n": 4.0,
        "b": 10.0,
        "epsilon_0": 0.1,
        "sigma_0": 5.0,
    },
    function_size=size,
)
# Plot the result
solution = job.result()
# Plot the result
_ = plt.figure()
stress_plot = plt.subplot(211)
plt.plot(solution["samples"]["x"], solution["functions"]["u"])
strain_plot = plt.subplot(212)
plt.plot(solution["samples"]["x"], solution["functions"]["sigma"])

plt.show()

Black-Scholes equation (quantitative finance)

The Black-Scholes use cases take the volatility of the asset or assets, and the option strike. For a single asset with a volatility σ=0.3\sigma = 0.3 and a strike K=1.2K = 1.2, the results are as follows:

use_case = "BS_1A"
optimizers = [("CMA", {"shot": 5000, "max_iter": 20, "sigma": 0.3})]

size = calculate_function_size(use_case, optimizers=optimizers)
print(size)

# Select the volatility & strike

job = quick.run(
    use_case=use_case,
    optimizers=optimizers,
    physical_parameters={"sigma": 0.3, "K": 1.2},
    function_size=size,
)

solution = job.result()

Compare the solution with the analytical price, and compute the RMSE on the sampled points (the price of the asset is S=1+xS = 1 + x):

from scipy.stats import norm


def black_scholes_call(t, S, sigma, K, T=1.0):
    tau = T - t
    d1 = (np.log(S / K) + 0.5 * sigma**2 * tau) / (sigma * np.sqrt(tau))
    d2 = d1 - sigma * np.sqrt(tau)
    return S * norm.cdf(d1) - K * norm.cdf(d2)


params = solution["arguments"].get("physical_parameters") or {
    "sigma": 0.15,
    "K": 1.4,
}
params = {k.lower(): v for k, v in params.items()}

t, x = np.meshgrid(
    solution["samples"]["x_0"], solution["samples"]["x_1"], indexing="ij"
)
S = 1 + x
reference = black_scholes_call(t, S, sigma=params["sigma"], K=params["k"])

F = np.asarray(solution["functions"]["F_0"])
rmse = np.sqrt(np.mean((F - reference) ** 2))
print(f"RMSE: {rmse:.4f}")
t_grid = np.asarray(solution["samples"]["x_0"])
x_grid = np.asarray(solution["samples"]["x_1"])

n_times = 5
indices = np.unique(
    np.linspace(0, len(t_grid) - 1, n_times).round().astype(int)
)
blues = ["#86b6ef", "#5598e7", "#2a78d6", "#1c5cab", "#0d366b"]
colors = [
    blues[i]
    for i in np.linspace(0, len(blues) - 1, len(indices)).round().astype(int)
]

fig, ax = plt.subplots(figsize=(8, 5))
for color, i in zip(colors, indices):
    ax.plot(
        x_grid,
        F[i],
        color=color,
        lw=2,
        marker="o",
        ms=4,
        label=f"t = {t_grid[i]:.2f}",
    )
    ax.plot(x_grid, reference[i], color=color, lw=1.5, ls="--")

ax.plot([], [], color="0.4", lw=2, marker="o", ms=4, label="Quantum Function")
ax.plot([], [], color="0.4", lw=1.5, ls="--", label="Reference")

ax.set_title(f"Black-Scholes 1D : F(t, x)   (RMSE = {rmse:.4f})")
ax.set_xlabel("x")
ax.set_ylabel("F(t, x)")
ax.grid(color="0.9", lw=0.8)
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False)
plt.show()

For a basket of two assets, set the volatility of each asset, the weight w1w_1 of the first asset (the weight of the second one is 1−w11 - w_1), and the correlation ρ\rho between the two assets. The following also selects the high-expressivity ansatz:

use_case = "BS_2A"
optimizers = [
    ("CMA", {"shot": 5000, "max_iter": 20, "sigma": 0.3}),
    ("LS_TRF", {"shot": 10000, "max_iter": 10, "psr": True}),
]

size = calculate_function_size(use_case, optimizers=optimizers)
print(size)

# Select the volatilities, weights, correlation & strike of the basket

job = quick.run(
    use_case=use_case,
    optimizers=optimizers,
    physical_parameters={
        "sigmas": (0.3, 0.38),
        "weights": (0.6, 0.4),
        "rho": 0.6,
        "K": 1.35,
    },
    ansatz="BPM High",
    size=size,
)

solution = job.result()
t_grid = np.asarray(solution["samples"]["x_0"])
x1 = np.asarray(solution["samples"]["x_1"])
x2 = np.asarray(solution["samples"]["x_2"])
F = np.asarray(solution["functions"]["F_0"])
assert F.shape == (len(t_grid), len(x1), len(x2)), F.shape

time = 0.0
i = int(np.abs(t_grid - time).argmin())

X1, X2 = np.meshgrid(x1, x2, indexing="ij")

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(projection="3d")
surface = ax.plot_surface(
    X1, X2, F[i], cmap="viridis", edgecolor="none", alpha=0.95
)
fig.colorbar(surface, ax=ax, shrink=0.6, pad=0.1, label="F")

ax.set_xlabel("Asset 1 (x_1)")
ax.set_ylabel("Asset 2 (x_2)")
ax.set_zlabel("F")
ax.set_title(f"Black-Scholes 2D : F à t = {t_grid[i]:.2f}")
plt.show()

For a basket of three assets, the weights of the first two assets are given and the weight of the third one is 1−w1−w21 - w_1 - w_2. The correlations are given pair by pair. The following selects the low-expressivity ansatz and configures the optimizer chain: two CMAES stages with an increasing number of shots and a decreasing sigma0, followed by a LS-TRF stage with the parameter-shift rule.

use_case = "BS_3A"
optimizers = [
    ("CMA", {"shot": 5000, "max_iter": 40, "sigma": 0.3}),
    ("CMA", {"shot": 40000, "max_iter": 20, "sigma": 0.12}),
    ("LS_TRF", {"shot": 10000, "max_iter": 10, "psr": True}),
]

size = calculate_function_size(use_case, optimizers=optimizers)
print(size)

# Select the volatilities, weights, correlations & strike of the basket

job = quick.run(
    use_case=use_case,
    optimizers=optimizers,
    physical_parameters={
        "sigmas": (0.3, 0.2, 0.25),
        "weights": (0.25, 0.35, 0.40),
        "rho12": 0.6,
        "rho13": 0.6,
        "rho23": 0.6,
        "K": 1.2,
    },
    ansatz="BPM High",
    size=size,
)

solution = job.result()
# Plot the result
t_grid = np.asarray(solution["samples"]["x_0"])
x1 = np.asarray(solution["samples"]["x_1"])
x2 = np.asarray(solution["samples"]["x_2"])
x3 = np.asarray(solution["samples"]["x_3"])
F = np.asarray(solution["functions"]["F_0"])
assert F.shape == (len(t_grid), len(x1), len(x2), len(x3)), F.shape

time = 0.0
i = int(np.abs(t_grid - time).argmin())

X1, X2, X3 = np.meshgrid(x1, x2, x3, indexing="ij")

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(projection="3d")
points = ax.scatter(
    X1.ravel(),
    X2.ravel(),
    X3.ravel(),
    c=F[i].ravel(),
    cmap="viridis",
    s=60,
    depthshade=False,
)
fig.colorbar(points, ax=ax, shrink=0.6, pad=0.1, label="F")

ax.set_xlabel("Asset 1 (x_1)")
ax.set_ylabel("Asset 2 (x_2)")
ax.set_zlabel("Asset 3 (x_3)")
ax.set_title(f"Black-Scholes 3D : F at t = {t_grid[i]:.2f}")
plt.show()

Fetch error messages

If your workload status is ERROR, use job.error_message() to fetch the error message to help debug, as follows:

job = quick.run(
    use_case="MD",
    physical_parameters={
        "t": 12.0,
        "K": 100.0,
        "n": 4.0,
        "b": 10.0,
        "epsilon_0": 0.1,
        "sigma_0": 5.0,
    },
    domain_data={"t": 10},
    run_local=True,
)
print(job.error_message())


# A wrapper can also be used for a more human readable version
def pprint_error(job):
    print("".join(eval(job.error_message())["error"]))


print("___")
pprint_error(job)

Next steps

Recommendations