Metadata-Version: 2.4
Name: nv-zf-sim
Version: 0.2.0
Summary: Zero-field ensemble NV-centre spin simulation with realistic ROI photon readout
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: jax>=0.4.20
Requires-Dist: diffrax>=0.5.0
Requires-Dist: numpy>=1.24
Requires-Dist: pandas>=1.5
Provides-Extra: dev
Requires-Dist: pytest>=7.4; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Provides-Extra: examples
Requires-Dist: matplotlib>=3.7; extra == "examples"
Requires-Dist: scipy>=1.10; extra == "examples"
Requires-Dist: jupyter>=1.0; extra == "examples"
Requires-Dist: nbconvert>=7.0; extra == "examples"
Dynamic: license-file

# nv-zf-sim

`nv-zf-sim` is an open-source Python package for simulating driven ground-state spin-1 dynamics in single nitrogen-vacancy (NV) centres and disordered NV-centre ensembles at zero magnetic field. Built with JAX and Diffrax, it supports configurable microwave control, transverse strain and detuning, relaxation and dephasing, orientation and coherence-time disorder, ensemble-resolved observables, and photon-count readout models for configurable regions of interest.

The package is intended for students, researchers, and quantum-sensing practitioners studying zero-field NV-centre dynamics, ensemble decoherence, pulsed control, and optically detected magnetic resonance (ODMR). Supporting documentation includes a [user guide](https://github.com/Govinden23/nv-zf-sim/blob/main/user_guide.md), a code-traceable [implemented equations reference](https://github.com/Govinden23/nv-zf-sim/blob/main/docs/theory/package_equations.pdf), and a [technical report](https://github.com/Govinden23/nv-zf-sim/blob/main/docs/technical_report.pdf).

## Key capabilities

- **Single-NV and ensemble spin dynamics** using a shared zero-field spin-1 model with microwave control, transverse strain, detuning, relaxation and dephasing.

- **Configurable ensemble disorder** in orientation, strain magnitude and phase, resonance detuning, microwave coupling and coherence time.

- **Vectorised simulation with JAX and Diffrax**, enabling the same experiment to be evaluated across sampled NV ensembles.

- **Built-in workflows and observables** for Rabi calibration, pulsed ODMR, Ramsey interferometry, phase-controlled excitation, Hahn echo, spin-state populations and coherences.

- **Photon readout modelling** that converts simulated populations into expected ROI photon counts, fluorescence contrast and Poisson shot-noise statistics.

## Installation

`nv-zf-sim` requires **Python 3.10 or later**.

### Install from PyPI

Install the core package with:

```bash
pip install nv-zf-sim
```

To include the dependencies required for plotting and running the example notebooks:

```bash
pip install "nv-zf-sim[examples]"
```

### Install from source

Clone the repository and install the package in editable mode:

```bash
git clone https://github.com/Govinden23/nv-zf-sim.git
cd nv-zf-sim
pip install -e .
```

To include the example and notebook dependencies:

```bash
pip install -e ".[examples]"
```

For development, testing, and example dependencies:

```bash
pip install -e ".[dev,examples]"
```

Verify the installation:

```bash
python -c "import nv_zf_sim; print('nv-zf-sim installed successfully')"
```

> **JAX note:** Hardware-accelerated JAX installations may require platform-specific configuration. See the [JAX installation guide](https://docs.jax.dev/en/latest/installation.html) when configuring GPU or other accelerator support.


## Model

`nv-zf-sim` models **driven ground-state spin-1 dynamics at zero magnetic field**. The coherent dynamics include axial zero-field splitting, transverse strain, and a configurable microwave drive, with phenomenological T₁ relaxation and Tφ dephasing added directly to the equations of motion.

Rather than constructing and propagating an explicit 3 × 3 density matrix, the package integrates an equivalent nine-component real ODE comprising three populations and the real and imaginary components of three coherences. The equations are evaluated in a rotating frame under the rotating-wave approximation, integrated with Diffrax, and vectorised across sampled NV ensembles using `jax.vmap`.

Ensemble disorder is introduced by sampling each NV's parameters once before the dynamics are solved. Detuning is sampled from a normal distribution, while transverse-strain magnitude and Tφ are sampled from log-normal distributions to represent non-negative, right-skewed quantities. NV orientations are sampled isotropically, and the sampled parameters remain fixed for the duration of each simulation. T₁ is currently shared across the ensemble rather than independently disordered.

See the [user guide](https://github.com/Govinden23/nv-zf-sim/blob/main/user_guide.md) for the available distributions and configuration options, and the [implemented equations reference](https://github.com/Govinden23/nv-zf-sim/blob/main/docs/theory/package_equations.pdf) for the complete code-traceable mathematical formulation.

## Example result

The figure below is generated by [`09_odmr_disorder_mechanism_decomposition.ipynb`](https://github.com/Govinden23/nv-zf-sim/blob/main/examples/notebooks/09_odmr_disorder_mechanism_decomposition.ipynb). It applies the same pulsed zero-field ODMR sweep to six cases derived from a sampled ensemble of 1,000 NV centres: one idealised reference, four cases containing a single disorder mechanism, and one case containing all modelled disorder mechanisms. The lower panel applies the photon-readout model to the complete disordered ensemble, including Poisson shot noise.

<p align="center">
  <img
    src="https://raw.githubusercontent.com/Govinden23/nv-zf-sim/main/docs/fig1_flagship_comparison.png"
    width="100%"
    alt="Pulsed ODMR simulations showing isolated disorder mechanisms, the complete disordered ensemble, and its predicted photon readout"
  >
</p>

<p align="center">
  <em>
    Mechanism-resolved pulsed ODMR simulations and the corresponding predicted
    photon readout. The upper panels isolate orientation, detuning, transverse-strain,
    and dephasing disorder, while the lower panel shows the noisy fluorescence signal
    predicted after all modelled disorder mechanisms are combined.
  </em>
</p>

**Simulation setup.** All panels use a 1.5 MHz Rabi drive and the same calibrated π-pulse duration of 373 ns. The pulse duration was obtained from a Rabi calibration performed on the complete disordered ensemble, representing a practical ensemble-calibration workflow. Because this duration is optimised for the ensemble rather than the idealised reference, the clean-reference response does not necessarily reach complete population inversion.

**Interpreting the spin response.** At zero magnetic field, transverse strain separates the two dark-state eigenmodes, while their relative excitation depends on the microwave phase and strain-axis orientation. In the idealised reference, the drive and strain axes are aligned, producing a predominantly single-branch response. For the parameters used here, dephasing produces only a small change because the 373 ns pulse is considerably shorter than the ensemble's typical dephasing time of approximately 2 μs. Detuning disorder broadens and reduces the resonance by distributing individual NV transition frequencies around the ensemble mean. Orientation and strain disorder weaken the phase-selective response through, respectively, variations in microwave projection and variations in the local strain axis. When all mechanisms are combined, the sharp branch-selective feature is replaced by a broader and shallower ensemble response.

**Predicted photon readout.** The lower panel converts the simulated bright-state population of the complete ensemble into normalised fluorescence with Poisson shot noise. Its contrast is much smaller than the underlying spin-population depletion because the readout model assumes finite bright–dark contrast that decays over the photon-collection window. The photon rate, contrast, and decay-time values used here are illustrative model parameters rather than measurements from a specific optical setup. Quantitative predictions of experimental contrast or signal-to-noise ratio therefore require calibration against the intended apparatus.

## Example notebooks

The repository includes executable Jupyter notebooks covering the principal simulation and readout workflows in `nv-zf-sim`.

| Notebook | Description |
|---|---|
| [00 — Single-NV Rabi calibration](https://github.com/Govinden23/nv-zf-sim/blob/main/examples/notebooks/00_single_rabi_calibration.ipynb) | Simulates coherent Rabi oscillations and extracts effective π- and π/2-pulse durations for a single NV. |
| [01 — Ensemble Rabi calibration and photon readout](https://github.com/Govinden23/nv-zf-sim/blob/main/examples/notebooks/01_ensemble_rabi_calibration.ipynb) | Simulates coherent Rabi oscillations in a disordered NV ensemble, extracts effective π- and π/2-pulse durations, and converts the resulting spin populations into ROI photon-count statistics. |
| [02 — Ensemble pulsed ODMR](https://github.com/Govinden23/nv-zf-sim/blob/main/examples/notebooks/02_ensemble_pulsed_odmr.ipynb) | Simulates zero-field pulsed ODMR spectra for a disordered ensemble and applies the photon-readout model. |
| [03 — Ramsey phase interference](https://github.com/Govinden23/nv-zf-sim/blob/main/examples/notebooks/03_ramsey_phase_interference.ipynb) | Demonstrates free-precession dynamics, phase accumulation, and ensemble dephasing. |
| [04 — Continuous microwave driving](https://github.com/Govinden23/nv-zf-sim/blob/main/examples/notebooks/04_continuous_microwave_driving.ipynb) | Simulates a spin-lock-style π/2ₓ–CWᵧ–π/2₋ₓ sequence, including phase checks, duration-dependent population and coherence dynamics, decay fitting, and density-matrix diagnostics. |
| [05 — Ensemble phase control](https://github.com/Govinden23/nv-zf-sim/blob/main/examples/notebooks/05_ensemble_phase_control_two_pi_over_2.ipynb) | Verifies the microwave phase convention using two back-to-back π/2 pulses and the collapse of bright-state responses when plotted against relative phase. |
| [06 — Random-orientation effects](https://github.com/Govinden23/nv-zf-sim/blob/main/examples/notebooks/06_random_orientation_effects.ipynb) | Quantifies how isotropic orientation disorder modifies microwave coupling, population transfer, and coherence generation. |
| [07 — Ensemble Hahn echo](https://github.com/Govinden23/nv-zf-sim/blob/main/examples/notebooks/07_ensemble_hahn_echo.ipynb) | Simulates refocusing under static disorder and ensemble dephasing. |
| [08 — Strain-branch-selective ODMR](https://github.com/Govinden23/nv-zf-sim/blob/main/examples/notebooks/08_single_nv_strain_branch_selective_odmr.ipynb) | Demonstrates strain-induced resonance splitting in a single NV and phase-selective excitation of the two branches. |
| [09 — ODMR disorder-mechanism decomposition](https://github.com/Govinden23/nv-zf-sim/blob/main/examples/notebooks/09_odmr_disorder_mechanism_decomposition.ipynb) | Isolates orientation, detuning, strain, and dephasing disorder before combining them in the full modelled ensemble and simulated photon readout. This notebook generates the flagship figure shown above. |

After installing the `examples` dependencies, launch the notebooks from the repository root:

```bash
jupyter notebook examples/notebooks
```

## API at a glance

Rabi calibration, pulsed ODMR, Ramsey interferometry, Hahn echo, and continuous-driving experiments are all constructed from the same core objects. Full parameter tables and worked examples are provided in the [user guide](https://github.com/Govinden23/nv-zf-sim/blob/main/user_guide.md), while the implemented mathematics is documented in the [equations reference](https://github.com/Govinden23/nv-zf-sim/blob/main/docs/theory/package_equations.pdf).

| API | Purpose |
|---|---|
| `SingleNVParameters` | Defines the physical parameters of one NV centre, including relaxation and dephasing times, detuning, transverse strain, and orientation. |
| `EnsembleParameters` | Defines the probability distributions used to sample orientation, strain, detuning, and dephasing across an ensemble. |
| `sample_ensemble(params)` | Samples a fixed, reproducible `NVEnsemble` from an `EnsembleParameters` configuration. |
| `Controls`, `WaveformControls`, `interp_controls` | Define constant microwave-control quadratures or piecewise-linear control waveforms used by the rotating-frame model. |
| `SolverParameters` | Configures the integration interval, solver tolerances, step-size controls, and output times. |
| `OutputParameters` | Selects the populations, coherences, and ensemble statistics returned by a simulation. |
| `Experiment` | Bundles the control protocol, physical parameters, solver configuration, and requested outputs into a runnable experiment. |
| `run_single_nv(experiment)` | Simulates one NV centre and returns a `SingleNVResult`. |
| `run_experiment(experiment, ensemble)` | Vectorises the same dynamics across an ensemble using `jax.vmap` and returns per-NV and ensemble-averaged results. |
| `extract_observable`, `extract_observables` | Extract selected populations or coherences from a solved state trajectory. |
| `ROIPhotonReadoutConfig`, `roi_photon_readout_from_p0` | Convert a reference and signal bright-state population into expected ROI photon counts and contrast. |
| `PhotonParameters`, `PhotonReadoutModel` | Convert complete three-state population trajectories into expected or Poisson-sampled photon-count measurements. |
| `ExperimentRun` and reporting utilities | Manage timestamped output directories and save simulation settings, tables, figures, and JSON summaries. |

## Limitations

`nv-zf-sim` is focused on driven ground-state spin dynamics in zero-field NV-centre ensembles. The current model does not include:

- hyperfine interactions or nuclear-spin dynamics;
- non-zero-field Zeeman effects;
- optical pumping, excited-state dynamics, or charge-state conversion;
- counter-rotating or other beyond-RWA corrections;
- microscopic spin-bath dynamics or spectral-noise models;
- interactions between different NV centres.

The photon-readout models are applied as a **post-processing layer**: simulated spin populations are converted into expected fluorescence or photon counts after the spin dynamics have been solved. Continuous optical excitation is therefore not coupled directly to the spin evolution.

Ensemble disorder is sampled once for each NV and held fixed during a simulation. Detuning, orientation, transverse strain, and Tφ may vary across the ensemble, while T₁ is currently shared.

For the complete modelling assumptions and implementation details, see the [implemented equations reference](https://github.com/Govinden23/nv-zf-sim/blob/main/docs/theory/package_equations.pdf) and the [technical report](https://github.com/Govinden23/nv-zf-sim/blob/main/docs/technical_report.pdf).

## Documentation

The repository includes practical, mathematical, and scientific documentation for different levels of use.

| Resource | Description |
|---|---|
| [User guide](https://github.com/Govinden23/nv-zf-sim/blob/main/user_guide.md) | Practical guidance for configuring simulations, sampling ensembles, constructing pulse sequences, interpreting outputs, and applying the photon-readout models. |
| [Implemented equations reference](https://github.com/Govinden23/nv-zf-sim/blob/main/docs/theory/package_equations.pdf) | A code-traceable mathematical description of the spin-1 dynamics, control conventions, disorder sampling, ensemble averaging, observables, and photon readout. |
| [Technical report](https://github.com/Govinden23/nv-zf-sim/blob/main/docs/technical_report.pdf) | Presents the physical motivation, modelling assumptions, numerical methods, verification studies, and interpretation of the zero-field NV-centre simulations. |
| [Example notebooks](https://github.com/Govinden23/nv-zf-sim/tree/main/examples/notebooks/) | Executable demonstrations covering Rabi calibration, pulsed ODMR, Ramsey interferometry, continuous driving, phase control, Hahn echo, ensemble disorder, and photon readout. |

## Citation

If you use `nv-zf-sim` in your own work, please cite it as:

> Govinden Modely Rungen. *nv-zf-sim: Zero-field ensemble NV-centre spin simulation with realistic ROI photon readout* (v0.2.1). Zenodo. https://doi.org/10.5281/zenodo.21793444

```bibtex
@software{modely_rungen_nv_zf_sim,
  author  = {Modely Rungen, Govinden},
  title   = {nv-zf-sim: Zero-field ensemble NV-centre spin simulation with realistic ROI photon readout},
  year    = {2026},
  version = {0.2.1},
  doi     = {10.5281/zenodo.21793444},
  url     = {https://github.com/Govinden23/nv-zf-sim}
}
```

Citation metadata is also available in [`CITATION.cff`](https://github.com/Govinden23/nv-zf-sim/blob/main/CITATION.cff).

## License

MIT — see [LICENSE](https://github.com/Govinden23/nv-zf-sim/blob/main/LICENSE).

