mqt.yaqs.simulator¶
High-level Simulator class for YAQS.
This module implements the common simulation routine for Hamiltonian (analog) and
circuit-based simulations as the public Simulator class. Analog evolution is
the primary mode supported by YAQS; circuit (strong/weak) simulation reuses the same
execution machinery.
The Simulator class owns the execution-side configuration (parallel vs.
serial execution, worker count, progress reporting, multiprocessing context, and
retry policy), while the physics inputs are passed to Simulator.run() as a
State and either a
Hamiltonian (analog) or a
QuantumCircuit (digital) together with a simulation
parameter object. Depending on the type of simulation parameters provided
(AnalogSimParams, StrongSimParams, or WeakSimParams), the simulation is
dispatched to the appropriate backend:
For analog simulations, a
Hamiltonianis validated and materialized for the selected state representation, then processed via the analog dispatch. Passing alist[State]triggers the deterministic unitary ensemble path.For circuit simulations, a
QuantumCircuitis used and processed via the circuit dispatch (strong for observables/trajectories, weak for measurement counts).
The module supports analog (TJM / MCWF / Lindblad / unitary ensemble) and digital (strong / weak) simulation, including functionality for:
Initializing the state (
State) to a canonical form (B normalized).Running trajectories with noise (using a provided
NoiseModel) and aggregating results.Parallel execution of trajectories using a
ProcessPoolExecutorwith progress reporting via tqdm.
Simulator.run() returns a Result
holding every simulation output (aggregated expectation values, per-trajectory data,
shared time grid, optional output state, measurement counts, and the sampled noise
model). The *SimParams object passed in is never mutated; Result.sim_params
references it unchanged.
Module Contents¶
- run_backend_parallel(worker_fn: Callable[[int], TRes], *, payload: dict[str, Any] | None, n_jobs: int, max_workers: int, show_progress: bool = True, desc: str, max_retries: int = 10, retry_exceptions: tuple[type[BaseException], Ellipsis] = (CancelledError, TimeoutError, OSError), mp_context: MPContext = 'auto') Iterator[tuple[int, TRes]][source]¶
Execute backend calls in parallel with bounded submission and retry logic.
This function manages the parallel execution of tasks using a
ProcessPoolExecutor, refactored to prevent task flooding and memory exhaustion:Worker-Global State: Uses
_worker_initto initialize large objects once per worker, avoiding per-task pickling overhead.Bounded In-Flight: Submits tasks in a queue-like manner, keeping only a limited number of futures active (
2 * max_workers) at any time.
- Parameters:
worker_fn – The worker function to execute. It must accept a single integer argument (the job index) and return a result of type TRes.
payload – A dictionary of large objects (e.g., State, NoiseModel) to be initialized in the global worker context. passed to _worker_init.
n_jobs – The total number of jobs to execute (indices 0 to n_jobs-1).
max_workers – The maximum number of worker processes to use.
show_progress – If True, displays a tqdm progress bar. Defaults to True.
desc – The description string for the progress bar.
max_retries – The maximum number of retry attempts for transient errors (e.g., TimeoutError). Defaults to 10.
retry_exceptions – A tuple of exception types that trigger a retry. Defaults to (CancelledError, TimeoutError, OSError).
mp_context – Multiprocessing context selector; see
get_parallel_context().
- Yields:
tuple[int, TRes] – A tuple containing the job index and its result, yielded in the order of completion.
- class Simulator(*, parallel: bool = True, max_workers: int | None = None, show_progress: bool = True, mp_context: MPContext = 'auto', max_retries: int = 10, retry_exceptions: tuple[type[BaseException], Ellipsis] = (CancelledError, TimeoutError, OSError))[source]¶
Public entry point for running YAQS simulations.
A
Simulatorowns the execution-side configuration: how trajectories are parallelized, how many workers to use, whether to display a progress bar, which multiprocessing context to use, and the retry policy for transient worker errors. The physics inputs (initial state, operator, simulation parameters, optional noise model) are passed per call torun().Multiple
run()calls share the same configuration. Each call constructs its own short-lived process pool whenparallel=True; the pool is not persisted across runs in the current implementation.- parallel¶
Whether to execute trajectories in parallel via a process pool.
- max_workers¶
Maximum number of worker processes when
parallel=True. Defaults tomax(1, available_cpus() - 1).
- show_progress¶
Whether to display a tqdm progress bar.
- mp_context¶
Multiprocessing context:
"auto"(default),"fork", or"spawn"."auto"selects"fork"on Linux and"spawn"elsewhere.
- max_retries¶
Maximum retry attempts for transient worker errors.
- retry_exceptions¶
Exception types that trigger a retry.
- parallel = True¶
- max_workers¶
- show_progress = True¶
- max_retries = 10¶
- retry_exceptions¶
- run(initial_state: State | list[State], operator: Hamiltonian | QuantumCircuit, sim_params: AnalogSimParams | StrongSimParams | WeakSimParams, noise_model: NoiseModel | None = None) Result[source]¶
Execute the common simulation routine for Hamiltonian (analog) and circuit simulations.
Dispatches the simulation to the appropriate backend based on the type of simulation parameters provided. For analog simulations, the
HamiltonianandStateare materialized for the active representation as needed (list[State]triggers the deterministic unitary ensemble path). For circuit-based simulations, the initialStatemust userepresentation="mps".- Parameters:
initial_state – The initial state as a
State, or a list of states for deterministic analog unitary ensemble evolution (AnalogSimParamsonly).operator –
Hamiltonianfor analog simulations or aQuantumCircuitfor circuit simulations.sim_params – Simulation parameters specifying the simulation mode and settings.
noise_model – The noise model to apply. If provided, it is sampled once at the beginning of the run to generate a concrete noise realization (static disorder). The sampled noise model is stored on the returned
Result.
- Returns:
A
Resultholding all simulation outputs. The suppliedsim_paramsis not mutated;Result.sim_paramsreferences the original configuration object.- Raises:
ValueError – If no output is specified (neither observables nor
get_state).TypeError – If the provided
initial_statetype is incompatible with the selected simulation mode.