Metadata-Version: 2.5
Name: optixstuff
Version: 7.0.0
Summary: Hardware abstractions for the HWO direct imaging simulation suite
Project-URL: Homepage, https://github.com/CoreySpohn/optixstuff
Project-URL: Issues, https://github.com/CoreySpohn/optixstuff/issues
Author-email: Corey Spohn <corey.a.spohn@nasa.gov>
License: MIT License
        
        Copyright (c) 2026 Corey Spohn
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Astronomy
Requires-Python: >=3.12
Requires-Dist: equinox>=0.13.2
Requires-Dist: hwoutils>=3.0.0
Requires-Dist: interpax>=0.3.12
Requires-Dist: jax>=0.8.1
Requires-Dist: jaxlib>=0.8.1
Requires-Dist: jaxtyping>=0.3.3
Requires-Dist: numpy>=2.0
Requires-Dist: scipy>=1.13
Provides-Extra: dev
Requires-Dist: pre-commit>=3.5; extra == 'dev'
Provides-Extra: docs
Requires-Dist: eyepiece>=0.17.0; extra == 'docs'
Requires-Dist: ipython>=8.18; extra == 'docs'
Requires-Dist: matplotlib>=3.10.7; extra == 'docs'
Requires-Dist: myst-nb>=1.0; extra == 'docs'
Requires-Dist: sphinx-autoapi>=3.0; extra == 'docs'
Requires-Dist: sphinx-book-theme>=1.1; extra == 'docs'
Requires-Dist: sphinx>=7.2; extra == 'docs'
Requires-Dist: sphinxcontrib-mermaid>=0.9; extra == 'docs'
Provides-Extra: test
Requires-Dist: eyepiece>=0.17.0; extra == 'test'
Requires-Dist: hypothesis>=6.79.1; extra == 'test'
Requires-Dist: ineedvalidation>=1.1.0; extra == 'test'
Requires-Dist: numpy>=2.0; extra == 'test'
Requires-Dist: psutil>=5.9.4; extra == 'test'
Requires-Dist: pytest-fail-slow>=0.1.0; extra == 'test'
Requires-Dist: pytest-markdown-docs>=0.5.0; extra == 'test'
Requires-Dist: pytest-testmon>=2.0.7; extra == 'test'
Requires-Dist: pytest-timeout>=1.3.1; extra == 'test'
Requires-Dist: pytest-xdist>=2.5; extra == 'test'
Requires-Dist: pytest>=7.3.2; extra == 'test'
Provides-Extra: viz
Requires-Dist: eyepiece>=0.17.0; extra == 'viz'
Description-Content-Type: text/markdown

# optixstuff

<p align="center">
  <a href="https://pypi.org/project/optixstuff/"><img src="https://img.shields.io/pypi/v/optixstuff.svg?style=flat-square&logo=pypi" alt="PyPI"/></a>
  <a href="https://optixstuff.readthedocs.io"><img src="https://readthedocs.org/projects/optixstuff/badge/?version=latest&style=flat-square" alt="Documentation Status"/></a>
  <a href="https://github.com/CoreySpohn/optixstuff/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/CoreySpohn/optixstuff/ci.yml?branch=main&style=flat-square&logo=github&label=tests" alt="Tests"/></a>
  <a href="https://github.com/CoreySpohn/optixstuff/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square" alt="License"/></a>
  <a href="https://github.com/CoreySpohn/optixstuff/blob/main/pyproject.toml"><img src="https://img.shields.io/badge/python-3.12%2B-blue.svg?style=flat-square&logo=python" alt="Python 3.12+"/></a>
  <a href="https://doi.org/10.5281/zenodo.20819379"><img src="https://img.shields.io/badge/DOI-10.5281%2Fzenodo.20819379-blue?style=flat-square" alt="DOI"/></a>
</p>

Shared hardware objects - with standard values - for the HWO direct-imaging
simulation suite.

## What optixstuff is

`optixstuff` is a **thin shared dependency** that defines the observatory's
hardware as composable JAX modules: primary aperture, throughput-affecting
elements, coronagraph backend, detector. Its job is to be the single source of
truth for the hardware configuration that downstream tools consume.

[coronagraphoto](https://github.com/CoreySpohn/coronagraphoto)
(2D image simulation), [coronachrome](https://github.com/CoreySpohn/coronachrome)
(lenslet-IFS dispersion + spectral extraction), and
[jaxEDITH](https://github.com/CoreySpohn/jaxedith)
(analytic aperture rates for exposure-time calculations) import the same
`Instrument` class and the same detector / throughput / primary types from
optixstuff; jaxEDITH reads coronagraph performance as `PerformanceCurves`
data, not from the coronagraph slot. Change a value here and every downstream
tool picks it up on the next import. The S/N and exposure-time reduction of a
`Rates` record, `optixstuff.snr` and `optixstuff.exposure_time` with
`optixstuff.PostProcessing`, lives here because both producers end at it; [how an exposure time is
computed](https://optixstuff.readthedocs.io/en/latest/explanation/exposure_time.html)
follows both.

## What optixstuff is *not*

- **Not a wavefront tool.** Diffraction, E-field propagation, and PSFs-from-first-principles
  belong to [dLux](https://github.com/LouisDesdoigts/dLux) and [HCIPy](https://github.com/ehpor/hcipy).
- **Not a PSF interpolator.** Image providers implement the shared
  `AbstractCoronagraph` contract; optixstuff owns the contract and scalar models.
- **Not a scene model.** Stars, planets, disks, and zodi live in
  [skyscapes](https://github.com/CoreySpohn/skyscapes).
- **Not a simulator.** Downstream tools (coronagraphoto, coronachrome, jaxEDITH)
  consume an `Instrument` to produce images, dispersed IFS frames, or count rates.
  The calculator here only reduces rates they produce to S/N or time.

## Architecture

Built on [JAX](https://github.com/google/jax) and
[Equinox](https://github.com/patrick-kidger/equinox), `optixstuff` provides:

- **Abstract interfaces** - `AbstractPrimary`, `AbstractOpticalElement`,
  `AbstractCoronagraph`, `AbstractDetector`, `AbstractDisperser`
- **Concrete implementations** - `SimplePrimary`, `SegmentedPrimary` (carries
  hex segment geometry for a diffraction backend), `ConstantThroughput`,
  `IdealDetector`, `Detector` (with optional wavelength-dependent QE),
  `LensletDisperser`
- **Container** - `Instrument`, a composable hardware configuration passed to all
  simulators

Optical elements and coronagraphs accept fidelity axes - **wavelength**, **position**, and
**time** - with defaults so that simple implementations can ignore unused axes while
future high-fidelity models (wavelength-dependent coatings, position-dependent vignetting,
time-dependent detector degradation) can use them without breaking the interface.

### Primary geometry and coronagraph grids

Primaries expose `diameter("circumscribed")`, `diameter("inscribed")`, and
`collecting_area_m2`. Build a lambda/D frame with `primary.frame(500.0)`.
`SimplePrimary` takes both diameters and collecting area as keyword arguments;
`SegmentedPrimary` derives them from segment size, gap, and ring count.
`Instrument` raises `ValueError` when its primary's diameter differs from the
diameter of the coronagraph's lambda/D frame, so the tables and the collecting
area describe one telescope. A yippy `Coronagraph` carries the matching
`primary`.

Coronagraph images use `optixstuff.grids.Image` and an explicit target `PixelGrid`.
Coordinates are `(x, y)`, arrays are `(..., y, x)`, and even-grid centres fall
between pixels. For example, `model.off_axis_psf(500.0, 3.0, target)` returns
per-pixel fractions of unocculted source flux. Use `.data` to obtain its array.
Select the imaging model with `model = coro.coronagraph_at(500.0)`. Its
`at_wavelength(500.0)` gives the source, stellar and uniform-sky grids.
Scene models return an image and a validity flag from
`render_scene(scene_image, 500.0, grid=target)`. The image is always finite; the
flag is False only when lit flux lies outside the cells the model covers, and
that flux contributes zero. `AbstractSceneCoronagraph.scene_grid` is the grid on
which a scene (a disk, for example) is built so that it reaches every source the
model can render.

A product ends where its data end. `resample` and `Image` never reflect or
extrapolate: a target pixel that reaches past the source footprint reads zero.
`optixstuff.grids.coverage(source_grid, target_grid, margin)` returns the target
pixels wholly inside the footprint, and `reconstruction_margin(name)` supplies
the margin that also excludes pixels whose value depends on the zero beyond the
data. When the pixels are at least as large as the product's cells, `resample`
deposits instead of sampling and reaches further, so pass
`reconstruction=` and `measure=` in place of `margin` to get the margin of the
read that is performed. `cubic_spline`, the not-a-knot cubic spline, and
`band_limited` have no finite reach, so their margin marks a support boundary
rather than an exact bound. `on_grid` reads every density as the integral of
its declared reconstruction over each pixel, on axis-aligned grids only. Consumers mask with it, and `exposure_time` and `snr` report an
unsupported aperture through `Rates.supported` rather than a number. NaN is
reserved for terminal statistics such as `snr` and `exposure_time`.

A speckle field is a product too, and its grid usually covers less of the
detector than the static coronagraph products. `Rates.supported` is the strict
flag: True where every product the render reads covers the pixel, the speckle
field included. `Rates.static_supported` is the same flag without the speckle
field, so `static_supported & ~supported` marks the pixels that lack only the
drift model; None means the record does not distinguish the two, and a reader
falls back to `supported`. Terminal statistics read `supported` alone. A
renderer may offer, on request, to keep the static light where only the field
is missing; such a record carries both flags beside its values, and the excess
it holds there is the field's stored samples, zero-filled, under the field's
own reconstruction. For reconstructions of finite reach (nearest, linear and
cubic) that excess is exactly zero beyond the field's footprint grown by the
margin `coverage` uses; `cubic_spline` and `band_limited` fields carry no such
bound. A field whose array is wider than its data (values on a list of pixels,
zero elsewhere) says so through `data_mask()`, and
`coverage(..., valid=mask, reconstruction=..., measure=...)` then refuses every
pixel whose read reaches a cell without data. A mask is accepted only for
reconstructions of finite reach.

The coronagraph slot is the image capability only: a frame, a bandpass and the
image methods above. Summary curves are a separate characterization record,
`PerformanceCurves`: throughput, core area, stellar leakage fraction, leakage
density, raw contrast, `iwa_lod` and `data_extent_lod`. A provider that stores a
record hands it out as data, and `record.evaluate("throughput", separation_lod)`
is the one read. A record holds data from its first to its last sample and
while the aperture fits inside `data_extent_lod`; `record.supported(separation_lod)`
reports exactly that. Beyond the samples `evaluate` only continues the end
segments of its interpolant, so a consumer gates on `supported` and treats the
rest as unsupported, never as a measurement. `HalfMaximum` and `Circular` are the aperture rules a record is
built for; import them from `optixstuff`.
`MultiBandCoronagraph` selects the first declared bandpass covering the wavelength.
Coronagraph timestamps use `time_d`, days from the scene epoch; exposure
durations remain seconds. A speckle field runs on its own clock: its methods
take `elapsed_s`, seconds since its clock origin, and `field.elapsed_s(time_d)`
converts scene days.

### Linear speckle fields

Subclass `LinearSpeckleField` and implement `coefficients(*, elapsed_s)`; it
never reads the static host `epoch_d`. Construct a `FocalResponse` with the
complex nominal amplitude density `e_nom`, sensitivity density `G`, native
`lod` grid, unocculted input energy and reference wavelength. The shared law
uses `response.per_pixel()` and returns the excess
`[2 Re(conj(e_nom) G eps) + |G eps|^2] / input_energy`, with `G` scaled by
`reference_wavelength_nm / wavelength_nm`.

`realize(wavelength_nm=..., elapsed_s=...)` returns an `Image` on the field's own
grid, with `Measure.integral()`, `stellar_flux_fraction` and `band_limited`
metadata; the image is zero past its grid. Wavelength arrays, including quadrature nodes `(W, Q)`, become leading
axes. Each native lambda/D coordinate uses the node wavelength: convert with
`image.grid.to_arcsec(node_nm)` before resampling that node onto a detector.

`broadened(quadrature=..., elapsed_s=...)` averages realized nodes at fixed native
lambda/D coordinates, normalizing the nm weights to sum to one per band.
Detector-band images instead require resampling and spectral weighting at each
node before integration. `realize_average(..., exposure_s=..., start_elapsed_s=...)`
retains its midpoint time-average meaning. Enable JAX x64 for deep contrast.
With a nonzero `epoch_d`, `elapsed_s(time_d)` refuses a time that is not
binary64. Nonlinear replay models
continue to implement `AbstractSpeckleField` directly.

### Detector chain

Readers supply `Rates` tagged `"photon"`, in photons/s/nm at shared quadrature
nodes. The detector converts them to `Rates` tagged `"electron"`, with spectral
QE and survival applied once, before integration. The observer owns the frame plan.

```python
import jax
import jax.numpy as jnp
from optixstuff.spectral import Band, Quadrature
from optixstuff import Detector, Rates, frames_for_time

detector = Detector(pixel_scale_arcsec=0.01, shape=(1, 1), qe=0.9)
quadrature = Quadrature.build([Band(500.0, 600.0)], detector, order=3)
rates = Rates(quadrature, "photon", planet=jnp.ones((1, 3)))
electrons = detector.electrons(rates)
plan = frames_for_time(time_s=600.0, frame_time_s=300.0)
mean, variance = detector.mean_and_variance(electrons, plan)
counts = detector.draw(jax.random.key(0), electrons, plan)
```

The six source fields retain their names throughout the chain. Image readers
use `(W, Q, ny, nx)` integrands; aperture readers use `(W, Q)`. The detector
returns `(W, *spatial)` electrons/s and count moments. See the
[detector contract](https://optixstuff.readthedocs.io/en/latest/explanation/detector_models.html)
for noise parameters, gain statistics, and readout overlap.

### Ecosystem position

```mermaid
flowchart TB
    physopt["<b>Physical optics</b><br/>dLux / HCIPy / PROPER<br/>E-fields -> PSFs"]
    provider["<b>Image provider</b><br/>PSF interpolation"]
    optix["<b>optixstuff</b><br/>Telescope / Coronagraph / Detector / Instrument<br/>Throughput chains / QE / Noise rates"]
    jaxedith["<b>jaxEDITH</b><br/>Analytic aperture rates"]
    corono["<b>coronagraphoto</b><br/>2D image simulation<br/>Multi-epoch scenes"]
    coronachrome["<b>coronachrome</b><br/>Lenslet-IFS dispersion<br/>Spectral extraction"]

    physopt -- PSF tables --> provider
    provider -- AbstractCoronagraph --> optix
    optix --> jaxedith
    optix --> corono
    optix --> coronachrome
```

## Installation

```bash
pip install optixstuff
```
