simulators
¶
Quantum simulator implementations.
SimulationJob
¶
Handle for a simulate() call running on a worker thread.
completed_steps and total_steps stay None until the backend
reports time points. QuTiP does not report them.
Attributes:
-
status(SimulationStatus) –pending,running,succeeded, orfailed. -
completed_steps(int | None) –Finished time points, or
Noneif this backend does not report them. -
total_steps(int | None) –Time points this run will report, or
None.
Source code in shadowsim/simulators/job.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | |
completed_steps
property
¶
Return how many time points have finished, or None.
total_steps
property
¶
Return how many time points this run reports, or None.
__init__
¶
__init__(simulator: Simulator) -> None
Bind a job to simulator without starting it.
Source code in shadowsim/simulators/job.py
result
¶
result(timeout: float | None = None) -> SimulationResult
Return the simulation result, waiting up to timeout seconds.
timeout=None waits until the job finishes. A finished successful
job returns its SimulationResult. A failed job raises the
exception from simulate().
Parameters:
-
timeout(float | None, default:None) –Seconds to wait.
Nonewaits until the job finishes.
Returns:
-
SimulationResult–The
SimulationResultfromsimulate().
Raises:
-
TimeoutError–The job is still pending or running when the wait ends.
-
Exception–Whatever
simulate()raised.
Source code in shadowsim/simulators/job.py
SimulationStatus
¶
Measurement
dataclass
¶
One number per time point, computed from the shot counts of chosen qubits.
expression may use numbers, parentheses, unary + and -,
+ - * / **, shots, and counts["01"]. A counts key has one
character per entry of qubits, in that order, so with qubits=(2, 0)
counts["10"] is the number of shots where qubit 2 read 1 and qubit 0 read 0.
A bitstring that was never observed is 0. shots is the total number of
shots at that time point. Values are floats, so ** cannot build an
unbounded integer.
The counts must come from a run in the basis this expression assumes. A Measurement does not change or check that basis.
An expectation backend has no counts. :func:apply_measurements then reads
a one-qubit expression from that qubit's distribution: counts["0"] is
(1 + expectation) / 2, counts["1"] is (1 - expectation) / 2, and
shots is 1. Dividing by shots gives the infinite-shot value. An
expression that uses raw counts without shots reads those probabilities.
Attributes:
-
qubits(tuple[int, ...]) –System qubit indexes, in the order a
countskey lists them. -
expression(str) –Arithmetic on
countsandshots. -
label(str) –Name of the resulting curve. Defaults to
expression.
Examples:
Probability that qubits 0 and 1 agree:
from shadowsim.simulators import Measurement
same = Measurement((0, 1), '(counts["00"] + counts["11"]) / shots')
print(same.evaluate({"000": 6, "110": 2, "011": 2}))
Source code in shadowsim/simulators/reducers.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | |
__post_init__
¶
Check qubits and parse expression.
Raises:
-
ValueError–qubitsis empty, repeats an index, or holds something other than non-negative integers, orexpressionis not allowed.
Source code in shadowsim/simulators/reducers.py
evaluate
¶
Return this measurement on one time point's counts.
Parameters:
-
counts(dict[str, int]) –Bitstring to shot count, where bit
iof a key is system qubiti.
Raises:
-
ValueError–A key is too short for
qubits, the expression divides by zero or overflows, or the result is not a finite real number.
Source code in shadowsim/simulators/reducers.py
SimulationResult
dataclass
¶
Outputs from a simulator simulate() / run() call.
Attributes:
-
times(NDArray[float64]) –Simulation time grid.
-
observables(list[NDArray[float64]]) –One expectation trajectory per measured observable / group.
-
states(list[ndarray] | None) –Optional state trajectory (
Nonewhen the backend does not store states). -
seed(int | None) –Random seed used for the run, if any.
-
algorithm(str) –Backend identifier (typically the simulator
id). -
runtime(float | None) –Wall-clock seconds for the
simulate()call, if recorded. -
metadata(dict[str, Any]) –Reproducibility and parameter metadata (version, params, …).
-
counts(list[dict[str, int]] | None) –One shot-count dict per entry of
times(Nonewhen the backend does not sample). Bitiof a key is system qubiti.
Source code in shadowsim/simulators/result.py
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | |
save
¶
Write this result to a directory as numeric arrays plus meta.json.
Layout::
path/
times.npy
observables.npz
states.npz # only when ``states`` is not None
counts.json # only when ``counts`` is not None
meta.json
Traces and states keep their shapes, including jagged traces. Archives
contain only numeric arrays, so load can read them with
allow_pickle=False.
Source code in shadowsim/simulators/result.py
load
classmethod
¶
load(path: str | Path) -> SimulationResult
Reload a result previously written by save.
Array files are read with allow_pickle=False. A numeric
observables.npy from an older save still loads. Object-dtype arrays
and other pickle payloads are rejected and not executed. states.npy
from an older save is refused, because that file was an object array.
Source code in shadowsim/simulators/result.py
Simulator
¶
Base class for quantum simulation backends.
Source code in shadowsim/simulators/simulator.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | |
__init__
¶
__init__(
hamiltonians: Sequence[Hamiltonian],
lindblads: Sequence[Operator],
initial_state: State,
*,
num_qubits: int,
total_time: float,
time_steps: int,
id: str,
) -> None
Initialize the shared simulator fields and time grid.
Source code in shadowsim/simulators/simulator.py
run
¶
run() -> SimulationResult
simulate
¶
simulate() -> SimulationResult
start
¶
start() -> SimulationJob
Run simulate() on a worker thread and return a job handle.
The handle comes back while that call is still in progress. simulate()
and run() stay synchronous and keep their current return values.
Split J and Trotter record finished time points on completed_steps
and total_steps. QuTiP leaves both None.
Returns:
-
SimulationJob–A job that moves from pending to running, then to succeeded or failed.
Raises:
-
RuntimeError–This simulator already has a pending or running job.
Source code in shadowsim/simulators/simulator.py
measure
¶
measure(
measurements: Sequence[Measurement],
) -> SimulationResult
Read measurements from the last simulate() and make them the results.
results, last_result, plots, and benchmarks then show one curve
per measurement. Each call reads the simulated result again, so a second
call replaces the first.
Raises:
-
ValueError–Nothing has been simulated yet, or a measurement cannot be read from the result (see :func:
apply_measurements).
Source code in shadowsim/simulators/simulator.py
get_results
¶
Return simulation results, optionally for one observable index.
Source code in shadowsim/simulators/simulator.py
plot_results
¶
plot_results(
indices: list[int] | None = None,
*,
labels: list[str] | None = None,
title: str | None = None,
) -> None
Plot expectation traces vs time in an interactive window.
Source code in shadowsim/simulators/simulator.py
save_result_plot
¶
save_result_plot(
indices: list[int] | None = None,
*,
dpi: float = 150,
labels: list[str] | None = None,
title: str | None = None,
output_dir: str | Path = "results",
) -> Path
Plot expectation traces vs tlist and save under output_dir.
Saves as {id}_{timestamp}.png (id is set per simulator subclass).
output_dir defaults to results/ and is created if it does not exist.
Does not open an interactive window.
Source code in shadowsim/simulators/simulator.py
__str__
¶
__repr__
¶
Return a string representation of the simulator.
Source code in shadowsim/simulators/simulator.py
HybridWMLSimulator
¶
Bases: ProductFormulaSimulator
Simulate open-system dynamics with hybrid wave-matrix Lindbladization.
Each of the num_steps samples one term. The weight of a Hamiltonian
eigenvalue λ is |λ|, and the weight of a Lindblad L is
||L||_F^2. Their sum is c. A sampled eigenvalue prepares its
eigenvector on a program register and applies exp(-i sgn(λ) SWAP Δ) on
that register and the term's qubits, with Δ = c t / num_steps, then
resets the program register. A sampled Lindblad applies
exp(-i J_L sqrt(τ)) on one ancilla and the Lindblad's qubits, with
τ = c t / (num_steps ||L||_F^2), then resets the ancilla. One seeded
sequence is frozen into the circuit and reused for every shot.
Counts come from circuit_backend. Omitting it uses Aer.
The shot count is that backend's shots attribute. Before the measurement,
each system qubit is rotated into its letter of basis (default all Z).
The ancilla and the program register are not measured. Bit i of a counts
key is system qubit i. Read those counts with :meth:measure.
With workers greater than 1, that backend is pickled into each worker process.
Each time point starts from initial_state. The term sequence and the shot
sampler are a pure function of seed and the time index, so workers=1
and a larger pool return the same counts. workers=1 (the default) runs
the points serially, in tlist order. progress(index, total) may run
in completion order when workers is greater than 1. A job from start()
counts each finished time point in completed_steps.
Source code in shadowsim/simulators/hybrid_wml_simulator.py
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 | |
__init__
¶
__init__(
hamiltonians: list[LocalHamiltonian],
lindblads: list[LocalOperator],
initial_state: State,
*,
num_qubits: int,
total_time: float,
time_steps: int,
num_steps: int,
verbose: bool = False,
seed: int | None = None,
progress: ProgressCallback | None = None,
workers: int = 1,
circuit_backend: CircuitBackend | None = None,
basis: str | None = None,
) -> None
Initialize a hybrid WML simulator for the given model.
Raises:
-
TypeError–An operator has the wrong type, or
seedorworkershas the wrong type. -
ValueError–workersornum_stepsis not positive,total_timeis negative,basisis malformed, the backend has no shot budget, an operator does not act on the register, or every sampling weight is zero.
Source code in shadowsim/simulators/hybrid_wml_simulator.py
metrics_circuit
¶
metrics_circuit() -> Program
Return the program executed at the final time, including measurement.
Source code in shadowsim/simulators/hybrid_wml_simulator.py
QutipSimulator
¶
Bases: Simulator
Simulate open or closed quantum dynamics with QuTiP.
Source code in shadowsim/simulators/qutip_simulator.py
__init__
¶
__init__(
hamiltonians: Sequence[Hamiltonian],
lindblads: Sequence[Operator],
initial_state: State,
observables: OperatorSet | Sequence[Operator],
*,
num_qubits: int,
total_time: float,
time_steps: int,
) -> None
Initialize a QuTiP simulator for the given model.
Source code in shadowsim/simulators/qutip_simulator.py
simulate
¶
simulate() -> SimulationResult
Evolve the system with QuTiP and store expectation traces.
Source code in shadowsim/simulators/qutip_simulator.py
__str__
¶
Return a string representation of the QutipSimulator.
Source code in shadowsim/simulators/qutip_simulator.py
__repr__
¶
Return a string representation of the QutipSimulator.
Source code in shadowsim/simulators/qutip_simulator.py
SplitJMatrixSimulator
¶
Bases: ProductFormulaSimulator
Simulate open-system dynamics with the Split JMatrix method.
Each of the num_steps applies every Lindblad jump once, then
trotter_depth Hamiltonian slices. order=1 (the default) applies each
local term once per slice of width t / (num_steps * trotter_depth), in
list order. order=2 uses one Strang step per slice: half-steps forward,
a full step on the last term, then half-steps in reverse. Either order
covers coherent time t.
Counts come from circuit_backend. Omitting it uses Aer.
The shot count is that backend's shots attribute. Before the measurement,
each system qubit is rotated into its letter of basis (default all Z).
The result keeps one counts dict per time point, where bit i of a key is
system qubit i and the ancilla bit is dropped.
Read those counts with :meth:measure.
With workers greater than 1, that backend is pickled into each worker process.
Each time point starts from initial_state and uses the same seed.
workers=1 (the default) runs those points serially, in tlist order.
workers greater than 1 runs one process-pool task per time point.
Traces are still returned in tlist order, and progress(index, total)
may run in completion order. A job from start() counts each finished
time point in completed_steps.
Source code in shadowsim/simulators/splitjmatrix_simulator.py
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
__init__
¶
__init__(
hamiltonians: List[LocalHamiltonian],
lindblads: List[LocalOperator],
initial_state: State,
*,
num_qubits: int,
total_time: float,
time_steps: int,
num_steps: int,
trotter_depth: int = 1,
order: Literal[1, 2] = 1,
verbose: bool = False,
seed: int | None = None,
progress: ProgressCallback | None = None,
workers: int = 1,
circuit_backend: CircuitBackend | None = None,
basis: str | None = None,
) -> None
Initialize a Split JMatrix simulator for the given model.
Source code in shadowsim/simulators/splitjmatrix_simulator.py
metrics_circuit
¶
metrics_circuit() -> Program
Return the program executed at the final time, including measurement.
Source code in shadowsim/simulators/splitjmatrix_simulator.py
TrotterizationSimulator
¶
Bases: ProductFormulaSimulator
Simulate closed-system dynamics with a Trotter product formula.
closed_system is true, so Lindblad operators are rejected.
Counts come from circuit_backend when that backend stores shots.
Omitting it uses Aer. Before the measurement, each
qubit is rotated into its letter of basis (default all Z). The result
keeps one counts dict per time point, where bit i of a key is qubit i.
Read them with :meth:measure. A backend without a shot budget, such as
PauliPropagation, returns the expectation of each qubit's basis letter
from the same circuit with the measurement removed, and the result has no
counts. :meth:measure reads a one-qubit measurement from that distribution:
counts["0"] is (1 + expectation) / 2, counts["1"] is
(1 - expectation) / 2, and shots is 1. Dividing by shots gives
the infinite-shot value, and an expression that uses raw counts without
shots reads those probabilities. Two or more qubits need a sampling backend.
The shot count is that backend's shots attribute when it has one.
With workers greater than 1, that backend is pickled into each worker process.
order=1 (the default) applies each local term once per slice of width
t / (num_steps * trotter_depth), in list order. order=2 uses one Strang
step per slice: half-steps forward, a full step on the last term, then half-steps
in reverse. trotter_depth is how many slices fit in one time sample, for both
orders.
Each time point starts from initial_state and uses the same seed.
workers=1 (the default) runs those points serially, in tlist order.
workers greater than 1 runs one process-pool task per time point.
Traces are still returned in tlist order, and progress(index, total)
may run in completion order. A job from start() counts each finished
time point in completed_steps.
Source code in shadowsim/simulators/trotterization_simulator.py
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | |
__init__
¶
__init__(
hamiltonians: list[LocalHamiltonian],
lindblads: Sequence[Operator],
initial_state: State,
*,
num_qubits: int,
total_time: float,
time_steps: int,
num_steps: int,
trotter_depth: int = 1,
order: Literal[1, 2] = 1,
verbose: bool = False,
seed: int | None = None,
progress: ProgressCallback | None = None,
workers: int = 1,
circuit_backend: CircuitBackend | None = None,
basis: str | None = None,
) -> None
Initialize a closed-system Trotterization simulator for the given model.
Source code in shadowsim/simulators/trotterization_simulator.py
metrics_circuit
¶
metrics_circuit() -> Program
Return the program executed at the final time.
A sampling backend includes the computational-basis measurement.
Source code in shadowsim/simulators/trotterization_simulator.py
apply_measurements
¶
apply_measurements(
result: SimulationResult,
measurements: Sequence[Measurement],
) -> SimulationResult
Return result with one curve per measurement in place of its observables.
Each curve has one value per entry of result.counts. The metadata gains
measurements: the qubits, expression, and label of each one, in order.
Only a sampling backend, such as Aer, records counts. An expectation backend,
such as PauliPropagation, returns one Pauli expectation per qubit instead
(observable_kind is "qubit_expectations"). A one-qubit measurement is
evaluated on that distribution: counts["0"] is (1 + expectation) / 2,
counts["1"] is (1 - expectation) / 2, and shots is 1. Dividing by
shots gives the infinite-shot value. An expression that uses raw counts
without shots reads those probabilities. Two or more qubits need a
sampling backend, because the result has no correlations between qubits.
Raises:
-
ValueError–measurementsis empty, or a measurement cannot be evaluated onresult.
Source code in shadowsim/simulators/reducers.py
__getattr__
¶
Import an optional simulator the first time it is accessed.