Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

Update QuTiP skill for version 5.3

Timothy Kassisf7b918d69443
diff --git a/skills/qutip/SKILL.md b/skills/qutip/SKILL.md
index 53b3ecc4..cddd1b40 100644
--- a/skills/qutip/SKILL.md
+++ b/skills/qutip/SKILL.md
@@ -1,315 +1,317 @@
---
name: qutip
-description: Quantum physics simulation library for open quantum systems. Use when studying master equations, Lindblad dynamics, decoherence, quantum optics, or cavity QED. Best for physics research, open system dynamics, and educational simulations. NOT for circuit-based quantum computing—use qiskit, cirq, or pennylane for quantum algorithms and hardware execution.
-license: BSD-3-Clause license
-metadata: {"version": "1.0", "skill-author": "K-Dense Inc."}
+description: Simulate and audit closed and open quantum-system models with QuTiP 5, including deterministic, trajectory, steady-state, spectral, and phase-space workflows. Use for local quantum-dynamics work where physical assumptions, dimensions, and numerical convergence must be explicit.
+license: MIT
+compatibility: Requires Python 3.11+, uv, and qutip==5.3.0 for executable simulations. Bundled planners and all script help run with the Python standard library; plotting requires the pinned graphics extra. No network service or credentials are used.
+metadata:
+ version: "1.1"
+ skill-author: K-Dense Inc.
+ last-reviewed: "2026-07-23"
---
-# QuTiP: Quantum Toolbox in Python
+# QuTiP 5
-## Overview
+## Scope
-QuTiP provides comprehensive tools for simulating and analyzing quantum mechanical systems. It handles both closed (unitary) and open (dissipative) quantum systems with multiple solvers optimized for different scenarios.
+Use QuTiP for finite-dimensional quantum mechanics, quantum optics, Lindblad
+dynamics, trajectories, weak-coupling Bloch-Redfield models, and specialized
+Floquet, HEOM, and permutational-invariance methods. It is not a hardware
+execution SDK. Circuit and control functionality moved to separate QuTiP family
+packages.
-## Installation
+This skill targets **QuTiP 5.3.0**, released 2026-05-22. QuTiP 5.3 requires
+Python 3.11 or newer. Its required distributions are NumPy (`>=1.23.2`), SciPy
+(`>=1.9.2`, excluding `1.16.0` and `1.17.0`), and `packaging`.
-```bash
-uv pip install qutip
-```
+## Reproducible uv snapshot
-Optional packages for additional functionality:
+Create a dedicated environment and pin every direct distribution:
```bash
-# Quantum information processing (circuits, gates)
-uv pip install qutip-qip
-
-# Quantum trajectory viewer
-uv pip install qutip-qtrl
+uv venv --python 3.11
+uv pip install "qutip==5.3.0"
```
-## Quick Start
-
-```python
-from qutip import *
-import numpy as np
-import matplotlib.pyplot as plt
+For plots:
-# Create quantum state
-psi = basis(2, 0) # |0⟩ state
-
-# Create operator
-H = sigmaz() # Hamiltonian
-
-# Time evolution
-tlist = np.linspace(0, 10, 100)
-result = sesolve(H, psi, tlist, e_ops=[sigmaz()])
-
-# Plot results
-plt.plot(tlist, result.expect[0])
-plt.xlabel('Time')
-plt.ylabel('⟨σz⟩')
-plt.show()
+```bash
+uv pip install "qutip[graphics]==5.3.0"
```
-## Core Capabilities
-
-### 1. Quantum Objects and States
+Optional QuTiP family packages are independently versioned:
-Create and manipulate quantum states and operators:
-
-```python
-# States
-psi = basis(N, n) # Fock state |n⟩
-psi = coherent(N, alpha) # Coherent state |α⟩
-rho = thermal_dm(N, n_avg) # Thermal density matrix
-
-# Operators
-a = destroy(N) # Annihilation operator
-H = num(N) # Number operator
-sx, sy, sz = sigmax(), sigmay(), sigmaz() # Pauli matrices
-
-# Composite systems
-psi_AB = tensor(psi_A, psi_B) # Tensor product
+```bash
+uv pip install "qutip-qip==0.4.2"
+uv pip install "qutip-qtrl==0.2.0"
+uv pip install "qutip-jax==0.1.1"
```
-**See** `references/core_concepts.md` for comprehensive coverage of quantum objects, states, operators, and tensor products.
-
-### 2. Time Evolution and Dynamics
-
-Multiple solvers for different scenarios:
+- `qutip-qip` 0.4.2 (2026-06-23) is the production/stable circuit, gate, and
+ noisy-device simulation package. Import from `qutip_qip`, not `qutip.qip`.
+- `qutip-qtrl` 0.2.0 (2026-06-23) provides GRAPE and CRAB **quantum optimal
+ control**. It is not a trajectory viewer. Import from `qutip_qtrl`, not
+ `qutip.control`; PyPI still classifies it pre-alpha.
+- `qutip-jax` 0.1.1 (2025-05-29) is the official JAX data backend for GPU and
+ automatic-differentiation experiments. It is explicitly pre-alpha.
+- `qutip-cupy` is an official QuTiP-organization repository, but it has no PyPI
+ release and its own README says it is not officially released. Do not put an
+ unreleased Git install into a reproducible workflow.
+
+Use a project lockfile or a hash-generating `uv pip compile` workflow when
+transitive dependency identity must also be frozen.
+
+## Non-negotiable model contract
+
+Before solving, record:
+
+1. **Units and convention.** QuTiP equations normally set \(\hbar=1\).
+ Hamiltonian entries are angular frequencies and rates have reciprocal-time
+ units. Convert cyclic frequency with \(2\pi f\); never mix Hz and rad/s.
+2. **Subsystem order.** `tensor(A, B, C)` fixes subsystem indices `0, 1, 2`.
+ Preserve that order in every state, operator, collapse channel, and partial
+ trace. `obj.ptrace([0, 2])` keeps those subsystems; it does not trace them.
+3. **State validity.** Check ket norm or density-matrix Hermiticity, unit trace,
+ and eigenvalues above a stated negative tolerance. Tiny negative values may
+ be numerical; material negativity invalidates a claimed state.
+4. **Generator meaning.** A Lindblad channel with rate `gamma` is represented
+ by `sqrt(gamma) * A`, not `gamma * A`. Define what each rate measures. For
+ example, `sqrt(gamma_phi / 2) * sigmaz()` gives coherence decay
+ `exp(-gamma_phi * t)`.
+5. **Approximations.** State rotating-wave, Born-Markov, secular, weak-coupling,
+ bath-equilibrium, truncation, symmetry, and initial-factorization assumptions
+ wherever used.
+6. **Numerics.** Justify Hilbert truncation, output grid, integration method,
+ tolerances, trajectory count, and random seeds. Report `result.stats`.
+7. **Convergence.** Sweep every artificial cutoff: Fock dimension, time/frequency
+ window and spacing, ODE tolerances, trajectories, Floquet harmonics, HEOM
+ depth and bath exponents, or PIQS representation as applicable.
+
+## Qobj, dimensions, and tensor order
+
+Prefer explicit imports and inspect both shape and structured dimensions:
```python
-# Closed systems (unitary evolution)
-result = sesolve(H, psi0, tlist, e_ops=[num(N)])
+from qutip import basis, qeye, sigmaz, tensor
-# Open systems (dissipation)
-c_ops = [np.sqrt(0.1) * destroy(N)] # Collapse operators
-result = mesolve(H, psi0, tlist, c_ops, e_ops=[num(N)])
+psi = tensor(basis(2, 0), basis(3, 1))
+z_on_first = tensor(sigmaz(), qeye(3))
-# Quantum trajectories (Monte Carlo)
-result = mcsolve(H, psi0, tlist, c_ops, ntraj=500, e_ops=[num(N)])
+assert psi.shape == (6, 1)
+assert psi.dims == [[2, 3], [1]]
+assert z_on_first.dims == [[2, 3], [2, 3]]
+rho_first = psi.proj().ptrace(0) # keep subsystem 0
```
-**Solver selection guide:**
-- `sesolve`: Pure states, unitary evolution
-- `mesolve`: Mixed states, dissipation, general open systems
-- `mcsolve`: Quantum jumps, photon counting, individual trajectories
-- `brmesolve`: Weak system-bath coupling
-- `fmmesolve`: Time-periodic Hamiltonians (Floquet)
+Matrix shape alone is insufficient: two objects can both be 6-by-6 but encode
+different tensor factorizations. Read `references/core_concepts.md` before
+building composite, superoperator, or channel models.
-**See** `references/time_evolution.md` for detailed solver documentation, time-dependent Hamiltonians, and advanced options.
+## Choose the solver by physics
-### 3. Analysis and Measurement
+| Model | Current API | Required justification |
+|---|---|---|
+| Closed, pure, unitary | `sesolve` | Hermitian Hamiltonian; no dissipation |
+| Lindblad/open or mixed | `mesolve` | Markovian completely positive model and channel rates |
+| Quantum jumps | `mcsolve` | Unravelling, trajectory convergence, seeds |
+| Microscopic weak bath | `brmesolve` | Born-Markov/weak coupling, spectra, secular choice |
+| Diffusive measurement | `ssesolve`, `smesolve` | monitored versus unmonitored channels |
+| Periodic drive | `FloquetBasis`, `fsesolve`, `fmmesolve` | verified period and Floquet convergence |
+| Structured non-Markovian bath | `qutip.solver.heom` | bath expansion and hierarchy convergence |
+| Symmetric spin ensemble | `qutip.piqs` | permutation symmetry and basis choice |
-Compute physical quantities:
+Do not select a more specialized solver merely because it exists.
-```python
-# Expectation values
-n_avg = expect(num(N), psi)
-
-# Entropy measures
-S = entropy_vn(rho) # Von Neumann entropy
-C = concurrence(rho) # Entanglement (two qubits)
-
-# Fidelity and distance
-F = fidelity(psi1, psi2)
-D = tracedist(rho1, rho2)
+## Deterministic open-system example
-# Correlation functions
-corr = correlation_2op_1t(H, rho0, taulist, c_ops, A, B)
-w, S = spectrum_correlation_fft(taulist, corr)
+QuTiP 5.3 uses ordinary option dictionaries. Solver controls, `e_ops`, and
+`args` are keyword-only; the old mutable options object is gone.
-# Steady states
-rho_ss = steadystate(H, c_ops)
+```python
+import numpy as np
+from qutip import basis, mesolve, sigmam, sigmaz
+
+omega = 2.0
+gamma = 0.15
+tlist = np.linspace(0.0, 20.0, 401)
+excited = basis(2, 0)
+
+result = mesolve(
+ 0.5 * omega * sigmaz(),
+ excited,
+ tlist,
+ c_ops=[np.sqrt(gamma) * sigmam()],
+ e_ops={"sigma_z": sigmaz(), "excited": excited.proj()},
+ options={
+ "method": "adams",
+ "atol": 1e-10,
+ "rtol": 1e-8,
+ "store_final_state": True,
+ "progress_bar": "",
+ },
+)
+
+population = np.asarray(result.e_data["excited"])
+assert np.max(np.abs(population - np.exp(-gamma * tlist))) < 2e-6
+assert isinstance(result.stats, dict)
```
-**See** `references/analysis.md` for entropy, fidelity, measurements, correlation functions, and steady state calculations.
+If the problem is stiff, compare `bdf` or `lsoda`; do not change an integrator
+without rerunning tolerance and invariant checks. QuTiP 5.3 also supports
+`options={"matrix_form": True}` in `mesolve`; benchmark and validate it before
+using it as a default.
-### 4. Visualization
+## Time-dependent systems
-Visualize quantum states and dynamics:
+Prefer trusted Pythonic callables or numeric coefficient arrays. Do not create
+coefficient source strings from user input.
```python
-# Bloch sphere
-b = Bloch()
-b.add_states(psi)
-b.show()
-
-# Wigner function (phase space)
-xvec = np.linspace(-5, 5, 200)
-W = wigner(psi, xvec, xvec)
-plt.contourf(xvec, xvec, W, 100, cmap='RdBu')
-
-# Fock distribution
-plot_fock_distribution(psi)
-
-# Matrix visualization
-hinton(rho) # Hinton diagram
-matrix_histogram(H.full()) # 3D bars
-```
-
-**See** `references/visualization.md` for Bloch sphere animations, Wigner functions, Q-functions, and matrix visualizations.
-
-### 5. Advanced Methods
+import numpy as np
+from qutip import QobjEvo, sigmax, sigmaz
-Specialized techniques for complex scenarios:
+def envelope(t, amplitude, center, width):
+ return amplitude * np.exp(-0.5 * ((t - center) / width) ** 2)
-```python
-# Floquet theory (periodic Hamiltonians)
-T = 2 * np.pi / w_drive
-f_modes, f_energies = floquet_modes(H, T, args)
-result = fmmesolve(H, psi0, tlist, c_ops, T=T, args=args)
-
-# HEOM (non-Markovian, strong coupling)
-from qutip.nonmarkov.heom import HEOMSolver, BosonicBath
-bath = BosonicBath(Q, ck_real, vk_real)
-hsolver = HEOMSolver(H_sys, [bath], max_depth=5)
-result = hsolver.run(rho0, tlist)
-
-# Permutational invariance (identical particles)
-psi = dicke(N, j, m) # Dicke states
-Jz = jspin(N, 'z') # Collective operators
+H = QobjEvo(
+ [0.5 * sigmaz(), [sigmax(), envelope]],
+ args={"amplitude": 0.2, "center": 5.0, "width": 1.0},
+)
+instantaneous_H = H(5.0)
+H.arguments(amplitude=0.1)
```
-**See** `references/advanced.md` for Floquet theory, HEOM, permutational invariance, stochastic solvers, superoperators, and performance optimization.
+The older `f(t, args)` coefficient signature is deprecated in 5.3 and is
+scheduled for removal in 5.5. See `references/time_evolution.md`.
-## Common Workflows
-
-### Simulating a Damped Harmonic Oscillator
+## Trajectories and stochastic solvers
```python
-# System parameters
-N = 20 # Hilbert space dimension
-omega = 1.0 # Oscillator frequency
-kappa = 0.1 # Decay rate
-
-# Hamiltonian and collapse operators
-H = omega * num(N)
-c_ops = [np.sqrt(kappa) * destroy(N)]
-
-# Initial state
-psi0 = coherent(N, 3.0)
-
-# Time evolution
-tlist = np.linspace(0, 50, 200)
-result = mesolve(H, psi0, tlist, c_ops, e_ops=[num(N)])
-
-# Visualize
-plt.plot(tlist, result.expect[0])
-plt.xlabel('Time')
-plt.ylabel('⟨n⟩')
-plt.title('Photon Number Decay')
-plt.show()
+import numpy as np
+from qutip import basis, mcsolve, sigmam, sigmaz
+
+tlist = np.linspace(0.0, 10.0, 201)
+result = mcsolve(
+ 0.5 * sigmaz(),
+ basis(2, 0),
+ tlist,
+ [np.sqrt(0.2) * sigmam()],
+ e_ops=[basis(2, 0).proj()],
+ ntraj=400,
+ seeds=20260723,
+ options={"keep_runs_results": False, "progress_bar": ""},
+)
```
-### Two-Qubit Entanglement Dynamics
-
-```python
-# Create Bell state
-psi0 = bell_state('00')
-
-# Local dephasing on each qubit
-gamma = 0.1
-c_ops = [
- np.sqrt(gamma) * tensor(sigmaz(), qeye(2)),
- np.sqrt(gamma) * tensor(qeye(2), sigmaz())
-]
-
-# Track entanglement
-def compute_concurrence(t, psi):
- rho = ket2dm(psi) if psi.isket else psi
- return concurrence(rho)
-
-tlist = np.linspace(0, 10, 100)
-result = mesolve(qeye([2, 2]), psi0, tlist, c_ops)
-
-# Compute concurrence for each state
-C_t = [concurrence(state.proj()) for state in result.states]
-
-plt.plot(tlist, C_t)
-plt.xlabel('Time')
-plt.ylabel('Concurrence')
-plt.title('Entanglement Decay')
-plt.show()
-```
+Report `ntraj`, `result.seeds`, uncertainty or repeated-seed sensitivity, and
+whether individual runs were retained. Reuse `seeds=previous_result.seeds` only
+when paired trajectories are intentional. `ssesolve` and `smesolve` use the
+boolean `heterodyne` argument, not legacy integer noise codes.
-### Jaynes-Cummings Model
+## Steady states, spectra, and phase space
```python
-# System parameters
-N = 10 # Cavity Fock space
-wc = 1.0 # Cavity frequency
-wa = 1.0 # Atom frequency
-g = 0.05 # Coupling strength
-
-# Operators
-a = tensor(destroy(N), qeye(2)) # Cavity
-sm = tensor(qeye(N), sigmam()) # Atom
-
-# Hamiltonian (RWA)
-H = wc * a.dag() * a + wa * sm.dag() * sm + g * (a.dag() * sm + a * sm.dag())
-
-# Initial state: cavity in coherent state, atom in ground state
-psi0 = tensor(coherent(N, 2), basis(2, 0))
-
-# Dissipation
-kappa = 0.1 # Cavity decay
-gamma = 0.05 # Atomic decay
-c_ops = [np.sqrt(kappa) * a, np.sqrt(gamma) * sm]
-
-# Observables
-n_cav = a.dag() * a
-n_atom = sm.dag() * sm
-
-# Evolve
-tlist = np.linspace(0, 50, 200)
-result = mesolve(H, psi0, tlist, c_ops, e_ops=[n_cav, n_atom])
-
-# Plot
-fig, axes = plt.subplots(2, 1, figsize=(8, 6), sharex=True)
-axes[0].plot(tlist, result.expect[0])
-axes[0].set_ylabel('⟨n_cavity⟩')
-axes[1].plot(tlist, result.expect[1])
-axes[1].set_ylabel('⟨n_atom⟩')
-axes[1].set_xlabel('Time')
-plt.tight_layout()
-plt.show()
-```
-
-## Tips for Efficient Simulations
+import numpy as np
+from qutip import QFunc, liouvillian, operator_to_vector, qfunc, steadystate
-1. **Truncate Hilbert spaces**: Use smallest dimension that captures dynamics
-2. **Choose appropriate solver**: `sesolve` for pure states is faster than `mesolve`
-3. **Time-dependent terms**: String format (e.g., `'cos(w*t)'`) is fastest
-4. **Store only needed data**: Use `e_ops` instead of storing all states
-5. **Adjust tolerances**: Balance accuracy with computation time via `Options`
-6. **Parallel trajectories**: `mcsolve` automatically uses multiple CPUs
-7. **Check convergence**: Vary `ntraj`, Hilbert space size, and tolerances
+rho_ss = steadystate(H, c_ops, method="direct")
+residual = (liouvillian(H, c_ops) * operator_to_vector(rho_ss)).norm()
+assert residual < 1e-9
-## Troubleshooting
+xvec = np.linspace(-5.0, 5.0, 151)
+Q_once = qfunc(rho_ss, xvec, xvec)
+q_many = QFunc(xvec, xvec)
+Q_again = q_many(rho_ss)
+assert Q_once.shape == (len(xvec), len(xvec))
+```
-**Memory issues**: Reduce Hilbert space dimension, use `store_final_state` option, or consider Krylov methods
+For `wigner`, `qfunc`, and `QFunc`, array element `[j, k]` corresponds to
+`yvec[j]`, `xvec[k]`. In QuTiP 5.3, `QFunc` is initialized with fixed
+coordinates and called with a state; it has no `.eval` method. This skill never
+uses Python dynamic-code execution. Prefer `plot_wigner`, `Result.plot_expect`,
+or explicit Matplotlib axes as documented in `references/visualization.md`.
+
+Direct `spectrum` is a stationary steady-state spectrum. An FFT of a finite
+correlation requires explicit checks for tail decay, timestep aliasing,
+frequency resolution, window sensitivity, and transform convention. See
+`references/analysis.md`.
+
+## Advanced boundaries
+
+- Import HEOM from `qutip.solver.heom`; the legacy QuTiP 4 nonmarkov HEOM
+ namespace is stale.
+- Use `FloquetBasis` for modes and quasi-energies. Verify
+ `H(t + T) == H(t)` numerically and sweep basis/truncation choices.
+- Access PIQS with `from qutip import piqs`. `Dicke.pisolve` is only the
+ optimized diagonal-state/diagonal-Hamiltonian route; general Dicke-basis
+ dynamics use the Liouvillian with `mesolve`.
+- `brmesolve` can violate positivity, especially without secularization. Check
+ density-matrix eigenvalues over time.
+- QIP and optimal control are extension-package concerns. Never present local
+ simulation as quantum-hardware execution.
+
+See `references/advanced.md` for HEOM, Floquet, PIQS, stochastic, and extension
+boundaries.
+
+## Safe local CLIs
+
+All bundled tools are local-only, emit strict JSON, reject non-finite JSON and
+unknown keys, and never load pickle files or executable model code. Simulation
+imports are lazy, so every `--help` works without QuTiP installed.
+
+| Script | Purpose |
+|---|---|
+| `scripts/qobj_model_validator.py` | Validate bounded Qobj model JSON, dimensions, states, rates, and role compatibility |
+| `scripts/two_level_simulation.py` | Run a bounded two-level Lindblad or jump simulation |
+| `scripts/solver_config_planner.py` | Select a current solver and option/checklist plan |
+| `scripts/convergence_sweep.py` | Sweep tolerances/grid size or trajectory count on a synthetic model |
+| `scripts/result_audit.py` | Audit JSON output without deserializing Python objects |
+| `scripts/steady_state_spectrum_planner.py` | Plan bounded steady-state and direct/FFT spectral checks |
+
+Example:
-**Slow simulations**: Use string-based time-dependence, increase tolerances slightly, or try `method='bdf'` for stiff problems
+```bash
+python skills/qutip/scripts/two_level_simulation.py --help
+python skills/qutip/scripts/two_level_simulation.py \
+ --decay-rate 0.2 --t-final 10 --time-points 201 \
+ --output two-level.json
+python skills/qutip/scripts/result_audit.py two-level.json
+```
-**Numerical instabilities**: Decrease time steps (`nsteps` option), increase tolerances, or check Hamiltonian/operators are properly defined
+## Completion checklist
-**Import errors**: Ensure QuTiP is installed correctly; quantum gates require `qutip-qip` package
+- Record units, \(\hbar\), tensor order, initial state, channels, and model
+ assumptions.
+- Validate Hermiticity, norm/trace, positivity, dimensions, and generator units.
+- Pin QuTiP and direct extensions; record platform, Python, NumPy, and SciPy.
+- Inspect result options and stats; do not assume states were stored.
+- Perform cutoff, grid, tolerance/integrator, and stochastic convergence sweeps.
+- Save portable numeric/configuration summaries as JSON or text. Do not load
+ untrusted QuTiP object/result files because object serialization can execute
+ code.
## References
-This skill includes detailed reference documentation:
-
-- **`references/core_concepts.md`**: Quantum objects, states, operators, tensor products, composite systems
-- **`references/time_evolution.md`**: All solvers (sesolve, mesolve, mcsolve, brmesolve, etc.), time-dependent Hamiltonians, solver options
-- **`references/visualization.md`**: Bloch sphere, Wigner functions, Q-functions, Fock distributions, matrix plots
-- **`references/analysis.md`**: Expectation values, entropy, fidelity, entanglement measures, correlation functions, steady states
-- **`references/advanced.md`**: Floquet theory, HEOM, permutational invariance, stochastic methods, superoperators, performance tips
-
-## External Resources
-
-- Documentation: https://qutip.readthedocs.io/
-- Tutorials: https://qutip.org/qutip-tutorials/
-- API Reference: https://qutip.readthedocs.io/en/stable/apidoc/apidoc.html
-- GitHub: https://github.com/qutip/qutip
-
+- `references/core_concepts.md` — Qobj, dimensions, tensor products, states,
+ channels, and unit conventions
+- `references/time_evolution.md` — current solver signatures, options, results,
+ QobjEvo, trajectories, and numerical controls
+- `references/analysis.md` — physical-state audits, steady states,
+ correlations, spectra, and convergence
+- `references/visualization.md` — Wigner, Q functions, `QFunc`, Bloch, result,
+ and matrix plots
+- `references/advanced.md` — Bloch-Redfield, stochastic, Floquet, HEOM, PIQS,
+ and QuTiP family package boundaries
+
+## Dated official sources
+
+Verified **2026-07-23**:
+
+- [QuTiP 5.3.0 PyPI metadata](https://pypi.org/project/qutip/)
+- [QuTiP 5.3.0 release](https://github.com/qutip/qutip/releases/tag/v5.3.0)
+- [QuTiP 5.3 changelog](https://qutip.readthedocs.io/en/stable/changelog.html)
+- [QuTiP 5.3 API](https://qutip.readthedocs.io/en/stable/apidoc/apidoc.html)
+- [QuTiP version-5 tutorials](https://github.com/qutip/qutip-tutorials/tree/main/tutorials-v5)
+- [qutip-qip PyPI](https://pypi.org/project/qutip-qip/)
+- [qutip-qtrl PyPI](https://pypi.org/project/qutip-qtrl/)
+- [qutip-jax PyPI](https://pypi.org/project/qutip-jax/)
+- [official unreleased qutip-cupy repository](https://github.com/qutip/qutip-cupy)
diff --git a/skills/qutip/references/advanced.md b/skills/qutip/references/advanced.md
index 0fd4f745..dc7d7fbc 100644
--- a/skills/qutip/references/advanced.md
+++ b/skills/qutip/references/advanced.md
@@ -1,555 +1,413 @@
-# QuTiP Advanced Features
+# QuTiP 5.3 Advanced Methods and Package Boundaries
-## Floquet Theory
+Research and API verification date: **2026-07-23**. Examples target
+`qutip==5.3.0`.
-For time-periodic Hamiltonians H(t + T) = H(t).
+Specialized methods add assumptions and convergence parameters. Use them only
+when the physical model requires them.
-### Floquet Modes and Quasi-Energies
+## Bloch-Redfield
-```python
-from qutip import *
-import numpy as np
-
-# Time-periodic Hamiltonian
-w_d = 1.0 # Drive frequency
-T = 2 * np.pi / w_d # Period
-
-H0 = sigmaz()
-H1 = sigmax()
-H = [H0, [H1, 'cos(w*t)']]
-args = {'w': w_d}
-
-# Calculate Floquet modes and quasi-energies
-f_modes, f_energies = floquet_modes(H, T, args)
-
-print("Quasi-energies:", f_energies)
-print("Floquet modes:", f_modes)
-```
-
-### Floquet States at Time t
-
-```python
-# Get Floquet state at specific time
-t = 1.0
-f_states_t = floquet_states(f_modes, f_energies, t)
-```
-
-### Floquet State Decomposition
-
-```python
-# Decompose initial state in Floquet basis
-psi0 = basis(2, 0)
-f_coeff = floquet_state_decomposition(f_modes, f_energies, psi0)
-```
-
-### Floquet-Markov Master Equation
-
-```python
-# Time evolution with dissipation
-c_ops = [np.sqrt(0.1) * sigmam()]
-tlist = np.linspace(0, 20, 200)
-
-result = fmmesolve(H, psi0, tlist, c_ops, e_ops=[sigmaz()], T=T, args=args)
-
-# Plot results
-import matplotlib.pyplot as plt
-plt.plot(tlist, result.expect[0])
-plt.xlabel('Time')
-plt.ylabel('⟨σz⟩')
-plt.show()
-```
-
-### Floquet Tensor
+`brmesolve` derives dissipative dynamics from system coupling operators and bath
+noise-power spectra:
```python
-# Floquet tensor (generalized Bloch-Redfield)
-A_ops = [[sigmaz(), lambda w: 0.1 * w if w > 0 else 0]]
-
-# Build Floquet tensor
-R, U = floquet_markov_mesolve(H, psi0, tlist, A_ops, e_ops=[sigmaz()],
- T=T, args=args)
-```
-
-### Effective Hamiltonian
-
-```python
-# Time-averaged effective Hamiltonian
-H_eff = floquet_master_equation_steadystate(H, c_ops, T, args)
-```
-
-## Hierarchical Equations of Motion (HEOM)
-
-For non-Markovian open quantum systems with strong system-bath coupling.
-
-### Basic HEOM Setup
-
-```python
-from qutip import heom
-
-# System Hamiltonian
-H_sys = sigmaz()
-
-# Bath correlation function (exponential)
-Q = sigmax() # System-bath coupling operator
-ck_real = [0.1] # Coupling strengths
-vk_real = [0.5] # Bath frequencies
-
-# HEOM bath
-bath = heom.BosonicBath(Q, ck_real, vk_real)
-
-# Initial state
-rho0 = basis(2, 0) * basis(2, 0).dag()
-
-# Create HEOM solver
-max_depth = 5
-hsolver = heom.HEOMSolver(H_sys, [bath], max_depth=max_depth)
-
-# Time evolution
-tlist = np.linspace(0, 10, 100)
-result = hsolver.run(rho0, tlist)
-
-# Extract reduced system density matrix
-rho_sys = [r.extract_state(0) for r in result.states]
+import numpy as np
+from qutip import basis, brmesolve, sigmax, sigmaz
+
+def bath_spectrum(w):
+ return 0.02 * w if w > 0.0 else 0.0
+
+result = brmesolve(
+ 0.5 * sigmaz(),
+ basis(2, 0),
+ np.linspace(0.0, 30.0, 601),
+ a_ops=[(sigmax(), bath_spectrum)],
+ e_ops={"z": sigmaz()},
+ sec_cutoff=0.1,
+ options={"atol": 1e-10, "rtol": 1e-8, "progress_bar": ""},
+)
```
-### Multiple Baths
+Required assumptions:
-```python
-# Define multiple baths
-bath1 = heom.BosonicBath(sigmax(), [0.1], [0.5])
-bath2 = heom.BosonicBath(sigmay(), [0.05], [1.0])
+- weak system-environment coupling (Born approximation);
+- initially factorized system/bath state where the derivation requires it;
+- bath correlations decay faster than system evolution (Markov approximation);
+- stationary bath spectra with the correct angular-frequency and
+ positive/negative-frequency convention;
+- a justified secular or partial-secular cutoff.
-hsolver = heom.HEOMSolver(H_sys, [bath1, bath2], max_depth=5)
-```
+`sec_cutoff=-1` disables secularization. QuTiP's documentation warns that the
+non-secular equation may produce negativity. Inspect trace, Hermiticity, and
+minimum density-matrix eigenvalue through the entire run.
-### Drude-Lorentz Spectral Density
+Environment objects can express thermal and fitted spectra more clearly than
+callbacks. When using a callback, test it over every transition frequency and
+near zero.
-```python
-# Common in condensed matter physics
-from qutip.nonmarkov.heom import DrudeLorentzBath
-
-lam = 0.1 # Reorganization energy
-gamma = 0.5 # Bath cutoff frequency
-T = 1.0 # Temperature (in energy units)
-Nk = 2 # Number of Matsubara terms
+## Diffusive stochastic evolution
-bath = DrudeLorentzBath(Q, lam, gamma, T, Nk)
-```
-
-### HEOM Options
+Use `ssesolve` for conditioned pure states and `smesolve` for density matrices:
```python
-options = heom.HEOMSolver.Options(
- nsteps=2000,
- store_states=True,
- rtol=1e-7,
- atol=1e-9
+result = smesolve(
+ H,
+ rho0,
+ tlist,
+ c_ops=unmonitored_channels,
+ sc_ops=monitored_channels,
+ heterodyne=False,
+ e_ops={"signal": measured_quadrature},
+ ntraj=300,
+ seeds=20260723,
+ options={
+ "dt": 0.001,
+ "store_measurement": True,
+ "progress_bar": "",
+ },
)
-
-hsolver = heom.HEOMSolver(H_sys, [bath], max_depth=5, options=options)
```
-## Permutational Invariance
+`heterodyne=False` selects homodyne and `True` selects heterodyne. Legacy
+integer noise selectors are stale.
-For identical particle systems (e.g., spin ensembles).
+Converge:
-### Dicke States
+- stochastic integration `dt`;
+- output grid;
+- trajectory count;
+- seed sensitivity;
+- monitored efficiency/model choices;
+- measurement timing (`"start"` versus default end-of-step semantics when
+ relevant).
-```python
-from qutip import dicke
+`SMESolver.run_from_experiment` can replay known numeric noise or measurement
+records. Treat records as bounded numeric data; do not accept executable
+callbacks from untrusted configuration.
-# Dicke state |j, m⟩ for N spins
-N = 10 # Number of spins
-j = N/2 # Total angular momentum
-m = 0 # z-component
+## Non-Markovian Monte Carlo with time-local rates
-psi = dicke(N, j, m)
-```
-
-### Permutation-Invariant Operators
+`nm_mcsolve` is for time-local master equations whose decay rates can become
+negative. Its current input is a collection of operator/rate pairs, not a
+generic two-time bath-correlation callback:
```python
-from qutip.piqs import jspin
-
-# Collective spin operators
-N = 10
-Jx = jspin(N, 'x')
-Jy = jspin(N, 'y')
-Jz = jspin(N, 'z')
-Jp = jspin(N, '+')
-Jm = jspin(N, '-')
+import numpy as np
+from qutip import basis, nm_mcsolve, sigmam, sigmaz
+
+def rate(t):
+ return 0.1 * np.cos(t)
+
+result = nm_mcsolve(
+ 0.5 * sigmaz(),
+ basis(2, 0),
+ np.linspace(0.0, 5.0, 101),
+ [(sigmam(), rate)],
+ e_ops=[basis(2, 0).proj()],
+ ntraj=400,
+ seeds=20260723,
+ options={"progress_bar": ""},
+)
```
-### PIQS Dynamics
-
-```python
-from qutip.piqs import Dicke
-
-# Setup Dicke model
-N = 10
-emission = 1.0
-dephasing = 0.5
-pumping = 0.0
-collective_emission = 0.0
-
-system = Dicke(N=N, emission=emission, dephasing=dephasing,
- pumping=pumping, collective_emission=collective_emission)
+This method does not make an arbitrary non-Markovian model valid. Verify that
+the time-local generator and influence-martingale construction apply, report
+sampling uncertainty, and audit completeness/positivity behavior.
-# Initial state
-psi0 = dicke(N, N/2, N/2) # All spins up
+## Floquet theory
-# Time evolution
-tlist = np.linspace(0, 10, 100)
-result = system.solve(psi0, tlist, e_ops=[Jz])
-```
-
-## Non-Markovian Monte Carlo
-
-Quantum trajectories with memory effects.
+For \(H(t+T)=H(t)\), the current QuTiP 5 abstraction is `FloquetBasis`:
```python
-from qutip import nm_mcsolve
-
-# Non-Markovian bath correlation
-def bath_correlation(t1, t2):
- tau = abs(t2 - t1)
- return np.exp(-tau / 2.0) * np.cos(tau)
-
-# System setup
-H = sigmaz()
-c_ops = [sigmax()]
-psi0 = basis(2, 0)
-tlist = np.linspace(0, 10, 100)
-
-# Solve with memory
-result = nm_mcsolve(H, psi0, tlist, c_ops, sc_ops=[],
- bath_corr=bath_correlation, ntraj=500,
- e_ops=[sigmaz()])
-```
-
-## Stochastic Solvers with Measurements
-
-### Continuous Measurement
+import numpy as np
+from qutip import FloquetBasis, QobjEvo, sigmax, sigmaz
-```python
-# Homodyne detection
-sc_ops = [np.sqrt(0.1) * destroy(N)] # Measurement operator
+drive_frequency = 2.0
+period = 2.0 * np.pi / drive_frequency
-result = ssesolve(H, psi0, tlist, sc_ops=sc_ops,
- e_ops=[num(N)], ntraj=100,
- noise=11) # 11 for homodyne
+def drive(t, amplitude, omega):
+ return amplitude * np.cos(omega * t)
-# Heterodyne detection
-result = ssesolve(H, psi0, tlist, sc_ops=sc_ops,
- e_ops=[num(N)], ntraj=100,
- noise=12) # 12 for heterodyne
+H = QobjEvo(
+ [0.5 * sigmaz(), [sigmax(), drive]],
+ args={"amplitude": 0.2, "omega": drive_frequency},
+)
+floquet = FloquetBasis(H, period)
+quasienergies = floquet.e_quasi
+modes_at_zero = floquet.mode(0.0)
```
-### Photon Counting
-
-```python
-# Quantum jump times
-result = mcsolve(H, psi0, tlist, c_ops, ntraj=50,
- options=Options(store_states=True))
-
-# Extract measurement times
-for i, jump_times in enumerate(result.col_times):
- print(f"Trajectory {i} jump times: {jump_times}")
- print(f"Which operator: {result.col_which[i]}")
-```
+Before using Floquet dynamics:
-## Krylov Subspace Methods
+1. numerically check `H(t + period) - H(t)` over representative times;
+2. state the quasi-energy branch convention;
+3. sweep Hilbert truncation and any precomputation grid;
+4. inspect near-degenerate quasi-energies;
+5. compare one-period propagation with direct evolution.
-Efficient for large systems.
+`fsesolve` handles closed periodic dynamics. `fmmesolve` handles a
+Floquet-Markov construction:
```python
-from qutip import krylovsolve
-
-# Use Krylov solver
-result = krylovsolve(H, psi0, tlist, krylov_dim=10, e_ops=[num(N)])
+result = fmmesolve(
+ floquet,
+ rho0,
+ tlist,
+ c_ops=coupling_operators,
+ spectra_cb=spectrum_callbacks,
+ e_ops={"z": sigmaz()},
+ w_th=temperature,
+)
```
-## Bloch-Redfield Master Equation
+The coupling operators and spectrum callbacks are paired by position. They are
+not ordinary Lindblad channels. Verify weak-coupling, bath, and thermal
+assumptions. QuTiP 5 result states are in the lab basis by default; the
+`store_floquet_state` option controls additional Floquet-basis storage.
-For weak system-bath coupling.
+Old free-function mode workflows may remain for compatibility, but new work
+should use `FloquetBasis`.
-```python
-# Bath spectral density
-def ohmic_spectrum(w):
- if w >= 0:
- return 0.1 * w # Ohmic
- else:
- return 0
-
-# Coupling operators and spectra
-a_ops = [[sigmax(), ohmic_spectrum]]
-
-# Solve
-result = brmesolve(H, psi0, tlist, a_ops, e_ops=[sigmaz()])
-```
+## HEOM
-### Temperature-Dependent Bath
+Import from the current namespace:
```python
-def thermal_spectrum(w):
- # Bose-Einstein distribution
- T = 1.0 # Temperature
- if abs(w) < 1e-10:
- return 0.1 * T
- n_th = 1 / (np.exp(abs(w)/T) - 1)
- if w >= 0:
- return 0.1 * w * (n_th + 1)
- else:
- return 0.1 * abs(w) * n_th
-
-a_ops = [[sigmax(), thermal_spectrum]]
-result = brmesolve(H, psi0, tlist, a_ops, e_ops=[sigmaz()])
+from qutip.solver.heom import DrudeLorentzBath, HEOMSolver
```
-## Superoperators and Quantum Channels
+The legacy QuTiP 4 nonmarkov HEOM namespace is stale.
-### Superoperator Representations
+Example:
```python
-# Liouvillian
-L = liouvillian(H, c_ops)
-
-# Convert between representations
-from qutip import (spre, spost, sprepost,
- super_to_choi, choi_to_super,
- super_to_kraus, kraus_to_super)
-
-# Superoperator forms
-L_spre = spre(H) # Left multiplication
-L_spost = spost(H) # Right multiplication
-L_sprepost = sprepost(H, H.dag())
-
-# Choi matrix
-choi = super_to_choi(L)
-
-# Kraus operators
-kraus = super_to_kraus(L)
+import numpy as np
+from qutip import basis, sigmax, sigmaz
+from qutip.solver.heom import DrudeLorentzBath, HEOMSolver
+
+H_system = 0.5 * sigmaz()
+rho0 = basis(2, 0).proj()
+
+bath = DrudeLorentzBath(
+ sigmax(),
+ lam=0.05,
+ gamma=1.0,
+ T=0.5,
+ Nk=3,
+)
+solver = HEOMSolver(
+ H_system,
+ bath,
+ max_depth=4,
+ options={
+ "atol": 1e-10,
+ "rtol": 1e-8,
+ "store_states": True,
+ "store_ados": False,
+ "progress_bar": "",
+ },
+)
+result = solver.run(rho0, np.linspace(0.0, 10.0, 201))
+reduced_states = result.states
```
-### Quantum Channels
+For arbitrary exponential expansions, the full current constructor is:
-```python
-# Depolarizing channel
-p = 0.1 # Error probability
-K0 = np.sqrt(1 - 3*p/4) * qeye(2)
-K1 = np.sqrt(p/4) * sigmax()
-K2 = np.sqrt(p/4) * sigmay()
-K3 = np.sqrt(p/4) * sigmaz()
-
-kraus_ops = [K0, K1, K2, K3]
-E = kraus_to_super(kraus_ops)
-
-# Apply channel
-rho_out = E * operator_to_vector(rho_in)
-rho_out = vector_to_operator(rho_out)
+```text
+BosonicBath(Q, ck_real, vk_real, ck_imag, vk_imag,
+ combine=True, tag=None)
```
-### Amplitude Damping
+Do not omit the imaginary coefficient/frequency lists; use empty lists only
+when the modeled correlation genuinely has no imaginary expansion.
-```python
-# T1 decay
-gamma = 0.1
-K0 = Qobj([[1, 0], [0, np.sqrt(1 - gamma)]])
-K1 = Qobj([[0, np.sqrt(gamma)], [0, 0]])
+HEOM convergence requires independent sweeps of:
-E_damping = kraus_to_super([K0, K1])
-```
+- hierarchy `max_depth`;
+- bath expansion count (`Nk` or fitted exponent count);
+- Matsubara versus Padé/environment approximation;
+- ODE tolerances/integrator;
+- system Hilbert truncation;
+- time grid and duration.
-### Phase Damping
+Record \(\lambda\), cutoff, temperature, and all energies in one consistent
+\(\hbar=k_B=1\) unit convention if that convention is used.
-```python
-# T2 dephasing
-gamma = 0.1
-K0 = Qobj([[1, 0], [0, np.sqrt(1 - gamma/2)]])
-K1 = Qobj([[0, 0], [0, np.sqrt(gamma/2)]])
+`result.states` are reduced system states. Set `store_ados=True` only when the
+full auxiliary-density hierarchy is needed; then `result.ado_states` can be
+large. A previous final ADO state may initialize a continuation only when its
+hierarchy is compatible.
-E_dephasing = kraus_to_super([K0, K1])
-```
+HEOM can mix supported bosonic and fermionic baths. Fermionic odd parity is a
+special solver construction and must match the initial operator parity.
-## Quantum Trajectories Analysis
+## Permutational invariance (PIQS)
-### Extract Individual Trajectories
+In QuTiP 5.3, use the `piqs` module exported by `qutip`:
```python
-options = Options(store_states=True, store_final_state=False)
-result = mcsolve(H, psi0, tlist, c_ops, ntraj=100, options=options)
+import numpy as np
+from qutip import mesolve, piqs
-# Access individual trajectories
-for i in range(len(result.states)):
- trajectory = result.states[i] # List of states for trajectory i
- # Analyze trajectory
+N = 10
+Jz = piqs.jspin(N, "z", basis="dicke")
+rho0 = piqs.dicke(N, N / 2, N / 2)
+
+ensemble = piqs.Dicke(
+ N,
+ emission=0.05,
+ dephasing=0.01,
+ collective_emission=0.02,
+)
+L = ensemble.liouvillian()
+result = mesolve(
+ L,
+ rho0,
+ np.linspace(0.0, 20.0, 201),
+ e_ops={"Jz": Jz},
+)
```
-### Trajectory Statistics
+`piqs.Dicke.pisolve(initial_state, tlist)` is an optimized method only for
+diagonal Hamiltonians and diagonal initial density matrices. It takes no
+`e_ops`; use the general Liouvillian path for arbitrary observables and
+non-diagonal cases.
-```python
-# Mean and standard deviation
-result = mcsolve(H, psi0, tlist, c_ops, e_ops=[num(N)], ntraj=500)
+PIQS exploits permutation symmetry in a Dicke basis. Before using it:
-n_mean = result.expect[0]
-n_std = result.std_expect[0]
+- verify identical two-level constituents and permutation-symmetric dynamics;
+- distinguish local and collective rates;
+- keep operators and states in the same `dicke` or `uncoupled` basis;
+- do not interpret Dicke-basis matrix dimension as \(2^N\);
+- compare with a small full-Hilbert-space model where feasible.
-# Photon number distribution at final time
-final_states = [result.states[i][-1] for i in range(len(result.states))]
-```
+`piqs.collapse_uncoupled` returns ordinary collapse operators in a \(2^N\)
+space and is only practical for modest `N`.
-## Time-Dependent Terms Advanced
+## Superoperators and channels
-### QobjEvo
+Current conversions:
```python
-from qutip import QobjEvo
-
-# Time-dependent Hamiltonian with QobjEvo
-def drive(t, args):
- return args['A'] * np.exp(-t/args['tau']) * np.sin(args['w'] * t)
-
-H0 = num(N)
-H1 = destroy(N) + create(N)
-args = {'A': 1.0, 'w': 1.0, 'tau': 5.0}
-
-H_td = QobjEvo([H0, [H1, drive]], args=args)
-
-# Can update args without recreating
-H_td.arguments({'A': 2.0, 'w': 1.5, 'tau': 10.0})
+from qutip import (
+ choi_to_kraus,
+ choi_to_super,
+ kraus_to_super,
+ operator_to_vector,
+ spre,
+ spost,
+ super_to_choi,
+ super_to_kraus,
+ vector_to_operator,
+)
```
-### Compiled Time-Dependent Terms
+QuTiP column-stacks vectorized operators. Use the conversion functions rather
+than manual reshape logic. Check complete positivity and trace preservation in
+the intended representation, and preserve structured dimensions.
-```python
-# Fastest method (requires Cython)
-H = [num(N), [destroy(N) + create(N), 'A * exp(-t/tau) * sin(w*t)']]
-args = {'A': 1.0, 'w': 1.0, 'tau': 5.0}
+## QuTiP family packages
-# QuTiP compiles this for speed
-result = sesolve(H, psi0, tlist, args=args)
-```
+Official PyPI metadata snapshot:
-### Callback Functions
+| Distribution | Latest published | Release date | Maturity | `Requires-Python` | Required distributions |
+|---|---:|---:|---|---|---|
+| `qutip` | 5.3.0 | 2026-05-22 | production/stable | `>=3.11` | NumPy `>=1.23.2`; SciPy `>=1.9.2` except `1.16.0`/`1.17.0`; `packaging` |
+| `qutip-qip` | 0.4.2 | 2026-06-23 | production/stable | not declared | NumPy `>=1.16.6`; SciPy `>=1.0`; QuTiP `>=4.6`; `packaging` |
+| `qutip-qtrl` | 0.2.0 | 2026-06-23 | pre-alpha classifier | not declared | NumPy `>=1.19`; SciPy `>=1.0`; QuTiP `>=5.0.1`; `packaging` |
+| `qutip-jax` | 0.1.1 | 2025-05-29 | pre-alpha classifier | not declared | QuTiP `>=5.1.0`; JAX; Diffrax; Equinox |
+| `qutip-cupy` | no PyPI project | — | unreleased repository | — | no released metadata |
-```python
-# Advanced control
-def time_dependent_coeff(t, args):
- # Access solver state if needed
- return complex_function(t, args)
+“Not declared” means the current PyPI `Requires-Python` field is empty, not
+that every Python release is supported. Resolve and test each extension in the
+same Python 3.11+ environment as QuTiP 5.3. Direct pins do not freeze transitive
+JAX/CuPy stacks; use a lockfile for a deployable environment.
-H = [H0, [H1, time_dependent_coeff]]
-```
+### qutip-qip 0.4.2
-## Parallel Processing
+Status: production/stable on PyPI, released 2026-06-23.
-### Parallel Map
+Purpose:
-```python
-from qutip import parallel_map
+- circuit and gate models;
+- `QubitCircuit` unitary circuit simulation;
+- `Processor` pulse/noise/open-system device simulation.
-# Define task
-def simulate(gamma):
- c_ops = [np.sqrt(gamma) * destroy(N)]
- result = mesolve(H, psi0, tlist, c_ops, e_ops=[num(N)])
- return result.expect[0]
-
-# Run in parallel
-gamma_values = np.linspace(0, 1, 20)
-results = parallel_map(simulate, gamma_values, num_cpus=4)
-```
-
-### Serial Map (for debugging)
+Migration boundary:
```python
-from qutip import serial_map
-
-# Same interface but runs serially
-results = serial_map(simulate, gamma_values)
+from qutip_qip.circuit import QubitCircuit
```
-## File I/O
-
-### Save/Load Quantum Objects
-
-```python
-# Save
-H.save('hamiltonian.qu')
-psi.save('state.qu')
-
-# Load
-H_loaded = qload('hamiltonian.qu')
-psi_loaded = qload('state.qu')
-```
+Do not import `qutip.qip` in QuTiP 5 code. This package is a local simulator,
+not a hardware provider or execution service.
-### Save/Load Results
+### qutip-qtrl 0.2.0
-```python
-# Save simulation results
-result = mesolve(H, psi0, tlist, c_ops, e_ops=[num(N)])
-result.save('simulation.dat')
+Status: latest published release 2026-06-23; PyPI classifier is pre-alpha.
-# Load results
-from qutip import Result
-loaded_result = Result.load('simulation.dat')
-```
+Purpose: quantum optimal control with GRAPE and CRAB, emphasizing integration
+with QuTiP physics models.
-### Export to MATLAB
+Migration boundary:
```python
-# Export to .mat file
-H.matlab_export('hamiltonian.mat', 'H')
+from qutip_qtrl import pulseoptim
```
-## Solver Options
+It replaces the old `qutip.control` import. It is **not** a trajectory viewer.
+Optimization success does not establish robustness: report bounds, objective,
+gradient/termination status, seeds, discretization, and validation under model
+uncertainty.
-### Fine-Tuning Solvers
+### qutip-jax 0.1.1
-```python
-options = Options()
+Status: latest published release 2025-05-29; explicitly pre-alpha and described
+as not ready for production use.
-# Integration parameters
-options.nsteps = 10000 # Max internal steps
-options.rtol = 1e-8 # Relative tolerance
-options.atol = 1e-10 # Absolute tolerance
+Purpose: a JAX linear-algebra data backend for GPU execution and automatic
+differentiation. It depends on QuTiP 5.1 or newer plus JAX, Diffrax, and Equinox.
-# Method selection
-options.method = 'adams' # Non-stiff (default)
-# options.method = 'bdf' # Stiff problems
+Validate dtype, device placement, JIT/gradient support for each operation, and
+results against the built-in QuTiP data backend.
-# Storage options
-options.store_states = True
-options.store_final_state = True
+### qutip-cupy
-# Progress
-options.progress_bar = True
+The repository belongs to the QuTiP GitHub organization and implements a CuPy
+data backend, but:
-# Random number seed (for reproducibility)
-options.seeds = 12345
+- PyPI returns no `qutip-cupy` project;
+- the repository README says it is not officially released;
+- the repository's installation text targets development-era QuTiP and is not
+ a reproducible 5.3 release recipe.
-result = mesolve(H, psi0, tlist, c_ops, options=options)
-```
+Do not recommend it as a stable extension. If a user explicitly accepts an
+experimental source build, isolate and audit that separately rather than adding
+it to this pinned skill snapshot.
-### Debugging
+## Parallel and performance boundaries
-```python
-# Enable detailed output
-options.verbose = True
+- `mcsolve`/stochastic solvers expose `map`, `num_cpus`, and related options.
+ Parallelism changes scheduling and cost, not the required trajectory
+ convergence.
+- `parallel_map` executes Python callables. Use only trusted, statically defined
+ local functions and bounded task lists.
+- Sparse matrices help only when operations preserve sparsity.
+- Large HEOM, Liouvillian, dense diagonalization, and PIQS/full-space conversions
+ can grow rapidly. Estimate dimensions and memory before construction.
+- QuTiP 5.3's `matrix_form` option for `mesolve` and new Krylov density-matrix
+ support are performance choices that require output equivalence tests.
-# Memory tracking
-options.num_cpus = 1 # Easier debugging
-```
+## Sources (verified 2026-07-23)
-## Performance Tips
-
-1. **Use sparse matrices**: QuTiP does this automatically
-2. **Minimize Hilbert space**: Truncate when possible
-3. **Choose right solver**:
- - Pure states: `sesolve` faster than `mesolve`
- - Stochastic: `mcsolve` for quantum jumps
- - Periodic: Floquet methods
-4. **Time-dependent terms**: String format fastest
-5. **Expectation values**: Only compute needed observables
-6. **Parallel trajectories**: `mcsolve` uses all CPUs
-7. **Krylov methods**: For very large systems
-8. **Memory**: Use `store_final_state` instead of `store_states` when possible
+- [Bloch-Redfield guide](https://qutip.readthedocs.io/en/stable/guide/dynamics/dynamics-bloch-redfield.html)
+- [Stochastic solver guide](https://qutip.readthedocs.io/en/stable/guide/dynamics/dynamics-stochastic.html)
+- [Floquet API](https://qutip.readthedocs.io/en/stable/apidoc/solver.html#floquet-states-and-floquet-markov-master-equation)
+- [HEOM API](https://qutip.readthedocs.io/en/stable/apidoc/heom.html)
+- [PIQS API](https://qutip.readthedocs.io/en/stable/apidoc/piqs.html)
+- [QuTiP 5.3.0 release](https://github.com/qutip/qutip/releases/tag/v5.3.0)
+- [qutip-qip 0.4.2](https://pypi.org/project/qutip-qip/)
+- [qutip-qtrl 0.2.0](https://pypi.org/project/qutip-qtrl/)
+- [qutip-jax 0.1.1](https://pypi.org/project/qutip-jax/)
+- [official qutip-cupy repository](https://github.com/qutip/qutip-cupy)
diff --git a/skills/qutip/references/analysis.md b/skills/qutip/references/analysis.md
index 69f81f1f..368d402a 100644
--- a/skills/qutip/references/analysis.md
+++ b/skills/qutip/references/analysis.md
@@ -1,523 +1,319 @@
-# QuTiP Analysis and Measurement
+# QuTiP 5.3 Analysis, Steady States, and Spectra
-## Expectation Values
+Research and API verification date: **2026-07-23**. Examples target
+`qutip==5.3.0`.
-### Basic Expectation Values
+## Analysis starts with invariants
-```python
-from qutip import *
-import numpy as np
-
-# Single operator
-psi = coherent(N, 2)
-n_avg = expect(num(N), psi)
-
-# Multiple operators
-ops = [num(N), destroy(N), create(N)]
-results = expect(ops, psi) # Returns list
-```
-
-### Expectation Values for Density Matrices
-
-```python
-# Works with both pure states and density matrices
-rho = thermal_dm(N, 2)
-n_avg = expect(num(N), rho)
-```
-
-### Variance
-
-```python
-# Calculate variance of observable
-var_n = variance(num(N), psi)
-
-# Manual calculation
-var_n = expect(num(N)**2, psi) - expect(num(N), psi)**2
-```
-
-### Time-Dependent Expectation Values
-
-```python
-# During time evolution
-result = mesolve(H, psi0, tlist, c_ops, e_ops=[num(N)])
-n_t = result.expect[0] # Array of ⟨n⟩ at each time
-```
-
-## Entropy Measures
-
-### Von Neumann Entropy
-
-```python
-from qutip import entropy_vn
-
-# Density matrix entropy
-rho = thermal_dm(N, 2)
-S = entropy_vn(rho) # Returns S = -Tr(ρ log₂ ρ)
-```
-
-### Linear Entropy
-
-```python
-from qutip import entropy_linear
-
-# Linear entropy S_L = 1 - Tr(ρ²)
-S_L = entropy_linear(rho)
-```
-
-### Entanglement Entropy
-
-```python
-# For bipartite systems
-psi = bell_state('00')
-rho = psi.proj()
-
-# Trace out subsystem B to get reduced density matrix
-rho_A = ptrace(rho, 0)
-
-# Entanglement entropy
-S_ent = entropy_vn(rho_A)
-```
-
-### Mutual Information
-
-```python
-from qutip import entropy_mutual
-
-# For bipartite state ρ_AB
-I = entropy_mutual(rho, [0, 1]) # I(A:B) = S(A) + S(B) - S(AB)
-```
-
-### Conditional Entropy
-
-```python
-from qutip import entropy_conditional
-
-# S(A|B) = S(AB) - S(B)
-S_cond = entropy_conditional(rho, 0) # Entropy of subsystem 0 given subsystem 1
-```
-
-## Fidelity and Distance Measures
-
-### State Fidelity
-
-```python
-from qutip import fidelity
-
-# Fidelity between two states
-psi1 = coherent(N, 2)
-psi2 = coherent(N, 2.1)
-
-F = fidelity(psi1, psi2) # Returns value in [0, 1]
-```
-
-### Process Fidelity
-
-```python
-from qutip import process_fidelity
-
-# Fidelity between two processes (superoperators)
-U_ideal = (-1j * H * t).expm()
-U_actual = mesolve(H, basis(N, 0), [0, t], c_ops).states[-1]
-
-F_proc = process_fidelity(U_ideal, U_actual)
-```
-
-### Trace Distance
-
-```python
-from qutip import tracedist
-
-# Trace distance D = (1/2) Tr|ρ₁ - ρ₂|
-rho1 = coherent_dm(N, 2)
-rho2 = thermal_dm(N, 2)
-
-D = tracedist(rho1, rho2) # Returns value in [0, 1]
-```
-
-### Hilbert-Schmidt Distance
+For every reported state, record quantitative checks before interpreting an
+observable:
```python
-from qutip import hilbert_dist
+import numpy as np
-# Hilbert-Schmidt distance
-D_HS = hilbert_dist(rho1, rho2)
+def density_audit(rho, tolerance=1e-9):
+ eigenvalues = np.asarray(rho.eigenenergies(), dtype=float)
+ trace = complex(rho.tr())
+ return {
+ "is_hermitian": bool(rho.isherm),
+ "trace_error": float(abs(trace - 1.0)),
+ "minimum_eigenvalue": float(eigenvalues.min()),
+ "positive_within_tolerance": bool(eigenvalues.min() >= -tolerance),
+ }
```
-### Bures Distance
+Also check:
-```python
-from qutip import bures_dist
+- `state.dims` matches every observable and the declared subsystem order;
+- ket norm or density-matrix trace stays stable over time;
+- Hermitian observables have negligible imaginary expectation;
+- populations remain within tolerance of `[0, 1]`;
+- symmetry, conserved quantity, or analytic-limit checks hold where applicable;
+- numerical tolerance is smaller than the effect being claimed.
-# Bures distance
-D_B = bures_dist(rho1, rho2)
-```
+Do not repair a state by clipping eigenvalues or renormalizing unless that
+post-processing is part of a documented method and its impact is reported.
-### Bures Angle
+## Expectations and uncertainty
```python
-from qutip import bures_angle
+from qutip import expect, num, variance
-# Bures angle
-angle = bures_angle(rho1, rho2)
+n_op = num(N)
+mean_n = expect(n_op, rho)
+variance_n = variance(n_op, rho)
```
-## Entanglement Measures
-
-### Concurrence
+For solver output, dict-form `e_ops` gives named `result.e_data`:
```python
-from qutip import concurrence
-
-# For two-qubit states
-psi = bell_state('00')
-rho = psi.proj()
-
-C = concurrence(rho) # C = 1 for maximally entangled states
+result = mesolve(
+ H,
+ rho0,
+ tlist,
+ c_ops=c_ops,
+ e_ops={"number": n_op, "energy": H},
+)
+number_vs_time = result.e_data["number"]
```
-### Negativity
-
-```python
-from qutip import negativity
-
-# Negativity (partial transpose criterion)
-N_ent = negativity(rho, 0) # Partial transpose w.r.t. subsystem 0
-
-# Logarithmic negativity
-from qutip import logarithmic_negativity
-E_N = logarithmic_negativity(rho, 0)
-```
+For Monte Carlo/stochastic results, report both ensemble means and sampling
+uncertainty. `std_expect` is trajectory spread, not automatically the standard
+error; a simple independent-trajectory standard error scales as
+`std / sqrt(ntraj)`, subject to the solver's sampling design.
-### Entangling Power
+## Entropy, purity, and distances
```python
-from qutip import entangling_power
+from qutip import entropy_linear, entropy_vn, fidelity, tracedist
-# For unitary gates
-U = cnot()
-E_pow = entangling_power(U)
+von_neumann_nats = entropy_vn(rho) # default natural-log base
+von_neumann_bits = entropy_vn(rho, base=2)
+linear_entropy = entropy_linear(rho)
+purity = float((rho * rho).tr().real)
+state_fidelity = fidelity(rho, sigma)
+trace_distance = tracedist(rho, sigma)
```
-## Purity Measures
-
-### Purity
-
-```python
-# Purity P = Tr(ρ²)
-P = (rho * rho).tr()
-
-# For pure states: P = 1
-# For maximally mixed: P = 1/d
-```
+Always state the logarithm base. Check the QuTiP definition before comparing
+fidelity values with a source that may square or unsquare the quantity.
-### Checking State Properties
+For bipartite entropy:
```python
-# Is state pure?
-is_pure = abs((rho * rho).tr() - 1.0) < 1e-10
-
-# Is operator Hermitian?
-H.isherm
-
-# Is operator unitary?
-U.check_isunitary()
+rho_A = rho_AB.ptrace(0) # keep subsystem 0
+entanglement_entropy = entropy_vn(rho_A, base=2)
```
-## Measurement
-
-### Projective Measurement
-
-```python
-from qutip import measurement
-
-# Measure in computational basis
-psi = (basis(2, 0) + basis(2, 1)).unit()
+This is an entanglement entropy only when the global bipartite state and the
+chosen measure meet the necessary assumptions. For mixed states, reduced-state
+entropy also contains classical mixture.
-# Perform measurement
-result, state_after = measurement.measure(psi, None) # Random outcome
+Common specialized functions include `concurrence`, `negativity`,
+`entropy_mutual`, and `partial_transpose`. Verify their supported dimensions and
+argument definitions in the current API before applying them.
-# Specific measurement operator
-M = basis(2, 0).proj()
-prob = measurement.measure_povm(psi, [M, qeye(2) - M])
-```
+## Steady-state calculation
-### Measurement Statistics
-
-```python
-from qutip import measurement_statistics
+Current signature:
-# Get all possible outcomes and probabilities
-outcomes, probabilities = measurement_statistics(psi, [M0, M1])
+```text
+steadystate(A, c_ops=[], *, method="direct", solver=None, **kwargs)
```
-### Observable Measurement
+`A` may be a Hamiltonian or a Liouvillian. Available high-level methods include
+`direct`, `eigen`, `svd`, `power`, and `propagator`; linear-system solver choices
+are separate.
```python
-from qutip import measure_observable
+from qutip import liouvillian, operator_to_vector, steadystate
-# Measure observable and get result + collapsed state
-result, state_collapsed = measure_observable(psi, sigmaz())
+rho_ss = steadystate(H, c_ops, method="direct")
+L = liouvillian(H, c_ops)
+residual = (L * operator_to_vector(rho_ss)).norm()
```
-### POVM Measurements
-
-```python
-from qutip import measure_povm
-
-# Positive Operator-Valued Measure
-E_0 = Qobj([[0.8, 0], [0, 0.2]])
-E_1 = Qobj([[0.2, 0], [0, 0.8]])
-
-result, state_after = measure_povm(psi, [E_0, E_1])
-```
+Report:
-## Coherence Measures
+- residual norm and normalization error;
+- Hermiticity and minimum eigenvalue;
+- method and linear solver;
+- matrix/data representation and relevant tolerances;
+- whether the zero eigenvalue is unique;
+- comparison with long-time evolution from more than one initial state when
+ uniqueness matters.
-### l1-norm Coherence
+A small residual does not prove uniqueness or physicality. Degenerate steady
+spaces require analysis of the Liouvillian nullspace and initial-state
+dependence.
-```python
-from qutip import coherence_l1norm
+The `svd` method is dense and intended for small systems. Sparse/direct methods
+can still be memory intensive; monitor fill-in and compare methods on a reduced
+model.
-# l1-norm of off-diagonal elements
-C_l1 = coherence_l1norm(rho)
-```
+For periodically driven systems, a static `steadystate` call is generally not
+the desired asymptotic object. Use an appropriate periodic/Floquet approach.
+In QuTiP 5.3, `steadystate_fourier` is the current name for the specialized
+cosine-driven Fourier solver; `steadystate_floquet` is deprecated.
-## Correlation Functions
+## Two-time correlations
-### Two-Time Correlation
+Current stationary/transient two-operator API:
```python
from qutip import correlation_2op_1t, correlation_2op_2t
-# Single-time correlation ⟨A(t+τ)B(t)⟩
-A = destroy(N)
-B = create(N)
-taulist = np.linspace(0, 10, 200)
-
-corr = correlation_2op_1t(H, rho0, taulist, c_ops, A, B)
-
-# Two-time correlation ⟨A(t)B(τ)⟩
-tlist = np.linspace(0, 10, 100)
-corr_2t = correlation_2op_2t(H, rho0, tlist, taulist, c_ops, A, B)
-```
-
-### Three-Operator Correlation
-
-```python
-from qutip import correlation_3op_1t
-
-# ⟨A(t)B(t+τ)C(t)⟩
-C_op = num(N)
-corr_3 = correlation_3op_1t(H, rho0, taulist, c_ops, A, B, C_op)
-```
-
-### Four-Operator Correlation
-
-```python
-from qutip import correlation_4op_1t
-
-# ⟨A(0)B(τ)C(τ)D(0)⟩
-D_op = create(N)
-corr_4 = correlation_4op_1t(H, rho0, taulist, c_ops, A, B, C_op, D_op)
-```
-
-## Spectrum Analysis
-
-### FFT Spectrum
-
-```python
-from qutip import spectrum_correlation_fft
-
-# Power spectrum from correlation function
-w, S = spectrum_correlation_fft(taulist, corr)
-```
-
-### Direct Spectrum Calculation
-
-```python
-from qutip import spectrum
+corr_1t = correlation_2op_1t(
+ H,
+ rho0,
+ taulist,
+ c_ops,
+ a_op,
+ b_op,
+ solver="me",
+ options={"atol": 1e-10, "rtol": 1e-8},
+)
-# Emission/absorption spectrum
-wlist = np.linspace(0, 2, 200)
-spec = spectrum(H, wlist, c_ops, A, B)
+corr_2t = correlation_2op_2t(
+ H,
+ rho0,
+ tlist,
+ taulist,
+ c_ops,
+ a_op,
+ b_op,
+)
```
-### Pseudo-Modes
-
-```python
-from qutip import spectrum_pi
-
-# Spectrum with pseudo-mode decomposition
-spec_pi = spectrum_pi(H, rho0, wlist, c_ops, A, B)
-```
+For `correlation_2op_1t`, the quantity is ordered according to the function's
+documented \(A(\tau)B(0)\)-style convention. Do not infer operator order from a
+variable name.
-## Steady State Analysis
+Passing `state0=None` requests a steady-state initial condition only for
+supported constant systems with collapse operators. Compute and audit the
+steady state explicitly when provenance matters.
-### Finding Steady State
+Current three-operator entry points include:
```python
-from qutip import steadystate
-
-# Find steady state ∂ρ/∂t = 0
-rho_ss = steadystate(H, c_ops)
-
-# Different methods
-rho_ss = steadystate(H, c_ops, method='direct') # Default
-rho_ss = steadystate(H, c_ops, method='eigen') # Eigenvalue
-rho_ss = steadystate(H, c_ops, method='svd') # SVD
-rho_ss = steadystate(H, c_ops, method='power') # Power method
+from qutip import correlation_3op, correlation_3op_1t, correlation_3op_2t
```
-### Steady State Properties
+QuTiP 5.3 added `max_t_plus_tau` and mapping controls to selected two-time and
+three-operator routines. The old `correlation_4op_1t` recipe is not a current
+public API; express a four-operator quantity through the documented
+three-operator interfaces when mathematically appropriate, or derive a tested
+regression workflow.
-```python
-# Verify it's steady
-L = liouvillian(H, c_ops)
-assert (L * operator_to_vector(rho_ss)).norm() < 1e-10
+Correlation checks:
-# Compute steady-state expectation values
-n_ss = expect(num(N), rho_ss)
-```
+- operator ordering and adjoints;
+- transient versus stationary definition;
+- normalized versus unnormalized coherence;
+- regression-theorem assumptions;
+- convergence of both `tlist` and `taulist`;
+- tail decay before finite-window transforms.
-## Quantum Fisher Information
+## Direct stationary spectrum
-```python
-from qutip import qfisher
+Current signature:
-# Quantum Fisher information
-F_Q = qfisher(rho, num(N)) # w.r.t. generator num(N)
+```text
+spectrum(H, wlist, c_ops, a_op, b_op, solver="es")
```
-## Matrix Analysis
-
-### Eigenanalysis
-
```python
-# Eigenvalues and eigenvectors
-evals, ekets = H.eigenstates()
-
-# Just eigenvalues
-evals = H.eigenenergies()
+import numpy as np
+from qutip import spectrum
-# Ground state
-E0, psi0 = H.groundstate()
+wlist = np.linspace(-5.0, 5.0, 1001)
+S = spectrum(H, wlist, c_ops, a_op, b_op, solver="es")
```
-### Matrix Functions
+The function computes the Fourier transform of a **steady-state** correlation.
+Supported solver strategies include exponential-series (`"es"`),
+pseudo-inverse (`"pi"`), and generic linear solve (`"solve"`).
-```python
-# Matrix exponential
-U = (H * t).expm()
+QuTiP 5 removed public `spectrum_ss` and `spectrum_pi`. Select the strategy with
+the `solver` argument to `spectrum`; do not call the removed functions.
-# Matrix logarithm
-log_rho = rho.logm()
+Audit:
-# Matrix square root
-sqrt_rho = rho.sqrtm()
+- stationarity and steady-state uniqueness;
+- angular-frequency units;
+- operator order;
+- whether the spectrum is symmetrized, one-sided, or normally ordered;
+- negative-frequency interpretation and thermal detailed balance;
+- frequency window/resolution;
+- convergence across solver strategies near singular points.
-# Matrix power
-rho_squared = rho ** 2
-```
+## FFT of a sampled correlation
-### Singular Value Decomposition
+Current signature:
-```python
-# SVD of operator
-U, S, Vh = H.svd()
+```text
+spectrum_correlation_fft(tlist, y, inverse=False)
```
-### Permutations
-
```python
-from qutip import permute
+from qutip import spectrum_correlation_fft
-# Permute subsystems
-rho_permuted = permute(rho, [1, 0]) # Swap subsystems
+frequencies, spectrum_values = spectrum_correlation_fft(taulist, corr)
```
-## Partial Operations
+Before trusting peaks:
-### Partial Trace
+1. require a uniform, strictly increasing `taulist`;
+2. verify the correlation has decayed at the end of the window;
+3. double the time window to test frequency resolution;
+4. halve the timestep to test aliasing and high-frequency content;
+5. compare window functions and disclose any window applied outside QuTiP;
+6. check forward/inverse sign and normalization conventions against an analytic
+ signal;
+7. avoid interpreting zero-padding as additional physical resolution.
-```python
-# Reduce to subsystem
-rho_A = ptrace(rho_AB, 0) # Keep subsystem 0
-rho_B = ptrace(rho_AB, 1) # Keep subsystem 1
-
-# Keep multiple subsystems
-rho_AC = ptrace(rho_ABC, [0, 2]) # Keep 0 and 2, trace out 1
-```
+Use a direct `spectrum` calculation as a cross-check when its steady-state
+assumptions apply.
-### Partial Transpose
+## Liouvillian and eigenvalue diagnostics
```python
-from qutip import partial_transpose
-
-# Partial transpose (for entanglement detection)
-rho_pt = partial_transpose(rho, [0, 1]) # Transpose subsystem 0
-
-# Check if entangled (PPT criterion)
-evals = rho_pt.eigenenergies()
-is_entangled = any(evals < -1e-10)
+eigenvalues = L.eigenenergies()
+gap_candidates = sorted(
+ (-value.real for value in eigenvalues if value.real < -1e-12)
+)
```
-## Quantum State Tomography
-
-### State Reconstruction
-
-```python
-from qutip_qip.tomography import state_tomography
-
-# Prepare measurement results
-# measurements = ... (experimental data)
-
-# Reconstruct density matrix
-rho_reconstructed = state_tomography(measurements, basis='Pauli')
-```
+Liouvillian spectra are non-Hermitian in general. Eigenvalue conditioning,
+degeneracy, and sparse solver targeting can make naive sorting misleading.
+Verify left/right eigenvector conventions and residuals before interpreting a
+spectral gap.
-### Process Tomography
+For Hamiltonians:
```python
-from qutip_qip.tomography import qpt
-
-# Characterize quantum process
-chi = qpt(U_gate, method='lstsq') # Chi matrix representation
+energies, states = H.eigenstates()
+ground_energy, ground_state = H.groundstate()
```
-## Random Quantum Objects
-
-Useful for testing and Monte Carlo simulations.
+Track basis and units, handle degeneracy explicitly, and sweep truncation before
+claiming spectral convergence.
-```python
-# Random state vector
-psi_rand = rand_ket(N)
+## Convergence matrix
-# Random density matrix
-rho_rand = rand_dm(N)
+Vary one numerical control at a time, then perform selected joint checks:
-# Random Hermitian operator
-H_rand = rand_herm(N)
+| Control | Typical comparison |
+|---|---|
+| Hilbert cutoff | observables and boundary occupation |
+| output grid | interpolated trace/peak/FFT quantities |
+| `atol`, `rtol` | endpoint and maximum trajectory differences |
+| integrator | representative observable and invariant differences |
+| simulation duration | steady-state distance and correlation tail |
+| frequency range/spacing | peak location, area, and edge sensitivity |
+| trajectories | mean, uncertainty, and seed sensitivity |
+| `sec_cutoff` | positivity and observable stability |
+| HEOM depth/exponents | reduced state and target observable |
-# Random unitary
-U_rand = rand_unitary(N)
+Define acceptance thresholds before looking at the final comparison. Report
+absolute and relative differences and handle near-zero denominators explicitly.
-# With specific properties
-rho_rank2 = rand_dm(N, rank=2) # Rank-2 density matrix
-H_sparse = rand_herm(N, density=0.1) # 10% non-zero elements
-```
+## Portable result audit
-## Useful Checks
+`../scripts/result_audit.py` reads only bounded strict JSON. It checks schema,
+version, finite values, monotonic time grids, population bounds, analytic
+reference error when available, convergence deltas, and whether assumptions,
+seeds, and solver stats were recorded. It does not load QuTiP result files or
+other Python-object serialization.
-```python
-# Check if operator is Hermitian
-H.isherm
+`../scripts/steady_state_spectrum_planner.py` produces a bounded plan for
+steady-state and direct/FFT spectrum checks without running a model.
-# Check if state is normalized
-abs(psi.norm() - 1.0) < 1e-10
+## Sources (verified 2026-07-23)
-# Check if density matrix is physical
-rho.tr() ≈ 1 and all(rho.eigenenergies() >= 0)
-
-# Check if operators commute
-commutator(A, B).norm() < 1e-10
-```
+- [Solver, correlation, spectrum, and steady-state API](https://qutip.readthedocs.io/en/stable/apidoc/solver.html)
+- [Steady-state guide](https://qutip.readthedocs.io/en/stable/guide/guide-steady.html)
+- [Correlation guide](https://qutip.readthedocs.io/en/stable/guide/guide-correlation.html)
+- [Quantum-object API](https://qutip.readthedocs.io/en/stable/apidoc/quantumobject.html)
+- [QuTiP 5.3.0 release notes](https://github.com/qutip/qutip/releases/tag/v5.3.0)
+- [QuTiP 5 changelog](https://qutip.readthedocs.io/en/stable/changelog.html)
diff --git a/skills/qutip/references/core_concepts.md b/skills/qutip/references/core_concepts.md
index 74876ba3..d23dcbf4 100644
--- a/skills/qutip/references/core_concepts.md
+++ b/skills/qutip/references/core_concepts.md
@@ -1,293 +1,300 @@
-# QuTiP Core Concepts
+# QuTiP 5.3 Core Concepts
-## Quantum Objects (Qobj)
+Research and API verification date: **2026-07-23**. Examples target
+`qutip==5.3.0`.
-All quantum objects in QuTiP are represented by the `Qobj` class:
+## Units and the equation being solved
-```python
-from qutip import *
+QuTiP does not attach physical units. The standard solver equations use
+\(\hbar=1\), so a Hamiltonian has angular-frequency units and time has reciprocal
+units:
-# Create a quantum object
-psi = basis(2, 0) # Ground state of 2-level system
-rho = fock_dm(5, 2) # Density matrix for n=2 Fock state
-H = sigmaz() # Pauli Z operator
-```
+\[
+\dot{\rho}=-i[H,\rho]+\sum_k\left(C_k\rho C_k^\dagger
+-\tfrac12\{C_k^\dagger C_k,\rho\}\right).
+\]
-Key attributes:
-- `.dims` - Dimension structure
-- `.shape` - Matrix dimensions
-- `.type` - Type (ket, bra, oper, super)
-- `.isherm` - Check if Hermitian
-- `.dag()` - Hermitian conjugate
-- `.tr()` - Trace
-- `.norm()` - Norm
+Choose one unit system and state it in reports:
-## States
+- if time is ns, Hamiltonian coefficients and rates are in ns\(^{-1}\);
+- a frequency quoted in cycles/time becomes angular frequency \(2\pi f\);
+- temperature in HEOM or thermal spectra must be converted consistently with
+ \(k_B=1\) only if that convention was explicitly selected.
-### Basis States
+Dimensional consistency is a model property, not something QuTiP can infer.
-```python
-# Fock (number) states
-n = 2 # Excitation level
-N = 10 # Hilbert space dimension
-psi = basis(N, n) # or fock(N, n)
-
-# Coherent states
-alpha = 1 + 1j
-coherent(N, alpha)
-
-# Thermal states (density matrices)
-n_avg = 2.0 # Average photon number
-thermal_dm(N, n_avg)
-```
+## Qobj structure
-### Spin States
+`Qobj` stores numerical data plus quantum dimension metadata:
```python
-# Spin-1/2 states
-spin_state(1/2, 1/2) # Spin up
-spin_coherent(1/2, theta, phi) # Coherent spin state
+from qutip import Qobj, basis, sigmaz
+
+ket = basis(2, 0)
+rho = ket.proj()
+H = 0.5 * sigmaz()
-# Multi-qubit computational basis
-basis([2,2,2], [0,1,0]) # |010⟩ for 3 qubits
+assert ket.isket and ket.dims == [[2], [1]]
+assert rho.isoper and rho.dims == [[2], [2]]
+assert H.isherm
```
-### Composite States
+Important properties and methods:
+
+| API | Meaning |
+|---|---|
+| `.dims` | Structured input/output Hilbert spaces |
+| `.shape` | Flattened matrix shape |
+| `.type` | `ket`, `bra`, `oper`, `super`, `operator-ket`, or `operator-bra` |
+| `.isket`, `.isoper`, `.issuper` | Semantic type checks |
+| `.isherm`, `.isunitary` | Cached/computed structural properties |
+| `.dag()` | Adjoint |
+| `.tr()` | Trace |
+| `.norm()` | L2 norm for kets by default; trace norm for operators by default |
+| `.proj()` | Ket/bra projector |
+| `.ptrace(sel)` | Keep selected subsystems and trace out the rest |
+| `.full()` | Dense matrix with flattened shape |
+| `.full_tensor()` | QuTiP 5.3 dense array reshaped by tensor dimensions |
+
+Construct raw `Qobj` values only when built-in constructors are unsuitable:
```python
-# Tensor products
-psi1 = basis(2, 0)
-psi2 = basis(2, 1)
-tensor(psi1, psi2) # |01⟩
-
-# Bell states
-bell_state('00') # (|00⟩ + |11⟩)/√2
-maximally_mixed_dm(2) # Maximally mixed state
+from qutip import Qobj
+
+rho = Qobj(
+ [[0.75, 0.1], [0.1, 0.25]],
+ dims=[[2], [2]],
+)
```
-## Operators
+Supplying correct matrix shape with incorrect `dims` can invalidate later
+tensor, partial-trace, and superoperator operations.
+
+## States and physicality
-### Creation/Annihilation
+### Kets
```python
-N = 10
-a = destroy(N) # Annihilation operator
-a_dag = create(N) # Creation operator
-num = num(N) # Number operator (a†a)
-```
+from qutip import basis, coherent
-### Pauli Matrices
+qubit = (basis(2, 0) + basis(2, 1)).unit()
+oscillator = coherent(30, 1.5)
-```python
-sigmax() # σx
-sigmay() # σy
-sigmaz() # σz
-sigmap() # σ+ = (σx + iσy)/2
-sigmam() # σ- = (σx - iσy)/2
+assert abs(qubit.norm() - 1.0) < 1e-12
```
-### Angular Momentum
+### Density matrices
+
+A physical finite-dimensional density matrix is Hermitian, trace one, and
+positive semidefinite:
```python
-# Spin operators for arbitrary j
-j = 1 # Spin-1
-jmat(j, 'x') # Jx
-jmat(j, 'y') # Jy
-jmat(j, 'z') # Jz
-jmat(j, '+') # J+
-jmat(j, '-') # J-
+import numpy as np
+from qutip import thermal_dm
+
+rho = thermal_dm(20, 0.7)
+tol = 1e-10
+eigenvalues = np.asarray(rho.eigenenergies(), dtype=float)
+
+assert rho.isherm
+assert abs(complex(rho.tr()) - 1.0) < tol
+assert eigenvalues.min() >= -tol
```
-### Displacement and Squeezing
+Use a tolerance tied to solver error and matrix scale. Report the minimum
+eigenvalue instead of silently clipping it. If a method such as non-secular
+Bloch-Redfield produces material negativity, revisit its physical assumptions.
-```python
-alpha = 1 + 1j
-displace(N, alpha) # Displacement operator D(α)
+Common constructors:
-z = 0.5 # Squeezing parameter
-squeeze(N, z) # Squeezing operator S(z)
+```python
+from qutip import (
+ basis,
+ coherent,
+ coherent_dm,
+ fock,
+ fock_dm,
+ maximally_mixed_dm,
+ thermal_dm,
+)
+
+psi_n = fock(16, 3)
+rho_n = fock_dm(16, 3)
+psi_alpha = coherent(24, 1.2)
+rho_alpha = coherent_dm(24, 1.2)
+rho_th = thermal_dm(24, 0.5)
+rho_mix = maximally_mixed_dm([2, 2])
```
-## Tensor Products and Composition
+Oscillator constructors use a finite truncation. Sweep the cutoff and monitor
+edge population, observables, and state trace. A normalized truncated state is
+not by itself evidence that the cutoff is adequate.
+
+## Tensor products and subsystem order
-### Building Composite Systems
+Arguments to `tensor` define subsystem order from left to right:
```python
-# Tensor product of operators
-H1 = sigmaz()
-H2 = sigmax()
-H_total = tensor(H1, H2)
+from qutip import basis, destroy, qeye, sigmaz, tensor
-# Identity operators
-qeye([2, 2]) # Identity for two qubits
+N = 12
+psi = tensor(basis(N, 2), basis(2, 0)) # cavity index 0, qubit index 1
+a = tensor(destroy(N), qeye(2))
+sz = tensor(qeye(N), sigmaz())
-# Partial application
-# σz ⊗ I for 3-qubit system
-tensor(sigmaz(), qeye(2), qeye(2))
+assert psi.dims == [[N, 2], [1]]
+assert a.dims == [[N, 2], [N, 2]]
+assert sz.dims == a.dims
```
-### Partial Trace
+`Qobj.ptrace(sel)` keeps `sel`:
```python
-# Composite system state
-rho = bell_state('00').proj() # |Φ+⟩⟨Φ+|
-
-# Trace out subsystem
-rho_A = ptrace(rho, 0) # Trace out subsystem 0
-rho_B = ptrace(rho, 1) # Trace out subsystem 1
+rho = psi.proj()
+rho_cavity = rho.ptrace(0)
+rho_qubit = rho.ptrace(1)
```
-## Expectation Values and Measurements
+The selected subsystems remain in their original order even if `sel` is passed
+in another order. Use `permute` when an explicit subsystem reordering is
+intended.
-```python
-# Expectation values
-psi = coherent(N, alpha)
-expect(num, psi) # ⟨n⟩
+For a composite operator with `dims == [[2, 3], [2, 3]]`,
+`full_tensor().shape` is `(2, 3, 2, 3)`. Treat this as a useful dimensional
+audit, not a replacement for documenting subsystem labels.
-# For multiple operators
-ops = [a, a_dag, num]
-expect(ops, psi) # Returns list
+## Operators and observables
-# Variance
-variance(num, psi) # Var(n) = ⟨n²⟩ - ⟨n⟩²
+```python
+from qutip import create, destroy, jmat, num, sigmam, sigmap, sigmax, sigmay, sigmaz
+
+N = 20
+a = destroy(N)
+adag = create(N)
+n = num(N)
+sx, sy, sz = sigmax(), sigmay(), sigmaz()
+sm, sp = sigmam(), sigmap()
+Jx = jmat(1, "x")
```
-## Superoperators and Liouvillians
+Hamiltonians and ideal observables should be Hermitian within tolerance.
+Collapse operators generally need not be Hermitian.
-### Lindblad Form
+Expectation and variance:
```python
-# System Hamiltonian
-H = num
+from qutip import expect, variance
-# Collapse operators (dissipation)
-c_ops = [np.sqrt(0.1) * a] # Decay rate 0.1
+mean_n = expect(n, rho)
+var_n = variance(n, rho)
+```
-# Liouvillian superoperator
-L = liouvillian(H, c_ops)
+Do not interpret a visibly non-real expectation of a Hermitian observable as a
+physical value; first audit Hermiticity, state validity, dimensions, and solver
+accuracy.
-# Alternative: explicit form
-L = -1j * (spre(H) - spost(H)) + lindblad_dissipator(a, a)
-```
+## Collapse operators and rate conventions
-### Superoperator Representations
+If a dissipator is written as \(\gamma\,\mathcal{D}[A]\rho\), pass
+\(C=\sqrt{\gamma}A\):
```python
-# Kraus representation
-kraus_to_super(kraus_ops)
+import numpy as np
+from qutip import sigmam, sigmaz
+
+gamma_down = 0.2
+gamma_phi = 0.05 # desired off-diagonal coherence decay
+c_ops = [
+ np.sqrt(gamma_down) * sigmam(),
+ np.sqrt(gamma_phi / 2.0) * sigmaz(),
+]
+```
-# Choi matrix
-choi_to_super(choi_matrix)
+The factor for dephasing depends on how a publication defines its dephasing
+rate. Derive the matrix-element decay for the chosen dissipator and test it on
+a two-level state instead of copying a symbol by name.
-# Chi (process) matrix
-chi_to_super(chi_matrix)
+For a thermal oscillator with occupation \(n_\mathrm{th}\):
-# Conversions
-super_to_choi(L)
-choi_to_kraus(choi_matrix)
+```python
+c_ops = [
+ np.sqrt(kappa * (n_th + 1.0)) * a,
+ np.sqrt(kappa * n_th) * a.dag(),
+]
```
-## Quantum Gates (requires qutip-qip)
+Rates must be finite and nonnegative in standard Lindblad form. Time-dependent
+rates require extra care: a coefficient multiplies the collapse **amplitude**,
+so a target rate \(\gamma(t)\) needs an amplitude proportional to
+\(\sqrt{\gamma(t)}\).
+
+## Liouvillians and vectorization
```python
-from qutip_qip.operations import *
-
-# Single-qubit gates
-hadamard_transform() # Hadamard
-rx(np.pi/2) # X-rotation
-ry(np.pi/2) # Y-rotation
-rz(np.pi/2) # Z-rotation
-phasegate(np.pi/4) # Phase gate
-snot() # Hadamard (alternative)
-
-# Two-qubit gates
-cnot() # CNOT
-swap() # SWAP
-iswap() # iSWAP
-sqrtswap() # √SWAP
-berkeley() # Berkeley gate
-swapalpha(alpha) # SWAP^α
-
-# Three-qubit gates
-fredkin() # Controlled-SWAP
-toffoli() # Controlled-CNOT
-
-# Expanding to multi-qubit systems
-N = 3 # Total qubits
-target = 1
-controls = [0, 2]
-gate_expand_2toN(cnot(), N, [controls[0], target])
+from qutip import liouvillian, operator_to_vector, vector_to_operator
+
+L = liouvillian(H, c_ops)
+rho_vec = operator_to_vector(rho)
+derivative = L * rho_vec
+rho_roundtrip = vector_to_operator(rho_vec)
+
+assert L.issuper
+assert (rho_roundtrip - rho).norm() < 1e-12
```
-## Common Hamiltonians
+QuTiP uses column-stacked operator vectorization. Use
+`operator_to_vector`/`vector_to_operator`; do not reproduce reshape order by
+guesswork.
-### Jaynes-Cummings Model
+Useful superoperator constructors and conversions include:
```python
-# Cavity mode
-N = 10
-a = tensor(destroy(N), qeye(2))
+from qutip import (
+ choi_to_kraus,
+ choi_to_super,
+ kraus_to_super,
+ spost,
+ spre,
+ sprepost,
+ super_to_choi,
+ super_to_kraus,
+)
+```
-# Atom
-sm = tensor(qeye(N), sigmam())
+For a quantum channel, check the intended representation and the map properties
+such as complete positivity and trace preservation. QuTiP exposes properties
+including `iscp`, `istp`, and `iscptp` on suitable map objects.
-# Hamiltonian
-wc = 1.0 # Cavity frequency
-wa = 1.0 # Atom frequency
-g = 0.05 # Coupling strength
-H = wc * a.dag() * a + wa * sm.dag() * sm + g * (a.dag() * sm + a * sm.dag())
-```
+## Truncation and basis audits
-### Driven Systems
+For every truncated bosonic or spin model:
-```python
-# Time-dependent Hamiltonian
-H0 = sigmaz()
-H1 = sigmax()
+1. increase each cutoff independently;
+2. compare the actual reported observables, not only energies;
+3. inspect occupation near the cutoff;
+4. recheck all tensor dimensions after changing a cutoff;
+5. state whether the model is in a bare, dressed, rotating, Floquet, Dicke, or
+ other basis;
+6. document every rotating-wave or excitation-number restriction.
-def drive(t, args):
- return np.sin(args['w'] * t)
+An excitation-number-restricted space does not have the same factorization as
+the corresponding full tensor space. Do not apply subsystem operations unless
+their meaning in the restricted representation is established.
-H = [H0, [H1, drive]]
-args = {'w': 1.0}
-```
+## Local model validation
-### Spin Chains
+`../scripts/qobj_model_validator.py` accepts a bounded strict-JSON model made
+only of numeric arrays. It rejects URLs, symlinks, duplicate keys, non-finite
+numbers, unknown roles, executable coefficients, dimensions whose product
+exceeds 64, and incompatible subsystem structures. It checks Hamiltonian and
+observable Hermiticity, initial-state norm/trace/positivity, and nonnegative
+collapse rates.
-```python
-# Heisenberg chain
-N_spins = 5
-J = 1.0 # Exchange coupling
-
-# Build Hamiltonian
-H = 0
-for i in range(N_spins - 1):
- # σᵢˣσᵢ₊₁ˣ + σᵢʸσᵢ₊₁ʸ + σᵢᶻσᵢ₊₁ᶻ
- H += J * (
- tensor_at([sigmax()], i, N_spins) * tensor_at([sigmax()], i+1, N_spins) +
- tensor_at([sigmay()], i, N_spins) * tensor_at([sigmay()], i+1, N_spins) +
- tensor_at([sigmaz()], i, N_spins) * tensor_at([sigmaz()], i+1, N_spins)
- )
-```
+It is a preflight audit, not a proof that the physical model is appropriate.
-## Useful Utility Functions
+## Sources (verified 2026-07-23)
-```python
-# Generate random quantum objects
-rand_ket(N) # Random ket
-rand_dm(N) # Random density matrix
-rand_herm(N) # Random Hermitian operator
-rand_unitary(N) # Random unitary
-
-# Commutator and anti-commutator
-commutator(A, B) # [A, B]
-anti_commutator(A, B) # {A, B}
-
-# Matrix exponential
-(-1j * H * t).expm() # e^(-iHt)
-
-# Eigenvalues and eigenvectors
-H.eigenstates() # Returns (eigenvalues, eigenvectors)
-H.eigenenergies() # Returns only eigenvalues
-H.groundstate() # Ground state energy and state
-```
+- [QuTiP 5.3 quantum-object API](https://qutip.readthedocs.io/en/stable/apidoc/quantumobject.html)
+- [Tensor-product guide](https://qutip.readthedocs.io/en/stable/guide/guide-tensor.html)
+- [QuTiP 5.3.0 release notes](https://github.com/qutip/qutip/releases/tag/v5.3.0)
+- [QuTiP 5.3 changelog](https://qutip.readthedocs.io/en/stable/changelog.html)
diff --git a/skills/qutip/references/time_evolution.md b/skills/qutip/references/time_evolution.md
index d99d3eae..76160262 100644
--- a/skills/qutip/references/time_evolution.md
+++ b/skills/qutip/references/time_evolution.md
@@ -1,348 +1,373 @@
-# QuTiP Time Evolution and Dynamics Solvers
-
-## Overview
-
-QuTiP provides multiple solvers for quantum dynamics:
-- `sesolve` - Schrödinger equation (unitary evolution)
-- `mesolve` - Master equation (open systems with dissipation)
-- `mcsolve` - Monte Carlo (quantum trajectories)
-- `brmesolve` - Bloch-Redfield master equation
-- `fmmesolve` - Floquet-Markov master equation
-- `ssesolve/smesolve` - Stochastic Schrödinger/master equations
-
-## Schrödinger Equation Solver (sesolve)
+# QuTiP 5.3 Time Evolution
+
+Research and API verification date: **2026-07-23**. All signatures and examples
+target `qutip==5.3.0`.
+
+## Solver selection
+
+| Solver | State/model | Main uncertainty |
+|---|---|---|
+| `sesolve` | Schrödinger equation, pure state, no collapse channels | ODE and model approximation |
+| `mesolve` | Lindblad master equation, mixed state, or Liouvillian | channel validity and ODE error |
+| `mcsolve` | quantum-jump trajectories | ODE error plus sampling error |
+| `brmesolve` | microscopic weak-coupling bath spectra | Born-Markov/secular approximation and positivity |
+| `ssesolve` | stochastic Schrödinger equation | diffusive record sampling |
+| `smesolve` | stochastic master equation with monitored/unmonitored channels | diffusive record sampling |
+| `fsesolve`/`fmmesolve` | periodic Floquet dynamics | period, basis, harmonic and bath approximations |
+
+Do not use `mcsolve` merely to make a deterministic calculation parallel. Do
+not use `brmesolve` as a generic replacement for a Lindblad model.
+
+## Current function signatures
+
+The important QuTiP 5.3 call boundaries are:
+
+```text
+sesolve(H, psi0, tlist, *, e_ops=None, args=None, options=None)
+mesolve(H, rho0, tlist, c_ops=None, *, e_ops=None, args=None, options=None)
+mcsolve(H, state, tlist, c_ops=(), *, e_ops=None, ntraj=500,
+ args=None, options=None, seeds=None, target_tol=None, timeout=None)
+brmesolve(H, psi0, tlist, a_ops=None, sec_cutoff=0.1, *,
+ c_ops=None, e_ops=None, args=None, options=None)
+ssesolve(H, psi0, tlist, sc_ops=(), heterodyne=False, *,
+ e_ops=None, args=None, ntraj=500, options=None, seeds=None,
+ target_tol=None, timeout=None)
+smesolve(H, rho0, tlist, c_ops=(), sc_ops=(), heterodyne=False, *,
+ e_ops=None, args=None, ntraj=500, options=None, seeds=None,
+ target_tol=None, timeout=None)
+```
-For closed quantum systems evolving unitarily.
+In 5.3, `e_ops`, `args`, and `options` are keyword-only. Passing solver options
+as arbitrary solver keyword arguments was removed. The old `qutip.Options`
+export is no longer present; pass an ordinary dictionary.
-### Basic Usage
+## `sesolve`: closed unitary evolution
```python
-from qutip import *
import numpy as np
+from qutip import basis, sesolve, sigmax, sigmaz
-# System setup
-N = 10
-psi0 = basis(N, 0) # Initial state
-H = num(N) # Hamiltonian
-
-# Time points
-tlist = np.linspace(0, 10, 100)
-
-# Solve
-result = sesolve(H, psi0, tlist)
-
-# Access results
-states = result.states # List of states at each time
-final_state = result.states[-1]
+H = 0.5 * sigmax()
+psi0 = basis(2, 0)
+tlist = np.linspace(0.0, 10.0, 201)
+
+result = sesolve(
+ H,
+ psi0,
+ tlist,
+ e_ops={"z": sigmaz()},
+ options={"atol": 1e-10, "rtol": 1e-8, "progress_bar": ""},
+)
+z = np.asarray(result.e_data["z"])
```
-### With Expectation Values
-
-```python
-# Operators to compute expectation values
-e_ops = [num(N), destroy(N), create(N)]
+Audit Hamiltonian Hermiticity and state norm. If norm drift is material, tighten
+tolerances or investigate the model; do not normalize away unexplained error.
-result = sesolve(H, psi0, tlist, e_ops=e_ops)
-
-# Access expectation values
-n_t = result.expect[0] # ⟨n⟩(t)
-a_t = result.expect[1] # ⟨a⟩(t)
-```
-
-### Time-Dependent Hamiltonians
+## `mesolve`: Lindblad or explicit Liouvillian evolution
```python
-# Method 1: String-based (faster, requires Cython)
-H = [num(N), [destroy(N) + create(N), 'cos(w*t)']]
-args = {'w': 1.0}
-result = sesolve(H, psi0, tlist, args=args)
-
-# Method 2: Function-based
-def drive(t, args):
- return np.exp(-t/args['tau']) * np.sin(args['w'] * t)
-
-H = [num(N), [destroy(N) + create(N), drive]]
-args = {'w': 1.0, 'tau': 5.0}
-result = sesolve(H, psi0, tlist, args=args)
-
-# Method 3: QobjEvo (most flexible)
-from qutip import QobjEvo
-H_td = QobjEvo([num(N), [destroy(N) + create(N), drive]], args=args)
-result = sesolve(H_td, psi0, tlist)
+import numpy as np
+from qutip import basis, mesolve, sigmam, sigmaz
+
+gamma = 0.2
+excited = basis(2, 0)
+tlist = np.linspace(0.0, 12.0, 241)
+
+result = mesolve(
+ 0.5 * sigmaz(),
+ excited,
+ tlist,
+ c_ops=[np.sqrt(gamma) * sigmam()],
+ e_ops={"p_excited": excited.proj()},
+ options={
+ "method": "adams",
+ "atol": 1e-10,
+ "rtol": 1e-8,
+ "store_final_state": True,
+ "progress_bar": "",
+ },
+)
```
-## Master Equation Solver (mesolve)
+When no collapse operators are supplied and `H` is not a superoperator,
+`mesolve` may defer to `sesolve`. If `H` is an explicit Liouvillian, document
+whether it is in valid Lindblad form or represents a deliberate approximation.
-For open quantum systems with dissipation and decoherence.
-
-### Basic Usage
+## `mcsolve`: quantum jumps
```python
-# System Hamiltonian
-H = num(N)
+result = mcsolve(
+ 0.5 * sigmaz(),
+ excited,
+ tlist,
+ [np.sqrt(gamma) * sigmam()],
+ e_ops=[excited.proj()],
+ ntraj=500,
+ seeds=20260723,
+ options={
+ "keep_runs_results": False,
+ "progress_bar": "",
+ },
+)
+
+mean_population = result.expect[0]
+trajectory_spread = result.std_expect[0]
+seed_manifest = result.seeds
+```
-# Collapse operators (Lindblad operators)
-kappa = 0.1 # Decay rate
-c_ops = [np.sqrt(kappa) * destroy(N)]
+`seeds` may be one integer/`SeedSequence` used to spawn trajectory seeds, or a
+list with one seed per trajectory. QuTiP stores the realized seeds in the
+result. Reusing them enables a paired comparison, but paired runs are not
+independent replicates.
-# Initial state
-psi0 = coherent(N, 2.0)
+Trajectory rigor:
-# Solve
-result = mesolve(H, psi0, tlist, c_ops, e_ops=[num(N)])
+- increase `ntraj` and report stabilization or a target uncertainty;
+- distinguish trajectory standard deviation from standard error of the mean;
+- set `options={"keep_runs_results": True}` only when individual trajectories
+ are actually required, because memory scales with trajectories and time
+ points;
+- collapse records are available per trajectory through result attributes such
+ as `collapse`; do not print unbounded records by default;
+- `target_tol` may stop before `ntraj`, so report the number actually run;
+- report timeout termination and solver stats.
-# Result is a density matrix evolution
-rho_t = result.states # List of density matrices
-n_t = result.expect[0] # ⟨n⟩(t)
-```
+For mixed initial conditions, current QuTiP can sample the initial mixture; the
+result then includes initial-state accounting. State this extra source of
+sampling explicitly.
-### Multiple Dissipation Channels
+## `brmesolve`: Bloch-Redfield evolution
```python
-# Photon loss
-kappa = 0.1
-# Dephasing
-gamma = 0.05
-# Thermal excitation
-nth = 0.5 # Thermal photon number
-
-c_ops = [
- np.sqrt(kappa * (1 + nth)) * destroy(N), # Thermal decay
- np.sqrt(kappa * nth) * create(N), # Thermal excitation
- np.sqrt(gamma) * num(N) # Pure dephasing
-]
-
-result = mesolve(H, psi0, tlist, c_ops)
+import numpy as np
+from qutip import basis, brmesolve, sigmax, sigmaz
+
+def one_sided_spectrum(w):
+ return 0.03 * w if w > 0.0 else 0.0
+
+tlist = np.linspace(0.0, 30.0, 601)
+result = brmesolve(
+ 0.5 * sigmaz(),
+ basis(2, 0),
+ tlist,
+ a_ops=[(sigmax(), one_sided_spectrum)],
+ e_ops={"z": sigmaz()},
+ sec_cutoff=0.1,
+ options={"atol": 1e-10, "rtol": 1e-8, "progress_bar": ""},
+)
```
-### Time-Dependent Dissipation
+The coupling operator in each `a_ops` pair is normally Hermitian, and the
+spectrum is a function of **angular frequency**. Prefer a current QuTiP
+Environment object when it represents the bath more clearly.
-```python
-# Time-dependent decay rate
-def kappa_t(t, args):
- return args['k0'] * (1 + np.sin(args['w'] * t))
-
-c_ops = [[np.sqrt(1.0) * destroy(N), kappa_t]]
-args = {'k0': 0.1, 'w': 1.0}
+Required checks:
-result = mesolve(H, psi0, tlist, c_ops, args=args)
-```
+- weak system-bath coupling (Born approximation);
+- short bath memory compared with system dynamics (Markov approximation);
+- stationary bath and correct positive/negative-frequency convention;
+- secular choice: `sec_cutoff=-1` disables secularization and can worsen
+ positivity;
+- density-matrix trace, Hermiticity, and minimum eigenvalue over time.
-## Monte Carlo Solver (mcsolve)
+See `advanced.md` for the physical boundaries.
-Simulates quantum trajectories for open systems.
+## Stochastic Schrödinger and master equations
-### Basic Usage
+Use these for diffusive continuous-measurement unravellings, not jump
+trajectories:
```python
-# Same setup as mesolve
-H = num(N)
-c_ops = [np.sqrt(0.1) * destroy(N)]
-psi0 = coherent(N, 2.0)
-
-# Number of trajectories
-ntraj = 500
-
-result = mcsolve(H, psi0, tlist, c_ops, e_ops=[num(N)], ntraj=ntraj)
+result = smesolve(
+ H,
+ rho0,
+ tlist,
+ c_ops=unmonitored_channels,
+ sc_ops=monitored_channels,
+ heterodyne=False, # homodyne
+ e_ops={"signal": measured_quadrature},
+ ntraj=200,
+ seeds=20260723,
+ options={"dt": 0.001, "store_measurement": True, "progress_bar": ""},
+)
+```
-# Results averaged over trajectories
-n_avg = result.expect[0]
-n_std = result.std_expect[0] # Standard deviation
+- `c_ops` are unmonitored deterministic dissipation channels.
+- `sc_ops` are monitored stochastic channels.
+- `heterodyne=False` is homodyne; `True` is heterodyne.
+- Legacy integer `noise` selectors are not current API.
+- Measurement records can be much larger than expectation summaries; store
+ them only when needed.
+- Converge the stochastic integration step `dt` separately from `ntraj`.
-# Individual trajectories (if options.store_states=True)
-options = Options(store_states=True)
-result = mcsolve(H, psi0, tlist, c_ops, ntraj=ntraj, options=options)
-trajectories = result.states # List of trajectory lists
-```
+## Time-dependent systems and QobjEvo
-### Photon Counting
+### Pythonic callable coefficients
```python
-# Track quantum jumps
-result = mcsolve(H, psi0, tlist, c_ops, ntraj=ntraj, options=options)
+import numpy as np
+from qutip import QobjEvo, sigmax, sigmaz
-# Access jump times and which operator caused the jump
-for traj in result.col_times:
- print(f"Jump times: {traj}")
+def pulse(t, amplitude, center, width):
+ return amplitude * np.exp(-0.5 * ((t - center) / width) ** 2)
-for traj in result.col_which:
- print(f"Jump operator indices: {traj}")
+H = QobjEvo(
+ [0.5 * sigmaz(), [sigmax(), pulse]],
+ args={"amplitude": 0.2, "center": 5.0, "width": 1.0},
+)
+H_at_t = H(5.0)
+H.arguments(amplitude=0.15)
```
-## Bloch-Redfield Solver (brmesolve)
+The Pythonic form `f(t, parameter, ...)` is current. The legacy
+`f(t, args_dictionary)` form is deprecated in 5.3 and scheduled for removal in
+5.5.
-For weak system-bath coupling in the secular approximation.
+### Sampled coefficients
```python
-# System Hamiltonian
-H = sigmaz()
-
-# Coupling operators and spectral density
-a_ops = [[sigmax(), lambda w: 0.1 * w if w > 0 else 0]] # Ohmic bath
-
-psi0 = basis(2, 0)
-result = brmesolve(H, psi0, tlist, a_ops, e_ops=[sigmaz(), sigmax()])
+coefficient_times = np.linspace(0.0, 10.0, 501)
+samples = np.cos(coefficient_times)
+H = QobjEvo(
+ [0.5 * sigmaz(), [sigmax(), samples]],
+ tlist=coefficient_times,
+ order=3,
+)
```
-## Floquet Solver (fmmesolve)
+Sample times must be sorted and match coefficient length. `order=0` gives a
+left/previous-value step function; the default cubic spline can overshoot.
+Converge the coefficient sampling independently of solver output times.
-For time-periodic Hamiltonians.
+QuTiP also accepts expression strings and may compile them, but this skill does
+not construct such expressions from configuration or user text. Use trusted
+callables or numeric arrays in generated workflows.
-```python
-# Time-periodic Hamiltonian
-w_d = 1.0 # Drive frequency
-H0 = sigmaz()
-H1 = sigmax()
-H = [H0, [H1, 'cos(w*t)']]
-args = {'w': w_d}
-
-# Floquet modes and quasi-energies
-T = 2 * np.pi / w_d # Period
-f_modes, f_energies = floquet_modes(H, T, args)
-
-# Initial state in Floquet basis
-psi0 = basis(2, 0)
+## Option dictionaries and integrators
-# Dissipation in Floquet basis
-c_ops = [np.sqrt(0.1) * sigmam()]
+Common solver options:
-result = fmmesolve(H, psi0, tlist, c_ops, e_ops=[num(2)], T=T, args=args)
+```python
+options = {
+ "method": "adams",
+ "atol": 1e-10,
+ "rtol": 1e-8,
+ "nsteps": 10000,
+ "store_states": False,
+ "store_final_state": True,
+ "progress_bar": "",
+}
```
-## Stochastic Solvers
+Options are solver- and integrator-specific. Consult the selected solver's
+`.options` documentation before using a key.
-### Stochastic Schrödinger Equation (ssesolve)
+Common integration choices:
-```python
-# Diffusion operator
-sc_ops = [np.sqrt(0.1) * destroy(N)]
+- `adams`: non-stiff default for many deterministic solvers;
+- `bdf`: stiff systems;
+- `lsoda`: switches between non-stiff and stiff methods;
+- explicit high-order methods such as `dop853`, `vern7`, or `vern9`;
+- `diag`: diagonalization-based constant-system evolution;
+- `krylov`: suitable cases where Krylov evolution is beneficial.
-# Heterodyne detection
-result = ssesolve(H, psi0, tlist, sc_ops=sc_ops, e_ops=[num(N)],
- ntraj=500, noise=1) # noise=1 for heterodyne
-```
+An integrator label is not an accuracy certificate. Compare at least two
+tolerance levels, inspect warnings/stats, and compare a second method for a
+representative stiff or difficult case.
-### Stochastic Master Equation (smesolve)
+QuTiP 5.3 adds `matrix_form` for `mesolve`/`MESolver`:
```python
-result = smesolve(H, psi0, tlist, c_ops=[], sc_ops=sc_ops,
- e_ops=[num(N)], ntraj=500)
+options = {"matrix_form": True, "atol": 1e-10, "rtol": 1e-8}
```
-## Propagators
+It uses matrix-matrix products and may reduce memory in suitable models.
+Benchmark both time and verified observables before adopting it.
-### Time-Evolution Operator
+## Time grids
-```python
-# Evolution operator U(t) such that ψ(t) = U(t)ψ(0)
-U = (-1j * H * t).expm()
-psi_t = U * psi0
-
-# For master equation (superoperator propagator)
-L = liouvillian(H, c_ops)
-U_super = (L * t).expm()
-rho_t = vector_to_operator(U_super * operator_to_vector(rho0))
-```
+`tlist` is the requested output grid, not necessarily the integrator's internal
+step sequence.
-### Propagator Function
+Checks:
-```python
-# Generate propagators for multiple times
-U_list = propagator(H, tlist, c_ops)
+1. finite, strictly increasing values;
+2. includes the physically intended initial time;
+3. resolves the fastest Hamiltonian, decay, drive-envelope, and measurement
+ scales in the returned output;
+4. long enough to capture transients or steady behavior;
+5. converged under a denser output grid where downstream interpolation, FFT, or
+ peak detection depends on sampling.
-# Apply to states
-psi_t = [U_list[i] * psi0 for i in range(len(tlist))]
-```
+For FFT spectra, a uniform `taulist` is required and its spacing/window set
+Nyquist range and frequency resolution.
-## Steady State Solutions
+## Result semantics
-### Direct Steady State
+Current solver results can contain:
-```python
-# Find steady state of Liouvillian
-rho_ss = steadystate(H, c_ops)
+| Attribute | Meaning |
+|---|---|
+| `times` | returned times |
+| `states` | stored states; may be empty depending on options and `e_ops` |
+| `final_state` | final state when requested |
+| `expect` | list aligned with list-form `e_ops` |
+| `e_data` | dictionary keyed like dict-form `e_ops` |
+| `options` | effective result/solver options |
+| `solver` | solver name |
+| `stats` | timing and diagnostic statistics |
-# Check it's steady
-L = liouvillian(H, c_ops)
-assert (L * operator_to_vector(rho_ss)).norm() < 1e-10
-```
+Multi-trajectory results add trajectory counts, seeds, standard deviations,
+average states, measurements, and optionally individual run results. Never
+assume `.states` means individual trajectories; inspect
+`keep_runs_results` and the concrete result type.
-### Pseudo-Inverse Method
+QuTiP 5.3 adds `Result.plot_expect()` and `MultiTrajResult.plot_expect()`.
+Prefer explicit axes in reusable code.
-```python
-# For degenerate steady states
-rho_ss = steadystate(H, c_ops, method='direct')
-# or 'eigen', 'svd', 'power'
-```
+## Repeated systems
-## Correlation Functions
-
-### Two-Time Correlation
+Solver classes (`SESolver`, `MESolver`, `MCSolver`, `BRSolver`, `SMESolver`,
+and others) can reuse a constructed right-hand side across runs:
```python
-# ⟨A(t+τ)B(t)⟩
-A = destroy(N)
-B = create(N)
-
-# Emission spectrum
-taulist = np.linspace(0, 10, 200)
-corr = correlation_2op_1t(H, None, taulist, c_ops, A, B)
+from qutip import MESolver
-# Power spectrum
-w, S = spectrum_correlation_fft(taulist, corr)
+solver = MESolver(H, c_ops, options={"atol": 1e-10, "rtol": 1e-8})
+first = solver.run(rho_a, tlist, e_ops=e_ops)
+second = solver.run(rho_b, tlist, e_ops=e_ops)
```
-### Multi-Time Correlation
+Use the class interface when repeated setup is material, and verify that
+updated arguments and initial states are the intended ones.
-```python
-# ⟨A(t3)B(t2)C(t1)⟩
-corr = correlation_3op_1t(H, None, taulist, c_ops, A, B, C)
-```
+## Portable output
-## Solver Options
+Do not load untrusted serialized Python or QuTiP objects. For exchange and
+audit, save:
-```python
-from qutip import Options
+- scalar configuration and assumptions;
+- real/imaginary numeric arrays;
+- dimensions, versions, tolerances, seeds, and solver stats;
+- checksums and schema versions where long-term provenance matters.
-options = Options()
-options.nsteps = 10000 # Max internal steps
-options.atol = 1e-8 # Absolute tolerance
-options.rtol = 1e-6 # Relative tolerance
-options.method = 'adams' # or 'bdf' for stiff problems
-options.store_states = True # Store all states
-options.store_final_state = True # Store only final state
+The bundled CLIs use bounded strict JSON and never pickle results.
-result = mesolve(H, psi0, tlist, c_ops, options=options)
-```
+## Local tools
-### Progress Bar
+- `../scripts/two_level_simulation.py`: bounded `mesolve`/`mcsolve` example.
+- `../scripts/solver_config_planner.py`: solver and option checklist.
+- `../scripts/convergence_sweep.py`: deterministic or trajectory convergence.
+- `../scripts/result_audit.py`: portable JSON audit.
-```python
-options.progress_bar = True
-result = mesolve(H, psi0, tlist, c_ops, options=options)
-```
-
-## Saving and Loading Results
-
-```python
-# Save results
-result.save("my_simulation.dat")
-
-# Load results
-from qutip import Result
-loaded_result = Result.load("my_simulation.dat")
-```
+## Sources (verified 2026-07-23)
-## Tips for Efficient Simulations
-
-1. **Sparse matrices**: QuTiP automatically uses sparse matrices
-2. **Small Hilbert spaces**: Truncate when possible
-3. **Time-dependent terms**: String format is fastest (requires compilation)
-4. **Parallel trajectories**: mcsolve automatically parallelizes
-5. **Convergence**: Check by varying `ntraj`, `nsteps`, tolerances
-6. **Solver selection**:
- - Pure states: Use `sesolve` (faster)
- - Mixed states/dissipation: Use `mesolve`
- - Noise/measurements: Use `mcsolve`
- - Weak coupling: Use `brmesolve`
- - Periodic driving: Use Floquet methods
+- [Dynamics API](https://qutip.readthedocs.io/en/stable/apidoc/solver.html)
+- [QobjEvo and coefficients API](https://qutip.readthedocs.io/en/stable/apidoc/time_dep.html)
+- [Dynamics user guide](https://qutip.readthedocs.io/en/stable/guide/guide-dynamics.html)
+- [Monte Carlo guide](https://qutip.readthedocs.io/en/stable/guide/dynamics/dynamics-monte.html)
+- [Stochastic solver guide](https://qutip.readthedocs.io/en/stable/guide/dynamics/dynamics-stochastic.html)
+- [Bloch-Redfield guide](https://qutip.readthedocs.io/en/stable/guide/dynamics/dynamics-bloch-redfield.html)
+- [QuTiP 5.3.0 release](https://github.com/qutip/qutip/releases/tag/v5.3.0)
+- [QuTiP 5 migration changelog](https://qutip.readthedocs.io/en/stable/changelog.html#qutip-5-0-0-2024-03-28)
diff --git a/skills/qutip/references/visualization.md b/skills/qutip/references/visualization.md
index e3f0cc85..50374cee 100644
--- a/skills/qutip/references/visualization.md
+++ b/skills/qutip/references/visualization.md
@@ -1,431 +1,334 @@
-# QuTiP Visualization
+# QuTiP 5.3 Visualization
-## Bloch Sphere
+Research and API verification date: **2026-07-23**. Examples target
+`qutip==5.3.0` with its pinned graphics extra.
-Visualize qubit states on the Bloch sphere.
-
-### Basic Usage
-
-```python
-from qutip import *
-import matplotlib.pyplot as plt
-
-# Create Bloch sphere
-b = Bloch()
-
-# Add states
-psi = (basis(2, 0) + basis(2, 1)).unit()
-b.add_states(psi)
+```bash
+uv pip install "qutip[graphics]==5.3.0"
+```
-# Add vectors
-b.add_vectors([1, 0, 0]) # X-axis
+Plots are diagnostics and communication artifacts, not substitutes for
+normalization, positivity, convergence, or uncertainty checks.
-# Display
-b.show()
-```
+## Phase-space coordinates and axis order
-### Multiple States
+For QuTiP's oscillator phase-space functions, the default scaling is
-```python
-# Add multiple states
-states = [(basis(2, 0) + basis(2, 1)).unit(),
- (basis(2, 0) + 1j*basis(2, 1)).unit()]
-b.add_states(states)
+\[
+a = \tfrac12 g(x + i y), \qquad g=\sqrt{2},
+\]
-# Add points
-b.add_points([[0, 1, 0], [0, -1, 0]])
+which corresponds to \(\hbar=2/g^2=1\).
-# Customize colors
-b.point_color = ['r', 'g']
-b.point_marker = ['o', 's']
-b.point_size = [20, 20]
+In QuTiP 5.3, returned arrays use:
-b.show()
+```text
+array[j, k] <-> yvec[j], xvec[k]
```
-### Animation
+This applies to `wigner`, `qfunc`, and class-based `QFunc`. Therefore, pass
+`xvec` horizontally and `yvec` vertically to Matplotlib:
```python
-# Animate state evolution
-states = result.states # From sesolve/mesolve
+image = ax.pcolormesh(xvec, yvec, values, shading="auto")
+```
-b = Bloch()
-b.vector_color = ['r']
-b.view = [-40, 30] # Viewing angle
+The 5.3 release notes explicitly clarified this order. Do not transpose by
+habit; test with unequal x/y lengths.
-# Create animation
-from matplotlib.animation import FuncAnimation
+## Wigner function
-def animate(i):
- b.clear()
- b.add_states(states[i])
- b.make_sphere()
- return b.axes
+Current signature:
-anim = FuncAnimation(b.fig, animate, frames=len(states),
- interval=50, blit=False, repeat=True)
-plt.show()
+```text
+wigner(psi, xvec, yvec=None, method="clenshaw", g=sqrt(2),
+ sparse=False, parfor=False, offset=0)
```
-### Customization
-
```python
-b = Bloch()
+import numpy as np
+import matplotlib.pyplot as plt
+from qutip import coherent, wigner
-# Sphere appearance
-b.sphere_color = '#FFDDDD'
-b.sphere_alpha = 0.1
-b.frame_alpha = 0.1
+N = 30
+state = coherent(N, 1.5)
+xvec = np.linspace(-5.0, 5.0, 201)
+yvec = np.linspace(-4.0, 4.0, 161)
+W = wigner(state, xvec, yvec, method="clenshaw")
-# Axes
-b.xlabel = ['$|+\\\\rangle$', '$|-\\\\rangle$']
-b.ylabel = ['$|+i\\\\rangle$', '$|-i\\\\rangle$']
-b.zlabel = ['$|0\\\\rangle$', '$|1\\\\rangle$']
+fig, ax = plt.subplots()
+limit = float(np.max(np.abs(W)))
+mesh = ax.pcolormesh(
+ xvec,
+ yvec,
+ W,
+ shading="auto",
+ cmap="RdBu_r",
+ vmin=-limit,
+ vmax=limit,
+)
+ax.set(xlabel="x", ylabel="y", title="Wigner function")
+fig.colorbar(mesh, ax=ax)
+fig.tight_layout()
+```
-# Font sizes
-b.font_size = 20
-b.font_color = 'black'
+Methods:
-# View angle
-b.view = [-60, 30]
+- `clenshaw`: robust default, especially at higher excitation;
+- `iterative`: recurrence method;
+- `laguerre`: can help for sparse high-dimensional states;
+- `fft`: computes y coordinates internally and has a different return form.
-# Save figure
-b.save('bloch.png')
-```
+The `offset` argument added in 5.3 supports Fock representations whose first
+represented number state is not zero.
-## Wigner Function
+Numerical checks:
-Phase-space quasi-probability distribution.
+- sweep Hilbert cutoff and phase-space extent;
+- increase grid density;
+- compare normalization using the documented coordinate scaling;
+- treat tiny negative values near numerical tolerance separately from robust
+ Wigner negativity;
+- preserve an equal data aspect ratio when x and y share physical units.
-### Basic Calculation
+Current convenience plotting:
```python
-# Create state
-psi = coherent(N, alpha)
-
-# Calculate Wigner function
-xvec = np.linspace(-5, 5, 200)
-W = wigner(psi, xvec, xvec)
-
-# Plot
-fig, ax = plt.subplots(1, 1, figsize=(6, 6))
-cont = ax.contourf(xvec, xvec, W, 100, cmap='RdBu')
-ax.set_xlabel('Re(α)')
-ax.set_ylabel('Im(α)')
-plt.colorbar(cont, ax=ax)
-plt.show()
+from qutip import plot_wigner
+
+fig, ax = plot_wigner(
+ state,
+ xvec=xvec,
+ yvec=yvec,
+ projection="2d",
+ colorbar=True,
+)
```
-### Special Colormap
+Use the returned figure and axis rather than relying on global plotting state.
-```python
-# Wigner colormap emphasizes negative values
-from qutip import wigner_cmap
+## Husimi Q function
-W = wigner(psi, xvec, xvec)
+### One state
-fig, ax = plt.subplots()
-cont = ax.contourf(xvec, xvec, W, 100, cmap=wigner_cmap(W))
-ax.set_title('Wigner Function')
-plt.colorbar(cont)
-plt.show()
-```
+Current signature:
-### 3D Surface Plot
+```text
+qfunc(state, xvec, yvec, g=sqrt(2), precompute_memory=1024)
+```
```python
-from mpl_toolkits.mplot3d import Axes3D
+from qutip import qfunc
-X, Y = np.meshgrid(xvec, xvec)
+Q = qfunc(state, xvec, yvec)
+assert Q.shape == (len(yvec), len(xvec))
-fig = plt.figure(figsize=(8, 6))
-ax = fig.add_subplot(111, projection='3d')
-ax.plot_surface(X, Y, W, cmap='RdBu', alpha=0.8)
-ax.set_xlabel('Re(α)')
-ax.set_ylabel('Im(α)')
-ax.set_zlabel('W(α)')
-plt.show()
+fig, ax = plt.subplots()
+mesh = ax.pcolormesh(xvec, yvec, Q, shading="auto", cmap="viridis")
+fig.colorbar(mesh, ax=ax)
```
-### Comparing States
+The Q function is nonnegative in exact arithmetic, but plotting still needs
+truncation, extent, and grid checks.
-```python
-# Compare different states
-states = [coherent(N, 2), fock(N, 2), thermal_dm(N, 2)]
-titles = ['Coherent', 'Fock', 'Thermal']
+### Many states on the same grid
-fig, axes = plt.subplots(1, 3, figsize=(15, 5))
+Current class usage is:
-for i, (state, title) in enumerate(zip(states, titles)):
- W = wigner(state, xvec, xvec)
- cont = axes[i].contourf(xvec, xvec, W, 100, cmap='RdBu')
- axes[i].set_title(title)
- axes[i].set_xlabel('Re(α)')
- if i == 0:
- axes[i].set_ylabel('Im(α)')
+```python
+from qutip import QFunc
-plt.tight_layout()
-plt.show()
+q_on_grid = QFunc(xvec, yvec, memory=256)
+Q_first = q_on_grid(state_a)
+Q_second = q_on_grid(state_b)
```
-## Q-Function (Husimi)
+`QFunc` is constructed with fixed coordinates and then **called with each
+state**. QuTiP 5.3 exposes no `.eval` method on this class. This skill does not
+use Python dynamic-code execution.
-Smoothed phase-space distribution (always positive).
+The `memory` parameter bounds internal workspace in MB and can raise
+`MemoryError` for a large state. For a one-off large state, use `qfunc` with a
+carefully selected `precompute_memory`.
-### Basic Usage
+## Bloch sphere
```python
-from qutip import qfunc
-
-Q = qfunc(psi, xvec, xvec)
+import matplotlib.pyplot as plt
+from qutip import Bloch, basis
-fig, ax = plt.subplots()
-cont = ax.contourf(xvec, xvec, Q, 100, cmap='viridis')
-ax.set_xlabel('Re(α)')
-ax.set_ylabel('Im(α)')
-ax.set_title('Q-Function')
-plt.colorbar(cont)
+psi = (basis(2, 0) + 1j * basis(2, 1)).unit()
+bloch = Bloch()
+bloch.add_states(psi)
+bloch.add_vectors([0.0, 0.0, 1.0], color="black")
+bloch.make_sphere()
plt.show()
```
-### Efficient Batch Calculation
+For dynamics, solve with saved states or the three Pauli expectations:
```python
-from qutip import QFunc
-
-# For calculating Q-function at many points
-qf = QFunc(rho)
-Q = qf.eval(xvec, xvec)
+from qutip import sigmax, sigmay, sigmaz
+
+result = mesolve(
+ H,
+ rho0,
+ tlist,
+ c_ops=c_ops,
+ e_ops=[sigmax(), sigmay(), sigmaz()],
+)
+bloch = Bloch()
+bloch.add_points([result.expect[0], result.expect[1], result.expect[2]])
+bloch.make_sphere()
```
-## Fock State Probability Distribution
-
-Visualize photon number distribution.
+Audit each Bloch vector norm. A density matrix maps inside the unit sphere; a
+vector materially outside it indicates numerical or modeling error.
-### Basic Histogram
+Use explicit colors and line styles and a colorblind-safe palette. QuTiP
+settings include:
```python
-from qutip import plot_fock_distribution
+import qutip
-# Single state
-psi = coherent(N, 2)
-fig, ax = plot_fock_distribution(psi)
-ax.set_title('Coherent State')
-plt.show()
+qutip.settings.colorblind_safe = True
```
-### Comparing Distributions
+Avoid mutating global settings in reusable library code unless the caller
+expects it.
-```python
-states = {
- 'Coherent': coherent(20, 2),
- 'Thermal': thermal_dm(20, 2),
- 'Fock': fock(20, 2)
-}
+## Fock distributions
-fig, axes = plt.subplots(1, 3, figsize=(15, 4))
-
-for ax, (title, state) in zip(axes, states.items()):
- plot_fock_distribution(state, fig=fig, ax=ax)
- ax.set_title(title)
- ax.set_ylim([0, 0.3])
+```python
+from qutip import plot_fock_distribution
-plt.tight_layout()
-plt.show()
+fig, ax = plot_fock_distribution(state)
+ax.set(title="Fock probabilities", xlabel="n", ylabel="Probability")
+fig.tight_layout()
```
-### Time Evolution
+For comparisons, share axes and use the returned `fig, ax`:
```python
-# Show evolution of photon distribution
-result = mesolve(H, psi0, tlist, c_ops)
-
-# Plot at different times
-times_to_plot = [0, 5, 10, 15]
-fig, axes = plt.subplots(1, 4, figsize=(16, 4))
-
-for ax, t_idx in zip(axes, times_to_plot):
- plot_fock_distribution(result.states[t_idx], fig=fig, ax=ax)
- ax.set_title(f't = {tlist[t_idx]:.1f}')
- ax.set_ylim([0, 1])
-
-plt.tight_layout()
-plt.show()
+fig, axes = plt.subplots(1, 2, figsize=(9, 3), sharey=True)
+plot_fock_distribution(state_a, fig=fig, ax=axes[0])
+plot_fock_distribution(state_b, fig=fig, ax=axes[1])
```
-## Matrix Visualization
+Report the probability in the highest represented levels. A visually small
+last bar may still be insufficient if a target observable weights high
+occupations strongly.
-### Hinton Diagram
+## Matrix diagnostics
-Visualize matrix structure with weighted squares.
+Hinton diagrams:
```python
from qutip import hinton
-# Density matrix
-rho = bell_state('00').proj()
-
-hinton(rho)
-plt.title('Bell State Density Matrix')
-plt.show()
+fig, ax = hinton(rho, color_style="phase")
```
-### Matrix Histogram
-
-3D bar plot of matrix elements.
+Three-dimensional matrix histograms:
```python
from qutip import matrix_histogram
-# Show real and imaginary parts
-H = sigmaz()
-
-fig, axes = plt.subplots(1, 2, figsize=(12, 5))
-
-matrix_histogram(H.full(), xlabels=['0', '1'], ylabels=['0', '1'],
- fig=fig, ax=axes[0])
-axes[0].set_title('Real Part')
-
-matrix_histogram(H.full(), bar_type='imag', xlabels=['0', '1'],
- ylabels=['0', '1'], fig=fig, ax=axes[1])
-axes[1].set_title('Imaginary Part')
-
-plt.tight_layout()
-plt.show()
+fig, ax = matrix_histogram(rho, bar_style="abs", color_style="phase")
```
-### Complex Phase Diagram
+QuTiP 5 uses `x_basis`, `y_basis`, `bar_style`, and `color_style` rather than
+old ad hoc label and bar-type recipes. Pass a `Qobj` where supported so
+dimension-aware labels can be retained.
-```python
-# Visualize complex matrix elements
-rho = coherent_dm(10, 2)
-
-# Plot complex elements
-fig, axes = plt.subplots(1, 2, figsize=(12, 5))
+For dense matrices beyond a modest size, a heatmap is usually more legible and
+less expensive than 3D bars. Never hide the imaginary part when it is relevant.
-# Absolute value
-matrix_histogram(rho.full(), bar_type='abs', fig=fig, ax=axes[0])
-axes[0].set_title('Absolute Value')
+## Solver result plots
-# Phase
-matrix_histogram(rho.full(), bar_type='phase', fig=fig, ax=axes[1])
-axes[1].set_title('Phase')
+QuTiP 5.3 adds result methods:
-plt.tight_layout()
-plt.show()
+```python
+fig, axes = result.plot_expect(labels=["population", "coherence"])
```
-## Energy Level Diagrams
+For publication or reusable analysis, explicit plotting remains clearer:
```python
-# Visualize energy eigenvalues
-H = num(N) + 0.1 * (create(N) + destroy(N))**2
-
-# Get eigenvalues and eigenvectors
-evals, ekets = H.eigenstates()
-
-# Plot energy levels
-fig, ax = plt.subplots(figsize=(8, 6))
-
-for i, E in enumerate(evals[:10]):
- ax.hlines(E, 0, 1, linewidth=2)
- ax.text(1.1, E, f'|{i}⟩', va='center')
-
-ax.set_ylabel('Energy')
-ax.set_xlim([-0.2, 1.5])
-ax.set_xticks([])
-ax.set_title('Energy Spectrum')
-plt.show()
+fig, ax = plt.subplots()
+ax.plot(result.times, result.e_data["population"], label="population")
+ax.set(xlabel="time", ylabel="expectation value")
+ax.legend()
+fig.tight_layout()
```
-## Quantum Process Tomography
-
-Visualize quantum channel/gate action.
+Multi-trajectory means need uncertainty bands:
```python
-from qutip.qip.operations import cnot
-from qutip_qip.tomography import qpt, qpt_plot_combined
-
-# Define process (e.g., CNOT gate)
-U = cnot()
+mean = np.asarray(result.expect[0])
+standard_error = np.asarray(result.std_expect[0]) / np.sqrt(result.num_trajectories)
+ax.plot(result.times, mean)
+ax.fill_between(
+ result.times,
+ mean - 1.96 * standard_error,
+ mean + 1.96 * standard_error,
+ alpha=0.25,
+)
+```
-# Perform QPT
-chi = qpt(U, method='choicm')
+Confirm that the trajectory estimator and sample count justify the chosen
+interval; the formula above is only a simple independent-sample approximation.
-# Visualize
-fig = qpt_plot_combined(chi)
-plt.show()
-```
+## Correlation and spectrum plots
-## Expectation Values Over Time
+Plot complex correlations deliberately:
```python
-# Standard plotting of expectation values
-result = mesolve(H, psi0, tlist, c_ops, e_ops=[num(N)])
-
-fig, ax = plt.subplots()
-ax.plot(tlist, result.expect[0])
-ax.set_xlabel('Time')
-ax.set_ylabel('⟨n⟩')
-ax.set_title('Photon Number Evolution')
-ax.grid(True)
-plt.show()
+fig, axes = plt.subplots(2, 1, sharex=True)
+axes[0].plot(taulist, np.real(correlation), label="real")
+axes[1].plot(taulist, np.imag(correlation), label="imaginary")
+axes[1].set_xlabel("delay")
+for ax in axes:
+ ax.legend()
```
-### Multiple Observables
+For spectra:
-```python
-# Plot multiple expectation values
-e_ops = [a.dag() * a, a + a.dag(), 1j * (a - a.dag())]
-labels = ['⟨n⟩', '⟨X⟩', '⟨P⟩']
+- label angular frequency and units;
+- show negative frequencies when physically meaningful;
+- disclose windowing, smoothing, and zero-padding;
+- avoid a logarithmic y-axis when values can be negative;
+- include frequency resolution and convergence information in the caption.
-result = mesolve(H, psi0, tlist, c_ops, e_ops=e_ops)
+## Animations
-fig, axes = plt.subplots(3, 1, figsize=(8, 9))
+Animations can conceal nonconvergence and are expensive to render. First
+produce static frames at physically meaningful times. If animation is needed:
-for i, (ax, label) in enumerate(zip(axes, labels)):
- ax.plot(tlist, result.expect[i])
- ax.set_ylabel(label)
- ax.grid(True)
+- cap frame count and resolution;
+- keep phase-space color limits fixed across frames;
+- avoid recomputing solver dynamics inside the frame callback;
+- save to a user-selected local path;
+- record the time-to-frame mapping.
-axes[-1].set_xlabel('Time')
-plt.tight_layout()
-plt.show()
-```
+QuTiP 5 includes animation helpers in its visualization API, but their inputs
+still require stored states and memory planning.
-## Correlation Functions and Spectra
+## Figure export
```python
-# Two-time correlation function
-taulist = np.linspace(0, 10, 200)
-corr = correlation_2op_1t(H, rho0, taulist, c_ops, a.dag(), a)
-
-# Plot correlation
-fig, ax = plt.subplots()
-ax.plot(taulist, np.real(corr))
-ax.set_xlabel('τ')
-ax.set_ylabel('⟨a†(τ)a(0)⟩')
-ax.set_title('Correlation Function')
-plt.show()
-
-# Power spectrum
-from qutip import spectrum_correlation_fft
-
-w, S = spectrum_correlation_fft(taulist, corr)
-
-fig, ax = plt.subplots()
-ax.plot(w, S)
-ax.set_xlabel('Frequency')
-ax.set_ylabel('S(ω)')
-ax.set_title('Power Spectrum')
-plt.show()
+fig.savefig("phase_space.svg", bbox_inches="tight")
+fig.savefig("phase_space.png", dpi=300, bbox_inches="tight")
```
-## Saving Figures
+Use an explicit local output path, avoid overwriting without user intent, and
+save the numeric data/configuration next to the figure. A raster image alone is
+not a reproducible result.
-```python
-# High-resolution saves
-fig.savefig('my_plot.png', dpi=300, bbox_inches='tight')
-fig.savefig('my_plot.pdf', bbox_inches='tight')
-fig.savefig('my_plot.svg', bbox_inches='tight')
-```
+## Sources (verified 2026-07-23)
+
+- [Visualization and animation API](https://qutip.readthedocs.io/en/stable/apidoc/visualization.html)
+- [Wigner and Q-function API](https://qutip.readthedocs.io/en/stable/apidoc/visualization.html#pseudoprobability-functions)
+- [Bloch sphere guide](https://qutip.readthedocs.io/en/stable/guide/guide-bloch.html)
+- [QuTiP 5.3.0 release notes](https://github.com/qutip/qutip/releases/tag/v5.3.0)
+- [Official QuTiP version-5 tutorials](https://github.com/qutip/qutip-tutorials/tree/main/tutorials-v5)
diff --git a/skills/qutip/scripts/_common.py b/skills/qutip/scripts/_common.py
new file mode 100644
index 00000000..132856ac
--- /dev/null
+++ b/skills/qutip/scripts/_common.py
@@ -0,0 +1,370 @@
+#!/usr/bin/env python3
+"""Shared bounded-I/O and validation helpers for the QuTiP CLIs."""
+
+from __future__ import annotations
+
+import json
+import math
+import os
+import stat
+import sys
+import tempfile
+from collections.abc import Callable, Iterable, Mapping, Sequence
+from pathlib import Path
+from typing import Any
+
+
+QUTIP_VERSION = "5.3.0"
+PINNED_INSTALL = 'uv pip install "qutip==5.3.0"'
+DEFAULT_SEED = 20_260_723
+
+MAX_INPUT_BYTES = 1024 * 1024
+MAX_REPORT_BYTES = 8 * 1024 * 1024
+MAX_HILBERT_DIMENSION = 64
+MAX_SUBSYSTEMS = 8
+MAX_MODEL_OBJECTS = 32
+MAX_TIME_POINTS = 5_001
+MAX_TRAJECTORIES = 2_000
+MAX_SWEEP_RUNS = 6
+MAX_TOTAL_SWEEP_TRAJECTORIES = 4_000
+MAX_FREQUENCY_POINTS = 10_001
+MAX_ABS_FREQUENCY = 100_000.0
+MAX_RATE = 10_000.0
+MAX_TIME = 100_000.0
+
+
+class CliError(ValueError):
+ """An expected command-line, schema, or numerical validation error."""
+
+
+def load_qutip() -> Any:
+ """Import the exact supported QuTiP release on demand."""
+
+ try:
+ import qutip
+ except ModuleNotFoundError as exc:
+ if exc.name != "qutip":
+ raise
+ raise CliError(
+ f"QuTiP {QUTIP_VERSION} is required; install it with "
+ f"`{PINNED_INSTALL}`"
+ ) from exc
+ installed = str(getattr(qutip, "__version__", "unknown"))
+ if installed != QUTIP_VERSION:
+ raise CliError(
+ f"this snapshot requires QuTiP {QUTIP_VERSION}, found {installed}; "
+ f"install it with `{PINNED_INSTALL}`"
+ )
+ return qutip
+
+
+def _reject_constant(value: str) -> None:
+ raise CliError(f"non-standard JSON constant is not allowed: {value}")
+
+
+def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for key, value in pairs:
+ if key in result:
+ raise CliError(f"duplicate JSON key is not allowed: {key!r}")
+ result[key] = value
+ return result
+
+
+def checked_input_file(
+ value: str | os.PathLike[str],
+ *,
+ suffixes: Iterable[str] = (".json",),
+ max_bytes: int = MAX_INPUT_BYTES,
+) -> Path:
+ """Return a bounded regular local input, rejecting URLs and symlinks."""
+
+ raw = os.fspath(value)
+ if "://" in raw:
+ raise CliError("network URLs are not accepted; provide a local file")
+ path = Path(raw).expanduser()
+ if path.is_symlink():
+ raise CliError(f"input must not be a symlink: {path}")
+ try:
+ info = path.stat()
+ except OSError as exc:
+ raise CliError(f"cannot access input file {path}: {exc}") from exc
+ if not stat.S_ISREG(info.st_mode):
+ raise CliError(f"input is not a regular file: {path}")
+ if info.st_size > max_bytes:
+ raise CliError(f"input is {info.st_size} bytes; limit is {max_bytes}")
+ allowed = {suffix.lower() for suffix in suffixes}
+ if path.suffix.lower() not in allowed:
+ raise CliError(f"input suffix must be one of: {', '.join(sorted(allowed))}")
+ return path.resolve()
+
+
+def checked_output_file(
+ value: str | os.PathLike[str],
+ *,
+ force: bool = False,
+) -> Path:
+ """Validate an explicit local JSON destination without following symlinks."""
+
+ raw = os.fspath(value)
+ if "://" in raw:
+ raise CliError("network URLs are not accepted as output paths")
+ path = Path(raw).expanduser()
+ if path.suffix.lower() != ".json":
+ raise CliError("output path must end in .json")
+ if path.is_symlink():
+ raise CliError(f"output must not be a symlink: {path}")
+ parent = path.parent
+ if not parent.exists() or not parent.is_dir() or parent.is_symlink():
+ raise CliError(f"output parent must be an existing regular directory: {parent}")
+ if path.exists():
+ if not path.is_file():
+ raise CliError(f"output exists and is not a regular file: {path}")
+ if not force:
+ raise CliError(f"refusing to overwrite existing output: {path}")
+ return parent.resolve() / path.name
+
+
+def load_json_object(value: str | os.PathLike[str]) -> dict[str, Any]:
+ """Load a bounded strict-JSON object from a local file."""
+
+ path = checked_input_file(value)
+ try:
+ with path.open("r", encoding="utf-8") as handle:
+ document = json.load(
+ handle,
+ parse_constant=_reject_constant,
+ object_pairs_hook=_unique_object,
+ )
+ except CliError:
+ raise
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
+ raise CliError(f"cannot read valid JSON from {path.name}: {exc}") from exc
+ if not isinstance(document, dict):
+ raise CliError("JSON root must be an object")
+ return document
+
+
+def validate_keys(
+ value: Mapping[str, Any],
+ *,
+ allowed: Iterable[str],
+ required: Iterable[str] = (),
+ context: str = "object",
+) -> None:
+ """Reject unknown keys and report missing required keys."""
+
+ allowed_set = set(allowed)
+ required_set = set(required)
+ unknown = sorted(set(value) - allowed_set)
+ missing = sorted(required_set - set(value))
+ if unknown:
+ raise CliError(f"{context} has unknown keys: {', '.join(unknown)}")
+ if missing:
+ raise CliError(f"{context} is missing keys: {', '.join(missing)}")
+
+
+def bounded_int(
+ value: Any,
+ *,
+ name: str,
+ minimum: int,
+ maximum: int,
+) -> int:
+ """Validate a bounded integer, rejecting booleans."""
+
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise CliError(f"{name} must be an integer")
+ if not minimum <= value <= maximum:
+ raise CliError(f"{name} must be from {minimum} through {maximum}")
+ return value
+
+
+def finite_float(
+ value: Any,
+ *,
+ name: str,
+ minimum: float | None = None,
+ maximum: float | None = None,
+ minimum_inclusive: bool = True,
+) -> float:
+ """Validate a finite number with optional bounds."""
+
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise CliError(f"{name} must be a number")
+ result = float(value)
+ if not math.isfinite(result):
+ raise CliError(f"{name} must be finite")
+ if minimum is not None:
+ valid = result >= minimum if minimum_inclusive else result > minimum
+ if not valid:
+ qualifier = "at least" if minimum_inclusive else "greater than"
+ raise CliError(f"{name} must be {qualifier} {minimum}")
+ if maximum is not None and result > maximum:
+ raise CliError(f"{name} must be no greater than {maximum}")
+ return result
+
+
+def bounded_dimensions(value: Any, *, name: str = "dims") -> list[int]:
+ """Validate subsystem dimensions and their bounded product."""
+
+ if not isinstance(value, list) or not value:
+ raise CliError(f"{name} must be a non-empty JSON array")
+ if len(value) > MAX_SUBSYSTEMS:
+ raise CliError(f"{name} may contain at most {MAX_SUBSYSTEMS} subsystems")
+ dimensions = [
+ bounded_int(item, name=f"{name}[{index}]", minimum=1, maximum=64)
+ for index, item in enumerate(value)
+ ]
+ product = math.prod(dimensions)
+ if product > MAX_HILBERT_DIMENSION:
+ raise CliError(
+ f"{name} product is {product}; limit is {MAX_HILBERT_DIMENSION}"
+ )
+ return dimensions
+
+
+def parse_csv_ints(
+ value: str,
+ *,
+ name: str,
+ minimum: int,
+ maximum: int,
+ max_items: int = MAX_SWEEP_RUNS,
+) -> list[int]:
+ """Parse a short comma-separated list of unique increasing integers."""
+
+ pieces = [piece.strip() for piece in value.split(",")]
+ if not pieces or any(not piece for piece in pieces):
+ raise CliError(f"{name} must be a comma-separated integer list")
+ if len(pieces) > max_items:
+ raise CliError(f"{name} may contain at most {max_items} values")
+ try:
+ values = [int(piece, 10) for piece in pieces]
+ except ValueError as exc:
+ raise CliError(f"{name} must contain only base-10 integers") from exc
+ checked = [
+ bounded_int(item, name=name, minimum=minimum, maximum=maximum)
+ for item in values
+ ]
+ if checked != sorted(set(checked)):
+ raise CliError(f"{name} values must be unique and strictly increasing")
+ return checked
+
+
+def ensure_strictly_increasing(values: Sequence[float], *, name: str) -> None:
+ """Require finite strictly increasing values."""
+
+ if len(values) < 2:
+ raise CliError(f"{name} must contain at least two values")
+ previous = finite_float(values[0], name=f"{name}[0]")
+ for index, value in enumerate(values[1:], start=1):
+ current = finite_float(value, name=f"{name}[{index}]")
+ if current <= previous:
+ raise CliError(f"{name} must be strictly increasing")
+ previous = current
+
+
+def to_jsonable(value: Any) -> Any:
+ """Convert trusted result scalars/arrays into strict-JSON-compatible values."""
+
+ if value is None or isinstance(value, (bool, str, int)):
+ return value
+ if isinstance(value, float):
+ if not math.isfinite(value):
+ raise CliError("report contains a non-finite float")
+ return value
+ if isinstance(value, complex):
+ if not math.isfinite(value.real) or not math.isfinite(value.imag):
+ raise CliError("report contains a non-finite complex value")
+ return {"real": float(value.real), "imag": float(value.imag)}
+ if isinstance(value, Mapping):
+ return {str(key): to_jsonable(item) for key, item in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [to_jsonable(item) for item in value]
+ if hasattr(value, "tolist"):
+ return to_jsonable(value.tolist())
+ if hasattr(value, "item"):
+ return to_jsonable(value.item())
+ return str(value)
+
+
+def strict_json_bytes(document: Any) -> bytes:
+ """Serialize deterministic RFC-compatible JSON with a size cap."""
+
+ normalized = to_jsonable(document)
+ try:
+ payload = (
+ json.dumps(
+ normalized,
+ indent=2,
+ sort_keys=True,
+ ensure_ascii=False,
+ allow_nan=False,
+ )
+ + "\n"
+ ).encode("utf-8")
+ except (TypeError, ValueError) as exc:
+ raise CliError(f"report is not strict JSON: {exc}") from exc
+ if len(payload) > MAX_REPORT_BYTES:
+ raise CliError(
+ f"report is {len(payload)} bytes; limit is {MAX_REPORT_BYTES}"
+ )
+ return payload
+
+
+def emit_json(
+ document: Any,
+ *,
+ output: str | os.PathLike[str] | None = None,
+ force: bool = False,
+) -> None:
+ """Print strict JSON or atomically write a private local JSON file."""
+
+ payload = strict_json_bytes(document)
+ if output is None:
+ print(payload.decode("utf-8"), end="")
+ return
+ destination = checked_output_file(output, force=force)
+ descriptor, temporary_name = tempfile.mkstemp(
+ prefix=f".{destination.name}.",
+ suffix=".tmp",
+ dir=destination.parent,
+ )
+ temporary = Path(temporary_name)
+ try:
+ with os.fdopen(descriptor, "wb") as handle:
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.chmod(temporary, 0o600)
+ if destination.exists() and not force:
+ raise CliError(f"refusing to overwrite existing output: {destination}")
+ os.replace(temporary, destination)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def add_output_arguments(parser: Any) -> None:
+ """Add common explicit JSON output controls to an ArgumentParser."""
+
+ parser.add_argument(
+ "--output",
+ help="write strict JSON to this local .json path (default: stdout)",
+ )
+ parser.add_argument(
+ "--force",
+ action="store_true",
+ help="allow replacing an existing regular output file",
+ )
+
+
+def run_cli(action: Callable[[], int | None]) -> int:
+ """Run one CLI action with concise expected-error reporting."""
+
+ try:
+ status = action()
+ except CliError as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ return 0 if status is None else int(status)
diff --git a/skills/qutip/scripts/convergence_sweep.py b/skills/qutip/scripts/convergence_sweep.py
new file mode 100644
index 00000000..b327c648
--- /dev/null
+++ b/skills/qutip/scripts/convergence_sweep.py
@@ -0,0 +1,358 @@
+#!/usr/bin/env python3
+"""Run bounded deterministic or trajectory convergence sweeps."""
+
+from __future__ import annotations
+
+import argparse
+from typing import Any
+
+from _common import (
+ DEFAULT_SEED,
+ MAX_SWEEP_RUNS,
+ MAX_TIME_POINTS,
+ MAX_TOTAL_SWEEP_TRAJECTORIES,
+ MAX_TRAJECTORIES,
+ QUTIP_VERSION,
+ CliError,
+ add_output_arguments,
+ emit_json,
+ finite_float,
+ load_qutip,
+ parse_csv_ints,
+ run_cli,
+)
+from two_level_simulation import SimulationConfig, run_simulation
+
+
+def _parse_rtols(value: str) -> list[float]:
+ pieces = [piece.strip() for piece in value.split(",")]
+ if not pieces or any(not piece for piece in pieces):
+ raise CliError("rtols must be a comma-separated number list")
+ if len(pieces) > MAX_SWEEP_RUNS:
+ raise CliError(f"rtols may contain at most {MAX_SWEEP_RUNS} values")
+ try:
+ values = [float(piece) for piece in pieces]
+ except ValueError as exc:
+ raise CliError("rtols must contain only numbers") from exc
+ checked = [
+ finite_float(
+ item,
+ name="rtol",
+ minimum=1.0e-12,
+ maximum=1.0e-2,
+ )
+ for item in values
+ ]
+ if any(left <= right for left, right in zip(checked, checked[1:])):
+ raise CliError("rtols must be strictly decreasing from coarse to fine")
+ return checked
+
+
+def _base_config(
+ *,
+ solver: str,
+ args: argparse.Namespace,
+ time_points: int,
+ trajectories: int,
+ rtol: float,
+) -> SimulationConfig:
+ return SimulationConfig(
+ solver=solver,
+ initial_state="excited",
+ omega=finite_float(
+ args.omega,
+ name="omega",
+ minimum=-100_000.0,
+ maximum=100_000.0,
+ ),
+ drive=finite_float(
+ args.drive,
+ name="drive",
+ minimum=-100_000.0,
+ maximum=100_000.0,
+ ),
+ decay_rate=finite_float(
+ args.decay_rate,
+ name="decay_rate",
+ minimum=0.0,
+ maximum=10_000.0,
+ ),
+ dephasing_rate=finite_float(
+ args.dephasing_rate,
+ name="dephasing_rate",
+ minimum=0.0,
+ maximum=10_000.0,
+ ),
+ t_final=finite_float(
+ args.t_final,
+ name="t_final",
+ minimum=0.0,
+ maximum=100_000.0,
+ minimum_inclusive=False,
+ ),
+ time_points=time_points,
+ trajectories=trajectories,
+ seed=int(args.seed),
+ method=str(args.method),
+ atol=max(1.0e-14, rtol * 0.01),
+ rtol=rtol,
+ )
+
+
+def run_sweep(
+ args: argparse.Namespace,
+ qutip_module: Any | None = None,
+) -> dict[str, Any]:
+ """Execute the requested bounded convergence sweep."""
+
+ import numpy as np
+
+ qutip = qutip_module or load_qutip()
+ acceptance = finite_float(
+ args.acceptance,
+ name="acceptance",
+ minimum=1.0e-12,
+ maximum=0.5,
+ )
+ seed = int(args.seed)
+ if seed < 0 or seed > 2**63 - 1:
+ raise CliError("seed must be from 0 through 2^63-1")
+
+ reports: list[dict[str, Any]] = []
+ run_summaries: list[dict[str, Any]] = []
+
+ if args.mode == "deterministic":
+ points = parse_csv_ints(
+ args.time_points,
+ name="time_points",
+ minimum=2,
+ maximum=MAX_TIME_POINTS,
+ )
+ rtols = _parse_rtols(args.rtols)
+ if len(points) < 2:
+ raise CliError("deterministic convergence requires at least two runs")
+ if len(points) != len(rtols):
+ raise CliError("time_points and rtols must contain the same number of values")
+ for index, (count, rtol) in enumerate(zip(points, rtols)):
+ config = _base_config(
+ solver="mesolve",
+ args=args,
+ time_points=count,
+ trajectories=1,
+ rtol=rtol,
+ )
+ report = run_simulation(config, qutip)
+ reports.append(report)
+ run_summaries.append(
+ {
+ "index": index,
+ "time_points": count,
+ "atol": config.atol,
+ "rtol": rtol,
+ "final_excited_population": float(
+ report["expectations"]["excited_population"][-1]
+ ),
+ "analytic_max_abs_error": report["analytic_reference"][
+ "max_abs_error"
+ ],
+ "final_state_valid": report["checks"]["final_state"].get(
+ "valid_within_tolerance", False
+ ),
+ "solver_stats": report["solver"]["stats"],
+ }
+ )
+
+ reference_times = np.asarray(reports[-1]["times"], dtype=float)
+ reference_values = np.asarray(
+ reports[-1]["expectations"]["excited_population"],
+ dtype=float,
+ )
+ comparisons = []
+ for index, report in enumerate(reports[:-1]):
+ times = np.asarray(report["times"], dtype=float)
+ values = np.asarray(
+ report["expectations"]["excited_population"],
+ dtype=float,
+ )
+ reference_on_grid = np.interp(times, reference_times, reference_values)
+ difference = float(np.max(np.abs(values - reference_on_grid)))
+ comparisons.append(
+ {
+ "run_index": index,
+ "reference_run_index": len(reports) - 1,
+ "max_abs_population_difference": difference,
+ "within_acceptance": difference <= acceptance,
+ }
+ )
+ status = (
+ "converged_at_requested_threshold"
+ if comparisons and all(item["within_acceptance"] for item in comparisons)
+ else "not_converged_at_requested_threshold"
+ )
+ design = {
+ "varied": ["time_points", "rtol", "atol"],
+ "paired_randomness": None,
+ }
+ else:
+ counts = parse_csv_ints(
+ args.trajectory_counts,
+ name="trajectory_counts",
+ minimum=2,
+ maximum=MAX_TRAJECTORIES,
+ )
+ if len(counts) < 2:
+ raise CliError("Monte Carlo convergence requires at least two runs")
+ if sum(counts) > MAX_TOTAL_SWEEP_TRAJECTORIES:
+ raise CliError(
+ f"sum of trajectory_counts exceeds {MAX_TOTAL_SWEEP_TRAJECTORIES}"
+ )
+ time_points = int(args.mc_time_points)
+ if not 2 <= time_points <= MAX_TIME_POINTS:
+ raise CliError(
+ f"mc_time_points must be from 2 through {MAX_TIME_POINTS}"
+ )
+ rtol = finite_float(
+ args.mc_rtol,
+ name="mc_rtol",
+ minimum=1.0e-12,
+ maximum=1.0e-2,
+ )
+ for index, count in enumerate(counts):
+ config = _base_config(
+ solver="mcsolve",
+ args=args,
+ time_points=time_points,
+ trajectories=count,
+ rtol=rtol,
+ )
+ if config.decay_rate == 0.0 and config.dephasing_rate == 0.0:
+ raise CliError(
+ "monte-carlo mode requires a nonzero decay or dephasing rate"
+ )
+ report = run_simulation(config, qutip)
+ reports.append(report)
+ standard_error = report["trajectory_statistics"][
+ "excited_population_standard_error_estimate"
+ ]
+ run_summaries.append(
+ {
+ "index": index,
+ "trajectories_requested": count,
+ "trajectories_run": report["trajectory_statistics"][
+ "trajectories_run"
+ ],
+ "final_excited_population": float(
+ report["expectations"]["excited_population"][-1]
+ ),
+ "final_standard_error_estimate": float(standard_error[-1]),
+ "analytic_max_abs_error": report["analytic_reference"][
+ "max_abs_error"
+ ],
+ "seed_count": len(
+ report["trajectory_statistics"]["seeds"] or []
+ ),
+ }
+ )
+ reference_value = run_summaries[-1]["final_excited_population"]
+ comparisons = []
+ for summary in run_summaries[:-1]:
+ difference = abs(summary["final_excited_population"] - reference_value)
+ uncertainty_scale = max(
+ summary["final_standard_error_estimate"],
+ run_summaries[-1]["final_standard_error_estimate"],
+ )
+ comparisons.append(
+ {
+ "run_index": summary["index"],
+ "reference_run_index": len(run_summaries) - 1,
+ "absolute_final_population_difference": difference,
+ "acceptance_threshold": acceptance,
+ "within_absolute_acceptance": difference <= acceptance,
+ "difference_over_larger_standard_error": (
+ difference / uncertainty_scale
+ if uncertainty_scale > 0.0
+ else None
+ ),
+ }
+ )
+ status = "sampling_diagnostic_complete"
+ design = {
+ "varied": ["ntraj"],
+ "paired_randomness": (
+ "The same base seed is intentionally used so QuTiP spawns "
+ "comparable trajectory prefixes; these are not independent replicates."
+ ),
+ }
+
+ return {
+ "report_type": "qutip.convergence_sweep",
+ "schema_version": 1,
+ "qutip_version": QUTIP_VERSION,
+ "mode": args.mode,
+ "acceptance": acceptance,
+ "design": design,
+ "runs": run_summaries,
+ "comparisons": comparisons,
+ "status": status,
+ "limits": {
+ "maximum_runs": MAX_SWEEP_RUNS,
+ "maximum_total_trajectories": MAX_TOTAL_SWEEP_TRAJECTORIES,
+ "maximum_time_points_per_run": MAX_TIME_POINTS,
+ },
+ "interpretation": (
+ "A synthetic sweep demonstrates numerical checks; repeat convergence "
+ "for every cutoff and reported observable in the scientific model."
+ ),
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Run a bounded synthetic QuTiP convergence sweep over deterministic "
+ "tolerances/grids or Monte Carlo trajectory counts."
+ )
+ )
+ parser.add_argument(
+ "--mode",
+ choices=("deterministic", "monte-carlo"),
+ default="deterministic",
+ )
+ parser.add_argument("--omega", type=float, default=1.0)
+ parser.add_argument("--drive", type=float, default=0.0)
+ parser.add_argument("--decay-rate", type=float, default=0.2)
+ parser.add_argument("--dephasing-rate", type=float, default=0.0)
+ parser.add_argument("--t-final", type=float, default=10.0)
+ parser.add_argument("--method", choices=("adams", "bdf", "lsoda"), default="adams")
+ parser.add_argument("--seed", type=int, default=DEFAULT_SEED)
+ parser.add_argument("--acceptance", type=float, default=1.0e-5)
+ parser.add_argument(
+ "--time-points",
+ default="101,201,401",
+ help="deterministic mode: increasing comma-separated output-grid sizes",
+ )
+ parser.add_argument(
+ "--rtols",
+ default="1e-5,1e-7,1e-9",
+ help="deterministic mode: decreasing comma-separated relative tolerances",
+ )
+ parser.add_argument(
+ "--trajectory-counts",
+ default="50,100,200",
+ help="Monte Carlo mode: increasing comma-separated trajectory counts",
+ )
+ parser.add_argument("--mc-time-points", type=int, default=101)
+ parser.add_argument("--mc-rtol", type=float, default=1.0e-8)
+ add_output_arguments(parser)
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ report = run_sweep(args)
+ emit_json(report, output=args.output, force=args.force)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/qutip/scripts/qobj_model_validator.py b/skills/qutip/scripts/qobj_model_validator.py
new file mode 100644
index 00000000..7cf54a38
--- /dev/null
+++ b/skills/qutip/scripts/qobj_model_validator.py
@@ -0,0 +1,327 @@
+#!/usr/bin/env python3
+"""Validate a bounded numeric QuTiP model described by strict JSON."""
+
+from __future__ import annotations
+
+import argparse
+import math
+import re
+from collections.abc import Mapping
+from typing import Any
+
+from _common import (
+ MAX_MODEL_OBJECTS,
+ QUTIP_VERSION,
+ CliError,
+ add_output_arguments,
+ bounded_dimensions,
+ emit_json,
+ finite_float,
+ load_json_object,
+ load_qutip,
+ run_cli,
+ validate_keys,
+)
+
+
+ROLES = {"hamiltonian", "initial_state", "collapse_operator", "observable"}
+UNIT_CONVENTIONS = {"hbar=1-angular-frequency", "dimensionless-scaled"}
+NAME_PATTERN = re.compile(r"[A-Za-z][A-Za-z0-9_.-]{0,63}\Z")
+MAX_ABS_ENTRY = 1.0e12
+
+
+def _name(value: Any, *, context: str) -> str:
+ if not isinstance(value, str) or not NAME_PATTERN.fullmatch(value):
+ raise CliError(
+ f"{context} must match {NAME_PATTERN.pattern!r} and be at most 64 characters"
+ )
+ return value
+
+
+def _complex_scalar(value: Any, *, name: str) -> complex:
+ if isinstance(value, Mapping):
+ validate_keys(
+ value,
+ allowed={"real", "imag"},
+ required={"real", "imag"},
+ context=name,
+ )
+ real = finite_float(value["real"], name=f"{name}.real")
+ imag = finite_float(value["imag"], name=f"{name}.imag")
+ result = complex(real, imag)
+ else:
+ result = complex(finite_float(value, name=name), 0.0)
+ if abs(result) > MAX_ABS_ENTRY:
+ raise CliError(f"{name} magnitude exceeds {MAX_ABS_ENTRY}")
+ return result
+
+
+def _numeric_data(
+ value: Any,
+ *,
+ role: str,
+ dimension: int,
+ context: str,
+) -> tuple[list[complex] | list[list[complex]], bool]:
+ if not isinstance(value, list) or not value:
+ raise CliError(f"{context}.data must be a non-empty JSON array")
+
+ is_matrix = all(isinstance(row, list) for row in value)
+ if any(isinstance(row, list) for row in value) and not is_matrix:
+ raise CliError(f"{context}.data cannot mix scalar entries and matrix rows")
+
+ if not is_matrix:
+ if role != "initial_state":
+ raise CliError(f"{context}.data must be a square matrix for role {role}")
+ if len(value) != dimension:
+ raise CliError(
+ f"{context}.data ket length is {len(value)}; expected {dimension}"
+ )
+ return [
+ _complex_scalar(item, name=f"{context}.data[{index}]")
+ for index, item in enumerate(value)
+ ], True
+
+ if len(value) != dimension:
+ raise CliError(
+ f"{context}.data has {len(value)} rows; expected {dimension}"
+ )
+ matrix: list[list[complex]] = []
+ for row_index, row in enumerate(value):
+ if len(row) != dimension:
+ raise CliError(
+ f"{context}.data[{row_index}] has {len(row)} entries; "
+ f"expected {dimension}"
+ )
+ matrix.append(
+ [
+ _complex_scalar(
+ item,
+ name=f"{context}.data[{row_index}][{column_index}]",
+ )
+ for column_index, item in enumerate(row)
+ ]
+ )
+ return matrix, False
+
+
+def _state_summary(qobj: Any, *, tolerance: float) -> tuple[dict[str, Any], bool]:
+ if qobj.isket:
+ norm = float(qobj.norm())
+ valid = abs(norm - 1.0) <= tolerance
+ return {
+ "representation": "ket",
+ "norm": norm,
+ "normalization_error": abs(norm - 1.0),
+ "normalized_within_tolerance": valid,
+ }, valid
+
+ trace = complex(qobj.tr())
+ hermitian = bool(qobj.isherm)
+ if hermitian:
+ eigenvalues = [float(value) for value in qobj.eigenenergies()]
+ minimum_eigenvalue = min(eigenvalues)
+ else:
+ minimum_eigenvalue = None
+ valid = (
+ hermitian
+ and abs(trace - 1.0) <= tolerance
+ and minimum_eigenvalue is not None
+ and minimum_eigenvalue >= -tolerance
+ )
+ return {
+ "representation": "density_matrix",
+ "is_hermitian": hermitian,
+ "trace": trace,
+ "trace_error": abs(trace - 1.0),
+ "minimum_eigenvalue": minimum_eigenvalue,
+ "positive_within_tolerance": (
+ minimum_eigenvalue is not None and minimum_eigenvalue >= -tolerance
+ ),
+ }, valid
+
+
+def validate_model(document: Mapping[str, Any], qutip_module: Any | None = None) -> dict[str, Any]:
+ """Validate one bounded model and return a portable report."""
+
+ validate_keys(
+ document,
+ allowed={"schema_version", "unit_convention", "tolerance", "objects"},
+ required={"schema_version", "unit_convention", "objects"},
+ context="model",
+ )
+ if document["schema_version"] != 1:
+ raise CliError("schema_version must be the integer 1")
+ convention = document["unit_convention"]
+ if convention not in UNIT_CONVENTIONS:
+ raise CliError(
+ "unit_convention must be one of: "
+ + ", ".join(sorted(UNIT_CONVENTIONS))
+ )
+ tolerance = finite_float(
+ document.get("tolerance", 1.0e-9),
+ name="tolerance",
+ minimum=1.0e-14,
+ maximum=1.0e-3,
+ )
+ objects = document["objects"]
+ if not isinstance(objects, list) or not 1 <= len(objects) <= MAX_MODEL_OBJECTS:
+ raise CliError(
+ f"objects must contain from 1 through {MAX_MODEL_OBJECTS} entries"
+ )
+
+ qutip = qutip_module or load_qutip()
+ summaries: list[dict[str, Any]] = []
+ names: set[str] = set()
+ dimensions_seen: list[list[int]] = []
+ hamiltonians = 0
+ initial_states = 0
+ valid = True
+
+ for index, raw in enumerate(objects):
+ context = f"objects[{index}]"
+ if not isinstance(raw, Mapping):
+ raise CliError(f"{context} must be a JSON object")
+ validate_keys(
+ raw,
+ allowed={"name", "role", "dims", "data", "rate"},
+ required={"name", "role", "dims", "data"},
+ context=context,
+ )
+ name = _name(raw["name"], context=f"{context}.name")
+ if name in names:
+ raise CliError(f"object names must be unique; duplicate {name!r}")
+ names.add(name)
+ role = raw["role"]
+ if role not in ROLES:
+ raise CliError(f"{context}.role must be one of: {', '.join(sorted(ROLES))}")
+ dimensions = bounded_dimensions(raw["dims"], name=f"{context}.dims")
+ dimension = math.prod(dimensions)
+ dimensions_seen.append(dimensions)
+ data, is_ket = _numeric_data(
+ raw["data"],
+ role=role,
+ dimension=dimension,
+ context=context,
+ )
+ if is_ket:
+ qobj = qutip.Qobj(
+ data,
+ dims=[dimensions, [1] * len(dimensions)],
+ )
+ else:
+ qobj = qutip.Qobj(data, dims=[dimensions, dimensions])
+
+ summary: dict[str, Any] = {
+ "name": name,
+ "role": role,
+ "dims": qobj.dims,
+ "shape": list(qobj.shape),
+ "qobj_type": qobj.type,
+ }
+
+ object_valid = True
+ if role == "hamiltonian":
+ hamiltonians += 1
+ if "rate" in raw:
+ raise CliError(f"{context}.rate is valid only for collapse_operator")
+ object_valid = bool(qobj.isoper and qobj.isherm)
+ summary["is_hermitian"] = bool(qobj.isherm)
+ elif role == "initial_state":
+ initial_states += 1
+ if "rate" in raw:
+ raise CliError(f"{context}.rate is valid only for collapse_operator")
+ state_summary, object_valid = _state_summary(
+ qobj,
+ tolerance=tolerance,
+ )
+ summary.update(state_summary)
+ elif role == "observable":
+ if "rate" in raw:
+ raise CliError(f"{context}.rate is valid only for collapse_operator")
+ object_valid = bool(qobj.isoper and qobj.isherm)
+ summary["is_hermitian"] = bool(qobj.isherm)
+ else:
+ if is_ket:
+ raise CliError(f"{context}.data must be an operator matrix")
+ if "rate" not in raw:
+ raise CliError(f"{context}.rate is required for collapse_operator")
+ rate = finite_float(
+ raw["rate"],
+ name=f"{context}.rate",
+ minimum=0.0,
+ maximum=10_000.0,
+ )
+ scaled = math.sqrt(rate) * qobj
+ object_valid = bool(qobj.isoper)
+ summary.update(
+ {
+ "rate": rate,
+ "scaling": "sqrt(rate) * operator",
+ "scaled_operator_norm": float(scaled.norm()),
+ }
+ )
+
+ summary["valid"] = object_valid
+ valid = valid and object_valid
+ summaries.append(summary)
+
+ if hamiltonians != 1:
+ raise CliError(f"model must contain exactly one hamiltonian; found {hamiltonians}")
+ if initial_states != 1:
+ raise CliError(
+ f"model must contain exactly one initial_state; found {initial_states}"
+ )
+
+ reference_dims = dimensions_seen[0]
+ compatible_dims = all(item == reference_dims for item in dimensions_seen)
+ valid = valid and compatible_dims
+
+ return {
+ "report_type": "qutip.qobj_model_validation",
+ "schema_version": 1,
+ "qutip_version": QUTIP_VERSION,
+ "unit_convention": convention,
+ "tolerance": tolerance,
+ "limits": {
+ "hilbert_dimension": 64,
+ "model_objects": MAX_MODEL_OBJECTS,
+ },
+ "checks": {
+ "exactly_one_hamiltonian": True,
+ "exactly_one_initial_state": True,
+ "all_dimensions_compatible": compatible_dims,
+ "numeric_data_only": True,
+ "collapse_rates_nonnegative": True,
+ },
+ "objects": summaries,
+ "valid": valid,
+ "interpretation": (
+ "Structural/numerical preflight only; physical assumptions and "
+ "approximation validity require independent review."
+ ),
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Validate a bounded strict-JSON QuTiP model containing one "
+ "Hamiltonian, one initial state, and optional collapse/observable objects."
+ )
+ )
+ parser.add_argument("model", help="local strict-JSON model path")
+ add_output_arguments(parser)
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ document = load_json_object(args.model)
+ report = validate_model(document)
+ emit_json(report, output=args.output, force=args.force)
+ return 0 if report["valid"] else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/qutip/scripts/result_audit.py b/skills/qutip/scripts/result_audit.py
new file mode 100644
index 00000000..ec0f6189
--- /dev/null
+++ b/skills/qutip/scripts/result_audit.py
@@ -0,0 +1,395 @@
+#!/usr/bin/env python3
+"""Audit portable QuTiP skill JSON without loading Python objects."""
+
+from __future__ import annotations
+
+import argparse
+import math
+from collections.abc import Mapping
+from typing import Any
+
+from _common import (
+ MAX_SWEEP_RUNS,
+ MAX_TIME_POINTS,
+ QUTIP_VERSION,
+ CliError,
+ add_output_arguments,
+ emit_json,
+ finite_float,
+ load_json_object,
+ run_cli,
+)
+
+
+def _check(
+ checks: list[dict[str, Any]],
+ *,
+ name: str,
+ passed: bool,
+ detail: str,
+ severity: str = "error",
+) -> None:
+ checks.append(
+ {
+ "name": name,
+ "passed": bool(passed),
+ "severity": severity,
+ "detail": detail,
+ }
+ )
+
+
+def _finite_sequence(
+ value: Any,
+ *,
+ name: str,
+ maximum: int,
+) -> list[float]:
+ if not isinstance(value, list) or not 2 <= len(value) <= maximum:
+ raise CliError(f"{name} must contain from 2 through {maximum} values")
+ result: list[float] = []
+ for index, item in enumerate(value):
+ number = finite_float(item, name=f"{name}[{index}]")
+ result.append(number)
+ return result
+
+
+def _audit_simulation(
+ document: Mapping[str, Any],
+ *,
+ tolerance: float,
+) -> list[dict[str, Any]]:
+ checks: list[dict[str, Any]] = []
+ required = {
+ "qutip_version",
+ "configuration",
+ "model",
+ "times",
+ "expectations",
+ "analytic_reference",
+ "trajectory_statistics",
+ "checks",
+ "solver",
+ }
+ missing = sorted(required - set(document))
+ _check(
+ checks,
+ name="required_fields",
+ passed=not missing,
+ detail="all required fields present" if not missing else f"missing: {missing}",
+ )
+ if missing:
+ return checks
+
+ _check(
+ checks,
+ name="exact_qutip_version",
+ passed=document["qutip_version"] == QUTIP_VERSION,
+ detail=f"reported {document['qutip_version']!r}; expected {QUTIP_VERSION}",
+ )
+
+ try:
+ times = _finite_sequence(
+ document["times"],
+ name="times",
+ maximum=MAX_TIME_POINTS,
+ )
+ increasing = all(right > left for left, right in zip(times, times[1:]))
+ except CliError as exc:
+ times = []
+ increasing = False
+ time_detail = str(exc)
+ else:
+ time_detail = f"{len(times)} finite values"
+ _check(
+ checks,
+ name="bounded_monotonic_time_grid",
+ passed=bool(times) and increasing,
+ detail=time_detail if not times or increasing else "times are not increasing",
+ )
+
+ expectations = document["expectations"]
+ if not isinstance(expectations, Mapping) or "excited_population" not in expectations:
+ populations: list[float] = []
+ population_detail = "expectations.excited_population is missing"
+ else:
+ try:
+ populations = _finite_sequence(
+ expectations["excited_population"],
+ name="expectations.excited_population",
+ maximum=MAX_TIME_POINTS,
+ )
+ except CliError as exc:
+ populations = []
+ population_detail = str(exc)
+ else:
+ population_detail = f"{len(populations)} finite values"
+ lengths_match = bool(times) and bool(populations) and len(times) == len(populations)
+ _check(
+ checks,
+ name="population_length",
+ passed=lengths_match,
+ detail=population_detail,
+ )
+ if populations:
+ violation = max(
+ max(0.0, -min(populations)),
+ max(0.0, max(populations) - 1.0),
+ )
+ else:
+ violation = math.inf
+ _check(
+ checks,
+ name="population_bounds",
+ passed=violation <= tolerance,
+ detail=f"maximum [0,1] violation is {violation}",
+ )
+
+ analytic = document["analytic_reference"]
+ analytic_ok = True
+ analytic_detail = "not applicable"
+ if isinstance(analytic, Mapping) and analytic.get("applicable"):
+ try:
+ reference = _finite_sequence(
+ analytic["excited_population"],
+ name="analytic_reference.excited_population",
+ maximum=MAX_TIME_POINTS,
+ )
+ reported_error = finite_float(
+ analytic["max_abs_error"],
+ name="analytic_reference.max_abs_error",
+ minimum=0.0,
+ )
+ recomputed = max(
+ abs(observed - expected)
+ for observed, expected in zip(populations, reference)
+ )
+ analytic_ok = (
+ len(reference) == len(populations)
+ and abs(recomputed - reported_error)
+ <= max(1.0e-12, 10.0 * tolerance)
+ )
+ analytic_detail = (
+ f"reported error {reported_error}; recomputed {recomputed}"
+ )
+ except (CliError, KeyError, ValueError) as exc:
+ analytic_ok = False
+ analytic_detail = str(exc)
+ _check(
+ checks,
+ name="analytic_reference_consistency",
+ passed=analytic_ok,
+ detail=analytic_detail,
+ )
+
+ model = document["model"]
+ assumptions = model.get("assumptions") if isinstance(model, Mapping) else None
+ _check(
+ checks,
+ name="physical_assumptions_recorded",
+ passed=isinstance(assumptions, list) and len(assumptions) >= 3,
+ detail="model assumptions are present" if assumptions else "assumptions missing",
+ severity="warning",
+ )
+
+ solver = document["solver"]
+ stats = solver.get("stats") if isinstance(solver, Mapping) else None
+ _check(
+ checks,
+ name="solver_stats_recorded",
+ passed=isinstance(stats, Mapping) and bool(stats),
+ detail="solver stats present" if stats else "solver stats missing or empty",
+ severity="warning",
+ )
+
+ configuration = document["configuration"]
+ solver_name = (
+ configuration.get("solver") if isinstance(configuration, Mapping) else None
+ )
+ trajectory = document["trajectory_statistics"]
+ if solver_name == "mcsolve":
+ count = trajectory.get("trajectories_run") if isinstance(trajectory, Mapping) else None
+ seeds = trajectory.get("seeds") if isinstance(trajectory, Mapping) else None
+ trajectory_ok = (
+ isinstance(count, int)
+ and count > 0
+ and isinstance(seeds, list)
+ and len(seeds) == count
+ )
+ trajectory_detail = (
+ f"trajectories_run={count}, seed_records="
+ f"{len(seeds) if isinstance(seeds, list) else 'missing'}"
+ )
+ else:
+ trajectory_ok = True
+ trajectory_detail = "deterministic solver"
+ _check(
+ checks,
+ name="trajectory_seed_manifest",
+ passed=trajectory_ok,
+ detail=trajectory_detail,
+ )
+ return checks
+
+
+def _audit_convergence(
+ document: Mapping[str, Any],
+ *,
+ tolerance: float,
+) -> list[dict[str, Any]]:
+ checks: list[dict[str, Any]] = []
+ runs = document.get("runs")
+ comparisons = document.get("comparisons")
+ _check(
+ checks,
+ name="bounded_run_count",
+ passed=isinstance(runs, list) and 2 <= len(runs) <= MAX_SWEEP_RUNS,
+ detail=(
+ f"run count {len(runs)}"
+ if isinstance(runs, list)
+ else "runs is not an array"
+ ),
+ )
+ _check(
+ checks,
+ name="comparisons_present",
+ passed=isinstance(comparisons, list) and bool(comparisons),
+ detail=(
+ f"comparison count {len(comparisons)}"
+ if isinstance(comparisons, list)
+ else "comparisons is not an array"
+ ),
+ )
+ _check(
+ checks,
+ name="exact_qutip_version",
+ passed=document.get("qutip_version") == QUTIP_VERSION,
+ detail=f"reported {document.get('qutip_version')!r}",
+ )
+ finite = True
+ maximum_difference = 0.0
+ if isinstance(comparisons, list):
+ for index, comparison in enumerate(comparisons):
+ if not isinstance(comparison, Mapping):
+ finite = False
+ continue
+ candidates = [
+ value
+ for key, value in comparison.items()
+ if "difference" in key and isinstance(value, (int, float))
+ ]
+ for value in candidates:
+ try:
+ number = finite_float(
+ value,
+ name=f"comparisons[{index}] difference",
+ minimum=0.0,
+ )
+ except CliError:
+ finite = False
+ else:
+ maximum_difference = max(maximum_difference, number)
+ _check(
+ checks,
+ name="finite_convergence_differences",
+ passed=finite,
+ detail=f"largest recorded absolute difference is {maximum_difference}",
+ )
+ design = document.get("design")
+ varied = design.get("varied") if isinstance(design, Mapping) else None
+ _check(
+ checks,
+ name="sweep_design_recorded",
+ passed=isinstance(varied, list) and bool(varied),
+ detail=f"varied controls: {varied!r}",
+ severity="warning",
+ )
+ _check(
+ checks,
+ name="requested_tolerance_recorded",
+ passed=isinstance(document.get("acceptance"), (int, float))
+ and abs(float(document["acceptance"]) - tolerance) >= 0.0,
+ detail=f"report acceptance: {document.get('acceptance')!r}",
+ severity="warning",
+ )
+ return checks
+
+
+def audit_document(
+ document: Mapping[str, Any],
+ *,
+ tolerance: float,
+) -> dict[str, Any]:
+ """Audit one recognized portable report."""
+
+ report_type = document.get("report_type")
+ if report_type == "qutip.two_level_simulation":
+ checks = _audit_simulation(document, tolerance=tolerance)
+ elif report_type == "qutip.convergence_sweep":
+ checks = _audit_convergence(document, tolerance=tolerance)
+ else:
+ raise CliError(
+ "unsupported report_type; expected qutip.two_level_simulation "
+ "or qutip.convergence_sweep"
+ )
+
+ failed = [
+ check
+ for check in checks
+ if not check["passed"] and check["severity"] == "error"
+ ]
+ warnings = [
+ check
+ for check in checks
+ if not check["passed"] and check["severity"] == "warning"
+ ]
+ status = "fail" if failed else ("pass_with_warnings" if warnings else "pass")
+ return {
+ "report_type": "qutip.result_audit",
+ "schema_version": 1,
+ "audited_report_type": report_type,
+ "tolerance": tolerance,
+ "status": status,
+ "checks": checks,
+ "summary": {
+ "passed": sum(check["passed"] for check in checks),
+ "errors": len(failed),
+ "warnings": len(warnings),
+ },
+ "safety": {
+ "input_format": "strict JSON",
+ "python_object_deserialization": False,
+ "network": False,
+ },
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Audit bounded QuTiP skill JSON without importing QuTiP or "
+ "deserializing Python objects."
+ )
+ )
+ parser.add_argument("report", help="local strict-JSON report path")
+ parser.add_argument("--tolerance", type=float, default=1.0e-6)
+ add_output_arguments(parser)
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ tolerance = finite_float(
+ args.tolerance,
+ name="tolerance",
+ minimum=1.0e-12,
+ maximum=0.1,
+ )
+ document = load_json_object(args.report)
+ report = audit_document(document, tolerance=tolerance)
+ emit_json(report, output=args.output, force=args.force)
+ return 0 if report["status"] != "fail" else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/qutip/scripts/solver_config_planner.py b/skills/qutip/scripts/solver_config_planner.py
new file mode 100644
index 00000000..1374d49e
--- /dev/null
+++ b/skills/qutip/scripts/solver_config_planner.py
@@ -0,0 +1,297 @@
+#!/usr/bin/env python3
+"""Create a bounded QuTiP 5 solver and validation plan without simulation."""
+
+from __future__ import annotations
+
+import argparse
+from typing import Any
+
+from _common import (
+ DEFAULT_SEED,
+ MAX_TIME,
+ MAX_TIME_POINTS,
+ MAX_TRAJECTORIES,
+ QUTIP_VERSION,
+ CliError,
+ add_output_arguments,
+ bounded_int,
+ emit_json,
+ finite_float,
+ run_cli,
+)
+
+
+MODELS = (
+ "closed",
+ "lindblad",
+ "quantum-jump",
+ "bloch-redfield",
+ "diffusive",
+ "periodic-closed",
+ "periodic-open",
+ "heom",
+ "piqs",
+)
+
+
+def create_plan(args: argparse.Namespace) -> dict[str, Any]:
+ """Select a current solver and produce a model-specific checklist."""
+
+ t_final = finite_float(
+ args.t_final,
+ name="t_final",
+ minimum=0.0,
+ maximum=MAX_TIME,
+ minimum_inclusive=False,
+ )
+ time_points = bounded_int(
+ args.time_points,
+ name="time_points",
+ minimum=2,
+ maximum=MAX_TIME_POINTS,
+ )
+ trajectories = bounded_int(
+ args.trajectories,
+ name="trajectories",
+ minimum=1,
+ maximum=MAX_TRAJECTORIES,
+ )
+ seed = bounded_int(args.seed, name="seed", minimum=0, maximum=2**63 - 1)
+ collapse_channels = bounded_int(
+ args.collapse_channels,
+ name="collapse_channels",
+ minimum=0,
+ maximum=64,
+ )
+ period = None
+ if args.period is not None:
+ period = finite_float(
+ args.period,
+ name="period",
+ minimum=0.0,
+ maximum=MAX_TIME,
+ minimum_inclusive=False,
+ )
+
+ method = "bdf" if args.stiff else "adams"
+ options: dict[str, Any] = {
+ "method": method,
+ "atol": 1.0e-10,
+ "rtol": 1.0e-8,
+ "store_states": bool(args.store_states),
+ "store_final_state": True,
+ "progress_bar": "",
+ }
+ required_inputs = [
+ "unit convention and hbar convention",
+ "ordered subsystem dimensions",
+ "initial-state norm/trace/positivity audit",
+ "Hamiltonian Hermiticity audit",
+ "time-grid scale justification",
+ ]
+ convergence = [
+ "tighten atol and rtol",
+ "compare at least one alternative integrator",
+ "increase output-grid density",
+ "sweep every Hilbert-space truncation",
+ ]
+ warnings: list[str] = []
+ call_arguments: dict[str, Any] = {
+ "tlist": {"start": 0.0, "stop": t_final, "points": time_points},
+ "options": options,
+ }
+
+ if args.model == "closed":
+ solver = "sesolve"
+ required_inputs.append("evidence that no dissipative channel is modeled")
+ if args.initial_state != "ket":
+ warnings.append(
+ "sesolve requires a ket; use mesolve for a density-matrix initial state"
+ )
+ if collapse_channels:
+ warnings.append("closed model conflicts with nonzero collapse_channels")
+ elif args.model == "lindblad":
+ solver = "mesolve"
+ required_inputs.extend(
+ [
+ "Markovian Lindblad approximation",
+ "each collapse operator written as sqrt(rate) times its operator",
+ ]
+ )
+ if collapse_channels == 0:
+ warnings.append("no collapse channels supplied; mesolve may defer to sesolve")
+ elif args.model == "quantum-jump":
+ solver = "mcsolve"
+ required_inputs.extend(
+ [
+ "physical meaning of the jump unravelling",
+ "nonzero collapse-operator list",
+ ]
+ )
+ convergence.extend(["increase ntraj", "repeat or pair seeds deliberately"])
+ call_arguments.update({"ntraj": trajectories, "seeds": seed})
+ options["keep_runs_results"] = bool(args.store_states)
+ if collapse_channels == 0:
+ warnings.append("mcsolve requires a nonzero jump channel for this plan")
+ elif args.model == "bloch-redfield":
+ solver = "brmesolve"
+ required_inputs.extend(
+ [
+ "Hermitian bath-coupling operators",
+ "angular-frequency bath spectra including negative-frequency behavior",
+ "Born-Markov and bath-stationarity assumptions",
+ "justified sec_cutoff",
+ ]
+ )
+ convergence.extend(
+ ["vary sec_cutoff", "track minimum density-matrix eigenvalue over time"]
+ )
+ call_arguments["sec_cutoff"] = 0.1
+ if not args.weak_coupling_confirmed:
+ warnings.append("weak-coupling assumption has not been confirmed")
+ elif args.model == "diffusive":
+ solver = "ssesolve" if args.initial_state == "ket" else "smesolve"
+ required_inputs.extend(
+ [
+ "separate monitored sc_ops from unmonitored c_ops",
+ "homodyne versus heterodyne measurement model",
+ "measurement efficiency and record convention",
+ ]
+ )
+ convergence.extend(["decrease stochastic dt", "increase ntraj"])
+ options["dt"] = t_final / max(time_points - 1, 1) / 2.0
+ options["store_measurement"] = False
+ call_arguments.update(
+ {"ntraj": trajectories, "seeds": seed, "heterodyne": False}
+ )
+ elif args.model == "periodic-closed":
+ solver = "FloquetBasis + fsesolve"
+ required_inputs.extend(
+ [
+ "verified H(t + T) equals H(t)",
+ "quasi-energy branch convention",
+ ]
+ )
+ convergence.extend(
+ ["compare one-period propagator with direct evolution", "sweep precompute grid"]
+ )
+ call_arguments["T"] = period
+ if period is None:
+ warnings.append("a positive --period is required")
+ elif args.model == "periodic-open":
+ solver = "FloquetBasis + fmmesolve"
+ required_inputs.extend(
+ [
+ "verified H(t + T) equals H(t)",
+ "paired coupling operators and bath spectrum callbacks",
+ "weak-coupling Floquet-Markov assumptions",
+ "temperature/frequency unit convention",
+ ]
+ )
+ convergence.extend(
+ [
+ "sweep Floquet precompute grid",
+ "compare with direct mesolve in a valid limit",
+ ]
+ )
+ call_arguments["T"] = period
+ if period is None:
+ warnings.append("a positive --period is required")
+ if not args.weak_coupling_confirmed:
+ warnings.append("weak-coupling assumption has not been confirmed")
+ elif args.model == "heom":
+ solver = "qutip.solver.heom.HEOMSolver"
+ required_inputs.extend(
+ [
+ "bath correlation expansion and coupling operator",
+ "temperature, cutoff, and energy units",
+ "factorized or continued ADO initial condition",
+ ]
+ )
+ convergence.extend(
+ [
+ "increase hierarchy max_depth",
+ "increase bath expansion terms",
+ "compare Matsubara and Pade/environment approximations",
+ ]
+ )
+ call_arguments.update({"max_depth": "model-specific", "bath": "required"})
+ else:
+ solver = "qutip.piqs.Dicke.liouvillian + mesolve"
+ required_inputs.extend(
+ [
+ "permutation symmetry of constituents and dynamics",
+ "Dicke versus uncoupled basis",
+ "separate local and collective rates",
+ ]
+ )
+ convergence.extend(
+ ["compare a small-N full-space model", "verify symmetry-sector assumptions"]
+ )
+
+ if args.time_dependent:
+ required_inputs.extend(
+ [
+ "QobjEvo with trusted Pythonic callables or numeric arrays",
+ "coefficient sampling/envelope convergence",
+ ]
+ )
+ if args.stiff:
+ convergence.append("compare bdf with lsoda on representative observables")
+
+ return {
+ "report_type": "qutip.solver_config_plan",
+ "schema_version": 1,
+ "qutip_version": QUTIP_VERSION,
+ "model": args.model,
+ "initial_state": args.initial_state,
+ "recommended_solver": solver,
+ "call_configuration": call_arguments,
+ "required_inputs_and_assumptions": required_inputs,
+ "convergence_plan": convergence,
+ "warnings": warnings,
+ "status": "needs_review" if warnings else "ready_for_model_construction",
+ "safety": {
+ "network": False,
+ "model_code_loaded": False,
+ "planner_only": True,
+ },
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Plan a QuTiP 5 solver configuration and model-specific numerical "
+ "checks without importing QuTiP or running a simulation."
+ )
+ )
+ parser.add_argument("--model", choices=MODELS, required=True)
+ parser.add_argument(
+ "--initial-state",
+ choices=("ket", "density"),
+ default="ket",
+ )
+ parser.add_argument("--collapse-channels", type=int, default=0)
+ parser.add_argument("--time-dependent", action="store_true")
+ parser.add_argument("--stiff", action="store_true")
+ parser.add_argument("--weak-coupling-confirmed", action="store_true")
+ parser.add_argument("--period", type=float)
+ parser.add_argument("--t-final", type=float, default=10.0)
+ parser.add_argument("--time-points", type=int, default=201)
+ parser.add_argument("--trajectories", type=int, default=400)
+ parser.add_argument("--seed", type=int, default=DEFAULT_SEED)
+ parser.add_argument("--store-states", action="store_true")
+ add_output_arguments(parser)
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ report = create_plan(args)
+ emit_json(report, output=args.output, force=args.force)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/qutip/scripts/steady_state_spectrum_planner.py b/skills/qutip/scripts/steady_state_spectrum_planner.py
new file mode 100644
index 00000000..7fb7d8ef
--- /dev/null
+++ b/skills/qutip/scripts/steady_state_spectrum_planner.py
@@ -0,0 +1,245 @@
+#!/usr/bin/env python3
+"""Plan bounded steady-state and spectrum calculations for QuTiP 5."""
+
+from __future__ import annotations
+
+import argparse
+import math
+from typing import Any
+
+from _common import (
+ MAX_ABS_FREQUENCY,
+ MAX_FREQUENCY_POINTS,
+ MAX_HILBERT_DIMENSION,
+ MAX_TIME,
+ QUTIP_VERSION,
+ CliError,
+ add_output_arguments,
+ bounded_int,
+ emit_json,
+ finite_float,
+ run_cli,
+)
+
+
+STEADY_METHODS = ("direct", "eigen", "svd", "power", "propagator")
+LINEAR_SOLVERS = (
+ "auto",
+ "solve",
+ "lstsq",
+ "spsolve",
+ "gmres",
+ "lgmres",
+ "bicgstab",
+ "splu",
+)
+
+
+def create_plan(args: argparse.Namespace) -> dict[str, Any]:
+ """Return a current API plan plus numerical acceptance checks."""
+
+ dimension = bounded_int(
+ args.dimension,
+ name="dimension",
+ minimum=2,
+ maximum=MAX_HILBERT_DIMENSION,
+ )
+ frequency_points = bounded_int(
+ args.frequency_points,
+ name="frequency_points",
+ minimum=2,
+ maximum=MAX_FREQUENCY_POINTS,
+ )
+ tau_points = bounded_int(
+ args.tau_points,
+ name="tau_points",
+ minimum=2,
+ maximum=MAX_FREQUENCY_POINTS,
+ )
+ frequency_min = finite_float(
+ args.frequency_min,
+ name="frequency_min",
+ minimum=-MAX_ABS_FREQUENCY,
+ maximum=MAX_ABS_FREQUENCY,
+ )
+ frequency_max = finite_float(
+ args.frequency_max,
+ name="frequency_max",
+ minimum=-MAX_ABS_FREQUENCY,
+ maximum=MAX_ABS_FREQUENCY,
+ )
+ if frequency_max <= frequency_min:
+ raise CliError("frequency_max must be greater than frequency_min")
+ tau_max = finite_float(
+ args.tau_max,
+ name="tau_max",
+ minimum=0.0,
+ maximum=MAX_TIME,
+ minimum_inclusive=False,
+ )
+ residual_tolerance = finite_float(
+ args.residual_tolerance,
+ name="residual_tolerance",
+ minimum=1.0e-14,
+ maximum=1.0e-3,
+ )
+ positivity_tolerance = finite_float(
+ args.positivity_tolerance,
+ name="positivity_tolerance",
+ minimum=1.0e-14,
+ maximum=1.0e-3,
+ )
+
+ warnings: list[str] = []
+ blockers: list[str] = []
+ steady_kwargs: dict[str, Any] = {"method": args.steady_method}
+ if args.linear_solver != "auto":
+ steady_kwargs["solver"] = args.linear_solver
+ if args.steady_method == "svd" and dimension > 16:
+ warnings.append("svd is dense and may be expensive beyond small systems")
+ if args.degenerate_possible:
+ warnings.append(
+ "a small residual does not choose a unique state from a degenerate nullspace"
+ )
+ if args.time_dependent:
+ blockers.append(
+ "static steadystate/spectrum is not generally valid for a time-dependent "
+ "Hamiltonian; use a periodic/Floquet or explicit long-time analysis"
+ )
+ if not args.stationary_confirmed:
+ blockers.append("stationarity has not been confirmed for spectral analysis")
+
+ dt = tau_max / (tau_points - 1)
+ nyquist = math.pi / dt
+ angular_resolution = 2.0 * math.pi / (tau_points * dt)
+ requested_abs_frequency = max(abs(frequency_min), abs(frequency_max))
+ if requested_abs_frequency > nyquist:
+ warnings.append(
+ "requested frequency range exceeds the FFT Nyquist angular frequency"
+ )
+
+ direct_plan = {
+ "api": "qutip.spectrum",
+ "signature": "spectrum(H, wlist, c_ops, a_op, b_op, solver='es')",
+ "solver_strategy": args.direct_solver,
+ "frequency_grid": {
+ "minimum": frequency_min,
+ "maximum": frequency_max,
+ "points": frequency_points,
+ "units": "angular frequency",
+ },
+ "checks": [
+ "steady-state uniqueness or nullspace structure",
+ "operator order and adjoints",
+ "positive/negative-frequency convention",
+ "compare es, pi, or solve strategy near singular features",
+ "expand frequency range and refine spacing",
+ ],
+ }
+ fft_plan = {
+ "apis": [
+ "qutip.correlation_2op_1t",
+ "qutip.spectrum_correlation_fft",
+ ],
+ "tau_grid": {
+ "start": 0.0,
+ "stop": tau_max,
+ "points": tau_points,
+ "step": dt,
+ },
+ "derived_angular_frequency_limits": {
+ "nyquist": nyquist,
+ "approximate_bin_spacing": angular_resolution,
+ },
+ "checks": [
+ "uniform strictly increasing tau grid",
+ "correlation tail decayed before tau_max",
+ "double tau_max to test resolution",
+ "halve dt to test aliasing",
+ "compare window choices and disclose them",
+ "verify transform sign/normalization on an analytic signal",
+ ],
+ }
+
+ selected: list[dict[str, Any]] = []
+ if args.spectrum_mode in {"direct", "both"}:
+ selected.append(direct_plan)
+ if args.spectrum_mode in {"fft", "both"}:
+ selected.append(fft_plan)
+
+ return {
+ "report_type": "qutip.steady_state_spectrum_plan",
+ "schema_version": 1,
+ "qutip_version": QUTIP_VERSION,
+ "model_size": {
+ "hilbert_dimension": dimension,
+ "liouvillian_shape": [dimension * dimension, dimension * dimension],
+ },
+ "steady_state": {
+ "api": "qutip.steadystate",
+ "kwargs": steady_kwargs,
+ "checks": {
+ "liouvillian_residual_norm_at_most": residual_tolerance,
+ "trace_error_at_most": residual_tolerance,
+ "minimum_eigenvalue_at_least": -positivity_tolerance,
+ "hermitian": True,
+ "compare_multiple_initial_states": bool(args.degenerate_possible),
+ },
+ },
+ "spectrum_mode": args.spectrum_mode,
+ "spectrum_plans": selected,
+ "warnings": warnings,
+ "blockers": blockers,
+ "status": "blocked_pending_model_evidence" if blockers else "ready_to_implement",
+ "safety": {
+ "planner_only": True,
+ "network": False,
+ "model_code_loaded": False,
+ "bounded_grids": True,
+ },
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Plan bounded QuTiP steady-state and direct/FFT spectrum checks "
+ "without importing QuTiP or running a model."
+ )
+ )
+ parser.add_argument("--dimension", type=int, default=2)
+ parser.add_argument("--steady-method", choices=STEADY_METHODS, default="direct")
+ parser.add_argument("--linear-solver", choices=LINEAR_SOLVERS, default="auto")
+ parser.add_argument(
+ "--spectrum-mode",
+ choices=("direct", "fft", "both"),
+ default="both",
+ )
+ parser.add_argument(
+ "--direct-solver",
+ choices=("es", "pi", "solve"),
+ default="es",
+ )
+ parser.add_argument("--frequency-min", type=float, default=-5.0)
+ parser.add_argument("--frequency-max", type=float, default=5.0)
+ parser.add_argument("--frequency-points", type=int, default=1001)
+ parser.add_argument("--tau-max", type=float, default=50.0)
+ parser.add_argument("--tau-points", type=int, default=2001)
+ parser.add_argument("--residual-tolerance", type=float, default=1.0e-9)
+ parser.add_argument("--positivity-tolerance", type=float, default=1.0e-9)
+ parser.add_argument("--stationary-confirmed", action="store_true")
+ parser.add_argument("--time-dependent", action="store_true")
+ parser.add_argument("--degenerate-possible", action="store_true")
+ add_output_arguments(parser)
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ report = create_plan(args)
+ emit_json(report, output=args.output, force=args.force)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/qutip/scripts/two_level_simulation.py b/skills/qutip/scripts/two_level_simulation.py
new file mode 100644
index 00000000..da003e1a
--- /dev/null
+++ b/skills/qutip/scripts/two_level_simulation.py
@@ -0,0 +1,394 @@
+#!/usr/bin/env python3
+"""Run a bounded synthetic two-level open-system simulation."""
+
+from __future__ import annotations
+
+import argparse
+import math
+from dataclasses import asdict, dataclass
+from typing import Any
+
+from _common import (
+ DEFAULT_SEED,
+ MAX_ABS_FREQUENCY,
+ MAX_RATE,
+ MAX_TIME,
+ MAX_TIME_POINTS,
+ MAX_TRAJECTORIES,
+ QUTIP_VERSION,
+ CliError,
+ add_output_arguments,
+ bounded_int,
+ emit_json,
+ finite_float,
+ load_qutip,
+ run_cli,
+ to_jsonable,
+)
+
+
+METHODS = {"adams", "bdf", "lsoda", "dop853", "vern7", "vern9"}
+INITIAL_STATES = {"excited", "ground", "plus"}
+
+
+@dataclass(frozen=True)
+class SimulationConfig:
+ solver: str
+ initial_state: str
+ omega: float
+ drive: float
+ decay_rate: float
+ dephasing_rate: float
+ t_final: float
+ time_points: int
+ trajectories: int
+ seed: int
+ method: str
+ atol: float
+ rtol: float
+
+ @classmethod
+ def from_namespace(cls, args: argparse.Namespace) -> "SimulationConfig":
+ solver = str(args.solver)
+ if solver not in {"mesolve", "mcsolve"}:
+ raise CliError("solver must be mesolve or mcsolve")
+ initial_state = str(args.initial_state)
+ if initial_state not in INITIAL_STATES:
+ raise CliError(
+ f"initial_state must be one of: {', '.join(sorted(INITIAL_STATES))}"
+ )
+ method = str(args.method)
+ if method not in METHODS:
+ raise CliError(f"method must be one of: {', '.join(sorted(METHODS))}")
+ config = cls(
+ solver=solver,
+ initial_state=initial_state,
+ omega=finite_float(
+ args.omega,
+ name="omega",
+ minimum=-MAX_ABS_FREQUENCY,
+ maximum=MAX_ABS_FREQUENCY,
+ ),
+ drive=finite_float(
+ args.drive,
+ name="drive",
+ minimum=-MAX_ABS_FREQUENCY,
+ maximum=MAX_ABS_FREQUENCY,
+ ),
+ decay_rate=finite_float(
+ args.decay_rate,
+ name="decay_rate",
+ minimum=0.0,
+ maximum=MAX_RATE,
+ ),
+ dephasing_rate=finite_float(
+ args.dephasing_rate,
+ name="dephasing_rate",
+ minimum=0.0,
+ maximum=MAX_RATE,
+ ),
+ t_final=finite_float(
+ args.t_final,
+ name="t_final",
+ minimum=0.0,
+ maximum=MAX_TIME,
+ minimum_inclusive=False,
+ ),
+ time_points=bounded_int(
+ args.time_points,
+ name="time_points",
+ minimum=2,
+ maximum=MAX_TIME_POINTS,
+ ),
+ trajectories=bounded_int(
+ args.trajectories,
+ name="trajectories",
+ minimum=1,
+ maximum=MAX_TRAJECTORIES,
+ ),
+ seed=bounded_int(
+ args.seed,
+ name="seed",
+ minimum=0,
+ maximum=2**63 - 1,
+ ),
+ method=method,
+ atol=finite_float(
+ args.atol,
+ name="atol",
+ minimum=1.0e-14,
+ maximum=1.0e-2,
+ ),
+ rtol=finite_float(
+ args.rtol,
+ name="rtol",
+ minimum=1.0e-14,
+ maximum=1.0e-2,
+ ),
+ )
+ if config.atol > config.rtol:
+ raise CliError("atol must be no greater than rtol")
+ if (
+ config.solver == "mcsolve"
+ and config.decay_rate == 0.0
+ and config.dephasing_rate == 0.0
+ ):
+ raise CliError("mcsolve requires at least one nonzero collapse rate")
+ return config
+
+
+def _initial_state(qutip: Any, label: str) -> Any:
+ excited = qutip.basis(2, 0)
+ ground = qutip.basis(2, 1)
+ if label == "excited":
+ return excited
+ if label == "ground":
+ return ground
+ return (excited + ground).unit()
+
+
+def _state_audit(state: Any, tolerance: float) -> dict[str, Any]:
+ if state is None:
+ return {"available": False}
+ if state.isket:
+ norm = float(state.norm())
+ return {
+ "available": True,
+ "representation": "ket",
+ "norm": norm,
+ "normalization_error": abs(norm - 1.0),
+ "valid_within_tolerance": abs(norm - 1.0) <= tolerance,
+ }
+ trace = complex(state.tr())
+ hermitian = bool(state.isherm)
+ minimum_eigenvalue = (
+ min(float(value) for value in state.eigenenergies())
+ if hermitian
+ else None
+ )
+ valid = (
+ hermitian
+ and abs(trace - 1.0) <= tolerance
+ and minimum_eigenvalue is not None
+ and minimum_eigenvalue >= -tolerance
+ )
+ return {
+ "available": True,
+ "representation": "density_matrix",
+ "is_hermitian": hermitian,
+ "trace": trace,
+ "trace_error": abs(trace - 1.0),
+ "minimum_eigenvalue": minimum_eigenvalue,
+ "valid_within_tolerance": valid,
+ }
+
+
+def _seed_manifest(seeds: Any) -> list[Any] | None:
+ if seeds is None:
+ return None
+ manifest: list[Any] = []
+ for seed in seeds:
+ if isinstance(seed, int):
+ manifest.append(seed)
+ continue
+ manifest.append(
+ {
+ "entropy": to_jsonable(getattr(seed, "entropy", None)),
+ "spawn_key": list(getattr(seed, "spawn_key", ())),
+ }
+ )
+ return manifest
+
+
+def run_simulation(
+ config: SimulationConfig,
+ qutip_module: Any | None = None,
+) -> dict[str, Any]:
+ """Execute one bounded model and return a strict-JSON-ready report."""
+
+ qutip = qutip_module or load_qutip()
+ import numpy as np
+
+ times = np.linspace(0.0, config.t_final, config.time_points)
+ excited = qutip.basis(2, 0)
+ psi0 = _initial_state(qutip, config.initial_state)
+ H = 0.5 * config.omega * qutip.sigmaz() + 0.5 * config.drive * qutip.sigmax()
+ c_ops = []
+ if config.decay_rate > 0.0:
+ c_ops.append(np.sqrt(config.decay_rate) * qutip.sigmam())
+ if config.dephasing_rate > 0.0:
+ c_ops.append(
+ np.sqrt(config.dephasing_rate / 2.0) * qutip.sigmaz()
+ )
+ e_ops = [excited.proj(), qutip.sigmax(), qutip.sigmay(), qutip.sigmaz()]
+ options = {
+ "method": config.method,
+ "atol": config.atol,
+ "rtol": config.rtol,
+ "store_final_state": True,
+ "progress_bar": "",
+ }
+
+ if config.solver == "mesolve":
+ result = qutip.mesolve(
+ H,
+ psi0,
+ times,
+ c_ops=c_ops,
+ e_ops=e_ops,
+ options=options,
+ )
+ trajectories_run = None
+ trajectory_std = None
+ standard_error = None
+ seed_manifest = None
+ else:
+ result = qutip.mcsolve(
+ H,
+ psi0,
+ times,
+ c_ops,
+ e_ops=e_ops,
+ ntraj=config.trajectories,
+ seeds=config.seed,
+ options={**options, "keep_runs_results": False},
+ )
+ trajectories_run = int(
+ getattr(result, "num_trajectories", config.trajectories)
+ )
+ trajectory_std = np.asarray(result.std_expect[0], dtype=float)
+ standard_error = trajectory_std / math.sqrt(trajectories_run)
+ seed_manifest = _seed_manifest(getattr(result, "seeds", None))
+
+ population = np.asarray(result.expect[0], dtype=float)
+ sigma_x = np.asarray(result.expect[1], dtype=float)
+ sigma_y = np.asarray(result.expect[2], dtype=float)
+ sigma_z = np.asarray(result.expect[3], dtype=float)
+
+ initial_population = {
+ "excited": 1.0,
+ "ground": 0.0,
+ "plus": 0.5,
+ }[config.initial_state]
+ analytic_applicable = config.drive == 0.0
+ analytic_population = (
+ initial_population * np.exp(-config.decay_rate * times)
+ if analytic_applicable
+ else None
+ )
+ max_abs_analytic_error = (
+ float(np.max(np.abs(population - analytic_population)))
+ if analytic_population is not None
+ else None
+ )
+ lower_violation = max(0.0, float(-np.min(population)))
+ upper_violation = max(0.0, float(np.max(population) - 1.0))
+ probability_violation = max(lower_violation, upper_violation)
+ invariant_tolerance = max(10.0 * config.atol, 10.0 * config.rtol)
+ final_state_audit = _state_audit(
+ getattr(result, "final_state", None),
+ invariant_tolerance,
+ )
+
+ return {
+ "report_type": "qutip.two_level_simulation",
+ "schema_version": 1,
+ "qutip_version": QUTIP_VERSION,
+ "unit_convention": "hbar=1; angular-frequency and reciprocal-time units",
+ "configuration": asdict(config),
+ "model": {
+ "hilbert_dimension": 2,
+ "hamiltonian": "0.5 * omega * sigma_z + 0.5 * drive * sigma_x",
+ "amplitude_decay": "sqrt(decay_rate) * sigma_minus",
+ "pure_dephasing": "sqrt(dephasing_rate / 2) * sigma_z",
+ "initial_population": initial_population,
+ "assumptions": [
+ "finite two-level model",
+ "time-independent Hamiltonian",
+ "Markovian Lindblad channels",
+ "dephasing_rate denotes off-diagonal coherence decay",
+ ],
+ },
+ "times": times,
+ "expectations": {
+ "excited_population": population,
+ "sigma_x": sigma_x,
+ "sigma_y": sigma_y,
+ "sigma_z": sigma_z,
+ },
+ "analytic_reference": {
+ "applicable": analytic_applicable,
+ "excited_population": analytic_population,
+ "max_abs_error": max_abs_analytic_error,
+ "reason_if_not_applicable": (
+ None
+ if analytic_applicable
+ else "nonzero transverse drive changes the population equation"
+ ),
+ },
+ "trajectory_statistics": {
+ "trajectories_requested": (
+ config.trajectories if config.solver == "mcsolve" else None
+ ),
+ "trajectories_run": trajectories_run,
+ "seeds": seed_manifest,
+ "excited_population_std": trajectory_std,
+ "excited_population_standard_error_estimate": standard_error,
+ },
+ "checks": {
+ "time_grid_strictly_increasing": True,
+ "maximum_population_bound_violation": probability_violation,
+ "population_within_tolerance": probability_violation
+ <= invariant_tolerance,
+ "final_state": final_state_audit,
+ },
+ "solver": {
+ "name": getattr(result, "solver", config.solver),
+ "options_requested": options,
+ "stats": getattr(result, "stats", {}),
+ },
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Run a bounded two-level Lindblad or quantum-jump simulation and "
+ "emit strict JSON with analytic and physical checks."
+ )
+ )
+ parser.add_argument("--solver", choices=("mesolve", "mcsolve"), default="mesolve")
+ parser.add_argument(
+ "--initial-state",
+ choices=tuple(sorted(INITIAL_STATES)),
+ default="excited",
+ )
+ parser.add_argument("--omega", type=float, default=1.0)
+ parser.add_argument("--drive", type=float, default=0.0)
+ parser.add_argument("--decay-rate", type=float, default=0.2)
+ parser.add_argument("--dephasing-rate", type=float, default=0.0)
+ parser.add_argument("--t-final", type=float, default=10.0)
+ parser.add_argument("--time-points", type=int, default=201)
+ parser.add_argument("--trajectories", type=int, default=400)
+ parser.add_argument("--seed", type=int, default=DEFAULT_SEED)
+ parser.add_argument("--method", choices=tuple(sorted(METHODS)), default="adams")
+ parser.add_argument("--atol", type=float, default=1.0e-10)
+ parser.add_argument("--rtol", type=float, default=1.0e-8)
+ add_output_arguments(parser)
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ config = SimulationConfig.from_namespace(args)
+ report = run_simulation(config)
+ emit_json(report, output=args.output, force=args.force)
+ checks = report["checks"]
+ return 0 if (
+ checks["population_within_tolerance"]
+ and checks["final_state"].get("valid_within_tolerance", False)
+ ) else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/qutip/tests/test_qutip_graphics.py b/skills/qutip/tests/test_qutip_graphics.py
new file mode 100644
index 00000000..a7a5f507
--- /dev/null
+++ b/skills/qutip/tests/test_qutip_graphics.py
@@ -0,0 +1,64 @@
+"""Pinned plotting smoke tests for the QuTiP 5.3 graphics extra."""
+
+from __future__ import annotations
+
+import unittest
+
+import matplotlib
+
+matplotlib.use("Agg")
+
+import matplotlib.pyplot as plt # noqa: E402
+import numpy as np # noqa: E402
+import qutip # noqa: E402
+
+
+class GraphicsApiTests(unittest.TestCase):
+ def tearDown(self) -> None:
+ plt.close("all")
+
+ def test_phase_space_and_matrix_plotting_apis(self) -> None:
+ self.assertEqual(qutip.__version__, "5.3.0")
+ state = qutip.fock_dm(6, 1)
+ coordinates = np.linspace(-2.0, 2.0, 15)
+
+ fig, ax = qutip.plot_wigner(
+ state,
+ xvec=coordinates,
+ yvec=coordinates,
+ projection="2d",
+ colorbar=True,
+ )
+ self.assertIsNotNone(fig)
+ self.assertIsNotNone(ax)
+
+ fig, ax = qutip.plot_fock_distribution(state)
+ self.assertIsNotNone(fig)
+ self.assertIsNotNone(ax)
+
+ fig, ax = qutip.hinton(state, color_style="phase")
+ self.assertIsNotNone(fig)
+ self.assertIsNotNone(ax)
+
+ fig, ax = qutip.matrix_histogram(
+ state,
+ bar_style="abs",
+ color_style="phase",
+ )
+ self.assertIsNotNone(fig)
+ self.assertIsNotNone(ax)
+
+ def test_result_plot_expect_current_method(self) -> None:
+ result = qutip.sesolve(
+ 0.5 * qutip.sigmax(),
+ qutip.basis(2, 0),
+ np.linspace(0.0, 1.0, 11),
+ e_ops=[qutip.sigmaz()],
+ )
+ fig, axes = result.plot_expect(labels=["sigma_z"])
+ self.assertIsNotNone(fig)
+ self.assertTrue(np.asarray(axes, dtype=object).size >= 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/skills/qutip/tests/test_qutip_synthetic.py b/skills/qutip/tests/test_qutip_synthetic.py
new file mode 100644
index 00000000..48fabaee
--- /dev/null
+++ b/skills/qutip/tests/test_qutip_synthetic.py
@@ -0,0 +1,322 @@
+"""Pinned, network-free synthetic physics tests for QuTiP 5.3.0."""
+
+from __future__ import annotations
+
+import inspect
+import json
+import math
+import sys
+import unittest
+from pathlib import Path
+
+import numpy as np
+import qutip
+
+
+SKILL_ROOT = Path(__file__).resolve().parents[1]
+SCRIPTS = SKILL_ROOT / "scripts"
+sys.path.insert(0, str(SCRIPTS))
+
+import _common # noqa: E402
+import convergence_sweep # noqa: E402
+import qobj_model_validator # noqa: E402
+import result_audit # noqa: E402
+import two_level_simulation # noqa: E402
+
+
+class VersionAndApiTests(unittest.TestCase):
+ def test_exact_version_and_current_solver_boundaries(self) -> None:
+ self.assertEqual(qutip.__version__, "5.3.0")
+ self.assertFalse(hasattr(qutip, "Options"))
+
+ sesolve_parameters = inspect.signature(qutip.sesolve).parameters
+ self.assertEqual(
+ sesolve_parameters["e_ops"].kind,
+ inspect.Parameter.KEYWORD_ONLY,
+ )
+ mc_parameters = inspect.signature(qutip.mcsolve).parameters
+ self.assertIn("seeds", mc_parameters)
+ self.assertIn("target_tol", mc_parameters)
+ stochastic_parameters = inspect.signature(qutip.smesolve).parameters
+ self.assertIn("heterodyne", stochastic_parameters)
+ self.assertNotIn("noise", stochastic_parameters)
+
+ def test_qobj_dims_tensor_order_and_qobjevo(self) -> None:
+ state = qutip.tensor(qutip.basis(2, 0), qutip.basis(3, 1))
+ self.assertEqual(state.dims, [[2, 3], [1]])
+ self.assertEqual(state.proj().ptrace(0).dims, [[2], [2]])
+ self.assertEqual(state.proj().ptrace(1).dims, [[3], [3]])
+
+ def coefficient(t, amplitude):
+ return amplitude * math.cos(t)
+
+ H = qutip.QobjEvo(
+ [qutip.sigmaz(), [qutip.sigmax(), coefficient]],
+ args={"amplitude": 0.25},
+ )
+ self.assertTrue(H(0.0).isherm)
+ before = complex(H(0.0)[0, 1])
+ H.arguments(amplitude=0.5)
+ after = complex(H(0.0)[0, 1])
+ self.assertAlmostEqual(after.real, 2.0 * before.real)
+
+ def test_qfunc_is_called_with_state_and_axis_order_is_y_x(self) -> None:
+ xvec = np.linspace(-2.0, 2.0, 7)
+ yvec = np.linspace(-1.0, 1.0, 5)
+ calculator = qutip.QFunc(xvec, yvec, memory=16)
+ self.assertTrue(callable(calculator))
+ self.assertFalse(hasattr(calculator, "eval"))
+ values = calculator(qutip.fock_dm(6, 0))
+ self.assertEqual(values.shape, (len(yvec), len(xvec)))
+ direct = qutip.qfunc(qutip.fock_dm(6, 0), xvec, yvec)
+ np.testing.assert_allclose(values, direct, atol=1.0e-13, rtol=1.0e-13)
+
+
+class BundledModelTests(unittest.TestCase):
+ def test_qobj_model_validator_accepts_physical_two_level_model(self) -> None:
+ document = {
+ "schema_version": 1,
+ "unit_convention": "hbar=1-angular-frequency",
+ "tolerance": 1.0e-10,
+ "objects": [
+ {
+ "name": "H",
+ "role": "hamiltonian",
+ "dims": [2],
+ "data": [[0.5, 0.0], [0.0, -0.5]],
+ },
+ {
+ "name": "psi0",
+ "role": "initial_state",
+ "dims": [2],
+ "data": [1.0, 0.0],
+ },
+ {
+ "name": "loss",
+ "role": "collapse_operator",
+ "dims": [2],
+ "data": [[0.0, 0.0], [1.0, 0.0]],
+ "rate": 0.2,
+ },
+ {
+ "name": "z",
+ "role": "observable",
+ "dims": [2],
+ "data": [[1.0, 0.0], [0.0, -1.0]],
+ },
+ ],
+ }
+ report = qobj_model_validator.validate_model(document, qutip)
+ self.assertTrue(report["valid"])
+ self.assertTrue(report["checks"]["all_dimensions_compatible"])
+ collapse = next(
+ item for item in report["objects"] if item["role"] == "collapse_operator"
+ )
+ self.assertEqual(collapse["scaling"], "sqrt(rate) * operator")
+
+ def test_mesolve_matches_amplitude_decay_and_audits_result(self) -> None:
+ config = two_level_simulation.SimulationConfig(
+ solver="mesolve",
+ initial_state="excited",
+ omega=1.0,
+ drive=0.0,
+ decay_rate=0.2,
+ dephasing_rate=0.05,
+ t_final=8.0,
+ time_points=161,
+ trajectories=1,
+ seed=20_260_723,
+ method="adams",
+ atol=1.0e-11,
+ rtol=1.0e-9,
+ )
+ report = two_level_simulation.run_simulation(config, qutip)
+ self.assertLess(report["analytic_reference"]["max_abs_error"], 2.0e-7)
+ self.assertTrue(report["checks"]["population_within_tolerance"])
+ self.assertTrue(
+ report["checks"]["final_state"]["valid_within_tolerance"]
+ )
+ self.assertTrue(report["solver"]["stats"])
+
+ portable = json.loads(_common.strict_json_bytes(report))
+ audit = result_audit.audit_document(portable, tolerance=1.0e-6)
+ self.assertEqual(audit["status"], "pass")
+
+ def test_mcsolve_is_seed_reproducible_and_bounded(self) -> None:
+ config = two_level_simulation.SimulationConfig(
+ solver="mcsolve",
+ initial_state="excited",
+ omega=1.0,
+ drive=0.0,
+ decay_rate=0.3,
+ dephasing_rate=0.0,
+ t_final=2.0,
+ time_points=21,
+ trajectories=20,
+ seed=12345,
+ method="adams",
+ atol=1.0e-9,
+ rtol=1.0e-7,
+ )
+ first = two_level_simulation.run_simulation(config, qutip)
+ second = two_level_simulation.run_simulation(config, qutip)
+ np.testing.assert_allclose(
+ first["expectations"]["excited_population"],
+ second["expectations"]["excited_population"],
+ atol=0.0,
+ rtol=0.0,
+ )
+ self.assertEqual(
+ first["trajectory_statistics"]["trajectories_run"],
+ 20,
+ )
+ self.assertEqual(len(first["trajectory_statistics"]["seeds"]), 20)
+
+ def test_deterministic_convergence_sweep(self) -> None:
+ parser = convergence_sweep.build_parser()
+ args = parser.parse_args(
+ [
+ "--mode",
+ "deterministic",
+ "--time-points",
+ "21,41",
+ "--rtols",
+ "1e-5,1e-8",
+ "--t-final",
+ "2",
+ "--acceptance",
+ "1e-4",
+ ]
+ )
+ report = convergence_sweep.run_sweep(args, qutip)
+ self.assertEqual(len(report["runs"]), 2)
+ self.assertEqual(len(report["comparisons"]), 1)
+ self.assertLess(
+ report["comparisons"][0]["max_abs_population_difference"],
+ 1.0e-4,
+ )
+
+
+class PhysicsApiTests(unittest.TestCase):
+ def test_steady_state_correlation_and_spectrum_are_finite(self) -> None:
+ H = 0.5 * qutip.sigmaz()
+ c_ops = [
+ np.sqrt(0.2) * qutip.sigmam(),
+ np.sqrt(0.05) * qutip.sigmap(),
+ ]
+ rho_ss = qutip.steadystate(H, c_ops, method="direct")
+ residual = (
+ qutip.liouvillian(H, c_ops)
+ * qutip.operator_to_vector(rho_ss)
+ ).norm()
+ self.assertLess(residual, 1.0e-11)
+ self.assertAlmostEqual(complex(rho_ss.tr()).real, 1.0, places=12)
+ self.assertGreaterEqual(min(rho_ss.eigenenergies()), -1.0e-12)
+
+ taulist = np.linspace(0.0, 8.0, 81)
+ correlation = qutip.correlation_2op_1t(
+ H,
+ rho_ss,
+ taulist,
+ c_ops,
+ qutip.sigmap(),
+ qutip.sigmam(),
+ )
+ self.assertTrue(np.isfinite(correlation).all())
+ frequencies = np.linspace(-3.0, 3.0, 61)
+ values = qutip.spectrum(
+ H,
+ frequencies,
+ c_ops,
+ qutip.sigmap(),
+ qutip.sigmam(),
+ solver="es",
+ )
+ self.assertTrue(np.isfinite(values).all())
+
+ def test_brmesolve_and_stochastic_solver_synthetic_runs(self) -> None:
+ times = np.linspace(0.0, 0.1, 6)
+
+ def spectrum(w):
+ return 0.02 * w if w > 0.0 else 0.0
+
+ br_result = qutip.brmesolve(
+ 0.5 * qutip.sigmaz(),
+ qutip.basis(2, 0),
+ times,
+ a_ops=[(qutip.sigmax(), spectrum)],
+ e_ops=[qutip.sigmaz()],
+ options={"progress_bar": ""},
+ )
+ self.assertTrue(np.isfinite(br_result.expect[0]).all())
+
+ stochastic = qutip.ssesolve(
+ 0.5 * qutip.sigmaz(),
+ qutip.basis(2, 0),
+ times,
+ sc_ops=[np.sqrt(0.05) * qutip.sigmaz()],
+ heterodyne=False,
+ e_ops=[qutip.sigmaz()],
+ ntraj=2,
+ seeds=123,
+ options={"dt": 0.005, "progress_bar": ""},
+ )
+ self.assertTrue(np.isfinite(stochastic.expect[0]).all())
+ self.assertEqual(stochastic.num_trajectories, 2)
+
+ def test_floquet_heom_and_piqs_current_namespaces(self) -> None:
+ def drive(t, amplitude, omega):
+ return amplitude * math.cos(omega * t)
+
+ omega = 2.0
+ period = 2.0 * math.pi / omega
+ H_periodic = qutip.QobjEvo(
+ [qutip.sigmaz(), [qutip.sigmax(), drive]],
+ args={"amplitude": 0.1, "omega": omega},
+ )
+ floquet = qutip.FloquetBasis(H_periodic, period)
+ self.assertEqual(len(floquet.e_quasi), 2)
+ self.assertEqual(len(floquet.mode(0.0)), 2)
+
+ from qutip import piqs
+ from qutip.solver.heom import DrudeLorentzBath, HEOMSolver
+
+ bath = DrudeLorentzBath(
+ qutip.sigmaz(),
+ lam=0.01,
+ gamma=1.0,
+ T=1.0,
+ Nk=1,
+ )
+ heom_solver = HEOMSolver(
+ 0.5 * qutip.sigmax(),
+ bath,
+ max_depth=1,
+ options={"progress_bar": "", "store_states": True},
+ )
+ heom_result = heom_solver.run(
+ qutip.basis(2, 0).proj(),
+ [0.0, 0.02],
+ )
+ self.assertEqual(len(heom_result.states), 2)
+ self.assertAlmostEqual(
+ complex(heom_result.states[-1].tr()).real,
+ 1.0,
+ places=8,
+ )
+
+ ensemble = piqs.Dicke(2, emission=0.1)
+ rho0 = piqs.dicke(2, 1, 1)
+ piqs_result = qutip.mesolve(
+ ensemble.liouvillian(),
+ rho0,
+ [0.0, 0.1],
+ e_ops=[piqs.jspin(2, "z", basis="dicke")],
+ )
+ self.assertEqual(len(piqs_result.expect[0]), 2)
+ self.assertTrue(hasattr(ensemble, "pisolve"))
+ self.assertFalse(hasattr(ensemble, "solve"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/skills/qutip/tests/test_scripts.py b/skills/qutip/tests/test_scripts.py
new file mode 100644
index 00000000..e5ac7c5b
--- /dev/null
+++ b/skills/qutip/tests/test_scripts.py
@@ -0,0 +1,208 @@
+"""Dependency-free tests for QuTiP skill CLI safety and planners."""
+
+from __future__ import annotations
+
+import json
+import stat
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+
+SKILL_ROOT = Path(__file__).resolve().parents[1]
+SCRIPTS = SKILL_ROOT / "scripts"
+sys.path.insert(0, str(SCRIPTS))
+
+import _common # noqa: E402
+import convergence_sweep # noqa: E402
+import qobj_model_validator # noqa: E402
+import result_audit # noqa: E402
+import solver_config_planner # noqa: E402
+import steady_state_spectrum_planner # noqa: E402
+import two_level_simulation # noqa: E402
+
+
+class CommonSafetyTests(unittest.TestCase):
+ def test_strict_json_rejects_urls_duplicates_nan_and_symlinks(self) -> None:
+ with self.assertRaises(_common.CliError):
+ _common.load_json_object("https://example.invalid/model.json")
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ duplicate = root / "duplicate.json"
+ duplicate.write_text('{"value": 1, "value": 2}', encoding="utf-8")
+ with self.assertRaises(_common.CliError):
+ _common.load_json_object(duplicate)
+
+ nonfinite = root / "nonfinite.json"
+ nonfinite.write_text('{"value": NaN}', encoding="utf-8")
+ with self.assertRaises(_common.CliError):
+ _common.load_json_object(nonfinite)
+
+ regular = root / "regular.json"
+ regular.write_text("{}", encoding="utf-8")
+ symlink = root / "symlink.json"
+ try:
+ symlink.symlink_to(regular)
+ except OSError:
+ self.skipTest("symlinks unavailable")
+ with self.assertRaises(_common.CliError):
+ _common.load_json_object(symlink)
+
+ def test_private_output_refuses_overwrite(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ output = Path(directory) / "report.json"
+ _common.emit_json({"ok": True}, output=output)
+ self.assertEqual(json.loads(output.read_text()), {"ok": True})
+ self.assertEqual(stat.S_IMODE(output.stat().st_mode), 0o600)
+ with self.assertRaises(_common.CliError):
+ _common.emit_json({"ok": False}, output=output)
+
+ def test_limits_and_nonfinite_values_are_enforced(self) -> None:
+ with self.assertRaises(_common.CliError):
+ _common.bounded_dimensions([8, 9])
+ with self.assertRaises(_common.CliError):
+ _common.finite_float(float("inf"), name="value")
+ with self.assertRaises(_common.CliError):
+ _common.parse_csv_ints(
+ "10,10",
+ name="counts",
+ minimum=1,
+ maximum=100,
+ )
+
+
+class HelpTests(unittest.TestCase):
+ def test_every_cli_has_dependency_free_help(self) -> None:
+ modules = (
+ convergence_sweep,
+ qobj_model_validator,
+ result_audit,
+ solver_config_planner,
+ steady_state_spectrum_planner,
+ two_level_simulation,
+ )
+ for module in modules:
+ with self.subTest(module=module.__name__):
+ help_text = module.build_parser().format_help()
+ self.assertIn("usage:", help_text)
+ self.assertIn("--help", help_text)
+ self.assertNotIn("Traceback", help_text)
+
+
+class PlannerTests(unittest.TestCase):
+ def test_lindblad_and_stochastic_solver_selection(self) -> None:
+ parser = solver_config_planner.build_parser()
+ lindblad = solver_config_planner.create_plan(
+ parser.parse_args(
+ ["--model", "lindblad", "--collapse-channels", "2"]
+ )
+ )
+ self.assertEqual(lindblad["recommended_solver"], "mesolve")
+ self.assertEqual(lindblad["status"], "ready_for_model_construction")
+
+ stochastic = solver_config_planner.create_plan(
+ parser.parse_args(
+ [
+ "--model",
+ "diffusive",
+ "--initial-state",
+ "density",
+ "--trajectories",
+ "25",
+ ]
+ )
+ )
+ self.assertEqual(stochastic["recommended_solver"], "smesolve")
+ self.assertEqual(stochastic["call_configuration"]["ntraj"], 25)
+ self.assertFalse(stochastic["call_configuration"]["heterodyne"])
+
+ def test_specialized_plans_surface_missing_assumptions(self) -> None:
+ parser = solver_config_planner.build_parser()
+ bloch_redfield = solver_config_planner.create_plan(
+ parser.parse_args(["--model", "bloch-redfield"])
+ )
+ self.assertEqual(bloch_redfield["recommended_solver"], "brmesolve")
+ self.assertIn(
+ "weak-coupling assumption has not been confirmed",
+ bloch_redfield["warnings"],
+ )
+
+ floquet = solver_config_planner.create_plan(
+ parser.parse_args(["--model", "periodic-open"])
+ )
+ self.assertIn("positive --period", " ".join(floquet["warnings"]))
+
+ def test_steady_spectrum_plan_computes_bounded_fft_grid(self) -> None:
+ parser = steady_state_spectrum_planner.build_parser()
+ report = steady_state_spectrum_planner.create_plan(
+ parser.parse_args(
+ [
+ "--stationary-confirmed",
+ "--tau-max",
+ "10",
+ "--tau-points",
+ "101",
+ ]
+ )
+ )
+ self.assertEqual(report["status"], "ready_to_implement")
+ fft = report["spectrum_plans"][1]
+ self.assertAlmostEqual(fft["tau_grid"]["step"], 0.1)
+ self.assertAlmostEqual(
+ fft["derived_angular_frequency_limits"]["nyquist"],
+ 10.0 * 3.141592653589793,
+ )
+
+ def test_planners_reject_unbounded_requests(self) -> None:
+ parser = steady_state_spectrum_planner.build_parser()
+ with self.assertRaises(_common.CliError):
+ steady_state_spectrum_planner.create_plan(
+ parser.parse_args(["--dimension", "65"])
+ )
+
+
+class PortableAuditTests(unittest.TestCase):
+ def test_simulation_report_audit_passes_without_qutip(self) -> None:
+ document = {
+ "report_type": "qutip.two_level_simulation",
+ "qutip_version": "5.3.0",
+ "configuration": {"solver": "mesolve"},
+ "model": {"assumptions": ["a", "b", "c"]},
+ "times": [0.0, 1.0, 2.0],
+ "expectations": {"excited_population": [1.0, 0.5, 0.25]},
+ "analytic_reference": {
+ "applicable": True,
+ "excited_population": [1.0, 0.5, 0.25],
+ "max_abs_error": 0.0,
+ },
+ "trajectory_statistics": {
+ "trajectories_run": None,
+ "seeds": None,
+ },
+ "checks": {},
+ "solver": {"stats": {"run time": 0.01}},
+ }
+ audit = result_audit.audit_document(document, tolerance=1.0e-8)
+ self.assertEqual(audit["status"], "pass")
+ self.assertEqual(audit["summary"]["errors"], 0)
+
+ def test_audit_rejects_out_of_range_population(self) -> None:
+ document = {
+ "report_type": "qutip.two_level_simulation",
+ "qutip_version": "5.3.0",
+ "configuration": {"solver": "mesolve"},
+ "model": {"assumptions": ["a", "b", "c"]},
+ "times": [0.0, 1.0],
+ "expectations": {"excited_population": [1.0, 1.2]},
+ "analytic_reference": {"applicable": False},
+ "trajectory_statistics": {},
+ "checks": {},
+ "solver": {"stats": {"run time": 0.01}},
+ }
+ audit = result_audit.audit_document(document, tolerance=1.0e-6)
+ self.assertEqual(audit["status"], "fail")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/skills/qutip/tests/test_static.py b/skills/qutip/tests/test_static.py
new file mode 100644
index 00000000..51969274
--- /dev/null
+++ b/skills/qutip/tests/test_static.py
@@ -0,0 +1,186 @@
+"""Static safety, provenance, and QuTiP 5 migration tests."""
+
+from __future__ import annotations
+
+import ast
+import re
+import unittest
+from pathlib import Path
+from urllib.parse import urlparse
+
+
+SKILL_ROOT = Path(__file__).resolve().parents[1]
+SCRIPTS = SKILL_ROOT / "scripts"
+REFERENCES = SKILL_ROOT / "references"
+CLI_NAMES = {
+ "convergence_sweep.py",
+ "qobj_model_validator.py",
+ "result_audit.py",
+ "solver_config_planner.py",
+ "steady_state_spectrum_planner.py",
+ "two_level_simulation.py",
+}
+REFERENCE_NAMES = {
+ "advanced.md",
+ "analysis.md",
+ "core_concepts.md",
+ "time_evolution.md",
+ "visualization.md",
+}
+OFFICIAL_HOSTS = {
+ "github.com",
+ "pypi.org",
+ "qutip.org",
+ "qutip.readthedocs.io",
+}
+
+
+class DocumentationTests(unittest.TestCase):
+ def test_frontmatter_version_license_compatibility_and_size(self) -> None:
+ text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")
+ self.assertLess(len(text.splitlines()), 500)
+ self.assertIn("\nlicense: MIT\n", text)
+ self.assertIn("\ncompatibility:", text)
+ self.assertRegex(
+ text,
+ r"\nmetadata:\n version: \"1\.1\"\n skill-author:"
+ r".*\n last-reviewed: \"2026-07-23\"",
+ )
+
+ def test_snapshot_and_extension_boundaries_are_pinned(self) -> None:
+ paths = [SKILL_ROOT / "SKILL.md", *sorted(REFERENCES.glob("*.md"))]
+ combined = "\n".join(path.read_text(encoding="utf-8") for path in paths)
+ for pin in (
+ "qutip==5.3.0",
+ "qutip-qip==0.4.2",
+ "qutip-qtrl==0.2.0",
+ "qutip-jax==0.1.1",
+ ):
+ self.assertIn(pin, combined)
+ self.assertIn("Python 3.11", combined)
+ self.assertIn("quantum optimal control", combined)
+ self.assertIn("not a trajectory viewer", combined)
+ self.assertIn("not officially released", combined)
+ self.assertNotRegex(combined, r"(?m)^\s*pip install\b")
+
+ def test_quitp4_patterns_are_removed(self) -> None:
+ paths = [SKILL_ROOT / "SKILL.md", *sorted(REFERENCES.glob("*.md"))]
+ combined = "\n".join(path.read_text(encoding="utf-8") for path in paths)
+ self.assertIsNone(re.search(r"from\s+qutip\s+import\s+\*", combined))
+ for stale_pattern in (
+ r"qutip\.nonmarkov\.heom",
+ r"\bOptions\s*\(",
+ r"\.[e]val\s*\(",
+ r"result\.save\s*\(",
+ r"Result\.load\s*\(",
+ r"correlation_4op_1t\s*\(",
+ r"spectrum_pi\s*\(",
+ ):
+ self.assertIsNone(re.search(stale_pattern, combined))
+ self.assertIn("qutip.solver.heom", combined)
+ self.assertIn("ordinary option dictionaries", combined)
+ self.assertIn("heterodyne", combined)
+ self.assertIn("QFunc(xvec, yvec", combined)
+ self.assertIn("has no `.eval` method", combined)
+
+ def test_reference_inventory_and_dates(self) -> None:
+ self.assertEqual(
+ {path.name for path in REFERENCES.glob("*.md")},
+ REFERENCE_NAMES,
+ )
+ for path in sorted(REFERENCES.glob("*.md")):
+ with self.subTest(path=path.name):
+ text = path.read_text(encoding="utf-8")
+ self.assertIn("2026-07-23", text)
+ self.assertIn("Sources (verified 2026-07-23)", text)
+
+ def test_documented_cli_inventory_exists(self) -> None:
+ scripts = {path.name for path in SCRIPTS.glob("*.py")}
+ self.assertTrue(CLI_NAMES.issubset(scripts))
+ skill = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")
+ for name in CLI_NAMES:
+ self.assertIn(f"scripts/{name}", skill)
+
+ def test_relative_links_exist_and_web_sources_are_official(self) -> None:
+ markdown_paths = [SKILL_ROOT / "SKILL.md", *sorted(REFERENCES.glob("*.md"))]
+ pattern = re.compile(r"\[[^\]]+\]\(([^)]+)\)")
+ for path in markdown_paths:
+ for target in pattern.findall(path.read_text(encoding="utf-8")):
+ if target.startswith(("#", "mailto:")):
+ continue
+ if target.startswith(("https://", "http://")):
+ host = (urlparse(target).hostname or "").lower()
+ self.assertIn(host, OFFICIAL_HOSTS, f"{path.name}: {target}")
+ if host == "github.com":
+ self.assertTrue(
+ urlparse(target).path.startswith("/qutip/"),
+ f"non-QuTiP GitHub source: {target}",
+ )
+ continue
+ relative = target.split("#", 1)[0]
+ self.assertTrue(
+ (path.parent / relative).exists(),
+ f"missing {target!r} from {path.name}",
+ )
+
+
+class ScriptSafetyTests(unittest.TestCase):
+ def test_scripts_parse_without_network_or_dynamic_execution(self) -> None:
+ forbidden_imports = {
+ "aiohttp",
+ "ftplib",
+ "http",
+ "pickle",
+ "requests",
+ "socket",
+ "subprocess",
+ "urllib",
+ }
+ forbidden_calls = {"eval", "exec", "compile", "__import__"}
+ paths = sorted(SCRIPTS.glob("*.py"))
+ self.assertEqual(
+ {path.name for path in paths},
+ {"_common.py", *CLI_NAMES},
+ )
+ for path in paths:
+ with self.subTest(path=path.name):
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
+ self.assertNotIn(node.func.id, forbidden_calls)
+ if isinstance(node, ast.Import):
+ roots = {alias.name.split(".", 1)[0] for alias in node.names}
+ self.assertFalse(roots & forbidden_imports)
+ if isinstance(node, ast.ImportFrom) and node.module:
+ self.assertNotIn(
+ node.module.split(".", 1)[0],
+ forbidden_imports,
+ )
+
+ def test_qutip_and_numpy_imports_are_lazy(self) -> None:
+ for path in sorted(SCRIPTS.glob("*.py")):
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ for node in tree.body:
+ if isinstance(node, ast.Import):
+ roots = {alias.name.split(".", 1)[0] for alias in node.names}
+ self.assertFalse(roots & {"qutip", "numpy"}, path.name)
+ if isinstance(node, ast.ImportFrom):
+ self.assertNotIn(
+ (node.module or "").split(".", 1)[0],
+ {"qutip", "numpy"},
+ path.name,
+ )
+
+ def test_no_generated_or_research_artifacts(self) -> None:
+ forbidden = [
+ *SKILL_ROOT.rglob("__pycache__"),
+ *SKILL_ROOT.rglob("*.pyc"),
+ *SKILL_ROOT.rglob("*.pyo"),
+ *SKILL_ROOT.rglob("research-*.json"),
+ *SKILL_ROOT.rglob("*.tmp"),
+ ]
+ self.assertEqual(forbidden, [])
+
+
+if __name__ == "__main__":
+ unittest.main()