Skip to content

Computational Notebooks

Numerical work becomes trustworthy when the physics, representation, algorithm, and validation evidence can all be inspected independently. A plot that looks plausible is not sufficient. A mature computational result should survive analytic limiting cases, physicality checks, resolution changes, alternative implementations, and a clean rerun from recorded inputs.

The pages in this chapter are notebook specifications. As of this review, they do not claim that corresponding executable artifacts have been reproduced or promoted. Each page defines an admission contract: the model, conventions, calculations, tests, metadata, and accepted outputs required before numerical results can be cited as reproduced artifacts.

Every notebook in this chapter should contain nine layers.

  1. Physics goal: State the question and the observable to be computed.
  2. Mathematical model: Give the Hamiltonian, channel, generator, stochastic equation, or work protocol.
  3. Units and parameters: Record dimensions, scales, basis order, frames, and numerical values.
  4. Analytic limiting case: Identify at least one result known independently of the numerical method.
  5. Numerical method: Name the integrator, matrix representation, stochastic convention, optimizer, and approximation.
  6. Convergence checks: Vary time step, tolerance, truncation, trajectory count, or sampling resolution as appropriate.
  7. Reproducible implementation: Pin dependencies, record random seeds, and separate source inputs from generated outputs.
  8. Validation test: Compare against an exact solution, structural identity, second method, or independently computed benchmark.
  9. Extensions: Mark optional investigations separately from the validated baseline.

The contract makes a notebook more than an illustrated derivation. It states what would falsify the calculation.

Read this pageUse it for
Simulating Quantum ChannelsConstructing Kraus and Choi representations, applying channels, and testing complete positivity and trace preservation.
Bloch Vector Noise ModelsVisualizing dephasing, depolarization, and amplitude damping as affine maps of a qubit Bloch vector.
Solving Lindblad EquationsComparing ODE and matrix-exponential solvers, finding steady states, and inspecting Liouvillian spectra.
Quantum Jump SimulationGenerating jump records, no-jump evolution, waiting-time histograms, and ensemble averages.
Diffusive Trajectory SimulationIntegrating stochastic master equations, generating noisy records, and checking conditional purification.
Non-Markovian Toy ModelsComparing exact enlarged-system evolution with Markovian reductions and trace-distance revivals.
Decoherence Timescale EstimationComputing coherence envelopes from spectra and filter functions and defining fitted timescales.
Optimal Control Toy ProblemsOptimizing small pulse families under dephasing and testing fidelity and robustness.
Quantum Thermodynamics Toy ModelsBuilding work distributions and testing Jarzynski and Crooks relations for a driven two-level system.

A productive first route is channels, Bloch vectors, and Lindblad equations. The two trajectory notebooks then add stochastic records. The remaining notebooks test memory, spectral estimation, control, and thermodynamic bookkeeping.

From Physics Statement to Numerical Artifact

Section titled “From Physics Statement to Numerical Artifact”

A reliable workflow proceeds in a fixed order.

Begin with the quantity that will answer the physics question. Examples include

⟨σz(t)⟩,Tr⁡[ρ(t)2],g(2)(τ),\langle \sigma_z(t)\rangle, \qquad \operatorname{Tr}[\rho(t)^2], \qquad g^{(2)}(\tau),

or a work probability P(W)P(W). This prevents the implementation from expanding into an unstructured simulation of every available variable.

State basis ordering, tensor-factor ordering, vectorization, complex-conjugation conventions, and units. If column stacking is used, then

vec⁡(AρB)=(BT⊗A)vec⁡(ρ).\operatorname{vec}(A\rho B) = (B^{\mathsf T}\otimes A) \operatorname{vec}(\rho).

Using row stacking changes the matrix representation of the superoperator. A solver may still run after a convention mismatch while producing a physically incorrect evolution.

Choose a reference frequency Ω0\Omega_0 or time t0t_0 and expose the dimensionless combinations that control the dynamics:

τ=Ω0t,γ~=γΩ0,Δ~=ΔΩ0.\tau=\Omega_0t, \qquad \tilde\gamma=\frac{\gamma}{\Omega_0}, \qquad \tilde\Delta=\frac{\Delta}{\Omega_0}.

Nondimensionalization improves conditioning and makes parameter regimes easier to compare. Physical units should still be recoverable from recorded metadata.

Every notebook needs a case whose answer is known. For zero-temperature qubit relaxation,

ρee(t)=ρee(0)e−γt.\rho_{ee}(t) = \rho_{ee}(0)e^{-\gamma t}.

For pure dephasing under the convention used by the notebook, the off-diagonal element must follow the corresponding analytic exponential. The convention must be checked rather than inferred from the name of a collapse operator.

Start with the minimum Hilbert space, one parameter set, and one observable. Add sweeps, optimization, or additional modes only after that baseline passes its tests. Complexity should enter in auditable increments.

Numerical state evolution should be tested against properties that do not depend on the plotted observable.

For every reported state, monitor

ϵtr=∣Tr⁡ρ−1∣,\epsilon_{\mathrm{tr}} = \left| \operatorname{Tr}\rho-1 \right|, ϵH=∥ρ−ρ†∥,\epsilon_{\mathrm{H}} = \left\| \rho-\rho^\dagger \right\|,

and the smallest eigenvalue λmin⁡(ρ)\lambda_{\min}(\rho). Small negative eigenvalues can arise from roundoff, but persistent or tolerance-dependent negativity can signal a bad integrator, an invalid generator, or an inconsistent approximation.

Trace, Hermiticity, and positivity tests serve different purposes. Renormalizing the trace does not repair non-Hermiticity or negative eigenvalues.

For Kraus operators {Kα}\{K_\alpha\}, a trace-preservation residual is

ϵTP=∥∑αKα†Kα−I∥.\epsilon_{\mathrm{TP}} = \left\| \sum_\alpha K_\alpha^\dagger K_\alpha -I \right\|.

For a Choi matrix J(Φ)J(\Phi), check Hermiticity, positive semidefiniteness, and the appropriate partial-trace identity. A few positive test states cannot establish complete positivity.

A finite-dimensional Lindblad solver should preserve trace and Hermiticity and should keep positive initial states positive to numerical tolerance. It should also reproduce known stationary states and decay rates. If the generator is represented as a matrix L\mathbb L, verify

ddt∣ρ⟩ ⁣⟩=L∣ρ⟩ ⁣⟩\frac{d}{dt} |\rho\rangle\!\rangle = \mathbb L |\rho\rangle\!\rangle

against direct evaluation of the operator equation on randomly selected test states.

Conditional states require normalization, record statistics, and ensemble checks. A trajectory algorithm can preserve each state’s norm while using the wrong jump probabilities or stochastic drift. Structural tests must therefore include both state and record.

A numerical value without a resolution study is an estimate with an unknown numerical error.

Let Oh(t)O_h(t) denote an observable computed at step size hh. A simple refinement residual is

Rh=max⁡t∣Oh(t)−Oh/2(t)∣.R_h = \max_t \left| O_h(t)-O_{h/2}(t) \right|.

Report RhR_h over the interval actually used in the analysis. One matching endpoint does not establish convergence of the trajectory.

Adaptive solvers require absolute and relative tolerances, an error norm, and any maximum-step restriction. Tightening only one tolerance may not probe the dominant error.

Bosonic modes require a cutoff nmax⁡n_{\max}. Convergence should be checked by increasing the cutoff and monitoring both observables and boundary population. A small occupation of the highest retained level is useful evidence but not sufficient when dynamics repeatedly reaches the boundary.

Noise-spectrum and filter-function calculations require stated integration intervals, infrared and ultraviolet cutoffs, grid spacing, and quadrature rules. Apparent convergence on a fixed window can hide cutoff dependence.

An optimizer’s termination flag is not a physics validation. Repeat from multiple initial guesses, compare with a baseline control, enforce amplitude and bandwidth constraints, and test the final pulse on a finer propagation grid than the optimization grid.

Statistical Error in Trajectory Simulations

Section titled “Statistical Error in Trajectory Simulations”

For NN independent trajectories with conditional states ρc(n)(t)\rho_c^{(n)}(t), the ensemble estimator is

ρˉN(t)=1N∑n=1Nρc(n)(t).\bar\rho_N(t) = \frac{1}{N} \sum_{n=1}^{N} \rho_c^{(n)}(t).

For an observable AA, define samples

Xn(t)=Tr⁡[Aρc(n)(t)].X_n(t) = \operatorname{Tr} \left[ A\rho_c^{(n)}(t) \right].

The estimated standard error of the sample mean is

SE⁡[XˉN(t)]=sX(t)N,\operatorname{SE} \left[ \bar X_N(t) \right] = \frac{s_X(t)}{\sqrt N},

where sXs_X is the sample standard deviation. Quadrupling the number of independent trajectories reduces ordinary Monte Carlo error by only a factor of two.

For waiting-time distributions or rare jumps, mean curves can converge before tails do. Report binning rules, censoring, number of events, and confidence intervals. Reusing correlated random streams across nominally independent trajectories invalidates the usual standard-error estimate.

Diffusive equations must state whether they use Itō or Stratonovich calculus. For an Itō Wiener increment,

E[dWt]=0,dWt2=dt.\mathbb E[dW_t]=0, \qquad dW_t^2=dt.

A discrete implementation should verify that normalized increments have approximately zero mean, variance dtdt, and negligible unintended temporal correlations.

For a counting process,

dNt∈{0,1},dNt2=dNt.dN_t\in\{0,1\}, \qquad dN_t^2=dN_t.

The time step must keep the probability of two or more unresolved jumps negligible when the algorithm assumes at most one. Event-driven methods remove that particular restriction but introduce their own root-finding and propagation tolerances.

The random seed belongs in run metadata, not as a substitute for uncertainty analysis. A trustworthy result should not depend qualitatively on one unusually favorable seed.

Whenever feasible, compare representations that fail differently.

CalculationPrimary methodIndependent comparison
channel actionKraus sumsuperoperator or Choi reconstruction
Lindblad dynamicsODE integrationmatrix exponential for a small system
steady statelong-time propagationnull space of the Liouvillian
jump ensembleMonte Carlo trajectoriesdirect master-equation solution
diffusive ensemblestochastic integrationunconditional dephasing solution
non-Markovian toy modelenlarged unitary evolutionanalytic one-excitation solution
coherence envelopenumerical spectral integralwhite-noise or quasistatic limit
control pulseoptimization gridfiner independent propagation grid
work distributionsampled histogramexact transition-probability sum

Agreement between two methods is strongest when they do not share the same implementation path. Two wrappers around the same erroneous matrix construction are not independent validation.

Each accepted run should record:

  • a stable identifier for the notebook source;
  • the execution environment and dependency versions;
  • operating-system and hardware details when numerically relevant;
  • all physical parameters with units;
  • basis, tensor ordering, and vectorization convention;
  • solver, tolerances, step restrictions, and truncations;
  • random-number generator and seeds;
  • optimizer configuration and initial guesses;
  • input-data checksums where external data are used;
  • run timestamp and elapsed time;
  • generated data files separate from display figures;
  • validation-test results and acceptance thresholds.

The Reproducibility Status page owns promotion labels across the site. A notebook specification should not silently upgrade itself from planned to reproduced because it ran once on one machine.

Plots should be generated from saved numerical data rather than being the only output. Axes need units, parameter values, and normalization conventions. Logarithmic plots must expose zeros, clipped values, and sign handling.

For each figure, preserve enough information to answer:

  1. Which run generated it?
  2. Which data columns were plotted?
  3. Which transformations or smoothing operations were applied?
  4. Which validation tests passed?
  5. Can the figure be regenerated without manual editing?

Interpolation may aid visualization but must not be confused with improved simulation resolution. Smoothing a noisy trajectory does not increase the detector bandwidth or trajectory count.

LevelEvidencePermitted claim
specificationmodel and required tests are documentedthe calculation is planned and auditable
executablecode runs in a recorded environmentthe implementation executes
validatedanalytic, structural, and convergence tests passbaseline outputs are numerically supported
reproducedan independent clean run regenerates accepted outputsthe artifact is reproduced under stated conditions
benchmarkedindependent methods or trusted data agree within toleranceperformance or accuracy comparison is supported

These levels describe evidence, not scientific importance. A small validated two-level calculation is more trustworthy than an elaborate untested simulation.

SymptomLikely causesFirst checks
trace driftwrong generator, loose integration, vectorization mismatchevaluate trace derivative and reduce step size
negative populationsinvalid equation, unstable method, excessive stepinspect generator and convergence under refinement
wrong steady statesign, rate, or basis errorsolve the analytic rate balance and Liouvillian null space
trajectory average mismatchincorrect jump probability or stochastic drifttest one-step expectation and record moments
cutoff dependenceinadequate Hilbert spaceinspect boundary occupation and increase truncation
false revivalfinite-size recurrence or sampling noisevary environment size, cutoff, and ensemble count
optimizer reports implausible fidelityobjective or propagator mismatchrecompute with an independent fine-grid solver
fluctuation relation failswork-sign, partition-function, or reverse-protocol errortest normalization and convention reversal

Failure is useful information. It should remain visible in validation logs rather than being removed from the final notebook.

This chapter owns computational specifications and validation workflows for the open-system examples listed here.

Notebook pages should link to canonical theory rather than becoming alternate derivations of the same result.

  • Treating a successful execution as validation.
  • Omitting basis, tensor-order, vectorization, or unit conventions.
  • Testing positivity only on a few hand-picked input states.
  • Renormalizing an invalid state and hiding the original residual.
  • Reporting solver tolerances without a refinement study.
  • Choosing a Hilbert-space cutoff from convenience rather than convergence.
  • Showing a trajectory ensemble without statistical uncertainty.
  • Using one random seed as evidence of robustness.
  • Fitting a decoherence time without reporting the fit window and model.
  • Optimizing and validating a control pulse on the same coarse grid.
  • Comparing methods that share the same faulty matrix construction.
  • Saving figures without the numerical data and run metadata that generated them.
  • Describing an unpromoted notebook specification as a reproduced artifact.

A qubit amplitude-damping channel uses

K0=(1001−p),K1=(0p00).\begin{aligned} K_0 &= \begin{pmatrix} 1&0\\ 0&\sqrt{1-p} \end{pmatrix}, \\[4pt] K_1 &= \begin{pmatrix} 0&\sqrt p\\ 0&0 \end{pmatrix}. \end{aligned}

Verify analytically that the trace-preservation residual vanishes for 0≤p≤10\le p\le1.

Solution

Direct multiplication gives

K0†K0=(1001−p),K_0^\dagger K_0 = \begin{pmatrix} 1&0\\ 0&1-p \end{pmatrix},

and

K1†K1=(000p).K_1^\dagger K_1 = \begin{pmatrix} 0&0\\ 0&p \end{pmatrix}.

Their sum is II, so

ϵTP=∥K0†K0+K1†K1−I∥=0.\epsilon_{\mathrm{TP}} = \left\| K_0^\dagger K_0 + K_1^\dagger K_1 -I \right\| =0.

The condition 0≤p≤10\le p\le1 also keeps the square roots real and gives the physical damping family.

An observable at a fixed time is Oh=0.7310O_h=0.7310, Oh/2=0.7270O_{h/2}=0.7270, and Oh/4=0.7260O_{h/4}=0.7260. Assuming the leading error is proportional to hqh^q, estimate the observed order qq.

Solution

The refinement differences are

Δh=∣Oh−Oh/2∣=0.0040\Delta_h = |O_h-O_{h/2}| =0.0040

and

Δh/2=∣Oh/2−Oh/4∣=0.0010.\Delta_{h/2} = |O_{h/2}-O_{h/4}| =0.0010.

For leading error ChqCh^q,

ΔhΔh/2≈2q.\frac{\Delta_h}{\Delta_{h/2}} \approx 2^q.

The ratio is 44, so q≈2q\approx2. This estimate is meaningful only if the three resolutions are already in the asymptotic convergence regime.

A trajectory estimate has standard error 0.020.02 using N=2500N=2500 independent trajectories. Approximately how many trajectories are required for standard error 0.0050.005 if ordinary Monte Carlo scaling applies?

Solution

Since standard error scales as N−1/2N^{-1/2}, reducing it by a factor of four requires increasing NN by a factor of sixteen:

N′=16N=40000.N' = 16N = 40000.

This estimate assumes independent samples and approximately unchanged variance. Rare-event observables may converge more slowly in practice.

A damped oscillator calculation at cutoff nmax⁡=20n_{\max}=20 places probability 3×10−33\times10^{-3} in level n=19n=19. At cutoff nmax⁡=30n_{\max}=30, the observable of interest changes by 4%4\%. Is the smaller cutoff validated?

Solution

No. The non-negligible boundary population already warns that the state reaches the truncation edge, and the 4%4\% observable shift under refinement confirms material cutoff dependence. The cutoff should be increased until both the boundary diagnostic and the observable change satisfy a predeclared tolerance.

Why is comparing a matrix-exponential solver with an ODE solver useful only if their Liouvillian construction is also tested independently?

Solution

Both propagators may act perfectly on the same incorrectly constructed matrix. Their agreement would then validate numerical exponentiation and integration of that matrix, not its correspondence with the intended operator equation. Testing the Liouvillian action against direct operator evaluation separates representation errors from propagation errors.

  • N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM (2002).
  • E. Hairer, S. P. Nørsett, and G. Wanner, Solving Ordinary Differential Equations I: Nonstiff Problems, 2nd rev. ed., Springer (1993).
  • E. Hairer and G. Wanner, Solving Ordinary Differential Equations II: Stiff and Differential-Algebraic Problems, 2nd rev. ed., Springer (1996).
  • H.-P. Breuer and F. Petruccione, The Theory of Open Quantum Systems, Oxford University Press (2002).
  • H. J. Carmichael, An Open Systems Approach to Quantum Optics, Springer (1993).
  • J. R. Johansson, P. D. Nation, and F. Nori, “QuTiP: An open-source Python framework for the dynamics of open quantum systems,” Computer Physics Communications 183, 1760–1772 (2012).
  • J. R. Johansson, P. D. Nation, and F. Nori, “QuTiP 2: A Python framework for the dynamics of open quantum systems,” Computer Physics Communications 184, 1234–1240 (2013).
  • G. K. Sandve, A. Nekrutenko, J. Taylor, and E. Hovig, “Ten simple rules for reproducible computational research,” PLoS Computational Biology 9, e1003285 (2013).