Skip to content

Feature: detector samplings RegularGrid and RectilinearGrid - #171

Merged
StackEnjoyer merged 3 commits into
masterfrom
feature/detector-sampling
Oct 23, 2026
Merged

StackEnjoyer merged 3 commits into
masterfrom
feature/detector-sampling

Conversation

@StackEnjoyer

@StackEnjoyer StackEnjoyer commented Oct 21, 2026 •

Copy link
Copy Markdown
Owner

Features

  • Breaking: readout keywords (n, crop_factor, x_min, …) move into RegularGrid(...)
  • Breaking: electric_field(pd, xs, zs), intensity(pd, xs, zs) replaced by RectilinearGrid(xs, zs)
  • RegularGrid, RectilinearGrid: samplings that set points, window and weights of readouts
  • optical_power(pd, s): power as Σ wᵢ Iᵢ with the weights of the sampling
  • BeamletOptics.AbstractDetectorSampling, sample_points: a new sampling only provides points and weights
  • electric_field(pd, points), intensity(pd, points): values at any array of local points
  • Breaking: BeamletOptics.AbstractSampling renamed to AbstractSourceSampling
x, z, I = intensity(pd, RegularGrid(n = 200, crop_factor = 5))
P = optical_power(pd, RectilinearGrid(xs, zs))

Bugfixes

  • A single window bound, e.g. only x_min, was silently ignored; now it moves its own side

Doc changes

  • Detectors page: new section on samplings
  • Tutorials, examples and figure scripts use RegularGrid
  • Agent skill: API.md, components/detectors.md, WORKFLOW.md, VISUALIZATION.md, templates/03_psf_airy.jl updated

Internal changes

  • Trapz dropped as a dependency

Closes #170, closes #168

The readouts electric_field, intensity and optical_power take a sampling
that sets the points, the window and the weights; optical_power is the
weighted sum of the intensity. The readout keywords move into
RegularGrid, the (pd, xs, zs) forms are replaced by RectilinearGrid.
A single window bound now moves only its own side. Trapz is dropped.

Closes #170, closes #168

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@StackEnjoyer StackEnjoyer added this to the v0.14.0 milestone Oct 21, 2026
@codecov

codecov Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.33333% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 90.30%. Comparing base (59682ca) to head (8f9bafd).

Files with missing lines Patch % Lines
src/BeamGroups/Sampling.jl 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #171      +/-   ##
==========================================
+ Coverage   90.25%   90.30%   +0.04%     
==========================================
  Files          85       86       +1     
  Lines        4587     4610      +23     
==========================================
+ Hits         4140     4163      +23     
  Misses        447      447              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@StackEnjoyer
StackEnjoyer marked this pull request as ready for review October 23, 2026 06:48

@TacHawkes TacHawkes left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!, Please review the newest Claudia Slop-Pop: https://www.youtube.com/watch?v=G7megUHUqFo

Okay, seriously: I have some issues with the state:

  1. OpticsBase also exports the RegularGrid. As we have control over both packages, we shouldn't introduce this name clash voluntarily.
  2. The GUI package needs fixing, but there is a lot to repair with 0.14 anyway.
  3. A single explicit bound like RegularGrid(x_min = 5mm) can produce a descending grid, then optical_power returns a negative power. There should be assertions for x_min/z_min < x_max/z_max
  4. Error reporting: A rectilinear grid with empty vectors fails with a weird DimensionMismatch.
  5. FieldCalculation:70 is too loose with points::AbstractArray, a single Point2 will throw a bounds error. Change to points::AbstractArray{<:AbstractVector}
  6. Chunking is one chunk per column: a 1×10⁶ grid gives 10⁶ chunks, and a 10⁵×2 grid uses only 2 threads. Chunking by length(points) would balance both.
  7. intensity builds the full weights matrix even though it doesn't use it.
  8. optical_power should write dots(weights, I) instead of sum(weigths .* I) to avoid allocations

@StackEnjoyer

Copy link
Copy Markdown
Owner Author
  1. The GUI package needs fixing, but there is a lot to repair with 0.14 anyway.

This is a general caveat of the structure of BMO <-> BMOGUI. The GUI pkg needs a tagged version of BMO afaik in order to work properly, also w.r.t. deving. I can look into working around this or how the SciML eco system works with multiple dev states in general.

Currently I am opening a bunch of issues to keep track of what needs to be fixed for the GUI once 0.14 hits. Will open issue for this.

@StackEnjoyer

Copy link
Copy Markdown
Owner Author
  1. OpticsBase also exports the RegularGrid. As we have control over both packages, we shouldn't introduce this name clash voluntarily.

RegularGrid is the "best" name to describe this and necessarily user-facing. Maybe we can work with modules to seperate namespaces?

- RegularGrid throws if a bound lies beyond its opposite side, RectilinearGrid
  needs non-empty ascending axes: a descending grid gave a negative power
- electric_field/intensity at points take AbstractArray{<:AbstractVector} only
- the field loop splits the points into equal chunks, independent of the shape
- RectilinearGrid weights stay a lazy outer product; optical_power sums the
  weighted intensity without temporary arrays

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@StackEnjoyer

Copy link
Copy Markdown
Owner Author

Agent response to review round 1 · points 3–8 fixed, 1–2 answered by the author · tests pass

Full response for agents

Findings

1 · noted

RegularGrid name clash with OpticsBase: answered by the author in the thread, not changed here.

2 · noted

GUI: answered by the author in the thread; the GUI follows once BMO is tagged.

3 · fixed in ea2640a

RegularGrid throws an ArgumentError if a given bound lies beyond the opposite side of the window (x_min > x_max, z_min > z_max, after merging with the automatic window). RectilinearGrid requires ascending xs and zs, so no sampling can produce negative trapezoid weights.

4 · fixed in ea2640a

RectilinearGrid with an empty axis throws ArgumentError("RectilinearGrid needs at least one point per axis") at construction instead of a DimensionMismatch in the readout.

5 · fixed in ea2640a

electric_field(pd, points) and intensity(pd, points) take points::AbstractArray{<:AbstractVector}; a single Point2 is a MethodError.

6 · fixed in ea2640a

The field loop splits eachindex(points) into min(length(points), max(100, 4 * nthreads())) equal chunks of consecutive points, independent of the array shape; one progress tick per chunk.

7 · fixed in ea2640a

RectilinearGrid (and so RegularGrid) returns its weights as an instantiated lazy broadcast of the two 1D trapezoid weight vectors; intensity and electric_field no longer allocate an n×n weights matrix. sample_points documents that weights may be an array or a lazy broadcast.

8 · fixed in ea2640a

optical_power is sum(Broadcast.instantiate(Broadcast.broadcasted(*, weights, I))): no temporary array, and it works for lazy and array weights alike. dot(weights, I) would need materialized weights, which point 7 avoids.

Verified

  • test/Components/TestDetectorSampling.jl: 37/37 pass, new tests for 3, 4, 5, 7 and tall/wide grids; the regular grid still reproduces the former keyword results within 1e-12
  • TestDetector.jl 293/293, TestProgress.jl 62/62, TestBugFixes.jl, TestAstigmaticGaussianSources.jl 744/744, TestAstigmaticGaussianPhysical.jl 168/168, E2E/TestMichelson.jl 30/30, TestPolarizedRays.jl 48/48, TestAgentSkill.jl 19/19: pass
  • Not run after these changes: the full suite and the docs build

Breaking: the former name is gone. api.md lists the detector samplings
among the public names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@StackEnjoyer
StackEnjoyer merged commit 008144c into master Oct 23, 2026
7 checks passed
@StackEnjoyer
StackEnjoyer deleted the feature/detector-sampling branch October 23, 2026 13:42
StackEnjoyer pushed a commit to StackEnjoyer/BeamletOpticsGUI.jl that referenced this pull request Oct 23, 2026
BeamletOptics master takes the grid and the window of a readout as a
sampling (RegularGrid, StackEnjoyer/BeamletOptics.jl#171): the view
evaluates `intensity` on a RegularGrid of its options, which keep their
keywords (`n`, `x_min`, `crop_factor`, ...), and integrates the power with
the weights of that sampling, like `optical_power`. Trapz is no longer a
dependency.

Closes #37

Co-Authored-By: Claude Opus 5.5 <[email protected]>
StackEnjoyer pushed a commit that referenced this pull request Oct 23, 2026
Since #171, optical_power takes the sampling as an argument instead of the keywords n, x_min, ...

Co-Authored-By: Claude Opus 5.5 <[email protected]>
StackEnjoyer pushed a commit that referenced this pull request Oct 27, 2026
* Speed up the aspheric SDFs: Horner sums, cached edge values

The distance field of an aspheric or acylindric surface evaluated the
asphere at its edge (sag and gradient) on every call, although both are
constant for a surface, and summed the even terms with integer powers.
The SDFs now store the edge values (`edge`, see `aspheric_edge`) and the
sums use Horner's scheme in r². An empty coefficient vector now gives
the conic surface instead of an error.

One `sdf` call of an asphere drops from ~107 ns to ~29 ns; a beam group
of 20000 rays through an aspheric lens solves in 83 ms instead of 163 ms
(1 thread). Distances agree with the previous code to ~3e-15 relative,
ray intersections are bit-identical.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Automatic differentiation on the optical axis

ForwardDiff through `solve_system!` gave the correct derivative for
rays off the axis but 0 or a wrong value for rays on it, without a
warning, e.g. for the spot position behind a lens w.r.t. its lateral
shift: 0 instead of 1.90 (bi-convex), -0.97 instead of -1.98
(bi-concave), NaN for parabolic and conic mirrors. Rays on the axis,
e.g. the chief ray of a rotationally symmetric system, are the ones an
optimizer differentiates. The causes, all where the derivative of a
normal is taken, i.e. in nested automatic differentiation:

- The radius of revolution `norm(Point2(x, z))` is `NaN` on the axis in
  nested AD, which turned the comparisons of SDF branches, and the
  derivative of the radius is not defined there. `_radial` is exactly 0
  on the axis, and the surfaces that cross the axis are computed from
  smooth expressions: the 3D distance from the center of a sphere
  (`CutSphereSDF`, `ConvexSphericalSurfaceSDF`), the sag and slope of
  aspheres and conics as functions of r².
- Where a concave surface touches the face of the lens body at its
  vertex, both are equally close, and the flat face was taken, which
  has no curvature. `UnionSDF` now resolves such ties by the operand
  that is closest beside the point (`_closest_operand`), independent of
  the order of the operands; within the aspheric SDFs the surface wins
  ties with the segments that close the perimeter.
- A hit of `_raymarch_outside` that ends slightly within the shape has
  its normal evaluated outside, as the exits of the inside march.
- `refractive_index(optic, λ)` returned `Float64`, which dropped the
  derivative w.r.t. a refractive index or the wavelength; it returns the
  number type of the optic and the wavelength.

New `test/TestAutoDiff.jl`: ForwardDiff against central finite
differences for rays on and off the axis through spherical, meniscus,
aspheric and cylindrical lenses and spherical, parabolic and conic
mirrors, w.r.t. a refractive index and through a GaussianBeamlet
(ForwardDiff added to the test dependencies). SDF values, normals and
hit lengths agree with the previous code to ~1e-17 m. Built on the
aspheric changes of #137.

* Automatic differentiation: polarization, beamsplitters, docs

A wider check of ForwardDiff against finite differences found further
failures, now fixed:

- Polarized rays and astigmatic beamlets at normal incidence threw an
  orthogonality error: `isparallel3d` took the `norm` of a cross product
  that vanishes but has a derivative, which is `NaN` (also its value)
  for dual numbers, hence the s-p basis was built from a zero vector. It
  now compares the squared norm. The Fresnel coefficients of lenses and
  polarizers are computed from the cosine of the angle of incidence
  (`_fresnel_coefficients`, `cos_angle3d`), since the derivative of the
  `acos` is not defined at normal incidence.
- `ThinBeamsplitter` (also within `CubeBeamsplitter`) required the
  reflectance in the number type of the shape; a constructor converts it.
- `CircularFlatMesh` built its vertices as `Float64`, which broke round
  plate beamsplitters, polarization filters and mirrors.

`test/TestAutoDiff.jl` now covers 68 cases: radius, thickness, tilt,
refractive index, polarized rays and astigmatic beamlets on the axis,
thin, plate and cube beamsplitters, total internal reflection, Malus'
law, the power on a detector and the power of a Michelson
interferometer vs. the position of a mirror.

New docs page "Automatic differentiation" (usage, covered components,
limitations: discrete events, edges, forward mode only, compile time,
`ObjectGroup(objects, T)`), and a section in the agent skill
(`WORKFLOW.md`). `ObjectGroup` still defaults to `Float64`; its
constructor is changed by #135.

* Asphere SDFs: evaluate sag and slope once per sdf call

The surface distances computed the sag and the slope via the functions of r for the NaN guard and the branch conditions, then again via the functions of r^2 for the distance. They now evaluate both once, as functions of r^2, with the guard taken from the square root argument. gradient_aspheric_equation delegates to the same slope, so its formula exists once.

Review F1 on PR #148.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* UnionSDF: state the scale for which the tie-break offset holds

Review F2 on PR #148.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* AutoDiff tests: compare with paraxial ABCD references

For a ray on the axis and a laterally shifted lens or mirror, the derivative of the spot w.r.t. the shift is 1 - A of the paraxial ABCD matrix, built in the test from the parameters.

Review F3 on PR #148.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* AutoDiff tests: readouts with a RegularGrid sampling

Since #171, optical_power takes the sampling as an argument instead of the keywords n, x_min, ...

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Internal: the CI job on Julia pre does not fail the CI (#173)

Julia 1.14.0-alpha1 calls issubnormal in normalize, which ForwardDiff 1.4.6
does not define for Dual (JuliaDiff/ForwardDiff.jl#852, fix in #855). The
job keeps running and reporting, but no longer blocks merges.

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Hugo Uittenbosch <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: Detector readouts on a sampling with its own window Feature: Detector readouts on arbitrary sample points

2 participants