Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions docs/make.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
57 changes: 57 additions & 0 deletions docs/src/basics/autodiff.md
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 9 additions & 0 deletions skills/beamletoptics/WORKFLOW.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions src/Mesh.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions src/OpticalComponents/Beamsplitters/ThinBeamsplitter.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
12 changes: 7 additions & 5 deletions src/OpticalComponents/Lenses.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
3 changes: 1 addition & 2 deletions src/OpticalComponents/Polarizers/LinearPolarizer.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
31 changes: 25 additions & 6 deletions src/SDFs/AbstractSDF.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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

"""
Expand Down Expand Up @@ -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)

Expand All @@ -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

Expand All @@ -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

Expand Down
Loading
Loading