From 956f6cc026ff2f9cfd7ab86426a4a69f9b83e451 Mon Sep 17 00:00:00 2001 From: Oliver Kliebisch Date: Sat, 10 Oct 2026 09:30:55 +0200 Subject: [PATCH 1/8] Speed up the aspheric SDFs: Horner sums, cached edge values MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/SDFs/AcylindricalSDF.jl | 14 +++-- src/SDFs/AsphericalLensSDF.jl | 90 ++++++++++++++++++++--------- test/Lenses/TestAsphericalLenses.jl | 22 +++++++ 3 files changed, 95 insertions(+), 31 deletions(-) diff --git a/src/SDFs/AcylindricalSDF.jl b/src/SDFs/AcylindricalSDF.jl index 32accf7a6..919325aee 100644 --- a/src/SDFs/AcylindricalSDF.jl +++ b/src/SDFs/AcylindricalSDF.jl @@ -22,6 +22,7 @@ mutable struct AconvexCylinderSDF{T} <: AbstractAcylindricalSurfaceSDF{T} conic_constant::T coefficients::Vector{T} max_sag::Point2{T} + edge::Point2{T} end """ @@ -42,7 +43,8 @@ function AconvexCylinderSDF(radius::R, diameter::D, height::H, conic_constant::C height, conic_constant, coefficients, - Point2(max_aspheric_value(1 / radius, conic_constant, coefficients, diameter)) + Point2(max_aspheric_value(1 / radius, conic_constant, coefficients, diameter)), + aspheric_edge(1 / radius, conic_constant, coefficients, diameter) ) return s @@ -65,7 +67,8 @@ function sdf(s::AconvexCylinderSDF{T}, point) where {T} s.conic_constant, s.diameter, s.coefficients, - s.max_sag + s.max_sag, + s.edge ), s.height / 2 ) @@ -88,6 +91,7 @@ mutable struct AconcaveCylinderSDF{T} <: AbstractAcylindricalSurfaceSDF{T} conic_constant::T coefficients::Vector{T} max_sag::Point2{T} + edge::Point2{T} end """ @@ -108,7 +112,8 @@ function AconcaveCylinderSDF(radius::R, diameter::D, height::H, conic_constant:: height, conic_constant, coefficients, - Point2(max_aspheric_value(1 / radius, conic_constant, coefficients, diameter)) + Point2(max_aspheric_value(1 / radius, conic_constant, coefficients, diameter)), + aspheric_edge(1 / radius, conic_constant, coefficients, diameter) ) return s @@ -132,7 +137,8 @@ function sdf(s::AconcaveCylinderSDF{T}, point) where {T} s.conic_constant, s.diameter, s.coefficients, - s.max_sag + s.max_sag, + s.edge ), s.height / 2 ) diff --git a/src/SDFs/AsphericalLensSDF.jl b/src/SDFs/AsphericalLensSDF.jl index 51e369a04..6523083fc 100644 --- a/src/SDFs/AsphericalLensSDF.jl +++ b/src/SDFs/AsphericalLensSDF.jl @@ -24,6 +24,7 @@ mutable struct ConvexAsphericalSurfaceSDF{T} <: AbstractAsphericalSurfaceSDF{T} dir::SMatrix{3, 3, T, 9} transposed_dir::SMatrix{3, 3, T, 9} max_sag::Point2{T} + edge::Point2{T} end function thickness(s::ConvexAsphericalSurfaceSDF) @@ -42,7 +43,8 @@ function ConvexAsphericalSurfaceSDF( Point3{T}(0), Matrix{T}(I, 3, 3), Matrix{T}(I, 3, 3), - Point2(max_aspheric_value(1/radius, conic_constant, coefficients, diameter)) + Point2(max_aspheric_value(1/radius, conic_constant, coefficients, diameter)), + aspheric_edge(1/radius, conic_constant, coefficients, diameter) ) end @@ -61,6 +63,19 @@ function max_aspheric_value(c, k, α_coeffs, d) end return f(r_max), r_max end + +""" + aspheric_edge(c, k, α_coeffs, d) + +Returns the sag of the asphere at its edge `r = d/2` and the norm of the gradient of its 2D +distance field there, as a `Point2`. Both are constant for a surface, hence the SDFs store them +instead of evaluating the asphere at the edge for every distance. +""" +function aspheric_edge(c, k, α_coeffs, d) + z = aspheric_equation(d / 2, c, k, α_coeffs) + return Point2(z, norm(gradient_aspheric_equation(d / 2, c, k, α_coeffs))) +end + """ ConcaveAsphericalSurfaceSDF @@ -88,6 +103,7 @@ mutable struct ConcaveAsphericalSurfaceSDF{T} <: AbstractAsphericalSurfaceSDF{T} dir::SMatrix{3, 3, T, 9} transposed_dir::SMatrix{3, 3, T, 9} max_sag::Point2{T} + edge::Point2{T} end function thickness(s::ConcaveAsphericalSurfaceSDF{T}) where {T} @@ -108,7 +124,8 @@ function ConcaveAsphericalSurfaceSDF( Point3{T}(0), SMatrix{3, 3}(one(T) * I), SMatrix{3, 3}(one(T) * I), - Point2(max_aspheric_value(1/radius, conic_constant, coefficients, diameter)) + Point2(max_aspheric_value(1/radius, conic_constant, coefficients, diameter)), + aspheric_edge(1/radius, conic_constant, coefficients, diameter) ) end @@ -132,8 +149,26 @@ function aspheric_equation(r, c, k, α_coeffs) if sqrt_arg < 0 return NaN # Handle as desired end - sum_α = sum(i -> α_coeffs[i] * r2^(i), eachindex(α_coeffs)) - return c * r2 / (1 + sqrt(sqrt_arg)) + sum_α + return c * r2 / (1 + sqrt(sqrt_arg)) + _even_aspheric_sum(r2, α_coeffs) +end + +# Σᵢ αᵢ r²ⁱ of the even aspheric terms, via Horner's scheme in r² +function _even_aspheric_sum(r2, α_coeffs) + acc = zero(r2 * zero(eltype(α_coeffs))) + for i in reverse(eachindex(α_coeffs)) + acc = muladd(acc, r2, α_coeffs[i]) + end + return acc * r2 +end + +# d/dr of `_even_aspheric_sum(r^2, α_coeffs)`, i.e. Σᵢ 2i αᵢ r²ⁱ⁻¹, via Horner's scheme in r² +function _even_aspheric_sum_derivative(r, α_coeffs) + r2 = r^2 + acc = zero(r2 * zero(eltype(α_coeffs))) + for i in reverse(eachindex(α_coeffs)) + acc = muladd(acc, r2, 2i * α_coeffs[i]) + end + return acc * r end function aspheric_equation(r::Real, a::AbstractAsphericalSurfaceSDF) @@ -146,7 +181,7 @@ function gradient_aspheric_equation(r, c, k, α_coeffs) sqrt_arg < 0 && return NaN gr = 2 * r / (Ri * (√(sqrt_arg) + 1)) + r^3 * (1 + k) / (Ri^3 * √(sqrt_arg) * (√(sqrt_arg) + 1)^2) - sum_r = sum(m -> 2 * (m) * α_coeffs[m] * r^(2(m - 1) + 1), eachindex(α_coeffs)) + sum_r = _even_aspheric_sum_derivative(r, α_coeffs) return Point2(-sum_r - gr, 1) end @@ -165,7 +200,7 @@ function sd_line_segment(p, a, b) end """ - convex_aspheric_surface_distance(r, z, c, k, d, α_coeffs) + convex_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, edge) Calculates the 2D distance field for an aspheric surface at radius `r` away from the optical axis position `z`. The asphere is defined by: @@ -173,20 +208,22 @@ position `z`. The asphere is defined by: - `k` : The conic constant of the surface - `d` : The diameter of the asphere - `α_coeffs` : The (even) aspheric coefficients, starting with A2. +- `max_sag` : the extremal sag and its radius, see `max_aspheric_value` +- `edge` : the sag and the gradient norm at the edge, see `aspheric_edge` Note that this is not just an infinite aspheric surface and also not a surface segment but a closed 2D perimeter. It is intended to pair the SDF derived from this distance field with a cylinder SDF to build a real lens. """ -function convex_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag) +function convex_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, edge) r2 = r^2 r2_bound = (d / 2)^2 z_aspheric_value = aspheric_equation(r, c, k, α_coeffs) grad_z = gradient_aspheric_equation(r, c, k, α_coeffs) - z_aspheric_boundary = aspheric_equation(d / 2, c, k, α_coeffs) - grad_z_boundary = gradient_aspheric_equation(d / 2, c, k, α_coeffs) + # sag and gradient norm at the edge, see `aspheric_edge` + z_aspheric_boundary, n_grad_z_boundary = edge # Handling NaN for points outside the aspheric surface if isnan(z_aspheric_value) || isnan(grad_z) || r2 > r2_bound @@ -199,7 +236,7 @@ function convex_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag) else distance_to_boundary = sqrt((r - sign(r) * d / 2)^2 + (z - z_aspheric_boundary)^2) end - return distance_to_boundary / norm(grad_z_boundary) + return distance_to_boundary / n_grad_z_boundary end # Calculate distance to the aspheric surface @@ -208,14 +245,13 @@ function convex_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag) # the asphere curves towards negative sag so we need to close the perimeter # at its max sag value instead of the boundary p = Point2(r, z) - n_gzb = norm(grad_z_boundary) a1, b1 = Point2(d / 2, z_aspheric_boundary), Point2(d / 2, max_sag[1]) - sdl1 = sd_line_segment(p, a1, b1) / n_gzb + sdl1 = sd_line_segment(p, a1, b1) / n_grad_z_boundary a2, b2 = Point2(d / 2, max_sag[1]), Point2(-d / 2, max_sag[1]) - sdl2 = sd_line_segment(p, a2, b2) / n_gzb + sdl2 = sd_line_segment(p, a2, b2) / n_grad_z_boundary a3, b3 = Point2(-d / 2, max_sag[1]), Point2(-d / 2, z_aspheric_boundary) - sdl3 = sd_line_segment(p, a3, b3) / n_gzb + sdl3 = sd_line_segment(p, a3, b3) / n_grad_z_boundary if z_aspheric_value < z < max_sag[1] return -min(distance_to_aspheric, sdl1, sdl2, sdl3) @@ -225,7 +261,7 @@ function convex_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag) else # If we are inside the aperture, let's close the perimeter with a line segment a, b = Point2(d / 2, z_aspheric_boundary), Point2(-d / 2, z_aspheric_boundary) - sdl = sd_line_segment(Point2(r, z), a, b) / norm(grad_z_boundary) + sdl = sd_line_segment(Point2(r, z), a, b) / n_grad_z_boundary if sign(c) * z_aspheric_value < sign(c) * z < sign(c) * z_aspheric_boundary return -min(sdl, distance_to_aspheric) else @@ -234,14 +270,14 @@ function convex_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag) end end -function concave_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag) +function concave_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, edge) r2 = r^2 r2_bound = (d / 2)^2 z_aspheric_value = aspheric_equation(r, c, k, α_coeffs) grad_z = gradient_aspheric_equation(r, c, k, α_coeffs) - z_aspheric_boundary = aspheric_equation(d / 2, c, k, α_coeffs) - grad_z_boundary = gradient_aspheric_equation(d / 2, c, k, α_coeffs) + # sag and gradient norm at the edge, see `aspheric_edge` + z_aspheric_boundary, n_grad_z_boundary = edge # Handling NaN for points outside the aspheric surface if isnan(z_aspheric_value) || isnan(grad_z) if z < 0 @@ -251,9 +287,7 @@ function concave_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag) else distance_to_boundary = sqrt((r - sign(r) * d / 2)^2 + (z - z_aspheric_boundary)^2) end - return distance_to_boundary / norm(grad_z_boundary) - # distance_to_boundary = sqrt((r - sign(r) * d / 2)^2 + z^2) - # return distance_to_boundary / norm(grad_z_boundary) + return distance_to_boundary / n_grad_z_boundary end distance_to_aspheric = abs(z - z_aspheric_value) / norm(grad_z) @@ -261,7 +295,7 @@ function concave_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag) if max_sag[1] > 0 && z_aspheric_boundary < 0 a, b = Point2(d / 2, z_aspheric_boundary), Point2(-d / 2, z_aspheric_boundary) - sdl = sd_line_segment(p, a, b) / norm(grad_z_boundary) + sdl = sd_line_segment(p, a, b) / n_grad_z_boundary if r2 > r2_bound # we are outside of the aperture, so the shortest distance can be determined @@ -279,11 +313,11 @@ function concave_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag) end else a1, b1 = Point2(d / 2, z_aspheric_boundary), Point2(d / 2, 0.0) - sdl1 = sd_line_segment(p, a1, b1) / norm(grad_z_boundary) + sdl1 = sd_line_segment(p, a1, b1) / n_grad_z_boundary a2, b2 = Point2(d / 2, 0.0), Point2(-d / 2, 0.0) - sdl2 = sd_line_segment(p, a2, b2) / norm(grad_z_boundary) + sdl2 = sd_line_segment(p, a2, b2) / n_grad_z_boundary a3, b3 = Point2(-d / 2, 0.0), Point2(-d / 2, z_aspheric_boundary) - sdl3 = sd_line_segment(p, a3, b3) / norm(grad_z_boundary) + sdl3 = sd_line_segment(p, a3, b3) / n_grad_z_boundary if r2 > r2_bound # we are outside of the aperture, so the shortest distance can be determined @@ -343,7 +377,8 @@ function sdf(surface::ConvexAsphericalSurfaceSDF{T}, point) where {T} surface.conic_constant, surface.diameter, surface.coefficients, - surface.max_sag + surface.max_sag, + surface.edge ), zero(T)) return sdf_v end @@ -364,7 +399,8 @@ function sdf(surface::ConcaveAsphericalSurfaceSDF{T}, point) where {T} surface.conic_constant, surface.diameter, surface.coefficients, - surface.max_sag + surface.max_sag, + surface.edge ), zero(T)) return sdf_v end diff --git a/test/Lenses/TestAsphericalLenses.jl b/test/Lenses/TestAsphericalLenses.jl index 98fcc9181..054d8ef3c 100644 --- a/test/Lenses/TestAsphericalLenses.jl +++ b/test/Lenses/TestAsphericalLenses.jl @@ -3,6 +3,7 @@ module TestAsphericalLenses using BeamletOptics using Test using GeometryBasics +using LinearAlgebra: norm const BMO = BeamletOptics @@ -66,6 +67,27 @@ const mm = 1e-3 @test wd≈93.2mm atol=1e-4 end + @testset "Aspheric equation and its gradient" begin + R, k = 50.3583mm, -0.789119 + A = [0, 2.10405e-7 * (1e3)^3, 1.76468e-11 * (1e3)^5, 1.02641e-15 * (1e3)^7] + c = 1 / R + for r in (0.0, 3mm, 12.5mm, 25mm) + # the conic sag plus the explicit sum of the even terms + sag = c * r^2 / (1 + sqrt(1 - (1 + k) * c^2 * r^2)) + sum(A[i] * r^(2i) for i in eachindex(A)) + @test BMO.aspheric_equation(r, c, k, A) ≈ sag rtol=1e-12 + # the gradient of the 2D distance field holds -dz/dr in its first component + h = 1e-7 + dz = (BMO.aspheric_equation(r + h, c, k, A) - BMO.aspheric_equation(r - h, c, k, A)) / 2h + @test BMO.gradient_aspheric_equation(r, c, k, A)[1] ≈ -dz rtol=1e-6 atol=1e-9 + end + # without coefficients, the surface is a conic + @test BMO.aspheric_equation(10mm, c, k, Float64[]) ≈ BMO.aspheric_equation(10mm, c, k, [0.0]) + # the SDFs store the sag and the gradient norm at the edge + s = BMO.ConvexAsphericalSurfaceSDF(A, R, k, 50mm) + @test s.edge[1] == BMO.aspheric_equation(25mm, c, k, A) + @test s.edge[2] ≈ norm(BMO.gradient_aspheric_equation(25mm, c, k, A)) + end + @testset "Aspherical meniscus without cylinder section" begin # A meniscus, whose center thickness does not exceed the sagitta of the convex surface, # is only supported for spherical surfaces From a8cc0139207f5f990fd8326bbb9f2e737abab5d8 Mon Sep 17 00:00:00 2001 From: Oliver Kliebisch Date: Sun, 11 Oct 2026 21:32:58 +0200 Subject: [PATCH 2/8] Automatic differentiation on the optical axis MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/OpticalComponents/Lenses.jl | 6 +- src/SDFs/AbstractSDF.jl | 19 ++++- src/SDFs/AsphericalLensSDF.jl | 135 +++++++++++++++++++------------- src/SDFs/ConicSDF.jl | 13 +-- src/SDFs/PrimitiveSDF.jl | 9 ++- src/SDFs/SphericalLensSDF.jl | 9 ++- src/SDFs/UnionSDF.jl | 28 ++++++- test/Project.toml | 2 + test/TestAutoDiff.jl | 110 ++++++++++++++++++++++++++ test/runtests.jl | 3 + 10 files changed, 259 insertions(+), 75 deletions(-) create mode 100644 test/TestAutoDiff.jl diff --git a/src/OpticalComponents/Lenses.jl b/src/OpticalComponents/Lenses.jl index 802d1dd9c..f052424dc 100644 --- a/src/OpticalComponents/Lenses.jl +++ b/src/OpticalComponents/Lenses.jl @@ -35,7 +35,11 @@ by specialized subtypes. abstract type AbstractRefractiveOptic{T, F} <: AbstractObject{T} end refractive_index(object::AbstractRefractiveOptic) = object.n -refractive_index(object::AbstractRefractiveOptic{<:Any, <:RefractiveIndex}, λ::Real)::Float64 = object.n(λ) +# The result is converted to the number type of the optic and the wavelength, since `n` may be any +# function: e.g. a `ForwardDiff.Dual` within automatic differentiation, else `Float64`. +function refractive_index(object::AbstractRefractiveOptic{T, <:RefractiveIndex}, λ::L) where {T, L <: Real} + return convert(promote_type(T, L), object.n(λ))::promote_type(T, L) +end """ interact3d(AbstractSystem, AbstractRefractiveOptic, Beam, Ray) diff --git a/src/SDFs/AbstractSDF.jl b/src/SDFs/AbstractSDF.jl index 3547a9b66..4c849a3e3 100644 --- a/src/SDFs/AbstractSDF.jl +++ b/src/SDFs/AbstractSDF.jl @@ -128,7 +128,10 @@ function _raymarch_outside(shape::AbstractSDF{S}, if dist > eps escaped = true elseif escaped - normal = normal3d(shape, pos) + # The normal is evaluated outside: a step may end slightly within the shape, where the + # gradient of a composite SDF may stem from a part other than the one whose surface is hit, + # e.g. the face of a lens body that the vertex of a concave surface touches. + normal = normal3d(shape, dist < 0 ? pos - (eps - dist) * dir : pos) # Filter out false positive hits caused by numerical noise when leaving an SDF. if !(dot(dir, normal) > eps) return Intersection(t0, normal, shape) @@ -218,6 +221,16 @@ end intersect3d(::NoBoundingSphere, object::AbstractSDF, ray::AbstractRay) = intersect3d(object, ray) # generic SDF transformations +# The distance √(a² + b²) from an axis, e.g. the radius of revolution. It is exactly 0 on the axis, +# also within nested automatic differentiation (e.g. the derivative of a normal, which is itself a +# gradient), where `norm(Point2(a, b))` gives `NaN` there and would let comparisons of SDF branches +# fail. The derivative w.r.t. a and b is not defined on the axis; SDFs that need it there use a +# smooth expression, e.g. the 3D distance from the center of a sphere. +function _radial(a, b) + r2 = a^2 + b^2 + return iszero(r2) ? zero(r2) : sqrt(r2) +end + """ op_revolve_z(p, sdf2d::Function, offset) @@ -226,7 +239,7 @@ the 2D shape around the z-axis. """ function op_revolve_z(p::Point3{T}, sdf2d::Function, offset = zero(T)) where {T <: Real} - q = Point2(norm(Point2(p[1], p[2])) - offset, p[3]) + q = Point2(_radial(p[1], p[2]) - offset, p[3]) return sdf2d(q) end @@ -238,7 +251,7 @@ the 2D shape around the y-axis. """ function op_revolve_y(p::Point3{T}, sdf2d::Function, offset = zero(T)) where {T <: Real} - q = Point2(norm(Point2(p[1], p[3])) - offset, p[2]) + q = Point2(_radial(p[1], p[3]) - offset, p[2]) return sdf2d(q) end diff --git a/src/SDFs/AsphericalLensSDF.jl b/src/SDFs/AsphericalLensSDF.jl index 6523083fc..af1c101e3 100644 --- a/src/SDFs/AsphericalLensSDF.jl +++ b/src/SDFs/AsphericalLensSDF.jl @@ -186,6 +186,36 @@ function gradient_aspheric_equation(r, c, k, α_coeffs) return Point2(-sum_r - gr, 1) end +# The sag and the squared slope (dz/dr)² of the asphere as functions of r². Both are smooth on the +# axis, also for automatic differentiation, in contrast to functions of the radius r. +function _aspheric_sag_r2(r2, c, k, α_coeffs) + return c * r2 / (1 + sqrt(1 - (1 + k) * c^2 * r2)) + _even_aspheric_sum(r2, α_coeffs) +end + +function _aspheric_slope2_r2(r2, c, k, α_coeffs) + Ri = 1 / c + sq = sqrt(1 - r2 * (1 + k) / Ri^2) + # dz/dr = r * G(r²) + acc = zero(r2 * zero(eltype(α_coeffs))) + for i in reverse(eachindex(α_coeffs)) + acc = muladd(acc, r2, 2i * α_coeffs[i]) + end + G = 2 / (Ri * (sq + 1)) + r2 * (1 + k) / (Ri^3 * sq * (sq + 1)^2) + acc + return r2 * G^2 +end + +# The smaller of the distance to the aspheric surface, `d_surface`, and the distance to the segments +# that close the 2D perimeter, `d_closure`, divided, i.e. scaled down, by the factor `g` (≥ 1) as the +# distance of the surface is. Within the surface threshold, where a closing segment may touch the +# surface, e.g. at the vertex of a concave asphere, the surface is taken if it is not farther than the +# unscaled segment: both give the same normal, but only the surface gives its change, e.g. its +# derivative in automatic differentiation. The value changes by less than the threshold. +function _min_surface_first(d_surface, d_closure, g) + near = d_surface ≤ Config.get_sdf_surface_threshold() + near && d_surface ≤ d_closure + Config.get_sdf_raymarch_eps() / 100 && return d_surface + return min(d_surface, d_closure / g) +end + """ sd_line_segment(p, a, b) @@ -216,8 +246,7 @@ a closed 2D perimeter. It is intended to pair the SDF derived from this distance field with a cylinder SDF to build a real lens. """ -function convex_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, edge) - r2 = r^2 +function convex_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, edge, r2 = r^2) r2_bound = (d / 2)^2 z_aspheric_value = aspheric_equation(r, c, k, α_coeffs) grad_z = gradient_aspheric_equation(r, c, k, α_coeffs) @@ -240,38 +269,37 @@ function convex_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, edg end # Calculate distance to the aspheric surface - distance_to_aspheric = abs(z - z_aspheric_value) / norm(grad_z) + # via r², i.e. smooth on the axis, equal to abs(z - z_aspheric_value) / norm(grad_z) + distance_to_aspheric = abs(z - _aspheric_sag_r2(r2, c, k, α_coeffs)) / sqrt(1 + _aspheric_slope2_r2(r2, c, k, α_coeffs)) if sign(c) == 1 && z_aspheric_boundary < 0 # the asphere curves towards negative sag so we need to close the perimeter # at its max sag value instead of the boundary p = Point2(r, z) a1, b1 = Point2(d / 2, z_aspheric_boundary), Point2(d / 2, max_sag[1]) - sdl1 = sd_line_segment(p, a1, b1) / n_grad_z_boundary a2, b2 = Point2(d / 2, max_sag[1]), Point2(-d / 2, max_sag[1]) - sdl2 = sd_line_segment(p, a2, b2) / n_grad_z_boundary a3, b3 = Point2(-d / 2, max_sag[1]), Point2(-d / 2, z_aspheric_boundary) - sdl3 = sd_line_segment(p, a3, b3) / n_grad_z_boundary + # unscaled distance to the closing segments + d_closure = min(sd_line_segment(p, a1, b1), sd_line_segment(p, a2, b2), sd_line_segment(p, a3, b3)) if z_aspheric_value < z < max_sag[1] - return -min(distance_to_aspheric, sdl1, sdl2, sdl3) + return -_min_surface_first(distance_to_aspheric, d_closure, n_grad_z_boundary) else - return min(distance_to_aspheric, sdl1, sdl2, sdl3) + return _min_surface_first(distance_to_aspheric, d_closure, n_grad_z_boundary) end else # If we are inside the aperture, let's close the perimeter with a line segment a, b = Point2(d / 2, z_aspheric_boundary), Point2(-d / 2, z_aspheric_boundary) - sdl = sd_line_segment(Point2(r, z), a, b) / n_grad_z_boundary + d_closure = sd_line_segment(Point2(r, z), a, b) if sign(c) * z_aspheric_value < sign(c) * z < sign(c) * z_aspheric_boundary - return -min(sdl, distance_to_aspheric) + return -_min_surface_first(distance_to_aspheric, d_closure, n_grad_z_boundary) else - return min(sdl, distance_to_aspheric) + return _min_surface_first(distance_to_aspheric, d_closure, n_grad_z_boundary) end end end -function concave_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, edge) - r2 = r^2 +function concave_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, edge, r2 = r^2) r2_bound = (d / 2)^2 z_aspheric_value = aspheric_equation(r, c, k, α_coeffs) grad_z = gradient_aspheric_equation(r, c, k, α_coeffs) @@ -290,12 +318,14 @@ function concave_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, ed return distance_to_boundary / n_grad_z_boundary end - distance_to_aspheric = abs(z - z_aspheric_value) / norm(grad_z) + # via r², i.e. smooth on the axis, equal to abs(z - z_aspheric_value) / norm(grad_z) + distance_to_aspheric = abs(z - _aspheric_sag_r2(r2, c, k, α_coeffs)) / sqrt(1 + _aspheric_slope2_r2(r2, c, k, α_coeffs)) p = Point2(r, z) if max_sag[1] > 0 && z_aspheric_boundary < 0 a, b = Point2(d / 2, z_aspheric_boundary), Point2(-d / 2, z_aspheric_boundary) - sdl = sd_line_segment(p, a, b) / n_grad_z_boundary + d_closure = sd_line_segment(p, a, b) + sdl = d_closure / n_grad_z_boundary if r2 > r2_bound # we are outside of the aperture, so the shortest distance can be determined @@ -304,33 +334,32 @@ function concave_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, ed else # return a negative sign within the asphere if z_aspheric_boundary < z < z_aspheric_value - return -min(distance_to_aspheric, sdl) + return -_min_surface_first(distance_to_aspheric, d_closure, n_grad_z_boundary) elseif z_aspheric_boundary > 0 && (0.0 < z < z_aspheric_value) - return -min(distance_to_aspheric, sdl) + return -_min_surface_first(distance_to_aspheric, d_closure, n_grad_z_boundary) else - return min(distance_to_aspheric, sdl) + return _min_surface_first(distance_to_aspheric, d_closure, n_grad_z_boundary) end end else a1, b1 = Point2(d / 2, z_aspheric_boundary), Point2(d / 2, 0.0) - sdl1 = sd_line_segment(p, a1, b1) / n_grad_z_boundary a2, b2 = Point2(d / 2, 0.0), Point2(-d / 2, 0.0) - sdl2 = sd_line_segment(p, a2, b2) / n_grad_z_boundary a3, b3 = Point2(-d / 2, 0.0), Point2(-d / 2, z_aspheric_boundary) - sdl3 = sd_line_segment(p, a3, b3) / n_grad_z_boundary + # unscaled distance to the closing segments + d_closure = min(sd_line_segment(p, a1, b1), sd_line_segment(p, a2, b2), sd_line_segment(p, a3, b3)) if r2 > r2_bound # we are outside of the aperture, so the shortest distance can be determined # by the perimeter line segments which include the boundary points of the asphere - return min(sdl1, sdl2, sdl3) + return d_closure / n_grad_z_boundary else # return a negative sign within the asphere if z_aspheric_boundary < 0 && (z_aspheric_value < z < 0.0) - return -min(distance_to_aspheric, sdl1, sdl2, sdl3) + return -_min_surface_first(distance_to_aspheric, d_closure, n_grad_z_boundary) elseif z_aspheric_boundary > 0 && (0.0 < z < z_aspheric_value) - return -min(distance_to_aspheric, sdl1, sdl2, sdl3) + return -_min_surface_first(distance_to_aspheric, d_closure, n_grad_z_boundary) else - return min(distance_to_aspheric, sdl1, sdl2, sdl3) + return _min_surface_first(distance_to_aspheric, d_closure, n_grad_z_boundary) end end end @@ -366,21 +395,19 @@ function sdf(surface::ConvexAsphericalSurfaceSDF{T}, point) where {T} # spherical logic is to have the z-axis as optical axis, so the aspheric code is written # with that convention in mind so everything matches ISO10110/textbook definitions. # We reinterpret the coordinates here, so xz is the transversal direction and y is the - # optical axis. - _pp = Point3(p_local[1], p_local[3], p_local[2]) # xzy - # rotate 2D sdf around the optical axis - sdf_v = op_revolve_z(_pp, - x -> convex_aspheric_surface_distance( - x[1], - x[2], - 1 / surface.radius, - surface.conic_constant, - surface.diameter, - surface.coefficients, - surface.max_sag, - surface.edge - ), zero(T)) - return sdf_v + # optical axis. The 2D distance is revolved around the optical axis, with r² from the + # coordinates, see `_aspheric_sag_r2`. + x, z = p_local[1], p_local[3] + return convex_aspheric_surface_distance( + _radial(x, z), + p_local[2], + 1 / surface.radius, + surface.conic_constant, + surface.diameter, + surface.coefficients, + surface.max_sag, + surface.edge, + x^2 + z^2) end function sdf(surface::ConcaveAsphericalSurfaceSDF{T}, point) where {T} @@ -388,21 +415,19 @@ function sdf(surface::ConcaveAsphericalSurfaceSDF{T}, point) where {T} # spherical logic is to have the z-axis as optical axis, so the aspheric code is written # with that convention in mind so everything matches ISO10110/textbook definitions. # We reinterpret the coordinates here, so xz is the transversal direction and y is the - # optical axis. - _pp = Point3(p_local[1], p_local[3], p_local[2]) # xzy - # rotate 2D sdf around the optical axis - sdf_v = op_revolve_z(_pp, - x -> concave_aspheric_surface_distance( - x[1], - x[2], - 1 / surface.radius, - surface.conic_constant, - surface.diameter, - surface.coefficients, - surface.max_sag, - surface.edge - ), zero(T)) - return sdf_v + # optical axis. The 2D distance is revolved around the optical axis, with r² from the + # coordinates, see `_aspheric_sag_r2`. + x, z = p_local[1], p_local[3] + return concave_aspheric_surface_distance( + _radial(x, z), + p_local[2], + 1 / surface.radius, + surface.conic_constant, + surface.diameter, + surface.coefficients, + surface.max_sag, + surface.edge, + x^2 + z^2) end """ diff --git a/src/SDFs/ConicSDF.jl b/src/SDFs/ConicSDF.jl index 2ce6ada66..141436d8a 100644 --- a/src/SDFs/ConicSDF.jl +++ b/src/SDFs/ConicSDF.jl @@ -1,4 +1,6 @@ -_conic_sag(r, R, k) = r^2 / (R * (1 + sqrt(1 - (1 + k) * r^2 / R^2))) +_conic_sag(r, R, k) = _conic_sag_r2(r^2, R, k) +# the sag as a function of r², which is smooth also on the axis, see `_radial` +_conic_sag_r2(r2, R, k) = r2 / (R * (1 + sqrt(1 - (1 + k) * r2 / R^2))) _conic_slope(r, R, k) = (r / R) / sqrt(1 - (1 + k) * r^2 / R^2) """ @@ -144,10 +146,11 @@ function sdf(s::ConicSDF{T}, point) where {T} Z_off = _conic_sag(s.x_off, R, s.k) r_hi = abs(s.x_off) + s.diameter / 2 - r_p = sqrt((x + s.x_off)^2 + z^2) - r_c = min(r_p, r_hi) + # r² of the point, clamped to the aperture: the sag via r² is smooth on the axis, also for + # automatic differentiation, in contrast to the radius + r_c2 = min((x + s.x_off)^2 + z^2, r_hi^2) - y_surf = -(_conic_sag(r_c, R, s.k) - Z_off) + y_surf = -(_conic_sag_r2(r_c2, R, s.k) - Z_off) # `g` uses the *global* (aperture-rim) slope rather than the local one at `r_c`. `Z'` # is monotone increasing in `r` for every conic family here, so `r_hi` is where the # true gradient magnitude is largest over the whole segment; dividing by this @@ -163,7 +166,7 @@ function sdf(s::ConicSDF{T}, point) where {T} g = sqrt(one(T) + _conic_slope(r_hi, R, s.k)^2) d_front = (y_surf - y) / g - d_cyl = sqrt(x^2 + z^2) - s.diameter / 2 + d_cyl = _radial(x, z) - s.diameter / 2 d_back = y - s.thickness return max(d_front, d_cyl, d_back) diff --git a/src/SDFs/PrimitiveSDF.jl b/src/SDFs/PrimitiveSDF.jl index f9f28a182..b029513e5 100644 --- a/src/SDFs/PrimitiveSDF.jl +++ b/src/SDFs/PrimitiveSDF.jl @@ -77,7 +77,7 @@ end function sdf(cylinder::CylinderSDF{T}, point) where T p = _world_to_sdf(cylinder, point) - d = abs.(Point2(norm(Point2(p[1], p[3])), p[2])) - + d = abs.(Point2(_radial(p[1], p[3]), p[2])) - Point2(cylinder.radius, cylinder.height) return min(maximum(d), zero(T)) + norm(max.(d, zero(T))) end @@ -128,11 +128,12 @@ end function sdf(cs::CutSphereSDF, point) p = _world_to_sdf(cs, point) - q = Point2(norm(Point2(p[1], p[3])), p[2]) + q = Point2(_radial(p[1], p[3]), p[2]) s = max((cs.height - cs.radius) * q[1]^2 + cs.w^2 * (cs.height + cs.radius - 2 * q[2]), cs.height * q[1] - cs.w * q[2]) if s < 0 - return norm(q) - cs.radius + # the 3D norm, not `norm(q)`: its derivatives are defined on the axis, where `q[1]` is not + return norm(Point3(p[1], p[3], q[2])) - cs.radius elseif q[1] < cs.w return cs.height - q[2] else @@ -191,7 +192,7 @@ end function sdf(ring::RingSDF, point) p = _world_to_sdf(ring, point) - return sdf_box(Point2(norm(Point2(p[1], p[3]))- ring.inner_radius, p[2]), Point2(ring.hwidth, ring.hthickness)) + return sdf_box(Point2(_radial(p[1], p[3])- ring.inner_radius, p[2]), Point2(ring.hwidth, ring.hthickness)) end """ diff --git a/src/SDFs/SphericalLensSDF.jl b/src/SDFs/SphericalLensSDF.jl index 924ffbe61..f562c817a 100644 --- a/src/SDFs/SphericalLensSDF.jl +++ b/src/SDFs/SphericalLensSDF.jl @@ -59,7 +59,7 @@ end function sdf(ps::PlanoSurfaceSDF{T}, point) where T p = _world_to_sdf(ps, point) - d = abs.(Point2(norm(Point2(p[1], p[3])), p[2] - thickness(ps)/2)) - + d = abs.(Point2(_radial(p[1], p[3]), p[2] - thickness(ps)/2)) - Point2(diameter(ps)/2, thickness(ps)/2) return min(maximum(d), zero(T)) + norm(max.(d, zero(T))) end @@ -177,7 +177,7 @@ function sdf(css::ConcaveSphericalSurfaceSDF{T}, point) where T p = _world_to_sdf(css, point) # cylinder sdf ps = p + Point3(zero(T), sag(css)/2, zero(T)) - d = abs.(Point2(norm(Point2(ps[1], ps[3])), ps[2])) - + d = abs.(Point2(_radial(ps[1], ps[3]), ps[2])) - Point2(diameter(css)/2, sag(css)/2) sdf1 = min(maximum(d), zero(T)) + norm(max.(d, zero(T))) # sphere sdf @@ -247,11 +247,12 @@ end function sdf(css::ConvexSphericalSurfaceSDF, point) p = _world_to_sdf(css, point) # -p[2] to align surface with neg. y-axis - q = Point2(norm(Point2(p[1], p[3])), -p[2] + radius(css)) + q = Point2(_radial(p[1], p[3]), -p[2] + radius(css)) s = max((css.height - radius(css)) * q[1]^2 + (diameter(css)/2)^2 * (css.height + radius(css) - 2 * q[2]), css.height * q[1] - diameter(css)/2 * q[2]) if s < 0 - return norm(q) - radius(css) + # the 3D norm, not `norm(q)`: its derivatives are defined on the axis, where `q[1]` is not + return norm(Point3(p[1], p[3], q[2])) - radius(css) elseif q[1] < diameter(css)/2 return css.height - q[2] else diff --git a/src/SDFs/UnionSDF.jl b/src/SDFs/UnionSDF.jl index 5e814d28d..c14b4d273 100644 --- a/src/SDFs/UnionSDF.jl +++ b/src/SDFs/UnionSDF.jl @@ -74,8 +74,30 @@ Base.:+(u1::UnionSDF{T}, u2::UnionSDF{T}) where T = UnionSDF{T}(u1.sdfs..., u2.s # Without this function it is not possible for SDFs encapsulated in a UnionSDF # to specialize normal3d as always the generic normal3d function is called. function normal3d(s::UnionSDF, pos) - # find the closes sub-sdf and call its normal method - idx = argmin(sdf(_sdf, pos) for _sdf in s.sdfs) + ds = map(_sdf -> sdf(_sdf, pos), s.sdfs) + return normal3d(s.sdfs[_closest_operand(s.sdfs, ds, pos)], pos) +end - return normal3d(s.sdfs[idx], pos) +""" + _closest_operand(operands, ds, pos) + +Returns the index of the operand closest to `pos`, for the SDF values `ds` of the `operands` at +`pos`. Operands that are equally close up to rounding touch each other tangentially near `pos`, +e.g. the vertex of a concave lens surface touches the face of the lens body. Both give the same +normal, but only the outer one, i.e. the boundary of the union next to `pos`, gives its change, +e.g. its derivative w.r.t. the pose of the lens in automatic differentiation. The outer one is the +closest operand at four points beside `pos`, `ρ` along the tangent plane and `ρ` outward, i.e. +outside of the union also if `pos` lies on its surface. +""" +function _closest_operand(operands, ds, pos; ρ = 1e-6) + d_min = minimum(ds) + tol = Config.get_sdf_raymarch_eps() / 100 + # the usual case, one closest operand, without allocations + count(d -> d ≤ d_min + tol, ds) == 1 && return findfirst(d -> d ≤ d_min + tol, ds) + tied = findall(d -> d ≤ d_min + tol, collect(ds)) + n = normal3d(operands[first(tied)], pos) + t1 = normal3d(Point3(n)) + t2 = cross(n, t1) + beside(o) = sum(sdf(o, pos + ρ * (t + n)) for t in (t1, -t1, t2, -t2)) + return tied[argmin(map(i -> beside(operands[i]), tied))] end \ No newline at end of file diff --git a/test/Project.toml b/test/Project.toml index 25fd4f4fe..04c304c9a 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -2,6 +2,7 @@ AbstractTrees = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" Aqua = "4c88cf16-eb10-579e-8560-4a9242c79595" BeamletOptics = "c387492b-ffec-4e51-9a46-bd230226031c" +ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" GeometryBasics = "5c1252a2-5f33-56bf-86c9-59e7332b4326" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" Logging = "56ddb016-857b-54e1-b83d-db4d58db5568" @@ -17,6 +18,7 @@ path = ".." AbstractTrees = "0.4" Aqua = "0.8" BeamletOptics = "0.14, 0.13" +ForwardDiff = "0.10, 1" GeometryBasics = "0.5" Logging = "1" Makie = "0.24" diff --git a/test/TestAutoDiff.jl b/test/TestAutoDiff.jl new file mode 100644 index 000000000..4f82e9769 --- /dev/null +++ b/test/TestAutoDiff.jl @@ -0,0 +1,110 @@ +module TestAutoDiff + +using BeamletOptics +using ForwardDiff +using LinearAlgebra +using Test + +const BMO = BeamletOptics + +const mm = 1e-3 + +#= +Derivatives of traced results w.r.t. the pose of a component, via ForwardDiff, compared with +central finite differences. The number type of the setup is that of the parameter `dx`, i.e. a +`ForwardDiff.Dual` within `ForwardDiff.derivative`. +=# + +""" +The `x` coordinate of the hit of a ray at the height `h` on a detector, with the `component` shifted +laterally by `dx`. `component(T)` builds it in the number type `T` with its axis along `y`; a mirror +reflects the ray back towards `-y` (`mirror = true`), where the detector lies. +""" +function spot_x(component, dx; h, mirror = false) + T = typeof(dx) + c = component(T) + translate3d!(c, [dx, zero(T), zero(T)]) + pd = Detector(T(40mm)) + if mirror + zrotate3d!(pd, T(π)) + translate3d!(pd, T[0, -30mm, 0]) + else + translate3d!(pd, T[0, 100mm, 0]) + end + # a mirror is hit from -y, the detector lies between source and mirror and does not stop it + y0 = mirror ? -20mm : -50mm + beam = Beam(T[h, y0, 0], T[0, 1, 0], T(1e-6)) + system = System([c, pd]) + solve_system!(system, beam) + return BMO.hit_point(last(BMO.hits(pd)))[1] +end + +function check_derivative(component; h, mirror = false) + f(dx) = spot_x(component, dx; h, mirror) + δ = 1e-6 + return ForwardDiff.derivative(f, 0.0), (f(δ) - f(-δ)) / 2δ +end + +n(T) = _ -> T(1.5) +lenses = [ + "bi-convex SphericalLens" => T -> SphericalLens(T(50mm), T(-50mm), T(5mm), T(25mm), n(T)), + "bi-concave SphericalLens" => T -> SphericalLens(T(-50mm), T(50mm), T(3mm), T(25mm), n(T)), + "meniscus SphericalLens" => T -> SphericalLens(T(30mm), T(50mm), T(4mm), T(25mm), n(T)), + "thin meniscus (MeniscusLensSDF)" => T -> SphericalLens(T(50mm), T(30mm), T(3mm), T(25.4mm), n(T)), + "plano-convex aspheric Lens" => T -> Lens(EvenAsphericalSurface(T(40mm), T(25mm), T(-1), T[0, 1e3]), + CircularFlatSurface(T(25mm)), T(6mm), n(T)), + "plano-concave aspheric Lens" => T -> Lens(EvenAsphericalSurface(T(-40mm), T(25mm), T(-1), T[0, -1e3]), + CircularFlatSurface(T(25mm)), T(3mm), n(T)), + "cylindrical Lens" => T -> Lens(CylindricalSurface(T(30mm), T(20mm), T(25mm)), T(5mm), n(T)), +] +mirrors = [ + "SphericalMirror" => T -> SphericalMirror(T(200mm), T(5mm), T(25mm)), + "ParabolicMirror" => T -> ParabolicMirror(T(100mm), T(25mm)), + "ConicMirror (hyperboloid)" => T -> ConicMirror(T(200mm), T(-2), T(25mm)), +] + +@testset "Automatic differentiation" begin + @testset "$label, h = $h" for (label, c) in lenses, h in (0.0, 2mm) + ad, fd = check_derivative(c; h) + @test isfinite(ad) + @test ad ≈ fd rtol = 1e-5 + end + @testset "$label, h = $h" for (label, c) in mirrors, h in (0.0, 2mm) + ad, fd = check_derivative(c; h, mirror = true) + @test isfinite(ad) + @test ad ≈ fd rtol = 1e-5 + end + @testset "refractive index" begin + # the spot of a ray at h = 2 mm behind a bi-convex lens with the refractive index `n0` + function spot(n0) + T = typeof(n0) + lens = SphericalLens(T(50mm), T(-50mm), T(5mm), T(25mm), _ -> n0) + pd = Detector(T(40mm)) + translate3d!(pd, T[0, 100mm, 0]) + beam = Beam(T[2mm, -50mm, 0], T[0, 1, 0], T(1e-6)) + solve_system!(System([lens, pd]), beam) + return BMO.hit_point(only(BMO.hits(pd)))[1] + end + ad = ForwardDiff.derivative(spot, 1.5) + fd = (spot(1.5 + 1e-6) - spot(1.5 - 1e-6)) / 2e-6 + @test ad ≈ fd rtol = 1e-5 + end + @testset "GaussianBeamlet" begin + # the hit point of a beamlet on the axis behind a lens that is shifted laterally + function spot(dx) + T = typeof(dx) + lens = SphericalLens(T(50mm), T(-50mm), T(5mm), T(25mm), _ -> T(1.5)) + translate3d!(lens, [dx, zero(T), zero(T)]) + pd = Detector(T(40mm)) + translate3d!(pd, T[0, 100mm, 0]) + g = GaussianBeamlet(T[0, -50mm, 0], T[0, 1, 0], T(1e-6), T(1mm)) + solve_system!(System([lens, pd]), g) + return BMO.hit_point(only(BMO.hits(pd)))[1] + end + ad = ForwardDiff.derivative(spot, 0.0) + fd = (spot(1e-6) - spot(-1e-6)) / 2e-6 + @test ad ≈ fd rtol = 1e-5 + end +end + +end # MODULE diff --git a/test/runtests.jl b/test/runtests.jl index 2c306ffb9..7e25194a6 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -47,6 +47,9 @@ include(joinpath(@__DIR__, "Components", "ConicMirrors", "TestParabolicMirror.jl include(joinpath(@__DIR__, "Components", "ConicMirrors", "TestEllipsoidalMirror.jl")) include(joinpath(@__DIR__, "Components", "ConicMirrors", "TestHyperbolicMirror.jl")) +# Test automatic differentiation through the tracing +include(joinpath(@__DIR__, "TestAutoDiff.jl")) + # Test progress bars of long-running calls include(joinpath(@__DIR__, "TestProgress.jl")) From ea8be0384ae16bdeae9f4d5c4323fc7a48b18c79 Mon Sep 17 00:00:00 2001 From: Oliver Kliebisch Date: Sun, 11 Oct 2026 22:08:19 +0200 Subject: [PATCH 3/8] 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. --- docs/make.jl | 1 + docs/src/basics/autodiff.md | 57 +++++++++++++++ skills/beamletoptics/WORKFLOW.md | 9 +++ src/Mesh.jl | 5 +- .../Beamsplitters/ThinBeamsplitter.jl | 6 ++ src/OpticalComponents/Lenses.jl | 6 +- .../Polarizers/LinearPolarizer.jl | 3 +- src/Utils/LinearAlgebraUtils.jl | 11 ++- src/Utils/OpticUtils.jl | 10 ++- test/TestAutoDiff.jl | 71 +++++++++++++++++++ 10 files changed, 167 insertions(+), 12 deletions(-) create mode 100644 docs/src/basics/autodiff.md diff --git a/docs/make.jl b/docs/make.jl index 104ece1f1..9dd1b74c7 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -126,6 +126,7 @@ makedocs(; "Polarizing components" => joinpath("basics", "components", "polarizers.md"), ], "Optical systems" => joinpath("basics", "systems.md"), + "Automatic differentiation" => joinpath("basics", "autodiff.md"), "Kinematics" => Any[ "Overview" => joinpath("basics", "kinematics", "kinematics.md"), "Optical elements" => joinpath("basics", "kinematics", "objects.md"), diff --git a/docs/src/basics/autodiff.md b/docs/src/basics/autodiff.md new file mode 100644 index 000000000..5b1f88258 --- /dev/null +++ b/docs/src/basics/autodiff.md @@ -0,0 +1,57 @@ +# Automatic differentiation + +Results of [`solve_system!`](@ref) can be differentiated with respect to the parameters of a setup +via forward-mode automatic differentiation with +[ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl), e.g. for gradient-based optimization +or sensitivity analysis. The derivative is exact up to the accuracy of the ray tracing, typically +better than ``10^{-5}`` relative, and it is free of the step size problem of finite differences. + +## Usage + +BMO is generic in its number type. Write the setup as a function of the parameter and build every +component, beam and detector in the number type `T` of the parameter, which is a +`ForwardDiff.Dual` while the derivative is computed: + +```julia +using BeamletOptics, ForwardDiff + +# x coordinate of the spot behind a lens that is shifted laterally by `dx` +function spot_x(dx) + T = typeof(dx) + lens = SphericalLens(T(50e-3), T(-50e-3), T(5e-3), T(25e-3), _ -> T(1.5)) + translate3d!(lens, [dx, zero(T), zero(T)]) + pd = Detector(T(40e-3)) + translate3d!(pd, T[0, 0.1, 0]) + beam = Beam(T[0, -0.05, 0], T[0, 1, 0], T(1e-6)) + solve_system!(System([lens, pd]), beam) + return BeamletOptics.hit_point(only(BeamletOptics.hits(pd)))[1] +end + +ForwardDiff.derivative(spot_x, 0.0) # ≈ 1.90 +``` + +The parameter can enter anywhere: the pose of a component (`translate3d!`, `rotate3d!`), its +geometry (radii, thicknesses), a refractive index (e.g. `_ -> n0` for the parameter `n0`) or a +source. Many parameters at once are differentiated with `ForwardDiff.gradient` or +`ForwardDiff.jacobian`. + +The test suite (`test/TestAutoDiff.jl`) compares the derivatives with finite differences for rays +and beamlets through spherical, aspheric, meniscus and cylindrical lenses, spherical, parabolic +and conic mirrors, prisms (including total internal reflection), thin, plate and cube +beamsplitters, polarizing filters, for polarized rays and for the optical power on a detector, +e.g. of a Michelson interferometer vs. the position of a mirror. + +## Limitations + +- **Discrete events are not differentiable.** Which surface a ray hits, the onset of total internal + reflection, a ray that misses an aperture or a detector, and the cutoff by `r_max` change the + result in steps. The derivative is that of the current path; at a step it is not defined, also + not for finite differences. +- **Edges and corners.** At the edge of a prism or the rim of a lens the normal changes abruptly, a + ray that hits such an edge has no meaningful derivative. +- **Number type of object groups.** An [`ObjectGroup`](@ref) is `Float64` unless its number type is + passed: `ObjectGroup(objects, T)`. +- **Forward mode only.** The cost grows with the number of parameters. Reverse-mode AD (Zygote, + Enzyme) is not supported, since the tracing mutates its beams and objects. +- **Compile time.** Each new combination of dual number and setup is compiled on its first call, + which takes several seconds. diff --git a/skills/beamletoptics/WORKFLOW.md b/skills/beamletoptics/WORKFLOW.md index 53acc58a4..0d66a48d5 100644 --- a/skills/beamletoptics/WORKFLOW.md +++ b/skills/beamletoptics/WORKFLOW.md @@ -46,6 +46,15 @@ end - Read everything you need from a detector **before** moving anything or solving again (hits reference beam state). - See `templates/01_singlet_spot_diagram.jl` (focus scan) and `templates/04_michelson_scan.jl` (fringes). +## Derivatives (optimization, sensitivity) + +- `ForwardDiff.derivative`/`gradient` work through `solve_system!` when every component, beam and + detector is built in the number type `T` of the parameter (`T = typeof(p)`); pass it to + `ObjectGroup(objects, T)`, groups are `Float64` otherwise. +- The derivative is that of the current light path: it is not defined where the path changes, e.g. a + ray that starts to miss a component, hits an edge, or begins total internal reflection. +- See the docs page "Automatic differentiation" (`docs/src/basics/autodiff.md`). + ## Interferometers and coherent sums - Use `GaussianBeamlet` (on-axis, paraxial) or `AstigmaticGaussianBeamlet` (tilted/off-axis) sources and diff --git a/src/Mesh.jl b/src/Mesh.jl index 2c4ba07d5..d6ccf09f8 100644 --- a/src/Mesh.jl +++ b/src/Mesh.jl @@ -295,12 +295,13 @@ Creates a 2D rectangular [`Mesh`](@ref) that is centered around the origin and a function CircularFlatMesh(radius::T, n::Int=30) where T<:Real # calculate vertices xs = [cos(x)*radius for x in LinRange(0, 2pi * (n-1)/n, n)] - ys = zeros(n+1) + ys = zeros(T, n+1) zs = [sin(x)*radius for x in LinRange(0, 2pi * (n-1)/n, n)] # add center vertex pushfirst!(xs, 0) pushfirst!(zs, 0) - vertices = Matrix{Float64}(undef, n+1, 3) + # in the number type of the radius, e.g. dual numbers in automatic differentiation + vertices = Matrix{T}(undef, n+1, 3) vertices[:, 1] = xs vertices[:, 2] = ys vertices[:, 3] = zs diff --git a/src/OpticalComponents/Beamsplitters/ThinBeamsplitter.jl b/src/OpticalComponents/Beamsplitters/ThinBeamsplitter.jl index 11d99d6ab..35a22687b 100644 --- a/src/OpticalComponents/Beamsplitters/ThinBeamsplitter.jl +++ b/src/OpticalComponents/Beamsplitters/ThinBeamsplitter.jl @@ -19,6 +19,12 @@ struct ThinBeamsplitter{T <: Real, S <: AbstractShape{T}} <: AbstractBeamsplitte transmittance::T end +# The factors in the number type of the `shape`, e.g. of a shape built from dual numbers for +# automatic differentiation w.r.t. its pose, while the reflectance is a `Float64` +function ThinBeamsplitter(shape::AbstractShape{T}, reflectance::Real, transmittance::Real) where {T} + return ThinBeamsplitter{T, typeof(shape)}(shape, T(reflectance), T(transmittance)) +end + reflectance(bs::ThinBeamsplitter) = bs.reflectance transmittance(bs::ThinBeamsplitter) = bs.transmittance diff --git a/src/OpticalComponents/Lenses.jl b/src/OpticalComponents/Lenses.jl index f052424dc..d37bc4de4 100644 --- a/src/OpticalComponents/Lenses.jl +++ b/src/OpticalComponents/Lenses.jl @@ -106,10 +106,8 @@ function interact3d(system::AbstractSystem, optic::AbstractRefractiveOptic, # Flip normal for refraction3d normal = -normal end - # Calculate (and correct into 1. quadrant) the angle of incidence - θi = angle3d(direction(ray), -normal) - # Get Fresnel coefficients - rs, rp, ts, tp = fresnel_coefficients(θi, n2 / n1) + # Fresnel coefficients from the cosine of the angle of incidence (in the 1. quadrant) + rs, rp, ts, tp = _fresnel_coefficients(cos_angle3d(direction(ray), -normal), n2 / n1) # Optical interaction if is_internally_reflected(rp, rs) # Update hint and outgoing ref. index diff --git a/src/OpticalComponents/Polarizers/LinearPolarizer.jl b/src/OpticalComponents/Polarizers/LinearPolarizer.jl index e65787a71..a04c59cee 100644 --- a/src/OpticalComponents/Polarizers/LinearPolarizer.jl +++ b/src/OpticalComponents/Polarizers/LinearPolarizer.jl @@ -143,8 +143,7 @@ function _film_interface(system::AbstractSystem, lp::LinearPolarizer, from, to, normal = -normal3d(intersection(ray)) npos = position(ray) + length(ray) * direction(ray) in_dir = direction(ray) - θi = angle3d(in_dir, -normal) - rs, rp, ts, tp = fresnel_coefficients(θi, n2 / n1) + rs, rp, ts, tp = _fresnel_coefficients(cos_angle3d(in_dir, -normal), n2 / n1) if is_internally_reflected(rp, rs) new_dir = reflection3d(in_dir, normal) J = SPBasis(-rs, 0, 0, rp) diff --git a/src/Utils/LinearAlgebraUtils.jl b/src/Utils/LinearAlgebraUtils.jl index aab9e35a6..a365af788 100644 --- a/src/Utils/LinearAlgebraUtils.jl +++ b/src/Utils/LinearAlgebraUtils.jl @@ -6,7 +6,9 @@ vectors, `norm(cross(v1, v2))` of the normalized vectors, is at most `atol`. """ function isparallel3d(v1::AbstractArray, v2::AbstractArray; atol = sqrt(eps(float(promote_type(eltype(v1), eltype(v2)))))) - return norm(cross(normalize(v1), normalize(v2))) ≤ atol + # the squared norm: `norm` of a cross product that vanishes is `NaN` for dual numbers whose + # derivative does not vanish, e.g. at normal incidence in automatic differentiation + return sum(abs2, cross(normalize(v1), normalize(v2))) ≤ atol^2 end """ @@ -142,6 +144,13 @@ function angle3d(target::AbstractArray{T}, start::AbstractArray{R}) where {T,R} return angle end +# The cosine of `angle3d(target, start)`, without the `acos`: differentiable also for parallel +# vectors, e.g. at normal incidence, where the derivative of the angle is not defined. +function cos_angle3d(target::AbstractArray{T}, start::AbstractArray{R}) where {T, R} + G = promote_type(T, R) + return clamp(dot(target, start) / (norm(target) * norm(start)), -one(G), one(G)) +end + """ angle3d(target::AbstractArray, start::AbstractArray, reference::AbstractArray) diff --git a/src/Utils/OpticUtils.jl b/src/Utils/OpticUtils.jl index 15b7c6fa0..2c69c9001 100644 --- a/src/Utils/OpticUtils.jl +++ b/src/Utils/OpticUtils.jl @@ -121,10 +121,14 @@ and the refractive index ratio `n = n₂ / n₁`. Returns rₛ, rₚ, tₛ and t !!! info The signs of rₛ, rₚ are based on the definition by Fowles (1975, 2nd Ed. p. 44) and Peatross (2015, 2023 Ed. p. 78) """ -function fresnel_coefficients(θ::T, n::Number) where {T} +fresnel_coefficients(θ::Real, n::Number) = _fresnel_coefficients(cos(θ), n) + +# The Fresnel coefficients for the cosine `cost` of the angle of incidence. Computed from the cosine, +# they are differentiable also at normal incidence, e.g. in automatic differentiation, where the +# derivative of the angle, an `acos`, is not defined. +function _fresnel_coefficients(cost::T, n::Number) where {T} C = Complex{T} - cost = cos(θ) - n2s2 = sqrt(C(n^2 - sin(θ)^2)) + n2s2 = sqrt(C(n^2 - (1 - cost^2))) # Calculate coefficients for reflection/transmission rs = (cost - n2s2) / (cost + n2s2) rp = (-n^2 * cost + n2s2) / (n^2 * cost + n2s2) diff --git a/test/TestAutoDiff.jl b/test/TestAutoDiff.jl index 4f82e9769..650ac98b4 100644 --- a/test/TestAutoDiff.jl +++ b/test/TestAutoDiff.jl @@ -63,6 +63,70 @@ mirrors = [ "ConicMirror (hyperboloid)" => T -> ConicMirror(T(200mm), T(-2), T(25mm)), ] +pd_at(T, y) = (d = Detector(T(40mm)); translate3d!(d, T[0, y, 0]); d) +hit_x(pd) = BMO.hit_point(only(BMO.hits(pd)))[1] +bi_convex(T) = SphericalLens(T(50mm), T(-50mm), T(5mm), T(25mm), _ -> T(1.5)) +polarized(T, x) = Beam(PolarizedRay(T[x, -50mm, 0], T[0, 1, 0], T(1e-6), Complex{T}[1, 0, 0])) + +""" +A Michelson interferometer with a cube beamsplitter, the optical power on its detector for the +arm mirror `m1` shifted by `dx` along its axis. +""" +function michelson_power(dx) + T = typeof(dx) + cm = T(1e-2) + cbs = CubeBeamsplitter(T(25.4mm), _ -> T(1.51509)) + zrotate3d!(cbs, T(-π / 2)) + translate3d!(cbs, T[0, 23.5cm, 0]) + m1 = RoundPlanoMirror(T(25.4mm), T(5mm)) + zrotate3d!(m1, T(-π / 2)) + translate3d!(m1, T[5cm + dx, 23.5cm, 0]) + m2 = RoundPlanoMirror(T(25.4mm), T(5mm)) + translate3d!(m2, T[0, 30cm, 0]) + pd = Detector(T(8mm)) + zrotate3d!(pd, T(π / 2)) + translate3d!(pd, T[-5cm, 23.5cm, 0]) + g = GaussianBeamlet(T[0, 0, 0], T[0, 1, 0], T(632.8e-9), T(0.5mm)) + solve_system!(System([cbs, m1, m2, pd]), g) + return optical_power(pd; progress = false, n = 40) +end + +# label, function of the parameter, value of the parameter +parametric_cases = [ + ("radius of curvature", R -> (T = typeof(R); l = SphericalLens(R, T(-50mm), T(5mm), T(25mm), _ -> T(1.5)); + d = pd_at(T, 100mm); solve_system!(System([l, d]), Beam(T[2mm, -50mm, 0], T[0, 1, 0], T(1e-6))); hit_x(d)), 50mm), + ("center thickness", t -> (T = typeof(t); l = SphericalLens(T(50mm), T(-50mm), t, T(25mm), _ -> T(1.5)); + d = pd_at(T, 100mm); solve_system!(System([l, d]), Beam(T[2mm, -50mm, 0], T[0, 1, 0], T(1e-6))); hit_x(d)), 5mm), + ("lens tilt", θ -> (T = typeof(θ); l = bi_convex(T); zrotate3d!(l, θ); + d = pd_at(T, 100mm); solve_system!(System([l, d]), Beam(T[0, -50mm, 0], T[0, 1, 0], T(1e-6))); hit_x(d)), 0.0), + ("PolarizedRay on the axis", dx -> (T = typeof(dx); l = bi_convex(T); translate3d!(l, [dx, zero(T), zero(T)]); + d = pd_at(T, 100mm); solve_system!(System([l, d]), polarized(T, 0)); hit_x(d)), 0.0), + ("PolarizedRay transmitted field (Fresnel)", θ -> (T = typeof(θ); l = bi_convex(T); zrotate3d!(l, θ); + d = pd_at(T, 100mm); solve_system!(System([l, d]), polarized(T, 0)); norm(BMO.polarization(only(BMO.hits(d))))), 0.3), + ("AstigmaticGaussianBeamlet on the axis", dx -> (T = typeof(dx); l = bi_convex(T); translate3d!(l, [dx, zero(T), zero(T)]); + d = pd_at(T, 100mm); g = AstigmaticGaussianBeamlet(T[0, -50mm, 0], T[0, 1, 0], T(1e-6), T(1mm)); + solve_system!(System([l, d]), g); hit_x(d)), 0.0), + ("ThinBeamsplitter tilt, reflected beam", θ -> (T = typeof(θ); bs = ThinBeamsplitter(T(30mm)); zrotate3d!(bs, T(π / 4) + θ); + translate3d!(bs, T[0, 50mm, 0]); d = Detector(T(40mm)); zrotate3d!(d, T(π / 2)); translate3d!(d, T[100mm, 50mm, 0]); + solve_system!(System([bs, d]), Beam(T[0, 0, 0], T[0, 1, 0], T(1e-6))); BMO.hit_point(only(BMO.hits(d)))[2]), 0.0), + ("CubeBeamsplitter tilt", θ -> (T = typeof(θ); c = CubeBeamsplitter(T(25mm), _ -> T(1.5)); zrotate3d!(c, θ); + translate3d!(c, T[0, 50mm, 0]); d = pd_at(T, 150mm); + solve_system!(System([c, d]), Beam(T[1mm, 0, 0], T[0, 1, 0], T(1e-6))); hit_x(d)), 0.05), + ("RoundPlateBeamsplitter tilt", θ -> (T = typeof(θ); p = RoundPlateBeamsplitter(T(25mm), T(5mm), _ -> T(1.5)); + zrotate3d!(p, T(π / 4) + θ); translate3d!(p, T[0, 50mm, 0]); d = pd_at(T, 150mm); + solve_system!(System([p, d]), Beam(T[0, 0, 0], T[0, 1, 0], T(1e-6))); hit_x(d)), 0.0), + ("total internal reflection in a RightAnglePrism", θ -> (T = typeof(θ); p = RightAnglePrism(T(25mm), T(25mm), _ -> T(1.5)); + zrotate3d!(p, θ); translate3d!(p, T[0, 50mm, 0]); b = Beam(T[4mm, 0, 0], T[0, 1, 0], T(1e-6)); + solve_system!(System([p]), b); BMO.direction(last(BMO.rays(b)))[2]), 0.0), + ("RoundPolarizationFilter angle (Malus)", θ -> (T = typeof(θ); f = RoundPolarizationFilter(T(25mm)); yrotate3d!(f, θ); + translate3d!(f, T[0, 50mm, 0]); d = pd_at(T, 100mm); b = Beam(PolarizedRay(T[0, 0, 0], T[0, 1, 0], T(1e-6), Complex{T}[1, 0, 0])); + solve_system!(System([f, d]), b); sum(abs2, BMO.polarization(only(BMO.hits(d))))), 0.5), + ("optical_power of a clipped GaussianBeamlet", dx -> (T = typeof(dx); d = Detector(T(2mm)); translate3d!(d, [dx, T(100mm), zero(T)]); + g = GaussianBeamlet(T[0, 0, 0], T[0, 1, 0], T(1e-6), T(1mm)); solve_system!(System([d]), g); + optical_power(d; progress = false, n = 60, x_min = -1mm, x_max = 1mm, z_min = -1mm, z_max = 1mm)), 0.5mm), + ("Michelson interferometer, power vs. mirror position", michelson_power, 1e-8), +] + @testset "Automatic differentiation" begin @testset "$label, h = $h" for (label, c) in lenses, h in (0.0, 2mm) ad, fd = check_derivative(c; h) @@ -89,6 +153,13 @@ mirrors = [ fd = (spot(1.5 + 1e-6) - spot(1.5 - 1e-6)) / 2e-6 @test ad ≈ fd rtol = 1e-5 end + @testset "$label" for (label, f, x0) in parametric_cases + ad = ForwardDiff.derivative(f, x0) + δ = 1e-9 + fd = (f(x0 + δ) - f(x0 - δ)) / 2δ + @test isfinite(ad) + @test ad ≈ fd rtol = 1e-4 atol = 1e-9 + end @testset "GaussianBeamlet" begin # the hit point of a beamlet on the axis behind a lens that is shifted laterally function spot(dx) From a943a3106f579825871ce907a330f0276bb5668b Mon Sep 17 00:00:00 2001 From: Hugo Uittenbosch Date: Fri, 23 Oct 2026 16:04:01 +0200 Subject: [PATCH 4/8] 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 --- src/SDFs/AsphericalLensSDF.jl | 74 ++++++++++++++--------------------- 1 file changed, 29 insertions(+), 45 deletions(-) diff --git a/src/SDFs/AsphericalLensSDF.jl b/src/SDFs/AsphericalLensSDF.jl index af1c101e3..91347ae84 100644 --- a/src/SDFs/AsphericalLensSDF.jl +++ b/src/SDFs/AsphericalLensSDF.jl @@ -145,11 +145,8 @@ Only even aspheres are implemented at the moment. This will change soon. """ function aspheric_equation(r, c, k, α_coeffs) r2 = r^2 - sqrt_arg = 1 - (1 + k) * c^2 * r2 - if sqrt_arg < 0 - return NaN # Handle as desired - end - return c * r2 / (1 + sqrt(sqrt_arg)) + _even_aspheric_sum(r2, α_coeffs) + _aspheric_sqrt_arg(r2, c, k) < 0 && return NaN + return _aspheric_sag_r2(r2, c, k, α_coeffs) end # Σᵢ αᵢ r²ⁱ of the even aspheric terms, via Horner's scheme in r² @@ -161,49 +158,39 @@ function _even_aspheric_sum(r2, α_coeffs) return acc * r2 end -# d/dr of `_even_aspheric_sum(r^2, α_coeffs)`, i.e. Σᵢ 2i αᵢ r²ⁱ⁻¹, via Horner's scheme in r² -function _even_aspheric_sum_derivative(r, α_coeffs) - r2 = r^2 - acc = zero(r2 * zero(eltype(α_coeffs))) - for i in reverse(eachindex(α_coeffs)) - acc = muladd(acc, r2, 2i * α_coeffs[i]) - end - return acc * r -end - function aspheric_equation(r::Real, a::AbstractAsphericalSurfaceSDF) aspheric_equation(r, 1 / a.radius, a.conic_constant, a.coefficients) end function gradient_aspheric_equation(r, c, k, α_coeffs) - Ri = 1 / c - sqrt_arg = 1 - r^2 * (1 + k) / Ri^2 - sqrt_arg < 0 && return NaN - gr = 2 * r / (Ri * (√(sqrt_arg) + 1)) + - r^3 * (1 + k) / (Ri^3 * √(sqrt_arg) * (√(sqrt_arg) + 1)^2) - sum_r = _even_aspheric_sum_derivative(r, α_coeffs) - - return Point2(-sum_r - gr, 1) + r2 = r^2 + _aspheric_sqrt_arg(r2, c, k) < 0 && return NaN + return Point2(-r * _aspheric_slope_r2(r2, c, k, α_coeffs), 1) end -# The sag and the squared slope (dz/dr)² of the asphere as functions of r². Both are smooth on the -# axis, also for automatic differentiation, in contrast to functions of the radius r. +# The argument of the square root in the sag of the asphere; the asphere is not defined where it is +# negative. +_aspheric_sqrt_arg(r2, c, k) = 1 - (1 + k) * c^2 * r2 + +# The sag, the slope divided by the radius, G = (dz/dr) / r, and the squared slope (dz/dr)² = r² G² +# of the asphere as functions of r². They are smooth on the axis, also for automatic +# differentiation, in contrast to functions of the radius r. function _aspheric_sag_r2(r2, c, k, α_coeffs) - return c * r2 / (1 + sqrt(1 - (1 + k) * c^2 * r2)) + _even_aspheric_sum(r2, α_coeffs) + return c * r2 / (1 + sqrt(_aspheric_sqrt_arg(r2, c, k))) + _even_aspheric_sum(r2, α_coeffs) end -function _aspheric_slope2_r2(r2, c, k, α_coeffs) - Ri = 1 / c - sq = sqrt(1 - r2 * (1 + k) / Ri^2) - # dz/dr = r * G(r²) +function _aspheric_slope_r2(r2, c, k, α_coeffs) + sq = sqrt(_aspheric_sqrt_arg(r2, c, k)) + # Σᵢ 2i αᵢ r²⁽ⁱ⁻¹⁾ of the even aspheric terms, via Horner's scheme in r² acc = zero(r2 * zero(eltype(α_coeffs))) for i in reverse(eachindex(α_coeffs)) acc = muladd(acc, r2, 2i * α_coeffs[i]) end - G = 2 / (Ri * (sq + 1)) + r2 * (1 + k) / (Ri^3 * sq * (sq + 1)^2) + acc - return r2 * G^2 + return 2c / (sq + 1) + r2 * (1 + k) * c^3 / (sq * (sq + 1)^2) + acc end +_aspheric_slope2_r2(r2, c, k, α_coeffs) = r2 * _aspheric_slope_r2(r2, c, k, α_coeffs)^2 + # The smaller of the distance to the aspheric surface, `d_surface`, and the distance to the segments # that close the 2D perimeter, `d_closure`, divided, i.e. scaled down, by the factor `g` (≥ 1) as the # distance of the surface is. Within the surface threshold, where a closing segment may touch the @@ -248,14 +235,12 @@ It is intended to pair the SDF derived from this distance field with a cylinder """ function convex_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, edge, r2 = r^2) r2_bound = (d / 2)^2 - z_aspheric_value = aspheric_equation(r, c, k, α_coeffs) - grad_z = gradient_aspheric_equation(r, c, k, α_coeffs) # sag and gradient norm at the edge, see `aspheric_edge` z_aspheric_boundary, n_grad_z_boundary = edge - # Handling NaN for points outside the aspheric surface - if isnan(z_aspheric_value) || isnan(grad_z) || r2 > r2_bound + # Points outside the aspheric surface, where it is not defined or beyond its edge + if _aspheric_sqrt_arg(r2, c, k) < 0 || r2 > r2_bound if z < z_aspheric_boundary distance_to_boundary = sqrt((r - sign(r) * d / 2)^2 + (z - z_aspheric_boundary)^2) elseif z_aspheric_boundary < z < 0 @@ -268,9 +253,9 @@ function convex_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, edg return distance_to_boundary / n_grad_z_boundary end - # Calculate distance to the aspheric surface - # via r², i.e. smooth on the axis, equal to abs(z - z_aspheric_value) / norm(grad_z) - distance_to_aspheric = abs(z - _aspheric_sag_r2(r2, c, k, α_coeffs)) / sqrt(1 + _aspheric_slope2_r2(r2, c, k, α_coeffs)) + # Calculate distance to the aspheric surface, via r², i.e. smooth on the axis + z_aspheric_value = _aspheric_sag_r2(r2, c, k, α_coeffs) + distance_to_aspheric = abs(z - z_aspheric_value) / sqrt(1 + _aspheric_slope2_r2(r2, c, k, α_coeffs)) if sign(c) == 1 && z_aspheric_boundary < 0 # the asphere curves towards negative sag so we need to close the perimeter # at its max sag value instead of the boundary @@ -301,13 +286,11 @@ end function concave_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, edge, r2 = r^2) r2_bound = (d / 2)^2 - z_aspheric_value = aspheric_equation(r, c, k, α_coeffs) - grad_z = gradient_aspheric_equation(r, c, k, α_coeffs) # sag and gradient norm at the edge, see `aspheric_edge` z_aspheric_boundary, n_grad_z_boundary = edge - # Handling NaN for points outside the aspheric surface - if isnan(z_aspheric_value) || isnan(grad_z) + # Points outside the aspheric surface, where it is not defined + if _aspheric_sqrt_arg(r2, c, k) < 0 if z < 0 distance_to_boundary = sqrt((r - sign(r) * d / 2)^2 + z^2) elseif 0 < z < z_aspheric_boundary @@ -318,8 +301,9 @@ function concave_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, ed return distance_to_boundary / n_grad_z_boundary end - # via r², i.e. smooth on the axis, equal to abs(z - z_aspheric_value) / norm(grad_z) - distance_to_aspheric = abs(z - _aspheric_sag_r2(r2, c, k, α_coeffs)) / sqrt(1 + _aspheric_slope2_r2(r2, c, k, α_coeffs)) + # distance to the aspheric surface, via r², i.e. smooth on the axis + z_aspheric_value = _aspheric_sag_r2(r2, c, k, α_coeffs) + distance_to_aspheric = abs(z - z_aspheric_value) / sqrt(1 + _aspheric_slope2_r2(r2, c, k, α_coeffs)) p = Point2(r, z) if max_sag[1] > 0 && z_aspheric_boundary < 0 From ce0e1f0957bc4eb64a4fe6ebd62030f3ef2e5e70 Mon Sep 17 00:00:00 2001 From: Hugo Uittenbosch Date: Fri, 23 Oct 2026 16:04:01 +0200 Subject: [PATCH 5/8] UnionSDF: state the scale for which the tie-break offset holds Review F2 on PR #148. Co-Authored-By: Claude Opus 5.5 --- src/SDFs/UnionSDF.jl | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/SDFs/UnionSDF.jl b/src/SDFs/UnionSDF.jl index c14b4d273..f653140ca 100644 --- a/src/SDFs/UnionSDF.jl +++ b/src/SDFs/UnionSDF.jl @@ -88,6 +88,13 @@ normal, but only the outer one, i.e. the boundary of the union next to `pos`, gi e.g. its derivative w.r.t. the pose of the lens in automatic differentiation. The outer one is the closest operand at four points beside `pos`, `ρ` along the tangent plane and `ρ` outward, i.e. outside of the union also if `pos` lies on its surface. + +!!! note + The offset `ρ` is absolute, 1 µm by default. The tie-break is valid for features that are + large against `ρ`, i.e. for optics on the mm scale. For features on the µm scale, e.g. + micro-optics, the probes can land beyond the feature and pick the inner operand. The traced + values are the same for either pick, as the tied operands give the same normal, but the + derivatives in automatic differentiation are those of the inner operand then. """ function _closest_operand(operands, ds, pos; ρ = 1e-6) d_min = minimum(ds) From 61540dacf17bc3124d51660df7d5cadefb9511f1 Mon Sep 17 00:00:00 2001 From: Hugo Uittenbosch Date: Fri, 23 Oct 2026 16:04:01 +0200 Subject: [PATCH 6/8] 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 --- test/TestAutoDiff.jl | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/test/TestAutoDiff.jl b/test/TestAutoDiff.jl index 650ac98b4..ec95d42fc 100644 --- a/test/TestAutoDiff.jl +++ b/test/TestAutoDiff.jl @@ -66,6 +66,10 @@ mirrors = [ pd_at(T, y) = (d = Detector(T(40mm)); translate3d!(d, T[0, y, 0]); d) hit_x(pd) = BMO.hit_point(only(BMO.hits(pd)))[1] bi_convex(T) = SphericalLens(T(50mm), T(-50mm), T(5mm), T(25mm), _ -> T(1.5)) +# paraxial ABCD matrices in reduced angles: a translation by the reduced distance `d` (length / n), +# and a refraction or reflection with the power `P` +translation(d) = [1 d; 0 1] +refraction(P) = [1 0; -P 1] polarized(T, x) = Beam(PolarizedRay(T[x, -50mm, 0], T[0, 1, 0], T(1e-6), Complex{T}[1, 0, 0])) """ @@ -138,6 +142,20 @@ parametric_cases = [ @test isfinite(ad) @test ad ≈ fd rtol = 1e-5 end + @testset "paraxial reference, $label" for (label, c, M, mirror) in [ + # front vertex at y = 0, back vertex at y = t, detector at y = 100 mm + ("bi-convex SphericalLens", bi_convex, + translation(100mm - 5mm) * refraction((1 - 1.5) / -50mm) * translation(5mm / 1.5) * + refraction((1.5 - 1) / 50mm), false), + # vertex at y = 0, detector at y = -30 mm + ("SphericalMirror", last(mirrors[1]), translation(30mm) * refraction(2 / 200mm), true), + ] + # A ray on the axis and the component shifted laterally by `dx`: the ray meets it at the + # height -dx, i.e. the spot lies at dx + A (-dx), with A the position element of the paraxial + # ABCD matrix `M` from the vertex to the detector, exact for the derivative at dx = 0. + ad = ForwardDiff.derivative(dx -> spot_x(c, dx; h = 0.0, mirror), 0.0) + @test ad ≈ 1 - M[1, 1] rtol = 1e-6 + end @testset "refractive index" begin # the spot of a ray at h = 2 mm behind a bi-convex lens with the refractive index `n0` function spot(n0) From bfdc5c7848298b6f855efa452ae54e85e8d59123 Mon Sep 17 00:00:00 2001 From: uitt_hu Date: Fri, 23 Oct 2026 22:35:24 +0200 Subject: [PATCH 7/8] 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 --- test/TestAutoDiff.jl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/TestAutoDiff.jl b/test/TestAutoDiff.jl index ec95d42fc..aaf9a042f 100644 --- a/test/TestAutoDiff.jl +++ b/test/TestAutoDiff.jl @@ -92,7 +92,7 @@ function michelson_power(dx) translate3d!(pd, T[-5cm, 23.5cm, 0]) g = GaussianBeamlet(T[0, 0, 0], T[0, 1, 0], T(632.8e-9), T(0.5mm)) solve_system!(System([cbs, m1, m2, pd]), g) - return optical_power(pd; progress = false, n = 40) + return optical_power(pd, RegularGrid(n = 40); progress = false) end # label, function of the parameter, value of the parameter @@ -127,7 +127,7 @@ parametric_cases = [ solve_system!(System([f, d]), b); sum(abs2, BMO.polarization(only(BMO.hits(d))))), 0.5), ("optical_power of a clipped GaussianBeamlet", dx -> (T = typeof(dx); d = Detector(T(2mm)); translate3d!(d, [dx, T(100mm), zero(T)]); g = GaussianBeamlet(T[0, 0, 0], T[0, 1, 0], T(1e-6), T(1mm)); solve_system!(System([d]), g); - optical_power(d; progress = false, n = 60, x_min = -1mm, x_max = 1mm, z_min = -1mm, z_max = 1mm)), 0.5mm), + optical_power(d, RegularGrid(n = 60, x_min = -1mm, x_max = 1mm, z_min = -1mm, z_max = 1mm); progress = false)), 0.5mm), ("Michelson interferometer, power vs. mirror position", michelson_power, 1e-8), ] From 341a97fad116655cdafe6b14585ee6be1ea95c3d Mon Sep 17 00:00:00 2001 From: Oliver Kliebisch Date: Mon, 26 Oct 2026 18:53:27 +0100 Subject: [PATCH 8/8] 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. --- .github/workflows/CI.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 594338f33..c6dcecccf 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -16,6 +16,9 @@ jobs: name: Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ matrix.arch }} runs-on: ${{ matrix.os }} timeout-minutes: 60 + # A Julia prerelease may break dependencies before they release a fix (e.g. #173): its job runs + # and reports, but does not fail the CI + continue-on-error: ${{ matrix.version == 'pre' }} permissions: # needed to allow julia-actions/cache to proactively delete old caches that it has created actions: write contents: read