Get started with Q-CTRL Dynamics Simulator
See the overview and the API reference
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.
This guide uses a small one-dimensional Fermi-Hubbard example to show the complete workflow from defining the model to plotting the measured dynamics.
Set up and load the function
Find access information for this quantum function in the Quantum Functions Catalog.
This guide shows how to load the Dynamics Simulator and simulate a four-site Fermi-Hubbard chain. The following code assumes that you already saved your IBM Quantum Platform API key and instance CRN to your local environment.
For account setup and client installation instructions, see Set up functions.
from qiskit_ibm_catalog import FunctionsCatalog
catalog = FunctionsCatalog(channel="ibm_quantum_platform")# Access the Q-CTRL Dynamics Simulator quantum function.
sim_qf = catalog.load("q-ctrl/dynamics-simulator")# Check the list of backends you have access to
catalog.backends()Output:
[<IBMBackend('ibm_boston')>,
<IBMBackend('ibm_chicago')>,
<IBMBackend('ibm_fez')>,
<IBMBackend('ibm_kingston')>,
<IBMBackend('ibm_marrakesh')>,
<IBMBackend('ibm_phoenix')>,
<IBMBackend('ibm_pittsburgh')>]
# Select the backend you want to use
backend = catalog.backend("ibm_phoenix")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 for how sizes work in general.
Pass the size to sim_qf.run() with the function_size argument. For the Dynamics Simulator, the size depends on the number of qubits, Trotter steps, and observables.
Each lattice site requires two qubits. The number of Trotter steps is set by simulation["step_count"], and the number of observables is the number of entries in observables.
Size | Qubits | Trotter steps | Observables | Rule |
|---|---|---|---|---|
S | ≤ 20 | ≤ 10 | ≤ 20 | All three metrics must satisfy the Small limits. |
M | ≤ 50 | ≤ 20 | ≤ 50 | At least one metric exceeds its Small limit, but all three remain within the Medium limits. |
L | > 50 | > 20 | > 50 | Any single metric exceeds its Medium limit. |
Select the size required by the largest of the three requirements. For example, a simulation with 20 qubits, 30 Trotter steps, and 20 observables requires "L" because the number of Trotter steps exceeds the Medium limit.
Calculate the size before submitting
Use the following helper to calculate the size from the number of qubits, Trotter steps, and observables. It returns the smallest size that satisfies all three requirements. No job is submitted.
# Size calculator for the dynamics simulator function.
#
# Input: the function inputs ``simulation``, ``observables`` and ``initial_state``, as
# accepted by the function (JSON strings or decoded values). Other inputs, such as
# ``model``, do not affect the size and are ignored.
# This function has no single "problem" argument, so they may be passed either as
# keywords -- ``calculate_function_size(model=..., simulation=...)`` -- or as one dict in the
# ``problem`` position, which is what keeps the signature the same as every other
# vendor's: ``calculate_function_size({"model": ..., "simulation": ...})``.
# Output: ``"S"``, ``"M"`` or ``"L"``, from the number of qubits (twice the number of
# lattice sites), the number of Trotter steps and the number of observables.
#
# The size is the largest size demanded by any single metric: a run is only ``"S"`` if
# every metric fits ``"S"``, and only ``"M"`` if every metric fits ``"M"``.
import json
from collections.abc import Mapping
from typing import Any, Literal
from qiskit_serverless import (
ServerlessError,
get_function_size,
get_logger,
send_error,
)
Size = Literal["S", "M", "L"]
_ORDER = {"S": 0, "M": 1, "L": 2}
# Error codes assigned by IBM; see the IBM Quantum error registry.
SIZE_TOO_SMALL_ERROR_CODE = "4600"
SIZE_TOO_LARGE_ERROR_CODE = "4601"
# Inclusive upper bounds for each size.
_SMALL_QUBITS, _SMALL_STEPS, _SMALL_OBSERVABLES = 20, 10, 20
_MEDIUM_QUBITS, _MEDIUM_STEPS, _MEDIUM_OBSERVABLES = 50, 20, 50
# Each lattice site contributes a spin-up and a spin-down mode.
_QUBITS_PER_SITE = 2
def calculate_function_size(problem: Any = None, **kwargs: Any) -> Size:
"""Return the size ("S", "M" or "L") needed to run the dynamics simulator."""
metrics = _measure(problem, **kwargs)
if _is_small(metrics):
return "S"
if _is_medium(metrics):
return "M"
return "L"
def _measure(problem: Any = None, **kwargs: Any) -> dict[str, int]:
"""Return the number of qubits, Trotter steps and observables."""
arguments = (
{**problem, **kwargs} if isinstance(problem, Mapping) else kwargs
)
initial_state = arguments.get("initial_state")
simulation = _parse_json_argument(
arguments.get("simulation"), "simulation"
)
observables = _parse_json_argument(
arguments.get("observables"), "observables"
)
if not isinstance(initial_state, str) or not initial_state:
raise ValueError("initial_state must be a non-empty string.")
if not isinstance(simulation, Mapping) or not isinstance(
simulation.get("step_count"), int
):
raise ValueError(
"simulation must be a mapping with an integer step_count."
)
if not isinstance(observables, list):
raise ValueError("observables must be a list.")
return {
"qubits": _QUBITS_PER_SITE * len(initial_state),
"steps": simulation["step_count"],
"observables": len(observables),
}
def _parse_json_argument(value: Any, argument_name: str) -> Any:
"""Decode ``value`` if it is a JSON string; return anything else unchanged."""
if not isinstance(value, str):
return value
try:
return json.loads(value)
except json.JSONDecodeError as error:
raise ValueError(
f"{argument_name} must contain valid JSON."
) from error
def _is_small(metrics: dict[str, int]) -> bool:
"""Determine if the metrics fit T-size 'S'."""
return (
metrics["qubits"] <= _SMALL_QUBITS
and metrics["steps"] <= _SMALL_STEPS
and metrics["observables"] <= _SMALL_OBSERVABLES
)
def _is_medium(metrics: dict[str, int]) -> bool:
"""Determine if the metrics fit T-size 'M'."""
return (
metrics["qubits"] <= _MEDIUM_QUBITS
and metrics["steps"] <= _MEDIUM_STEPS
and metrics["observables"] <= _MEDIUM_OBSERVABLES
)
def validate_size(problem: Any = None, **kwargs: Any) -> None:
"""Call once at the start of your function. Compare the size the job was given with
the calculated size and log both. Raise if the given size is smaller than the calculation;
report a non-fatal event and continue if it is larger."""
logger = get_logger()
provided = get_function_size()
if not provided:
# Empty on non-Fleets (Ray) jobs, where sizes do not apply.
logger.warning(
"No function size was given to this job; skipping the size check."
)
return
provided = provided.upper()
expected = calculate_function_size(problem, **kwargs)
logger.info(
"Function size given: '%s'; calculated size: '%s'.",
provided,
expected,
)
if _ORDER[provided] < _ORDER[expected]:
logger.error(
"Size '%s' is too small; the calculated size is '%s'.",
provided,
expected,
)
raise ServerlessError(
code=SIZE_TOO_SMALL_ERROR_CODE,
message=f"Size '{provided}' is too small for this problem; expected '{expected}' or larger.",
)
if _ORDER[provided] > _ORDER[expected]:
logger.warning(
"Size '%s' is larger than this problem needs; the calculated size is '%s'.",
provided,
expected,
)
send_error(
code=SIZE_TOO_LARGE_ERROR_CODE,
message="The specified function size is larger than this job requires.",
exception="FunctionSizeTooLarge",
args={
"provided_size": provided,
"calculated_size": expected,
"solution": (
"No action is required and the job completed normally. To reduce "
"cost, use a smaller function size for jobs of this kind."
),
},
)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 to learn more.
Example: Simulate a four-site Fermi-Hubbard chain
Consider a four-site one-dimensional Fermi-Hubbard chain with hopping amplitude , no on-site interaction, and zero chemical potential. A single spin-up fermion begins at site 0 and evolves across the chain.
This small problem keeps the focus on the Dynamics Simulator workflow:
- Define the model and simulation.
- Define the initial state and observables.
- Submit the quantum function job.
- Retrieve the expectation values.
- Plot the dynamics.
1. Define the problem
site_count = 4
model = {
"hopping_amplitude": 1.0,
"on_site_interaction": 0.0,
"chemical_potential": 0.0,
}
simulation = {
"time_step": 0.2,
"step_count": 8,
}
initial_state = "eeeu"
observables = [
{
"operators": [[["Nup", site]]],
"coefficients": [1.0],
}
for site in range(site_count)
]
shot_count = 2048The observable list measures the spin-up occupation
at each site. The observables are returned in the same order in which they are supplied.
2. Run the dynamics simulation
Submit the problem through the quantum function. The Quantum Functions Catalog handles IBM Quantum authentication, so you don't pass separate Fire Opal or hardware-provider credentials to sim_qf.run(). Calculate the function size from the simulation inputs, as described in Function sizes, and pass the returned value through function_size. Each lattice site in initial_state requires two qubits, simulation["step_count"] gives the number of Trotter steps, and len(observables) gives the number of observables.
# Calculate the workload size
function_size = calculate_function_size(
initial_state=initial_state,
simulation=simulation,
observables=observables,
)
print(f"Workload size: {function_size}")Output:
Workload size: S
job = sim_qf.run(
model=model,
simulation=simulation,
observables=observables,
initial_state=initial_state,
shots=shot_count,
backend_name=backend.name,
function_size=function_size,
)print(job.job_id, job.status())Output:
68202fad-6919-425d-8fd2-c1c649cd15b1 DONE
The returned object is a quantum function job. You can keep the job ID to retrieve or inspect the workload later.
3. Retrieve the result
result = job.result()
print("Result keys:", sorted(result.keys()))
print("Warnings:", result.get("warnings", []))Output:
Result keys: ['metadata', 'observable_expectation_values', 'observables', 'warnings']
Warnings: []
Convert the observable expectation values to a NumPy array. Each row corresponds to one observable, and each column corresponds to a recorded simulation time, beginning at . For this example, the four rows contain the spin-up occupations of sites 0 through 3.
import numpy as np
expectation_values = np.asarray(
result["observable_expectation_values"],
dtype=float,
)
print("Expectation-value array shape:", expectation_values.shape)Output:
Expectation-value array shape: (4, 9)
4. Visualize the dynamics
The initial state contains one spin-up fermion and no spin-down fermions. Its evolution therefore remains in the single-particle subspace, whose four basis states correspond to the fermion occupying sites 0, 1, 2, and 3.
In this subspace, the Hamiltonian connects neighboring sites with hopping amplitude . For the parameters used here,
Diagonalize this matrix with NumPy and evolve the initial state at the same times that were returned by the Dynamics Simulator. The squared magnitude of each state amplitude gives the spin-up occupation of the corresponding site.
This calculation gives exact Hamiltonian evolution. Differences between the hardware estimates and this reference can include the finite Trotter step, measurement statistics, and residual hardware errors.
times = np.arange(expectation_values.shape[1]) * simulation["time_step"]
# This reference is specific to a single spin-up fermion.
if (
len(initial_state) != site_count
or initial_state.count("u") != 1
or initial_state.count("e") != site_count - 1
):
raise ValueError(
"This reference requires one spin-up fermion and otherwise empty sites."
)
# Build the Hamiltonian in the single-particle subspace.
hamiltonian = -model["hopping_amplitude"] * (
np.eye(site_count, k=1) + np.eye(site_count, k=-1)
)
hamiltonian -= model["chemical_potential"] * np.eye(site_count)
# The rightmost character of initial_state corresponds to site 0.
initial_amplitudes = np.zeros(site_count, dtype=complex)
initial_site = initial_state[::-1].index("u")
initial_amplitudes[initial_site] = 1.0
# Evolve the initial state in the Hamiltonian eigenbasis.
energies, eigenvectors = np.linalg.eigh(hamiltonian)
initial_coefficients = eigenvectors.conj().T @ initial_amplitudes
phases = np.exp(-1j * np.outer(energies, times))
states = eigenvectors @ (initial_coefficients[:, None] * phases)
ideal_expectation_values = np.abs(states) ** 2Plot one panel for each site. The solid curves show the exact reference at the recorded times, and the markers show the hardware estimates returned by the Dynamics Simulator.
import matplotlib.pyplot as plt
import qctrlvisualizer as qv
from qctrlvisualizer import QCTRL_STYLE_COLORS as colors
plt.style.use(qv.get_qctrl_style())
fig, ax = plt.subplots(figsize=(10, 6))
for site in range(len(expectation_values)):
site_color = colors[site % len(colors)]
ax.plot(
times,
ideal_expectation_values[site],
color=site_color,
linewidth=2,
label=f"Site {site}: exact reference",
)
ax.plot(
times,
expectation_values[site],
color=site_color,
linestyle="--",
linewidth=1.5,
marker="o",
markersize=5,
label=f"Site {site}: hardware estimate",
)
ax.set_xlim(times[0], times[-1])
ax.set_ylim(-0.05, 1.05)
ax.set_xlabel(r"Time (units of $\hbar/t_h$)")
ax.set_ylabel(r"$\langle n_{i\uparrow} \rangle$")
ax.set_title("Spin-up occupation dynamics")
ax.legend(
ncol=2,
fontsize=10,
loc="best",
)
fig.tight_layout()
plt.show()Output:
At , the exact spin-up occupation is 1 at site 0 and 0 at the other sites. As the system evolves, hopping spreads the particle's probability across the chain. The occupation of site 1 increases first, followed by increasing occupation at sites 2 and 3. For the parameters in this example, the final recorded time is . The exact occupations of sites 0 through 3 are approximately 0.026, 0.370, 0.392, and 0.211, respectively.
The exact occupations satisfy the following equation at every time, reflecting conservation of particle number:
Individual site occupations can rise and fall as the particle evolves through the finite chain.
Fetch error messages
If the workload enters the ERROR state, call job.result() to retrieve the error message. You can also inspect the function logs, if they are available.
print(job.status())
if job.status() == "ERROR":
print(job.result())
print(job.logs())Output:
DONE
Common input-validation issues include an unsupported model or simulation method, an initial-state string that is too long, mismatched observable terms and coefficients, or an observable that references a site outside the initial-state string.
Next steps
- Review the
simulate_dynamicsAPI reference for the underlying model, simulation, observable, output, and validation definitions. - Try the Spin and charge dynamics in the Fermi-Hubbard model tutorial.
- Visit the API reference for this quantum function.
- Modify the model parameters, initial state, time step, step count, and observables to study a different one-dimensional Fermi-Hubbard dynamics problem.
- Learn how to choose a problem size.