Skip to content
opticsWolfPublic

About

A high-performance optical engine utilizing a Scattering Matrix algorithm for stable simulation of light in stratified media.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Navette - Weaving thin-film systems that perform

Navette crates.io PyPI Rust 1.88+ Python 3.12+ License: LGPL-3.0-or-later CI

Navette is a high-performance, physically rigorous 1D optical engine designed for the simulation of light propagation in stratified media. Built on a modern Scattering Matrix (S-matrix) architecture, it offers a numerically stable and vectorized alternative to traditional Transfer Matrix Methods (TMM).

1. Unconditional Numerical Stability

Traditional TMM suffers from numerical divergence (exponentially growing evanescent waves) when dealing with thick layers or highly absorbing materials. Navette utilizes the Redheffer Star Product to propagate scattering matrices, ensuring that all matrix elements remain bounded and physically meaningful, regardless of layer thickness.

2. High-Concurrency Performance

As a Principal Performance Engineer, you need tools that scale. Navette is built for speed:

  • Parallel Execution: Utilizes Rust + rayon data-parallelism across wavelengths/angles to saturate all available CPU cores.

  • Vectorized Engine: Operations are performed across the entire (wavelength × angle) coordinate space in a single pass, eliminating Python's loop overhead.

  • Memory Efficiency: Collapses multi-layer stacks into a compact global S-matrix to minimize cache misses.

Measured, not claimed. All numbers below are --release builds on a 32-core Windows box, taken by the scripts named beside them under validation/benches/; each of those scripts refuses to run against a debug build (see the profile note under Getting started). "vs numba" compares against the numba reference implementation this engine replaced.

What Measured Script
Full observable mask, 40 lambda x 3 theta, 5 layers (complex amplitudes + dispersion) 0.164 ms median -- ~1.4 us per point for every channel bench_backside_speed
Rigorous 12-channel request, 6 layers, 20 000 / 60 000 points 1.68 ms / 4.02 ms, i.e. 1.1-1.8x the numba kernel bench_core_engine_scaling.py
Photometric 4-channel request, same grid sizes 1.50 ms / 3.70 ms bench_core_engine_scaling.py
pchip interpolation, 1 M points 1.22 ms (1.2 ns/pt) vs 1.59 ms numba; accuracy identical (~1e-14 vs analytic) on both sides 1dinterpol_test_bench
dE76 / dE94 / CMC / DIN99 / dE2000 batches 23-36x faster than the reference, at exact parity with colour-science including black/white/near-black rows bench_validate_color
Weaver set_data / get_weaved / unweave_cached 1.5-7.8x the Python reference across small and mid grids navette_spectral_bench
Batch unweave_collection 1.15-2.29x faster than before R5.1; still the one path that can trail the reference at extreme key counts navette_spectral_bench
One LM thickness optimize (synthesis), with needle re-fold 2.1 ms, re-fold 9.1 % overhead bench_refold
One needle insertion, AR coating, 61 lambda, 4 -> 26 films scan 2.2-2.6 ms; LM re-optimize 19-66 ms -- the scan is ~4 % of an insertion bench_needle_insertion
Structure grid assert 0.9 us bench_grid_assert

Two caveats kept deliberately visible: small grids (under ~2 000 points) are dispatch-bound and still behind the numba kernel; and in needle synthesis the time goes to the thickness re-optimization after each insertion, not to the needle scan, so a faster scan would barely move a design run.

3. Partial Coherence Support

Real-world systems involve thick substrates — a 1 mm glass slide — where the path-length spread across the layer exceeds the source coherence length and the phase relation between its two surfaces is destroyed. Navette cuts the stack into maximal coherent runs at the layers you flag, uses the complex Redheffer star product inside a block and a real intensity star product across blocks (Katsidis & Siapkas 2002; Byrnes, arXiv:1603.02720). A flagged layer contributes only its attenuation τ = exp(−2·Im β).

  • Coherent blocks preserve phase for thin-film interference; incoherent joins switch to intensity propagation, so a macroscopic substrate stops producing the unphysical ringing that assuming perfect coherence gives it.

  • The flag goes on an interior row, and thickness is part of what it claims. Rows 0 and last are half-spaces — the block sweep never reads their flags, so flagging "the substrate" as the exit medium is a no-op and now says so. A thick substrate is an interior layer with a real thickness, flagged, between the films and the exit medium. The flag asserts decoherence, which needs the spread to exceed L_C = λ²/Δλ; in the UV–VIS–NIR that is roughly 50–100 µm. Flag something thinner and you get a warning quoting the source bandwidth that layer would need — a number you can check against your own source rather than a threshold somebody picked. The flag is still honoured either way: the thin incoherent limit is a legitimate thing to ask for, as long as it is what you meant.

  • Three coherence modes, and one of them refuses rather than guesses. FRONT_BLOCK (the default) is exact for intensities — Rs, Rp, Ts, Tp, A are correct totals over every incoherent echo — but its p–s cross channel comes from the first coherent block alone. On a flagged stack, the twelve observables that need that channel (Δ, DOP, S2/S3, the raw cross terms and the retardance, in reflection and transmission) would be a ratio of two different stacks, so the doors refuse them and name COHERENCY_MATRIX, which cascades the cross channel with the echoes. FULLY_COHERENT treats the whole stack as one block. With nothing flagged all modes agree bit for bit and nothing is refused.

  • Synthesis honours the flag, for fixed plates. The needle pipeline splits a design at every coherent: false film and joins the coherent blocks with the same intensity cascade the engine uses, so a coating on both faces of a substrate plate is designed against the light that really comes out. An incoherent film must be fixed (optimize: false, needle: false), and construction refuses one that is not, naming it. See Through a Thick Plate below for what such a run can and cannot target.

  • Checked against something that is not itself. The parity suite compares the engine to a port of the same algorithm, which pins the port rather than the physics. validation/review/incoherent_check.py uses three oracles that do not know how Navette works: the lossless-slab closed form R = 2R₁/(1+R₁) (1e-12), bit-identical reflectance from 10 µm to 3.7 mm, and the definition itself — a flagged answer IS the coherent answer averaged over one round-trip phase period (8e-17). The same average on the Stokes vector is what put numbers on the cross-channel refusal above.

4. Advanced Physics Modeling

Navette goes beyond simple Fresnel equations to provide research-grade accuracy:

  • Interface Roughness: Implements the Névot-Croce model, providing superior accuracy for high-frequency or X-ray reflectometry compared to standard Gaussian approximations.

  • Ellipsometric Rigor: Outputs (Ψ,Δ) parameters that strictly follow the Azzam & Bashara convention, ensuring direct compatibility with commercial ellipsometers (e.g., Woollam, Horiba).

  • Dispersion Models as Data: A material is a model name plus plain params — nineteen of them, from Konstant and Table (measured nk) through Cauchy / Sellmeier (each with an Urbach tail), Lorentz, Drude, DrudeLorentz, CodyLorentz, four ForouhiBloomer variants, TaucLorentz and UBF, to the free-form PointWise, Spline and BSplineEps (a Kramers-Kronig-consistent B-spline in ε₂). Six EMA mixing rules (Bruggeman, Maxwell-Garnett, Looyenga, Lichtenecker, Mori-Tanaka, power-law) compose them, and EMA specs nest, so a rough oxide on a mixed host is one spec rather than a preprocessing step. Oscillator models derive ε₁ from ε₂ by Kramers-Kronig, validated in validation/review/ against an analytic Lorentz oscillator and an independent pair-sampled principal-value quadrature — with the residual near resonance attributed, by an h-refinement study, to the FFT-KK grid rather than the quadrature. Optical gain is refused at every door: Im(n) < 0 is not representable on either path — the coherent one conjugates the propagation phase back to decay, so a gain layer returns the loss layer's answer with a positive absorptance — and the message says what to do if the sign is a provider convention rather than a mistake.

  • Guided Modes and Field Profiles: eigenmode_landscape scans |1/r(n_eff)|² over a complex effective-index box, find_eigenmodes locates the minima and Nelder-Mead refines them (a converged surface-plasmon mode reaches 1e-24 on the pinned stack), and field_profile returns normalised |E(z)| through the stack with per-layer boundaries. These kernels solve the whole stack as one coherent block by construction and do not consult incoherent_flags — a guided mode is a coherent-stack concept and there is no eigenmode to find across a partition — which every one of their docstrings now says, because every other method on the same object does honour the flags.

  • Differential Phase Observables: PDts/PDtp are first-class compute() keys — the transmitted phase with the equivalent incidence-medium layer subtracted (arg(t) − 2π·n(λ)·D·cosθ/λ), so a target on Δφ constrains what the coating adds, not the ambient's round trip. The reference index follows the wavelength (per-λ columns), keys emit the wrapped principal value in (−π, π], and a differential_phase(*, s_pol=True, p_pol=True) view returns both. Group delay over Δφ (GD/GDD with a differential target) carries the reference's own dispersion, and the synthesis merit's phase demands share the same derivation — the merit op point and the compute key agree bit for bit. Coherent stacks only, as with the dispersion keys.

5. Automated Coating Design

Navette doesn't just simulate — it synthesizes, with the classic needle method running natively on the same engine:

  • Needle Insertion: Probes every candidate position with an infinitesimal test layer and inserts real material where the merit function improves most — the Tikhonravov needle algorithm, merit-driven and target-aware.

  • Thickness Optimization: Levenberg-Marquardt refinement over free layers with bounds and clamping, interleaved with insertion passes and impact-ranked cleanup (merge, thin-layer removal, re-optimization).

  • Multi-domain Targets: One joint merit over spectral, angular, and CIE color demands — multiple angles, illuminants with own-white metamerism control, and per-target wavelength windows — all folded into the needle gradient with analytic chain-rule terms, so a single run designs for daylight and showroom light at once.

  • Polarization and Dispersion Targets: Besides intensity, absorptance, phase, differential phase, retardance (RetR/DeltaR) and colour, synthesis scores the front s/p intensity ratio, extinction ratio and diattenuation (RatioR/T, ExtR/T, DiattR/T), the ellipsometric Ψ (PsiR/T), the group delay and its ω derivatives (GDR/T, GDDR/T, TODR/T, FODR/T × s/p, in fs^n), and the Stokes vector and degree of polarization of the reflected or transmitted light for an input state (S0R…S3R, DOPR, S0T…S3T, DOPT, with stokes_input=(q1, q2, q3) on the target, partial polarization allowed). Each is checked against the engine's own observable at the same point (DiattR against Diattenuation_R, DOPR against DOP_R; the dispersion targets equal GD_R_s…FOD_T_p bit for bit), and each comes with an analytic LM Jacobian and an analytic needle fold, pinned against the merit slope. The full table of what can be targeted, on a coherent stack and through a plate, is measured in CI: docs/spectralweave-target-kinds.md.

  • One Design, Several Surroundings: A coating measured bare and then laminated is two optical problems with one set of films. run_needle(design={...}, environments=[...]) defines the films once, as a named design segment, and lists what sits around them in each environment; one optimization moves one set of thicknesses against every environment's demands at the same time, so the films cannot drift apart. Demands carry an environment= tag; an unknown name refuses, naming the roster, because scoring against the wrong surroundings looks like a physics result rather than a mistake. The needle sees all of them at once — each environment scans its own assembly and a site in the shared design is routed by parameter into a shared bucket, so the candidate that lands is the one that helps the joint merit, not the first environment. Cost is honest and linear: K environments means K assemblies and K solves per evaluation. The same design writes as a program document (design: / environments: sections) and compiles through the same compiler — the two spellings land on identical merit bits.

  • Through a Thick Plate: A substrate plate is a film of the design with coherent: false, optimize: false and needle: false; the films before it coat the front face, the films after it the back face, and the run's substrate is the medium behind the plate (air for a free-standing window). Forward solve, needle gradient and the optimizer's analytic Jacobian all go through the engine's block cascade, so both faces are designed against the incoherent sum of their echoes. Three rules follow from the physics. Seed every face you want coated: the plate never hosts a needle, so a face with no film on it has nowhere to put one and stays bare. No phase through a plate: phase is not defined across an incoherent layer, so a phase, retardance, differential-phase, group-delay or S2/S3 demand on a stack with a plate is dropped when the run starts, with one warning (intensity, absorption, colour, the s/p ratios, Ψ, S0/S1 and DOP read intensities only and reach through); in a multi-environment run it is dropped only from the plate environments and kept where the coating sits in coherent surroundings, which is how a phase demand and a plate share one design. Back-incidence demands are dropped the same way where the exit medium absorbs. A run refuses only when no demand is left. Thickness counts the coating: the max_total_thickness_nm budget and the run's final_coating_thickness_nm sum the coherent films, not the plate (DesignStack.coating_thickness(); total_thickness() includes it).

  • Graded Media: Mixture gradients are a first-class layer property, not a hand-built stack of sublayers. A gradient spec names the two endpoint materials, the EMA kernel (any of the six in-tree mixing rules) and the profile mode — FixedSpan, where composition runs f_start → f_end across the film, or RateCapped, a thickness-relative slope clamped to [f_min, f_max] so a thick film saturates into a pure-material tail. Single-material drift (InhMode) has the same two modes. Graded layers still serve as pinned background (substrate diffusion gradients, rugate foundations) while the needle designs around them — what is new is that a graded span's thickness can itself be an optimizer parameter. Two things about graded spans are easy to get wrong and are written down in docs/graded-media.md: a span expands into sublayer rows (16 authored spans can reach the solver as 80 rows, and the row count is what a solve costs), and Névot-Croce interface roughness on a graded span applies at every sublayer boundary — where the model's σ ≪ thickness condition is the first thing to fail.

  • One Physical Layer, One Parameter: A profiled film is one layer, so the optimizer moves its total thickness as a single number rather than one parameter per sublayer, and a thickness-relative profile is re-derived at the construction points when its span rescales instead of carrying stale nk. For the same reason the thin-layer floor, the thickness ceiling and the layer budget are span quantities: they count design layers, not solver rows.

  • Thin-Layer Policy: A film driven below the minimum thickness you can actually deposit need not be deleted. thin_layer_policy decides: 'remove' (the default, and bit-for-bit the historical behaviour), 'clamp_up_final' — the search runs exactly as before and only the final pass lifts a surviving sub-minimum film to the floor — or 'clamp_up_always'. A film that carries an interface slice clamps up like any other single layer.

  • Fabrication Tolerances as a Model, Not a Postscript: Six independent error channels — thickness, n, k, grading amplitude, roughness and interface width — each drawn per layer from one of four laws, all of the shape v_out = v·(1 + rel) + abs. Gaussian and Uniform are the single-law cases, Combined sums them, and Cascaded composes the two relative stages as factors — v·(1 + G)·(1 + U) — which is the right shape when the errors are stages in series: a rate calibration that is off, then a per-run monitor error acting on the already-mis-calibrated deposit. Two stages of 10% compose to 21%, not 20%, and that missing percent is the entire difference between the two laws. Each channel carries its own defaults, because an absolute spread carries the unit of the quantity it perturbs and the six do not share one: 0.5 nm on a thickness, 0.001 on a refractive index, 0.0001 on k — where a nanometre-sized spread would put roughly half of all draws at k < 0, which is optical gain, so the run would die at the gain door instead of reporting a tolerance. Nothing draws until you ask: error_mask is all-zero by default. Floors apply to the result, never to the error, so a perturbed thickness cannot go negative while the signed grading amplitude stays signed. The cost is a struct read per draw, not a re-parse — 10,000 Monte-Carlo expansions of a three-layer stack with all six channels live spend 0.03 s, of which setup is 0.009%.

  • Saved Designs Stay Readable: state files carry a schema version and the reader accepts a range ([1, 2]), not a point. A state written by an older build is reconstructed from its defaults rather than refused; one written by a newer build is refused with a message that says so, because the remedy there is upgrading, not hand-editing the file.

6. Fitting Measured Data

The same engine runs backwards: navette.fit fits any scalar of a model to measured data — film thicknesses, group factors, the numbers of any dispersion model, and the instrument's own departures. Guide: docs/fitting.md.

  • One Residual Vector: spectra (any synthesis channel, Ψ/Δ included, at several angles and over several measured samples) and optical-constant tables share one χ², so a film's thickness and its dispersion are fitted together. Parameters are addressed (layer[ar:2].thickness, group[H].n_factor, material[TiO2].A) or selected (kind=thickness, tag=H), with bounds, log scaling, Gaussian priors and ties.
  • Staged Strategies: a fit is a list of stages, each freeing a set of parameters — LSQ, a scan, Latin-hypercube multi-starts, or a global search (native differential evolution in every build) polished by LSQ. Generated strategy families run in a tournament on your data, or in a recovery benchmark that draws "true" models from the program's error laws and scores which strategy finds them.
  • The Instrument as Parameters: angle offset, wavelength shift, scale and offset, and a Gaussian slit bandwidth per dataset (data[R].angle_offset). Instrument files in their own units, percent and Ψ/Δ conventions convert in and back out losslessly.
  • Free-Form Optical Constants: PointWise, Spline and BSplineEps make the knot values themselves the parameters, with a smoothness prior on their second differences.
  • Honest Reports: χ², AIC/BIC, standard errors, covariance and correlation, which bound a parameter sits at, and the fitted curves. The Jacobian is exact for thickness columns on coherent stacks and closed form for the common dispersion models on nk data; the rest is differenced only where a parameter can act. A fit is a program document (fit section) that saves and reloads bit-exactly, and a progress callback can stop it.

Technical Specifications

Feature Implementation & Engineering Benefit
Core Algorithm 1D Scattering Matrix ($S$-matrix): Utilizes the Redheffer Star Product to eliminate numerical divergence and precision loss in thick or highly absorbing layers.
Propagation Logic Hybrid Mixed Coherence: Sophisticated dual-stage engine supporting phase-accurate (coherent) and intensity-only (incoherent) layers within a single pass.
Coherent Blocks $2 \times 2$ Complex Field Matrices: Maintains full phase and amplitude information, ensuring rigorous calculation of thin-film interference and ellipsometric parameters.
Incoherent Blocks Stokes-Mueller / Intensity Redheffer: Prevents unphysical interference artifacts in macroscopic substrates by utilizing intensity-based propagation.
Coherence Modes Three, with a refusal instead of a guess: FRONT_BLOCK (default, exact intensities), COHERENCY_MATRIX (adds the cascaded p–s coherency channel), FULLY_COHERENT. The twelve cross-channel observables are refused under the default on a flagged stack rather than answered from the front block alone.
Multi-Environment Design One set of films, K surroundings: a named design segment is defined once and optimized against every environment's demands at the same time, so a coating measured bare and then laminated cannot drift into two designs. K environments means K assemblies and K solves per evaluation — honest and linear.
Fitting Staged least squares with a global stage: thickness, group, dispersion and instrument parameters against spectra and nk tables in one χ², analytic Jacobian, covariance and correlation in the report, strategies compared by tournament or recovery benchmark.
Material Models Nineteen dispersion models (three of them free-form) + six EMA mixing rules, composable and nestable, with Kramers-Kronig ε₁ for the oscillator families and independently validated quadrature.
Guided Modes Complex eigenmode search: landscape scan → coarse minima → Nelder-Mead refinement over complex n_eff, plus normalised |E(z)| field profiles. Solves the stack as one coherent block by construction.
Fabrication Tolerances Six channels × four laws: thickness, n, k, grading amplitude, roughness and interface width, each drawn from Gaussian, Uniform, Combined or Cascaded — the last composing the relative stages as factors rather than summing them. Per-channel defaults in the unit of the quantity perturbed; floors on the result, never on the error; all-zero mask until a channel is switched on.
Roughness Model Névot-Croce (Exact Wavevector): Achieves research-grade accuracy for X-ray and UV interfaces by modeling exact wavevector correlations across boundaries.
Optimization Rust / rayon + PyO3: Native multi-threaded kernels (GIL released) with a thin Python API, optimized for high-concurrency simulation and real-time GUI responsiveness.
Polarization Full $s$ and $p$ Support: Comprehensive Jones and Stokes calculus integration, following standard commercial ellipsometry conventions (Azzam & Bashara). The cross-polarization observables (Δ, DOP, S2/S3, retardance) need COHERENCY_MATRIX on a stack with an incoherent flag; see Partial Coherence Support.
Complexity $O(N)$ Scaling: Optimized linear time complexity relative to the number of layers, ensuring stable performance for complex multi-stack architectures.

Project layout

Navette/
├── Cargo.toml                # Rust workspace (cargo check/test --workspace)
├── pyproject.toml            # maturin project: builds the `navette` wheel (src layout)
├── src/navette/              # unified Python package
│   ├── __init__.py           # version + public surface
│   ├── color/                # wrapper over native `navette._color`
│   ├── interpolate/          # wrapper over native `navette._interpolate`
│   ├── smatrix/              # ScatterMatrix + needle (native `navette._smatrix`)
│   ├── spectralweave/        # weavers + merit (native `navette._spectralweave`)
│   ├── materials/            # dispersion models (native `navette._materials`)
│   ├── _*.py                 # shims re-exporting the `navette._navette` submodules
│   ├── structure/            # stacks, architect (native model + thin wrappers)
│   ├── synthesis/            # needle pipeline driver (native DesignStack)
│   ├── config/               # native-validated holders, program documents
│   └── data/CIE/             # bundled reference spectra
├── rust/                     # Rust sources: one engine crate + bindings
│   ├── navette/              # pure-Rust engine (color/interpolate/materials/
│   │                         # smatrix/spectralweave/structure modules;
│   │                         # published as `navette` on crates.io)
│   └── navette-py/           # PyO3 aggregator -> navette._navette (one wheel)
├── validation/               # tests, parity, benches, goldens + references (see validation/README.md)
├── tools/check_exposure.py   # bidirectional exposure lint (CI)
├── examples/  docs/plans/  benchmarks/

Install & build

# Single aggregated native extension (navette._navette, all engines):
maturin develop --release
# checks
cargo check --workspace
cargo test --workspace     # everything (needs Python for binding crates)
cargo test-pure            # pure-Rust gate (no Python needed)
cargo fmt --all            # rustfmt defaults; CI fails on any diff
python tools/check_toolchain.py   # is your clippy as new as CI's?
pytest validation

Lint on the toolchain CI uses. cargo clippy only reports the lints its own version knows. Between 0.6.13 and 0.6.30 the local toolchain was one minor version behind CI's stable, the local run was clean, and CI was red for 17 consecutive pushes on a lint the local clippy did not have. tools/check_toolchain.py fails when that gap reopens.

Run this once per clone so git blame skips the tree-wide reformat commit (0.6.32) and points at whoever actually wrote each line:

git config blame.ignoreRevsFile .git-blame-ignore-revs

Always pass --release. Plain maturin develop builds with the dev profile: the extension imports and computes correctly, but runs several times slower, so every timing taken against it is meaningless. This is not hypothetical — a whole round of committed benchmark results (and the conclusions drawn from them) had to be discarded for exactly this reason. navette.build_profile() reports which profile is installed, and the benches under validation/benches/ exit rather than time a "debug" one.

Architecture: Rust core, Python addon

All logic and all validation live in the navette Rust crate — it runs fully standalone (file → design → solve → report, no interpreter). The Python package is a thin addon: validated config holders, YAML→dict parsing, result reshapes, and re-exports. Conversely every feature-level Rust function is exposed via PyO3, so Python can drive the whole engine. tools/check_exposure.py enforces this both ways in CI (see docs/plans/exposure_audit.md).

CI

.github/workflows/ci.yml runs on every push and pull request: cargo test --workspace, a zero-compiler-warnings check (-D warnings), pytest validation on Windows and Linux (pinned runner images, so the recorded fingerprints stay platform-stable), five blocking lints — exposure, CIE sync, .pyi surface sync, message hygiene (tools/check_message_whitespace.py: space runs and console-unencodable characters inside message literals) and review-harness documentation (tools/check_review_docs.py: every harness in validation/review/ is listed in that directory's README with the section or plan item that asked for it, and none imports the parity reference they exist to be independent of) — and an assertion that the installed extension is a release build. cargo clippy -D warnings (since 0.6.6) and cargo fmt --all --check (since 0.6.32) are blocking; nothing in the workflow is advisory any more.

Layout notes

  • rust/ holds the Cargo workspace (the single navette engine crate plus the navette-py PyO3 aggregator) — the idiomatic Rust layout, publishable to crates.io.
  • src/navette/ is the Python package in src-layout — the idiomatic Python layout, which maturin detects automatically for mixed projects.

Release & publish

Release automation: tag vX.Y.Z (must match pyproject.toml, workspace Cargo.toml, its internal navette dependency, __about__.py and both Cargo.lock entries — all six enforced by CI) → .github/workflows/release.yml builds wheels (Linux/Windows/macOS) and publishes to PyPI (trusted publisher) + crates.io (token), leaf crates first.

maturin build --release   # -> target/wheels/navette-0.10.0-*.whl (single wheel, all engines)

There is a seventh site the gate does not see: the wheel filename in the block just above. It is prose, so CI cannot compare it to the tag — it is kept current by hand, and a stale one misleads a reader without failing a build.

The same asymmetry runs through this file. Every claim above is checked by a test somewhere, but nothing checks that a claim exists: a subsystem can be built, tested and released while this README says nothing about it. That is not hypothetical — the six-channel fabrication-error model shipped across 0.7.15–0.7.26 before it was described here at all, and it hid that long because its own mask defaults to all-zero, so no test and no example had reason to mention it either. Before tagging, read the feature list against what the release actually added, and treat a feature nobody had to document as a feature nobody had to exercise.

Optimizer backends

LmConfig(backend=...) chooses which least-squares solver runs. navette._smatrix.available_lsq_backends() reports what the installed wheel actually has; a name it lacks is refused with the rebuild command, never quietly replaced by a different solver.

Name What it is
"builtin" (default) This crate's bounded Levenberg-Marquardt: QR step solve, gain-ratio damping, analytic Jacobian. Bounds are enforced by vetoing and clamping the solved step, so a thickness may finish exactly on a bound — which is how the synthesis loop learns a film wants removing.
"trf" Trust-region reflective (Branch-Coleman-Li), the reference method for bounded least squares and the same algorithm as scipy.optimize.least_squares(method="trf"). Hand-rolled, no dependency, always available. Bounds enter the subproblem rather than clipping its answer, so a boundary optimum is handled by construction — but its iterates are strictly interior, so it stops one ULP short of a bound instead of on it. lambda_* and damping do nothing here.

Optional cargo features

Off by default, so a standard wheel pulls no extra dependencies.

Feature What it adds
opt-minpack-lm LmConfig(backend="minpack_lm") — the levenberg-marquardt crate (MINPACK lmdif-derived, MIT), as a reference to compare the built-in LM against. Unbounded, so it runs on an interior reparametrization: its optima are strictly inside the thickness box, where the built-in's may sit exactly on it.
opt-argmin LmConfig(backend="argmin_gauss_newton") and "argmin_trust_region" — two solvers from the argmin ecosystem (MIT/Apache-2.0), as baselines, not as candidates. Both unbounded. The Gauss-Newton one is undamped, so it raises as soon as JᵀJ is singular — a film driven toward zero thickness is enough — and it refuses two of the three refold starts in validation/review/lm_check.py. The trust region finds the right optimum but has no convergence test of its own, so it always runs the full max_iterations: 218–393 residual evaluations where "trf" takes 8–32. Shares nalgebra with opt-minpack-lm.
opt-basin LmConfig(backend="basin_lm_qr") and "basin_trf" — Basin's pivoted-QR LM and full trust-region reflective solver (MIT/Apache-2.0), using its plain Vec backend. LM uses the interior reparametrization, so a far start can saturate at a bound — reported as StuckAtBound rather than as convergence; full TRF handles bounds and fixed coordinates natively. It also adds basin's global methods to the fit engine's global stages: "basin_de", "de_inject" and "cma_es" (the native "de" and "de_best" are in every build). See the tolerance mappings, evaluation budgets, and comparisons.
maturin develop --release --features opt-minpack-lm
maturin develop --release --features opt-argmin
maturin develop --release --features opt-basin

The released packages carry none of these. The PyPI wheels are built with default features, so after pip install navette, available_lsq_backends() lists only "builtin" and "trf". PyPI has no source distribution for pip to rebuild with a feature, so getting one means cloning this repository and running the maturin develop line above in that checkout. The crate on crates.io has the same defaults; a Rust user switches a backend on in Cargo.toml:

navette = { version = "0.10", features = ["opt-basin"] }

Manual fallback: cargo publish -p navette; maturin upload target/wheels/navette-X.Y.Z-*.whl.

About

A high-performance optical engine utilizing a Scattering Matrix algorithm for stable simulation of light in stratified media.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages