Repository navigation
Speed up the aspheric SDFs: Horner sums, cached edge values - #137
Merged
Merged
Conversation
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]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
StackEnjoyer
approved these changes
Oct 10, 2026
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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, seeaspheric_edge) and the sums use Horner's scheme in r². An empty coefficient vector now gives the conic surface instead of an error.One
sdfcall 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 .