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 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 118890c6e..03d139046 100644 --- a/skills/beamletoptics/WORKFLOW.md +++ b/skills/beamletoptics/WORKFLOW.md @@ -47,6 +47,15 @@ end - A detector holds the hits of consecutive solves side by side; you decide when to evaluate. `spot_diagram` shows all hits; `electric_field`, `intensity`, `optical_power` superpose all hits **coherently**. For solves that follow each other in time, know what this computes, or evaluate after each solve and reset (`initialize = true`). - 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 04040df48..0f61abab1 100644 --- a/src/Mesh.jl +++ b/src/Mesh.jl @@ -303,12 +303,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 d386471cb..beb643b25 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 dd75902d5..9e908665c 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) @@ -102,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 e2d55bc64..a8a40bca9 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 = hit_point(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/SDFs/AbstractSDF.jl b/src/SDFs/AbstractSDF.jl index b85fdf7a1..c628e3d1f 100644 --- a/src/SDFs/AbstractSDF.jl +++ b/src/SDFs/AbstractSDF.jl @@ -135,8 +135,16 @@ function _raymarch_outside(shape::AbstractSDF{S}, elseif escaped # The probe lies within `eps` of the surface (inside or outside): the hit is its root. A # rejected hit leaves the marching at the probe. - t_hit = _secant_root(shape, pos0, dir, t_prev, dist_prev, t0, dist, eps) - normal = normal3d(shape, pos0 + t_hit * dir) + t_hit, d_hit, slope = _secant_root(shape, pos0, dir, t_prev, dist_prev, t0, dist, eps) + p_hit = pos0 + t_hit * dir + # The normal is evaluated outside: the root may lie 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. Exactly on the + # surface, such parts tie. The point is moved back along the ray until it lies about as far + # outside as the root lies inside, by the slope of the SDF along the ray, at least by + # `eps / 100` and at most by `eps`. + back = clamp(d_hit < 0 ? 2 * d_hit / slope : zero(d_hit), eps / 100, eps) + normal = normal3d(shape, p_hit - back * dir) # Filter out false positive hits caused by numerical noise when leaving an SDF. if !(dot(dir, normal) > eps) return Intersection(t_hit, normal, shape) @@ -151,7 +159,8 @@ end # SDF is about linear, as near a surface. A step is kept if it reduces |SDF| and does not lead back # before the probe `a`. The result is the hit of `_raymarch_outside` within `eps` of the surface: the # hit changes continuously with the ray and the shape, e.g. for finite differences, instead of -# jumping with the marching steps. +# jumping with the marching steps. Returns the path length of the root, the SDF there and the slope of +# the SDF along the ray between the last two points, which is negative for a ray towards the surface. function _secant_root(shape::AbstractSDF, pos, dir, a, fa, b, fb, eps) for _ in 1:8 abs(fb) ≤ eps * 1e-3 && break @@ -161,7 +170,7 @@ function _secant_root(shape::AbstractSDF, pos, dir, a, fa, b, fb, eps) abs(fm) < abs(fb) || break a, fa, b, fb = b, fb, m, fm end - return b + return b, fb, (fb - fa) / (b - a) end """ @@ -334,6 +343,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) @@ -342,7 +361,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 @@ -354,7 +373,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..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,29 +158,49 @@ 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) +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) 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 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(_aspheric_sqrt_arg(r2, c, k))) + _even_aspheric_sum(r2, α_coeffs) +end + +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 - return acc * r + return 2c / (sq + 1) + r2 * (1 + k) * c^3 / (sq * (sq + 1)^2) + acc 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) +_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 +# 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 """ @@ -216,17 +233,14 @@ 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) # 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 @@ -239,47 +253,44 @@ 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 - distance_to_aspheric = abs(z - z_aspheric_value) / norm(grad_z) + # 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 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) # 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 @@ -290,12 +301,15 @@ 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) + # 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 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 +318,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 +379,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 +399,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..f653140ca 100644 --- a/src/SDFs/UnionSDF.jl +++ b/src/SDFs/UnionSDF.jl @@ -74,8 +74,37 @@ 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. + +!!! 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) + 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/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 bafc0389f..34a89b36d 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/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..aaf9a042f --- /dev/null +++ b/test/TestAutoDiff.jl @@ -0,0 +1,199 @@ +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)), +] + +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])) + +""" +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, RegularGrid(n = 40); progress = false) +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, 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), +] + +@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 "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) + 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 "$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) + 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 f2ae71d7c..1d28e3ac5 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -48,6 +48,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"))