Metadata-Version: 2.4
Name: gratinglab
Version: 0.3.16
Summary: Open platform for diffraction grating groove metrology and efficiency analysis
Author: Jake McCoy, Aditi Gangadharan
License-Expression: BSD-3-Clause
Project-URL: Homepage, https://github.com/jamccoy/gratinglab
Project-URL: Changelog, https://github.com/jamccoy/gratinglab/blob/master/CHANGELOG.md
Keywords: diffraction,grating,diffraction grating,diffraction efficiency,optics,rcwa,integral method,spectroscopy,afm,metrology,blaze,groove profile,ultraviolet,infrared,x-ray
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Physics
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Topic :: Scientific/Engineering :: Visualization
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.26
Requires-Dist: scipy>=1.11
Requires-Dist: pydantic>=2.6
Requires-Dist: endstation>=0.7.1
Requires-Dist: threadpoolctl>=3.1
Provides-Extra: dev
Requires-Dist: pytest>=9.2; extra == "dev"
Requires-Dist: pytest-qt>=4.5; extra == "dev"
Requires-Dist: matplotlib>=3.8; extra == "dev"
Requires-Dist: pandas>=2.1; extra == "dev"
Requires-Dist: ruff>=0.17; extra == "dev"
Provides-Extra: gui
Requires-Dist: matplotlib>=3.8; extra == "gui"
Requires-Dist: PySide6-Essentials!=6.12.0,>=6.7; python_version < "3.12" and extra == "gui"
Requires-Dist: PySide6-Essentials>=6.7; python_version >= "3.12" and extra == "gui"
Requires-Dist: endstation[qt]>=0.7.1; extra == "gui"
Provides-Extra: metrology
Requires-Dist: matplotlib>=3.9; extra == "metrology"
Provides-Extra: refractiveindex
Requires-Dist: pyyaml>=6; extra == "refractiveindex"
Provides-Extra: mut
Requires-Dist: mutmut<3.3,>=3.2; extra == "mut"
Dynamic: license-file

# gratinglab

[![PyPI](https://img.shields.io/pypi/v/gratinglab?cacheSeconds=3600)](https://pypi.org/project/gratinglab/)
[![Python](https://img.shields.io/pypi/pyversions/gratinglab?cacheSeconds=3600)](https://pypi.org/project/gratinglab/)
[![tests](https://github.com/jamccoy/gratinglab/actions/workflows/test.yml/badge.svg)](https://github.com/jamccoy/gratinglab/actions/workflows/test.yml)
[![License: BSD-3-Clause](https://img.shields.io/badge/license-BSD--3--Clause-blue)](https://github.com/jamccoy/gratinglab/blob/master/LICENSE)

**[PyPI](https://pypi.org/project/gratinglab/)** · **[Documentation](https://github.com/jamccoy/gratinglab/wiki)** · **[Changelog](https://github.com/jamccoy/gratinglab/blob/master/CHANGELOG.md)** · **[Releases](https://github.com/jamccoy/gratinglab/releases)** · **[Issues](https://github.com/jamccoy/gratinglab/issues)**

gratinglab is a Python package for measuring the groove profiles of diffraction
gratings from atomic force microscope (AFM) scans and for computing the diffraction
efficiency of a grating from such a profile.

The AFM metrology is the part of the package used day to day. It measures blaze angles
from a scan, averages the grooves into a single profile, reports how much that profile
varies down the scan, corrects for the shape of the AFM tip where the data allow it,
and exports the averaged groove as a boundary profile. The three rigorous
efficiency solvers left experimental status in 0.3, after agreeing with one
another and with measured efficiencies from a grating whose groove was also
measured by AFM (the TASTE comparison in `docs/findings.md`). Their known limits
are stated in the table under Status.

Rigorous methods for computing grating efficiency are well established, and open codes
exist for several of them, although each carries its own conventions and
normalizations. gratinglab is intended to fill two gaps that remain: running the same
physical problem through several methods so that their results can be compared
directly, and starting that problem from a measured surface rather than an idealised
one. To this end, the physical problem and the numerical method are kept separate. A
`Problem` describes the grating and can be saved to a file, and the same `Problem` is
passed to every solver, so any difference between their results is attributable to
the methods themselves.

```
AFM scan  ->  BoundaryProfile   (gratinglab.metrology)
                      |          measured period, averaged groove, facet fit
                      v
Problem       (period + profile + materials; no solver fields)
Illumination  (wavelength + direction + polarization)
                      |
                      v
Solver (plugin)  ->  Result (+ provenance)
```

The metrology and the solvers are distributed as one package so that no information is
lost between them. A plain boundary file records the groove shape but not the grating
period, which must then be entered again by hand. `BoundaryProfile.to_problem()`
carries the period measured from the scan, together with the fitted facet angle. A
profile can be saved with that information intact in gratinglab's own `.json` format
(`gratinglab.io.boundary.write_boundary_json`); reading it back gives the same
problem, and "Load boundary profile" in the efficiency window takes the period from
it. The Boundary tab of the metrology window exports `.json`, `.csv`, or a `.ggp`
boundary file for PCGrate, and its "Send to efficiency window" button opens the groove
in the efficiency window directly.

```python
from gratinglab.metrology.boundary import build_boundary_profile

profile = build_boundary_profile(data, scan_x_size, settings)
problem = profile.to_problem(coating="Au", blaze_angle=29.5)
```

## Status

The project is at a pre-alpha stage. The AFM metrology is the more mature of its two
parts. On the efficiency side, the scalar and integral solvers, the comparison and
convergence harnesses and the materials layer work end to end. They are checked
against closed-form results, published benchmark tables, energy balance and
reciprocity. Efficiencies are absolute when a coating is named, using an optical
constant table supplied by the user (see Install). Since 0.2.0 two more rigorous
backends sit beside them, both written in-house: a rigorous coupled-wave analysis
(RCWA), which also models coated gratings through conformal layers, and the
C-method (Chandezon). Each has a tab in the efficiency window since 0.2.1.

The three rigorous solvers are out of experimental status as of 0.3. On the
December 2018 TASTE campaign (296 measured efficiencies, computed on the
grating's own AFM groove), the integral method, the C-method and RCWA agree with
one another to 2e-4 RMS and with the measurement to 0.038, so the 0.038 residual
does not come from the solvers. Two limits apply. The C-method refuses a wall too
steep for its truncation. On a measured polygon under
`conductivity="tabulated"`, the integral solver needs `profile_smoothing="auto"`
for a correct absorption. It is opt-in because it moves finely sampled profiles
at long wavelengths; with the default the polygon is solved as given, and the
energy-balance warning names the option when it fires. A tightly rounded valley
is a known limitation.
The scalar solver is an approximation and is described as one.

**Every modelling method here still needs verification**, the rigorous ones
included. The checks in the table below show that each method reproduces the
cases it was checked on; they do not show that it is right on yours. Nor does
agreement between the solvers: they share the problem specification, the optical
constant tables and the angle conventions, so a mistake in any of those moves all
of them together and no comparison between them can see it. A number from any
solver is evidence to be checked against measurement or a published benchmark
before it is relied on.

## Scope

The metrology (`gratinglab.metrology`) reads AFM scans: Bruker/Veeco Nanoscope `.spm`
files, Asylum Research `.ibw` files (not yet checked against a file from an
instrument), or Gwyddion text exports. It produces blaze angles for each groove with statistics
over groups of scan rows and a correction for the correlation between those groups,
an averaged groove normalised to one period, and statistics describing how that
groove varies between horizontal swaths of the scan. It can also undo the broadening
introduced by the AFM tip where the tip reached the surface, and it marks the regions
the tip could not reach instead of estimating them.

It also reads Zeiss SmartSEM electron micrographs (`metrology.io.sem`), with the
instrument's own pixel size, stage tilt and foreshortening. A cross-section is the
one groove measurement with no tip to correct for, and the only one that can see an
undercut or measure the width of a crest. Tracing a groove off a micrograph into a
profile is not written yet.

The efficiency side comprises the problem specification, the groove profiles
(blazed, lamellar, sinusoidal, trapezoidal with a sidewall angle and corner radius,
and any measured profile), the solvers, the comparison and convergence harnesses,
the materials layer, and a calculation of the resolving power implied by the number
of grooves measured.

The aim is gratings in general: reflection and transmission, metallic and
dielectric, bare and coated, from X-rays to the infrared. Any half-cone angle γ is
supported, from 90° (in-plane, classical) through general conical incidence to
extreme off-plane at grazing incidence (γ of a degree or two). That last is the soft
X-ray spectroscopy regime, where the integral method is the established approach and
general-purpose RCWA codes are least reliable. `Illumination.classical`,
`Illumination.conical(theta, phi)` and `Illumination.offplane(graze, azimuth)` all
build the same object, and every solver accepts any of them. Which method serves which regime, and what is not yet covered
(multilayer stacks checked against an independent code, for one), is mapped in
[`docs/roadmap.md`](https://github.com/jamccoy/gratinglab/blob/master/docs/roadmap.md#regimes-and-the-methods-that-serve-them).

The method backends, in order of development:

| Method | Status |
|---|---|
| Scalar (Kirchhoff, x-ray blaze form) | an approximation; checked against closed-form results |
| Integral method (boundary integral, conical, undercut-capable) | perfect and finite conductivity (`conductivity="tabulated"`, Goray & Schmidt 2010), absolute efficiencies with the absorbed fraction recorded; a corner-graded mesh for profiles with corners (`corner_grading=4`, the default; `0` is the equal-arc mesh), under either boundary condition; checked against published benchmark tables (Maystre & Popov; Goray & Schmidt), energy balance and reciprocity |
| RCWA (in-plane, conical, off-plane; Li factorization, S-matrix, layer stacks) | lamellar gratings exact and other profiles staircased, transmitted orders, and coatings through conformal layers (`Problem.layers`); checked against Fresnel, the Airy film formula, reciprocity, the integral solver, and published lamellar values (Granet; Lalanne & Hugonin; Gralak; Goray & Schmidt's conical tables). Not yet checked: staircase accuracy in metallic TM, and layers of a second material against an independent code |
| C-method (Chandezon) | perfect conductor in any mount, and one interface into an absorbing or lossless material, conical and coupled; checked against Goray & Schmidt's Table 3, Fresnel and the integral solver. Refuses vertical facets, undercuts, and walls too steep for the scan (the harmonics a wall needs grow with its slope times P sin γ / λ; measured against the integral solver, see the method note); converges slowly on sawtooth corners, and loses precision at high truncation on profiles deeper than about half the period, both reported in provenance. No coatings |

The comparison harness also accepts an efficiency table already computed by an
external program as one of its methods, so that comparison plots can be made without
a licence for the program that produced the reference data:

```python
reference = read_scan("run.txt", method="integral")
align(sweep(problem, illumination, wavelengths, ["scalar", reference]))
```

Because the file does not record the physics behind it, the caller states which method
produced an imported table. Comparison legends then name the method, for example
`scalar vs integral`, while `Provenance.version` records the program and version that
generated the file.

### Resolving power from a measured surface

A scan records the number of grooves it covers, so resolving power can be computed
without entering anything by hand:

```python
problem = profile.to_problem(coating="Au")     # n_grooves = the grooves averaged
resolving_power(problem, illumination, wavelength=2.0, order=3).r
```

The resolving power follows from the Rayleigh criterion as `R = |m|·N`, and
`line_profile` gives the line shape for a finite number of grooves from which that
result is derived. A problem whose `n_grooves` is not set is refused rather than
treated as having infinitely many grooves. Resolving power that includes
groove-placement errors is not implemented yet, and the ideal formula is not offered
in its place.

### Correcting for the AFM tip

An AFM image is the true surface dilated by the shape of the tip.
`tip_correction='erosion'` reverses this dilation where it can be reversed (Villarrubia
1997) and reports a certainty map showing where it cannot. The tip is modelled as a
spherical apex on two flanks whose angles may differ, so a pyramidal probe such as
Bruker's ScanAsyst-Air can be represented. No method can recover the bottom of a
trough the tip did not enter, and the correction leaves such regions as upper bounds
instead of filling them in.

On one real scan, the blaze angle implied by the groove depth and the fitted facet
angle disagree by 7.6°.
Erosion with the probe at its nominal radius recovers none of that difference, and
reproducing it by simulation requires an apex worn to about 80 nm, which excludes the
nominal tip as the cause
([findings](https://github.com/jamccoy/gratinglab/blob/master/docs/findings.md)).

## Install

```bash
pip install gratinglab                       # solvers only: numpy, scipy, pydantic
pip install "gratinglab[metrology]"          # + AFM readers and the boundary pipeline
pip install "gratinglab[gui]"                # + the Qt windows
pip install "gratinglab[refractiveindex]"    # + refractiveindex.info tables
```

With [uv](https://docs.astral.sh/uv/), the same extras work:

```bash
uv pip install "gratinglab[refractiveindex]"    # into the active environment
uv add gratinglab                               # into a uv project
uv tool install "gratinglab[gui]"               # gratinglab-gui as a standalone command
```

From a checkout, use `pip install -e ".[dev,gui,metrology,refractiveindex]"` instead.

Neither the package nor its repository carries optical constant tables, so absolute
efficiencies, and the `coating="Au"` examples above, require tables supplied by the
user. A library is a directory of such tables, one
material per file, each named after its material:

| File | From | Range |
|---|---|---|
| `Pt.txt` | a [CXRO](https://henke.lbl.gov/optical_constants/) export | x-ray |
| `Pt.yml` | a [refractiveindex.info](https://refractiveindex.info) file, renamed from its author's name | ultraviolet to infrared |
| `Pt.ari` | a PCGrate table | whatever it covers |

Saving one as `~/.gratinglab/materials/Pt.yml` makes `coating="Pt"` available.
`GRATINGLAB_MATERIALS` points to a different directory, and
`materials.from_cxro_file(path)` or `from_refractiveindex_file(path)` reads a single
file without a library. The YAML files require the `refractiveindex` extra.
[`SOURCES.md`](https://github.com/jamccoy/gratinglab/blob/master/src/gratinglab/materials/data/SOURCES.md)
explains why none are distributed.

Without a table, `coating="typical:Au"` (or `typical:SiO2`, `typical:C@2.0` with
a density) uses an approximate X-ray model built from physical facts, 30 eV to
30 keV, for Au, Pt, Ni, C, Si and O. Where it cannot answer for its index, near
an absorption edge or at low energy, the result's provenance says so.
[`docs/typical-materials.md`](https://github.com/jamccoy/gratinglab/blob/master/docs/typical-materials.md)
has the model and how far it agrees with real tables.

The core install does not include a plotting stack, so a user who only runs the solvers
does not install one. A subpackage that needs an optional extra names it when it is
missing, instead of failing with a bare `ModuleNotFoundError`.

Apart from numpy, scipy and pydantic, the only dependency is
**[endstation](https://pypi.org/project/endstation/)**
([source](https://github.com/jamccoy/endstation)), a library of shared components for
desktop scientific applications by the same author, which gratinglab is built on.
gratinglab uses its guards for optional extras (the messages described above), form
validation, Qt layout sizing, test helpers, and the tools that build the icon and the
macOS application and publish the wiki. The core of endstation has no dependencies of
its own, so it adds nothing to a solver-only install; its Qt components are installed
only with the `gui` extra.

### Where the measurement data lives

AFM scans are not included in the repository, because they are research data. The
same applies to the private reference corpus of efficiency tables:

| Data | Environment variable | Default |
|---|---|---|
| AFM scans | `GRATINGLAB_AFM_DIR` | `~/Documents/Research/afm_scans` |
| Reference efficiency tables | `GRATINGLAB_REF_DIR` | `~/Documents/Research/diffraction_efficiency` |

Tests that need either are skipped when it is absent, so the suite passes on a fresh
clone. Most of the metrology tests do not need it: they run against a committed
synthetic scan of a grating with known geometry
(`tools/metrology/make_synthetic_scan.py`), which also allows a test to check that the
pipeline recovers the period and blaze angle used to generate it.

## GUI

```bash
.venv/bin/python -m pip install -e ".[gui,metrology]"
gratinglab-app                 # the chooser: one place to start, every window
gratinglab-gui                 # straight to geometry, solvers, comparison
gratinglab-geometry            # straight to the geometry, with no solver
gratinglab-metrology-gui       # straight to AFM import, blaze angles, boundary profiles
```

`gratinglab-app` opens a chooser for the three windows, which stays open as the main
menu while you work, as Gwiddion's toolbox does; closing it closes every window. Each
window has a **Go** menu that switches to another window or back to the chooser
(`Ctrl+Shift+M`). There is one window of each kind, so opening one that is already
open brings it forward. The chooser has the same
**View → Theme** and **Help** menus as the windows, so the theme, which applies to the
whole application, and the theory pages can be reached without opening a window
first. While the chooser is on screen it imports both windows on a background thread,
so the first window opens in about a fifth of a second; the matplotlib and scipy
imports otherwise take several seconds. `gratinglab-gui`, `gratinglab-geometry` and
`gratinglab-metrology-gui` open one window directly.

The geometry window (**Explore a geometry**) is the efficiency window's geometry form
and Grating Geometry tab on their own: the 3D view, the cross-section and the sin β
ladder, redrawn as the form changes, with no solver. **Send to efficiency window**
(`Ctrl+E`) copies its form into the efficiency window, opening it if need be, and
solves nothing; the efficiency window keeps its own Grating Geometry tab.

The windows are built with Qt (PySide6), so `pip install "gratinglab[gui]"` needs no
system toolkit to be installed first. PySide6 is licensed under the LGPLv3 and is an
optional, dynamically linked extra, so this package remains under the BSD-3 licence.

The grating geometry is set in a dock on the left of the efficiency window (Ctrl+G
hides it), and the window has one tab for each task:

- **Grating Geometry:** a rotatable 3D view of the diffraction cone, in which every wave
  vector is drawn as an exact unit vector. In the reference off-plane geometry the
  orders separate in azimuth rather than in polar angle (93.8° of azimuthal spread at
  0.0° of polar spread), so the view looking down the cone axis, zoomed to the cone rim,
  makes them distinguishable at true scale. The grazing angle γ is not exaggerated: the
  view is orthographic and every zoom, pan and roll is uniform, so every angle in it
  stays true, and the magnification is stated beside it. Drag to orbit, Shift+drag to
  pan, Alt+drag to roll, and the wheel zooms about the cursor. Alongside it are the cross-section in the dispersion plane, a
  `sin β` diagram that includes the evanescent orders, and the groove profile. The view
  updates as values are typed.
- **Scalar (Kirchhoff):** the scalar solution, the efficiency of each order with
  per-order visibility, and a provenance panel that lists every validity warning, the
  summed-efficiency check, and whether convergence was demonstrated. A result that
  violates energy conservation is flagged. "Check convergence…" runs a convergence
  sweep and reports the coarsest setting that meets the criterion, with a progress bar
  and a Cancel button. Because solvers report progress for each wavelength, Cancel
  stops the computation itself.
- **Integral method:** the rigorous backend, with the same panel and provenance, its
  own boundary-condition control (perfect conductivity or tabulated optical
  constants) and a **Corner mesh** control: off, or a grading order that clusters
  the boundary nodes at the profile's corners, which a cornered profile needs to
  converge quickly (4, the default). It takes minutes where the scalar solver takes milliseconds, so the
  window opens on the scalar solver and this tab computes only when asked to.
- **Compare:** the geometry solved by several solvers at once, each with the
  settings on its own tab. Efficiency is drawn with order by colour and solver by
  line style, above each solver's difference from a chosen reference, on a linear
  or log scale. A solver that cannot model the problem, such as the C-method on a
  lamellar groove, is named with its reason and the others still run.

  ![The Compare tab: four solvers on a 40 nm gold sinusoid at 80 degrees, 2 to 6 nm](https://raw.githubusercontent.com/jamccoy/gratinglab/master/docs/images/compare-tab.png)

  *Four solvers on one problem: a 40 nm gold sinusoid, 5% deep, at 80° incidence,
  unpolarized. The lower panel is each solver's difference from the C-method on a
  log scale: the integral method and RCWA agree with it to within 2e-6, and the
  scalar one is off by up to 0.018.*
- **Setup:** the material library, showing which optical constants are installed, the
  range each covers, where each came from, and how to add others. The coating itself is
  chosen in the geometry dock, because it is a `Problem` field, like the period, and the
  same `Problem` is used by every tab.

Each registered solver receives a tab generated from the solver registry, so a
new backend appears in the window once it is registered.

The **Help** menu contains the theory pages, rendered with typeset equations and
tables. It is on every window, including the metrology window, whose results are
reported in the angles the conventions page defines and whose analysis
`theory/metrology.md` describes.
**Help → About gratinglab** names the authors and states which version is running and
when it was released, so a bug report can say which copy it came from.
**View → Theme** switches between System (following the operating system), Light,
Dark, Solarized Light, Solarized Dark and High contrast; the choice is remembered and
applies to the metrology window too. Diffraction orders are coloured by sign, cool for
negative and warm for positive, with each order's colour shown beside it in the order
list.

A macOS `.app` is built with `python tools/apps.py bundle --app gratinglab`, on macOS
13 or later, the minimum supported by the PySide6 wheels. That is one `gratinglab.app`
opening the chooser; `--app metrology` and `--app efficiency` build bundles that open
one window directly. `--dest ~/Applications` puts it where Finder will list it. The
bundle is a stub that execs the console script in this checkout's virtualenv, not a
frozen application, so it is not portable to another machine; `python tools/apps.py
check --app gratinglab` reports when that virtualenv has moved. `python tools/apps.py
icon --app gratinglab` regenerates the icon from the artwork in `gratinglab.gui.icon`.

## Documentation

| Document | Contents |
|---|---|
| [`docs/roadmap.md`](https://github.com/jamccoy/gratinglab/blob/master/docs/roadmap.md) | The current state of the project, planned work and open questions; the place to start |
| [`docs/conventions.md`](https://github.com/jamccoy/gratinglab/blob/master/docs/conventions.md) | The normative definitions: signs, units, normalizations, and errata in the references |
| [`docs/theory/scalar.md`](https://github.com/jamccoy/gratinglab/blob/master/docs/theory/scalar.md) | The derivation of the scalar solver, its closed-form results and its limits |
| [`docs/theory/integral.md`](https://github.com/jamccoy/gratinglab/blob/master/docs/theory/integral.md) | The boundary-integral solver: conical formulation, perfect and finite conductivity |
| [`docs/theory/metrology.md`](https://github.com/jamccoy/gratinglab/blob/master/docs/theory/metrology.md) | The assumptions of the AFM pipeline, what it measures and what it does not, including what tip erosion can recover |
| [`docs/typical-materials.md`](https://github.com/jamccoy/gratinglab/blob/master/docs/typical-materials.md) | The X-ray index model used without a table, what it is checked against, and its measured accuracy |
| [`docs/findings.md`](https://github.com/jamccoy/gratinglab/blob/master/docs/findings.md) | Empirical results, each with the evidence for it |
| [`docs/references.md`](https://github.com/jamccoy/gratinglab/blob/master/docs/references.md) | The literature each part of the package is based on |
| [`docs/mutation-testing.md`](https://github.com/jamccoy/gratinglab/blob/master/docs/mutation-testing.md) | What is mutated, what is not, and how to interpret a surviving mutant |
| [`benchmarks/corpus.toml`](https://github.com/jamccoy/gratinglab/blob/master/benchmarks/corpus.toml) | Geometry for the reference corpus, most of it recovered from the data |

`conventions.md` should be read before writing a solver or reporting a bug involving a
sign. In brief: the time convention is `exp(-iωt)`, the complex refractive index is
*n* = n′ + ik, the grating equation is `sin α + sin β_m = mλ/(p sin γ)`, efficiencies
are absolute, lengths are in nm, and angles are in degrees at the API boundary.

Each solver has a theory page stating its assumptions, its derivation in the notation
of the code, and the conditions under which its results cease to be reliable.

The [wiki](https://github.com/jamccoy/gratinglab/wiki) is a published copy of `docs/`
and of the metrology window's own help pages, which appear there with an "AFM" prefix.
Changes are made to the sources in the repository and then republished:

```bash
git clone https://github.com/jamccoy/gratinglab.wiki.git ../gratinglab.wiki
.venv/bin/python tools/publish_wiki.py --wiki ../gratinglab.wiki   # then review and push
```

## Development

```bash
.venv/bin/python -m pip install -e ".[dev,gui,metrology,refractiveindex]"
.venv/bin/python -m pytest
.venv/bin/ruff check .
```

A full run is about 2750 tests and some minutes of every core, most of it
thousands of small solves rather than a few long ones. For the loop before a
push there is a quicker pass, which leaves out the tests that build a real Qt
window, caps the BLAS pools at one thread and runs at a lower priority:

```bash
.venv/bin/python tools/test_fast.py
```

It takes pytest's own arguments (`-k`, `-x`, a path), and `--gui` puts the Qt
tests back. The deselection is a marker, so plain pytest can do it too:

```bash
.venv/bin/python -m pytest -m "not gui"
```

Neither replaces the full suite, which CI runs on four platform and version
legs; they are for keeping an older machine usable between pushes.

The test suite relies on three practices in particular:

- **Physical self-checks.** `checks.check_reciprocity` and `checks.check_energy_balance`
  test properties that any correct model must satisfy, independently of how the
  solver computes its result. They require no reference data and apply to every
  backend.
- **Demonstrated convergence.** `convergence.check_convergence` varies whatever a
  solver declares as its accuracy parameter and reports the coarsest setting that
  meets the criterion, or reports that none did. It requires three consecutive values
  to agree, because the quadrature error of a blazed profile does not decrease
  monotonically, so a single agreement can be coincidental
  ([findings](https://github.com/jamccoy/gratinglab/blob/master/docs/findings.md#quadrature-error-is-not-monotone-in-the-number-of-points)).

  ```python
  report = check_convergence(scalar, problem, illumination, wavelengths)
  report.converged_at           # 4096 -- what a production run should use
  report.scan.provenance.converged   # True
  ```
- **Mutation testing.** The suite is run against deliberately altered copies of the
  physics code to check that the changes are detected. Coverage shows that a line was
  executed; mutation testing shows whether any test would fail if that line were wrong.
  Both runs so far have found real gaps in the tests; see
  [findings](https://github.com/jamccoy/gratinglab/blob/master/docs/findings.md#mutation-testing-found-a-real-gap)
  and [docs/mutation-testing.md](https://github.com/jamccoy/gratinglab/blob/master/docs/mutation-testing.md)
  for how to run it.

  ```bash
  .venv/bin/python -m pip install -e ".[mut]"
  .venv/bin/mutmut run
  ```

## License, copyright and reuse

gratinglab is released under the
[BSD 3-Clause License](https://github.com/jamccoy/gratinglab/blob/master/LICENSE),
copyright (c) 2026 Jake McCoy. What follows is a plain summary for convenience; the
`LICENSE` file is what governs, and nothing here is legal advice.

**What you may do.** Use, modify and redistribute the code, in source or binary form,
for any purpose, including commercial use and inside closed-source work. There is no
copyleft obligation: software that imports gratinglab does not become BSD-licensed,
and you are not required to publish your modifications.

**What you must do.** Retain the copyright notice, the list of conditions and the
disclaimer when you redistribute — in the source for a source distribution, and in the
documentation or other accompanying materials for a binary one. The third clause
separately forbids using the author's or contributors' names to endorse or promote a
derived product without prior written permission.

**What you do not get.** The software is provided as is, without warranty of any kind,
and the author is not liable for any use of it. The efficiency solvers are young and
validated on few gratings (see Status).

Contributions are accepted under the same licence. A pull request is taken as agreement
that the contribution may be distributed under BSD-3-Clause.

### Citing it

[`CITATION.cff`](https://github.com/jamccoy/gratinglab/blob/master/CITATION.cff) is
the citation of record, and GitHub's "Cite this repository" renders it as BibTeX or
APA. It names the version, which is checked against `gratinglab.__version__` on every
release, so a citation generated from it points at the code that produced the number
rather than at whatever is current. If a result depends on a solver backend or on an
optical constant table, cite those too: the method's own reference is in
[`docs/references.md`](https://github.com/jamccoy/gratinglab/blob/master/docs/references.md),
and `Provenance` records what a run actually used.

### The licences you inherit by installing it

| Installed with | Package | Licence |
|---|---|---|
| core | numpy, scipy | BSD-3-Clause |
| core | pydantic | MIT |
| core | [endstation](https://pypi.org/project/endstation/) | BSD-3-Clause |
| `[gui]`, `[metrology]` | matplotlib | PSF-based, BSD-compatible |
| `[gui]` | PySide6-Essentials | LGPL-3.0 |
| `[refractiveindex]` | PyYAML | MIT |

A solver-only install is permissive throughout. The `gui` extra installs PySide6,
which is LGPL-3.0. PyQt6 is not used because its GPL licence would extend to code
that imports it.
Importing an LGPL library dynamically does not change the licence of what you write,
but redistributing a bundled application that ships Qt inside it brings LGPL
obligations for that component — chiefly your users' right to substitute their own
build of it. Running the window yourself, or installing either extra from PyPI, raises
no such question.

### What this licence does not cover

**Optical constant tables.** None are distributed with the package or kept in the
repository: the suite runs on an invented gold-sized table of its own, and its
refractiveindex.info reader fixtures are files that site dedicates CC0. A table you
add is governed by the terms of whoever published it, not by this licence. CXRO states
no terms at all, and a table exported from another program carries whatever that
program's terms attach to it.
[`SOURCES.md`](https://github.com/jamccoy/gratinglab/blob/master/src/gratinglab/materials/data/SOURCES.md)
records where each kind of table comes from.

**Measurement data.** AFM scans and the reference efficiency corpus are the research
group's data and are deliberately absent from the repository, as described above under
Install. The code is open; the measurements it was validated against are not ours to
publish, and the documentation says which results are therefore not reproducible from
a bare clone.
