Skip to content

Speed up the aspheric SDFs: Horner sums, cached edge values - #137

Merged
StackEnjoyer merged 1 commit into
masterfrom
perf/aspheric-sdf
Oct 14, 2026
Merged

StackEnjoyer merged 1 commit into
masterfrom
perf/aspheric-sdf

Conversation

@TacHawkes

Copy link
Copy Markdown
Collaborator

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.

Closes #136 .

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]>
@TacHawkes TacHawkes added this to the v0.14.0 milestone Oct 10, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-10T07:52:26.553547Z 956f6cc PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@codecov

codecov Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.25%. Comparing base (66b711e) to head (956f6cc).

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #137      +/-   ##
==========================================
+ Coverage   89.22%   89.25%   +0.02%     
==========================================
  Files          81       81              
  Lines        4500     4512      +12     
==========================================
+ Hits         4015     4027      +12     
  Misses        485      485              

☔ 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 merged commit ec793df into master Oct 14, 2026
7 checks passed
@StackEnjoyer
StackEnjoyer deleted the perf/aspheric-sdf branch October 14, 2026 09:57
StackEnjoyer pushed a commit that referenced this pull request Oct 19, 2026
* SDF ray marching: rays inside leave at the first exit

`_raymarch_inside` stepped a fixed 1 m along the ray and then marched
back from outside. It thus found the last exit within that metre, not
the first. Rays from a surface into an object (as after refraction)
compared with a reference from the sign of the SDF, 200 per shape for
58 shapes: 216 of 11600 left at a wrong point, by up to 33 mm, e.g. in
meniscus lenses, plano- and bi-concave lenses, concave and acylindrical
surfaces, rings, mirrors with holes and differences of SDFs; some found
no exit at all. In addition, `intersect3d` took a ray that starts below
the surface for a ray outside if the SDF increases along it, e.g. from
the middle of the wall of a ring towards its inner face.

The ray is now marched inside by the distance `-sdf`, which does not
pass the exit for an SDF that is exact or a lower bound inside:
- a minimum step leaves the starting surface and the internal faces of
  composite SDFs, where the SDF is about 0 within the object; a point
  with sdf about 0 is an exit only if the ray is outside just behind it
- an over-relaxed step (Keinert et al., 2014) is kept only if the balls
  around both ends cover it
- a step that ends outside brackets the exit, which is found by the
  Illinois method on the sign of the SDF; the returned point lies
  outside, at most `eps` behind the last point inside, such that the
  next ray from it does not start inside (Issue#11 would fail otherwise)
- the normal is evaluated `eps` outside of the exit, as for hits from
  outside: inside a composite SDF the gradient may stem from another
  part, and exactly on the surface some SDFs have no gradient; a normal
  against the leaving ray (a part that touches the exit point from
  outside, Issue#82) is evaluated `h` outside instead
- a ray below the surface counts as inside in any direction

The same 58 shapes with 500 rays each: 0 of 29000 wrong in exit point,
normal or side of the surface. New tests: a ring wall and a lens in
`TestAbstractSDF.jl`, all shapes of `TestSDFBoundingSpheres.jl` against
the sign reference. The preference `sdf_inside_step` is no longer used.

Cost: an aspheric lens takes ~55 % longer (2000 rays 17.8 -> 27.8 ms,
before the speed-up of the aspheric SDF in #137), spherical lenses ~7 %:
leaving the starting surface needs more steps than the jump did.

Fixes #142

* Exit of the inside ray march changes continuously with the setup

`_bracketed_exit` returned the outer end of the final bracket, which
moves in steps of the bracket width `eps` when a parameter of the setup
changes. Finite differences saw this as noise: the derivative of a spot
position w.r.t. a lens shift differed from ForwardDiff by 7e-6 relative
(1e-11 on master), which matters for optimizers and tolerancing based on
finite differences.

The exit is now the secant root of the final bracket with the unscaled
SDF values. It changes continuously, and lies within `eps` of the
surface, far below the threshold `h` at which the next ray from it would
count as starting inside. Finite differences and ForwardDiff agree to
~1e-11 again.

Part of #142
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.

Aspheric SDFs re-evaluate constant edge values on every distance call

2 participants