diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index baa0cd7ca..f5be49d39 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -23,8 +23,8 @@ jobs: fail-fast: false matrix: version: + - '1.12' - '1.10' - - '1.9' - 'pre' os: - ubuntu-latest diff --git a/.gitignore b/.gitignore index aa358e46c..13a9e65e5 100644 --- a/.gitignore +++ b/.gitignore @@ -13,7 +13,16 @@ Thumbs.db *.jl.mem .vscode +# ignore image formats *.png +*.gif +*.svg + +# allow pre-rendered images within docs folder +!docs/src/**/*.png +!docs/src/**/*.gif +!docs/src/**/*.svg + snoop_compile/ /Manifest.toml diff --git a/Project.toml b/Project.toml index 43c81799d..07026b71e 100644 --- a/Project.toml +++ b/Project.toml @@ -1,7 +1,7 @@ name = "BeamletOptics" uuid = "c387492b-ffec-4e51-9a46-bd230226031c" +version = "0.13.0" authors = ["Hugo Uittenbosch , Oliver Kliebisch and Thomas Dekorsy "] -version = "0.12.1" [deps] AbstractTrees = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" @@ -13,6 +13,8 @@ LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" MarchingCubes = "299715c1-40a9-479a-aaf9-4a633d36f717" MeshIO = "7269a6da-0436-5bbc-96c2-40638cbb6118" PrecompileTools = "aea7be01-6a6a-4083-8856-8a6e6704d82a" +Preferences = "21216c6a-2e73-6563-6e65-726566657250" +Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" Trapz = "592b5752-818d-11e9-1e9a-2b8ca4a44cd1" @@ -30,18 +32,22 @@ ForwardDiff = "0.10, 1.0.1" GeometryBasics = "0.5" InteractiveUtils = "1" LinearAlgebra = "1" +Logging = "1" Makie = "0.22, 0.23, 0.24" MarchingCubes = "0.1" MeshIO = "0.5" PrecompileTools = "1" +Preferences = "1.5.2" +Random = "1" StaticArrays = "1" Test = "1" Trapz = "2" -julia = "1.9.4" +julia = "1.10" [extras] Aqua = "4c88cf16-eb10-579e-8560-4a9242c79595" +Logging = "56ddb016-857b-54e1-b83d-db4d58db5568" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] -test = ["Aqua", "Test"] \ No newline at end of file +test = ["Aqua", "Test", "Logging"] diff --git a/docs/DocUtils.jl b/docs/DocUtils.jl new file mode 100644 index 000000000..5ef8a8999 --- /dev/null +++ b/docs/DocUtils.jl @@ -0,0 +1,128 @@ +module DocUtils + +using GLMakie: Figure, Axis, hidedecorations!, text!, save +using Dates: now + +const GLOBAL_USE_PLACEHOLDERS = true + +""" + conditional_include(fname; use_placeholder=!haskey(ENV, "CI")) + +This is a function to speed up compilation time when building the docs locally. +It checks whether the `include` call is made locally or from within the **CI environment**. +In the former case, script evaluation is avoided and a placeholder figure is created for +each `save` call within the script. + +Evaluation can be forced by setting `use_placeholder = false`. Global evaluation can be forced +by setting `GLOBAL_USE_PLACEHOLDERS = false` in this file (does not apply for CI env.). +""" +function conditional_include(fname::String; use_placeholder::Bool=!haskey(ENV, "CI")) + # Check for global flag if not within CI env. + if !haskey(ENV, "CI") && !GLOBAL_USE_PLACEHOLDERS + use_placeholder = false + end + # Check if to run script + if use_placeholder + content = read(fname, String) + # match save("filename") but ignore comments, i.e. # save(...) + pattern = Regex("^[ \\t]*save\\(\\s*\"([^\"]+)\"\\s*,\\s*([a-zA-Z_][a-zA-Z0-9_]*)", "m") + for match in eachmatch(pattern, content) + save_name = match.captures[1] + fig_name = match.captures[2] + offset = match.offset + prior_content = content[1:offset] + # find last missing fig_name variable match + npattern = Regex("\\Q$fig_name\\E\\s*=\\s*Figure\\(.*?size\\s*=\\s*\\(([\\d]+)\\s*,\\s*([\\d]+)\\)") + matches = collect(eachmatch(npattern, prior_content)) + if !isempty(matches) + nmatch = last(matches) + _width = parse(Int, nmatch.captures[1]) + _height = parse(Int, nmatch.captures[2]) + else + @info "Using default height for $fig_name" + _width = 600 + _height = 300 + end + # save placeholder + fig = Figure(size=(_width, _height)) + ax = Axis(fig[1,1], backgroundcolor=:gray) + hidedecorations!(ax) + text!(ax, 0, 0; + text="$save_name\n($_width x $_height)", + align=(:center, :center), + color=:white, + fontsize=20 + ) + save(save_name, fig) + @info "Saving placeholder for $save_name (Size: $_width x $_height, fig_var_name=$fig_name)" + end + else + @info "Running script for $fname" + t1 = now() + include(fname) + t2 = now() + @info " Runtime: $(t2-t1)" + end +end + +function replace_build_with_src(path::String) + clean_path = abspath(path) + build_segment = joinpath("docs", "build") + src_segment = joinpath("docs", "src") + src_path = replace(clean_path, build_segment => src_segment) + return src_path +end + +""" + prerender_include(fname::String, cname::String) + +This function runs the build script and places the images within the docs\\src folder when run outside of the CI/CD pipeline. +It is recommended to use this approach when the rendered image is too computationally intensive for the github runner. +If a prerendered image already exists, it has to be **deleted manually** in order to trigger a re-run. + +# Arguments + +- `fname`: points to the BMO render script +- `cname`: points to the executing markdown script + +!!! info + It is highly recommended that the `@__FILE__` macro is passed into `cname` within the executing markdown block. + E.g. within a .md file: + + `Main.DocUtils.prerender_include("myscript.jl", @__FILE__)` +""" +function prerender_include(fname::String, cname::String) + location = replace_build_with_src(dirname(cname)) + content = read(fname, String) + pattern = Regex("^[ \\t]*save\\(\\s*\"([^\"]+)\"\\s*,\\s*([a-zA-Z_][a-zA-Z0-9_]*)", "m") + all_files_there = true + for match in eachmatch(pattern, content) + # check if file already exists + save_name = match.captures[1] + if !isfile(joinpath(location, save_name)) + if haskey(ENV, "CI") + throw(ErrorException("Running $fname in CI pipeline, missing $save_name at $location")) + end + all_files_there = false + break + end + end + # if all pre-rendered files exist, do nothing + if all_files_there + @info "Found pre-rendered images for $fname" + return nothing + end + # if files missing, run script + @warn "Detected missing pre-rendered file/s for script $fname, running..." + include(fname) + # scan for figs, copy to src folder + for match in eachmatch(pattern, content) + save_name = match.captures[1] + path_name = dirname(cname) + @info "Copying $save_name from \\build to \\src" + cp(joinpath(path_name, save_name), joinpath(location, save_name); force=true) + end + return nothing +end + +end \ No newline at end of file diff --git a/docs/make.jl b/docs/make.jl index 18892aff6..bf6f0d371 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -4,7 +4,14 @@ using BeamletOptics using Documenter using DocumenterCitations -DocMeta.setdocmeta!(BeamletOptics, :DocTestSetup, :(using BeamletOptics); recursive=true) +include(joinpath(@__DIR__, "DocUtils.jl")) + +DocMeta.setdocmeta!( + BeamletOptics, + :DocTestSetup, + :(using BeamletOptics); + recursive=true +) bib = CitationBibliography(joinpath(@__DIR__, "src", "refs.bib")) @@ -34,12 +41,18 @@ makedocs(; "Aspherical lenses" => joinpath("examples", "aspherical_lenses.md"), "Double Gauss lens" => joinpath("examples", "double_gauss.md"), "Lens groups" => joinpath("examples", "lens_groups.md"), + "Double slit" => joinpath("examples", "double_slit.md"), ], ], "Basics" => Any[ "Introduction" => joinpath("basics", "intro.md"), "Rays" => joinpath("basics", "rays.md"), - "Beams" => joinpath("basics", "beams.md"), + "Beams" => Any[ + "Basic beam" => joinpath("basics", "beams", "beams.md"), + "Stigmatic Gaussian" => joinpath("basics", "beams", "stigmatic_beam.md"), + "Astigmatic Gaussian" => joinpath("basics", "beams", "astigmatic_beam.md"), + "Beam groups" => joinpath("basics", "beams", "beam_groups.md"), + ], "Optical components" => Any[ "Overview" => joinpath("basics", "components", "components.md"), "Mirrors" => joinpath("basics", "components", "mirrors.md"), diff --git a/docs/src/api/docdev.md b/docs/src/api/docdev.md index 6cddf0ce0..f1b70ee46 100644 --- a/docs/src/api/docdev.md +++ b/docs/src/api/docdev.md @@ -27,10 +27,9 @@ In general, you can generate and include figures into your documentation section - files will be saved with respect to the calling environment 3. In the markdown file that contains your documentation and should load your images, do the following: 1. create a `@setup` code block - 2. include the `conditional_include` via e.g. `include(joinpath(@__DIR__, "..", "assets", "cond_save.jl"))` - - ensure that the relative file path is correct - 3. load your script during build via `conditional_include` - - more info on this function is provided in the `cond_save.jl` file + 2. load your script during build via `Main.DocUtils.conditional_include` + - more info on this function is provided in the `DocUtils.jl` file + 3. Or, alternatively use `Main.DocUtils.prerender_include` to generate the image locally 4. Load the image within your markdown file via `![My figure](my_fig.png)` Examples for this pattern can be found at the top of most .md files of the documentation, e.g. `beamsplitters.md`. diff --git a/docs/src/api/meshes.md b/docs/src/api/meshes.md index efcd417e0..9a4319e24 100644 --- a/docs/src/api/meshes.md +++ b/docs/src/api/meshes.md @@ -1,9 +1,7 @@ ```@setup rays -include(joinpath(@__DIR__, "..", "assets", "cond_save.jl")) - dir = joinpath(@__DIR__, "..", "assets") -conditional_include(joinpath(dir, "meshes.jl")) +Main.DocUtils.conditional_include(joinpath(dir, "meshes.jl")) ``` # Meshes diff --git a/docs/src/api/sdfs.md b/docs/src/api/sdfs.md index f90ccea4d..d5d84f0c8 100644 --- a/docs/src/api/sdfs.md +++ b/docs/src/api/sdfs.md @@ -1,9 +1,7 @@ ```@setup rays -include(joinpath(@__DIR__, "..", "assets", "cond_save.jl")) - dir = joinpath(@__DIR__, "..", "assets") -conditional_include(joinpath(dir, "raymarching.jl")) +Main.DocUtils.conditional_include(joinpath(dir, "raymarching.jl")) ``` # Signed Distance Functions (SDFs) diff --git a/docs/src/assets/beam_renders/agb_showcase.jl b/docs/src/assets/beam_renders/agb_showcase.jl new file mode 100644 index 000000000..133ad275e --- /dev/null +++ b/docs/src/assets/beam_renders/agb_showcase.jl @@ -0,0 +1,98 @@ +using GLMakie, BeamletOptics + +GLMakie.activate!(; ssao=true) + +const BMO = BeamletOptics + +const mm = 1e-3 + +include(joinpath(@__DIR__, "..", "render_utils.jl")) + +## +c_view = [ + 0.605459 0.783477 -0.139944 -0.0298959 + -0.0484677 0.211806 0.976109 -0.0106539 + 0.7944 -0.584211 0.166213 -1.69474 + 0.0 0.0 0.0 1.0 +] + +agb = AstigmaticGaussianBeamlet([0,0,0], [0,1,0], 9e-4, 2e-3; support=[0,0,1]) + +l = ThinLens(20e-3, 20e-3, BMO.inch, 1.5) +s = System([l]) + +translate3d!(l, [0, 30e-3, 0]) + +fig1 = Figure(size=(600,300)) +display(fig1) +ax = LScene(fig1[1,1]) +hide_axis(ax) + +render!(ax, agb; flen=0.1-0.03, show_beams=true, show_pos=true, color=RGBAf(1,0,0,0.1)) + +set_orthographic(ax) +set_view(ax, c_view) + +save("agbtest1.png", fig1; px_per_unit=8, update = false) + +## +solve_system!(s, agb; check_invariant=false) + +fig = Figure(size=(600,300)) +display(fig) +ax = LScene(fig[1,1]) +hide_axis(ax) +render!(ax, agb; flen=0.1-0.03, show_beams=true, show_pos=true, color=RGBAf(1,0,0,0.1)) +render!(ax, l; color=RGBAf(1, 1, 1, .1)) + +c_view = [ + 0.653709 0.756746 -5.27356e-16 -0.0173098 + -0.352701 0.304679 0.884744 -0.00702154 + 0.669526 -0.578366 0.466077 -0.0223342 + 0.0 0.0 0.0 1.0 +] + +set_view(ax, c_view) +save("agbtest2.png", fig; px_per_unit=8, update = false) + +## +s1 = BMO.CylinderSDF(BMO.inch/2, BMO.inch) +s2 = BMO.CylinderSDF(BMO.inch/2, BMO.inch) +l1 = BMO.Lens(s1, n->1.5) +l2 = BMO.Lens(s2, n->1.5) +translate3d!(l1, [0, 50mm, 0]) +translate3d!(l2, [0, 100mm, 0]) +xrotate3d!(l1, deg2rad(90)) +xrotate3d!(l2, deg2rad(90)) +yrotate3d!(l1, deg2rad(90)) +translate3d!(l2, [5mm, 0, 0]) + +system = System([l1, l2]) + +z_os = 0e-3 +w0 = 2mm +λ0 = 1000e-9 +dir = [0,1,0] +E0 = [0,0,1] +beam = AstigmaticGaussianBeamlet([0., 0, z_os], dir, λ0, w0; E0, support=[0,0,1]) + +solve_system!(system, beam; check_invariant=false) + +## +fig = Figure(size=(600,400)) +display(fig) +ax = LScene(fig[1,1]) +hide_axis(ax) +render!(ax, l1; color=RGBAf(1, 1, 1, .2)) +render!(ax, l2; color=RGBAf(1, 1, 1, .2)) +render!(ax, beam; color=RGBAf(1,0,0,0.2), z_res=4, r_res=20, show_waist=true, markersize=4, flen=0.1) + +view = [ + 0.763832 0.645415 3.88578e-16 -0.0541476 + -0.444252 0.525762 0.725407 -0.0339012 + 0.468188 -0.554089 0.68832 -0.0967937 + 0.0 0.0 0.0 1.0 +] + +set_view(ax, view) +save("agbtest3.png", fig; px_per_unit=8, update = false) \ No newline at end of file diff --git a/docs/src/assets/cond_save.jl b/docs/src/assets/cond_save.jl deleted file mode 100644 index d9413c042..000000000 --- a/docs/src/assets/cond_save.jl +++ /dev/null @@ -1,37 +0,0 @@ -using GLMakie - -const GLOBAL_USE_PLACEHOLDERS = true - -""" - conditional_include(fname; use_placeholder=!haskey(ENV, "CI")) - -This is a function to speed up compilation time when building the docs locally. -It checks whether the `include` call is made locally or from within the **CI environment**. -In the former case, script evaluation is avoided and a placeholder figure is created for -each `save` call within the script. - -Evaluation can be forced by setting `use_placeholder = false`. Global evaluation can be forced -by setting `GLOBAL_USE_PLACEHOLDERS = false` in this file (does not apply for CI env.). -""" -function conditional_include(fname::String; use_placeholder::Bool=!haskey(ENV, "CI")) - # Check for global flag if not within CI env. - if !haskey(ENV, "CI") && !GLOBAL_USE_PLACEHOLDERS - use_placeholder = false - end - # Check if to run script - if use_placeholder - content = read(fname, String) - # match save("filename") - pattern = r"""save\(\s*"([^"]+)""" - filenames = [m.captures[1] for m in eachmatch(pattern, content)] - for f in filenames - fig = Figure(size=(600,300)) - Box(fig[1, 1], color = :gray) - save(f, fig) - @info "Saving placeholder for $f" - end - else - @info "Running script for $fname" - include(fname) - end -end \ No newline at end of file diff --git a/docs/src/assets/examples/double_slit.jl b/docs/src/assets/examples/double_slit.jl new file mode 100644 index 000000000..de65ac792 --- /dev/null +++ b/docs/src/assets/examples/double_slit.jl @@ -0,0 +1,131 @@ +using BeamletOptics, GLMakie + +function get_view(ls::LScene) + cam = ls.scene.camera_controls + eye = cam.eyeposition[] + lookat = cam.lookat[] + up = cam.upvector[] + return eye, lookat, up +end + +function set_view(ls::LScene, eye, lookat, up) + cam = ls.scene.camera_controls + cam.eyeposition[] = Vec3f(eye...) + cam.lookat[] = Vec3f(lookat...) + cam.upvector[] = Vec3f(up...) + update_cam!(ls.scene, cam) +end + +# Parameters +λ = 633e-9 # 633 nm (HeNe Laser) +a = 10e-6 # Slit width (10 µm) +d = 100e-6 # Slit separation (100 µm) +L = 0.2 # Propagation distance (0.2 m) +W = 0.5e-3 # calculation window (0.5 mm) +nx = 251 # resolution + +# Define the Aperture Mask (Double Slit) +x = LinRange(-W / 2, W / 2, nx) +z = LinRange(-W / 2, W / 2, nx) +amplitude = zeros(nx, nx) + +for i in 1:nx, j in 1:nx + # Slits are long along z, narrow along x + in_slit1 = abs(x[i] - d / 2) < a / 2 + in_slit2 = abs(x[i] + d / 2) < a / 2 + + if (in_slit1 || in_slit2) + amplitude[i, j] = 1.0 + end +end + +phase = zeros(nx, nx) +dir = [0.0, 1.0, 0.0] # Propagation along Y +## +# Decompose into Astigmatic Beamlets +@info "Decomposing Double Slit into AGBs..." +# We explicitly define the basis to ensure Grid X = World X +e1 = [1.0, 0.0, 0.0] +e2 = [0.0, 0.0, 1.0] +beams = WavefrontBeamletDecomposition(x, z, amplitude, phase, dir, λ; + threshold = 1e-3, overlap = 3.0, basis = (e1, e2)) + +@info "Number of beamlets generated: $(length(beams))" + +# Define the System and Propagate +target_pd = Detector(30e-3) +translate_to3d!(target_pd, [0.0, L, 0.0]) +system = System([target_pd]) + +@info "Propagating to screen at L = $L m..." +solve_system!(system, beams) + +# Extract Results +@info "Calculating Intensity Pattern..." +n_eval = 500 +# Evaluate over a 30mm window to see many fringes +xs_eval, zs_eval, I = intensity(target_pd; n = n_eval, + x_min = -15e-3, x_max = 15e-3, z_min = -15e-3, z_max = 15e-3) + +## +# Visualization +fig = Figure(size = (800, 600), fontsize = 18) +display(fig) + +# Axis 1: 3D Scene (The Setup) +ax3d = LScene(fig[1:2, 1], show_axis = false) + +# We create a mesh grid for the surface to ensure correct orientation in 3D +X_mask = [xv for xv in x, zv in z] +Z_mask = [zv for xv in x, zv in z] +Y_mask = fill(0.0, size(X_mask)) +surface!(ax3d, X_mask, Y_mask, Z_mask, + color = amplitude, colormap = :binary, transparency = true) + +# Render Intensity Results (at y = L) +X_res = [xv for xv in xs_eval, zv in zs_eval] +Z_res = [zv for xv in xs_eval, zv in zs_eval] +Y_res = fill(L, size(X_res)) +I_norm = I ./ (maximum(I) + 1e-12) # Avoid division by zero +plt_res = surface!(ax3d, X_res, Y_res, Z_res, + color = I_norm, colormap = :magma, + transparency = false, + shading = NoShading, + depth_shift = -1e-3) # Subtle shift to win Z-fighting without clipping + +# Render a few representative beamlets +step = max(1, length(beams) ÷ 15) +for i in 1:step:length(beams) + render!(ax3d, beams[i], color = (:cyan, 0.05), show_beams = false, flen = 0.0) +end + +# Render the system components (Detector frame) +#render!(ax3d, system) + +# Axis 2: 2D Intensity Map (Zoomed) +ax2d = Axis(fig[1, 2], + title = "Diffraction Pattern (Detector Plane)", + xlabel = "x [mm]", ylabel = "z [mm]", yticks = -1:2:1, + aspect = DataAspect()) +hm = heatmap!(ax2d, xs_eval .* 1000, zs_eval .* 1000, I, colormap = :magma) +ylims!(-1.1, 1.1) + +# Axis 3: 1D Cross-section +ax1d = Axis(fig[2, 2], + title = "Interference Fringes (x-slice)", + xlabel = "x Position [mm]", ylabel = "Intensity", + yticksvisible = false, yticklabelsvisible = false) +lines!(ax1d, xs_eval .* 1000, I[:, size(I, 2) ÷ 2], color = :red, linewidth = 2) + +# This makes the 1.2m distance look shorter so we can zoom in on X/Z details +scale!(ax3d.scene, 1.0, 0.15, 1.0) + +# Set a nice default camera view +cl = ([0.005679703099338854, -0.010364784764641269, 0.002815435213044604], + [-0.003708494535423113, 0.026029085430702627, 0.0009259786679933707], + [-0.021598444746385476, 0.046277584411491254, 0.998695114799569]) + +rowsize!(fig.layout, 1, Relative(1 // 4)) + +set_view(ax3d, cl...) +save("agb_doubleslit_experiment.png", fig; px_per_unit = 8, update = false) diff --git a/docs/src/basics/beams.md b/docs/src/basics/beams.md deleted file mode 100644 index 0dbfe22b1..000000000 --- a/docs/src/basics/beams.md +++ /dev/null @@ -1,138 +0,0 @@ -```@setup beams -include(joinpath(@__DIR__, "..", "assets", "cond_save.jl")) - -beam_showcase_dir = joinpath(@__DIR__, "..", "assets", "beam_renders") - -conditional_include(joinpath(beam_showcase_dir, "beam_showcase.jl")) -conditional_include(joinpath(beam_showcase_dir, "gb_showcase.jl")) -conditional_include(joinpath(beam_showcase_dir, "collimated_sc.jl")) -conditional_include(joinpath(beam_showcase_dir, "pointsource_sc.jl")) -``` - -# Beams - -As mentioned in the [Rays](@ref) section, a beam within the context of this package serves as a data structure for storing collections of rays, forming the backbone of the simulation framework. Beams are intended to be designed as [AbstractTrees](https://github.com/JuliaCollections/AbstractTrees.jl) to allow for ray bifurcations, e.g. in the case of optical elements such as beamsplitters. The [`solve_system!`](@ref) function relies on this data structure to perform ray tracing computations within optical systems. - -To ensure compatibility and extensibility, beam types must adhere to the [`BeamletOptics.AbstractBeam`](@ref) interface. Refer to its documentation for more information. - -## Basic beam - -A minimal implementation of the [`BeamletOptics.AbstractBeam`](@ref) type is provided by the [`Beam`](@ref). It can be used to store a light path through an optical system. If the beam is split, its children will be recursively traced until all paths are solved. - -```@docs; canonical=false -Beam -``` - -A ray tracing example through an arbitrary system using a [`Beam`](@ref) is shown below. Individual [`Ray`](@ref) segments are marked by their starting position and direction. The [Beam expander](@ref) and [Miniature microscope](@ref) tutorial covers the use of the [`Beam`](@ref) in more detail. - -![Beam structure](beam_showcase.png) - -## Beam groups - -For convenience, the [`BeamletOptics.AbstractBeamGroup`](@ref) offers a container-like interface for groups of [`Beam`](@ref)s as commonly used in other software packages. The following concrete implementations are currently provided: - -```@repl -using BeamletOptics # hide -BeamletOptics.list_subtypes(BeamletOptics.AbstractBeamGroup); -``` - -Refer to the following sections for convenience constructors to generate the sources listed above. - -### Collimated beam source - -The collimated beam source is ideal to model light coming from a focal plane at infinity. This is useful for simulating plane wavefronts. You can define a collimated monochromatic [`Beam`](@ref) source as follows: - -```@docs; canonical=false -CollimatedSource(::AbstractArray{<:Real}, ::AbstractArray{<:Real}, ::Real, ::Real) -``` - -![Collimated group of beams](collimated_beam_source.png) - -A special constructor called [`UniformDiscSource`](@ref) is available, which offers an equal-area -sampling (Fibonnaci-pattern) sampling and is thus favorable in situations where the weighting of the -individual beams becomes important, e.g. for calculating a point spread function using the [`intensity`](@ref) function. - -```@docs; canonical=false -UniformDiscSource -``` - -![Collimated uniform group of beams](collimated_uniform_beam_source.png) - -### Point beam source - -The `PointSource` type is used to model emission from a spatially localized source that radiates [`Beam`](@ref)s in a range of directions. This is commonly used to simulate conical emission patterns, such as light emerging from a fiber tip or a light source for a lens objective with a known focal distance. You can specify the origin and a propagation direction, which are then used to construct the monochromatic `PointSource`. - -```@docs; canonical=false -PointSource(::AbstractArray{<:Real}, ::AbstractArray{<:Real}, ::Real, ::Real) -``` - -Below you can find an exemplary illustration of a `PointSource`. - -![Point source of beams](point_beam_source.png) - -## Gaussian beamlet - -Lasers are common devices in modern optical laboratories. Modeling their propagation through an optical setup can be of interest when planning new experiments. Geometrical ray tracing struggles to capture the propagation of a laser beam correctly, since it can not inherently capture the wave nature of e.g. the [Gaussian beam](https://www.rp-photonics.com/gaussian_beams.html). - -The electric field of the ``\text{TEM}_{00}`` spatial Gaussian mode can be calculated analytically using the [`BeamletOptics.electric_field`](@ref) function: - -```@docs; canonical=false -BeamletOptics.electric_field(r::Real, z::Real, E0, w0, w, k, ψ, R) -``` - -The evolution of this field through an optical system can be modeled e.g. by the ray transfer matrix formalism using the complex ``q``-factor [Saleh2019; pp. 27](@cite). A Julia-based implementation of this approach can be found in [ABCDMatrixOptics.jl](https://github.com/JuliaPhysics/ABCDMatrixOptics.jl). However, in the case of this package another approach will be used. - -### Complex ray tracing - -In 1968 an internal publication at Bell Labs by J. Arnaud introduced the concept of complex rays wherein three geometrical beams can be used to model the propagation of a Gaussian in fundamental mode through a symmetric optical system, i.e. without the Gaussian obtaining astigmatism and/or higher-order abberations. This method is analoguos to the ray transfer matrix based ``q``-method [Arnaud1968](@cite). - -Without extensions of the original method, the following key assumptions must be met such that this method can be applied - -- all (complex) beams of the Gaussian in question must intersect the same optical elements -- the optical elements are large compared to the beam (waist) -- the paraxial approximation must hold for each beam -- the Gaussian may not be clipped by hard apertures -- Lagrange invariant must be fulfilled - -Various versions of this approach have been implemented under different names in commercial software, most notably [FRED](https://photonengr.com/fred-software/) and [Code V](https://www.synopsys.com/optical-solutions/codev.html), as well as in open source software, e.g. - -- [Raypier](https://github.com/bryancole/raypier_optics) - based on Cython, maintenance status not known -- [Poke](https://github.com/Jashcraf/poke) - based on Zemax API and Python, maintained by J. Ashcraft et al. [Ashcraft:2022](@cite) -- [IfoCAD](https://www.aei.mpg.de/ifocad-de) - maintenance status not known, refer to Wanner et al. [Wanner:2017](@cite) - -This package implements the above method via the [`GaussianBeamlet`](@ref) and the `BeamletOptics.AstigmaticGaussianBeamlet` (**Work in progress**). - -### Stigmatic Beamlets - -The [`GaussianBeamlet`](@ref) implements the [`BeamletOptics.AbstractBeam`](@ref) interface and can be used to model the propagation of a monochromatic Gaussian (``\text{TEM}_{00}``-mode) through optical system where all optics lie on the optical axis, e.g. no tip and/or tilt dealignment, and abberations can be neglected. It is represented by a `chief` (red), `waist` (blue) and `divergence` (green) beam. See below how these beans are placed in relation to the envelope of the Gaussian beam. - -![Complex ray tracing I](gbtest1.png) - -```@docs; canonical=false -GaussianBeamlet -``` - -A [`GaussianBeamlet`](@ref) can be constructed via: - -```@docs; canonical=false -GaussianBeamlet(::AbstractArray{<:Real}, ::AbstractArray{<:Real}, ::Real, ::Real) -``` - -#### Obtaining the beam parameters - -Once a `GaussianBeamlet` has been traced through an optical system, several parameters might be of interest for further analysis. In order to relate the traced geometrical beams/rays to the Gaussian parameters, the publications of Arnaud, Herloski et al. and DeJager et al. are used [Arnaud1968, Herloski1983, DeJager1992](@cite). Consider the following system where a Gaussian beam with arbitrary parameters has been traced through a lens using the approach outlined in the [Complex ray tracing](@ref) section. - -![Complex ray tracing II](gbtest2.png) - -The user can obtain parameters such as the beam waist radius, the radius of curvature and more using the [`BeamletOptics.gauss_parameters`](@ref) function. Below the local waist radius and curvature ``R = r^{-1}`` have been calculated for the example above. - -![Gauss beam parameters](gauss_parameters.png) - -## Astigmatic Polarized Beamlets - -- Assumptions - - homogeneous polarization distribution across waist - - Lagrange invariant - -!!! warning - NOT YET IMPLEMENTED \ No newline at end of file diff --git a/docs/src/basics/beams/astigmatic_beam.md b/docs/src/basics/beams/astigmatic_beam.md new file mode 100644 index 000000000..813efe221 --- /dev/null +++ b/docs/src/basics/beams/astigmatic_beam.md @@ -0,0 +1,122 @@ +```@setup astigmatic_beamlet +beam_showcase_dir = joinpath(@__DIR__, "..", "..", "assets", "beam_renders") + +Main.DocUtils.conditional_include(joinpath(beam_showcase_dir, "agb_showcase.jl")) +``` + +# Astigmatic polarized beamlets + +Standard stigmatic beamlets are limited to symmetric systems. For the modeling of arbitrary optical systems, including off-axis components, tilted lenses, or complex media like atmospheric turbulence, the package provides the [`AstigmaticGaussianBeamlet`](@ref). This type implements the astigmatic Gaussian beamlet ray tracing formalism initially proposed by Greynolds (1986) [Greynolds:1986_1, Greynolds:1986_2](@cite). + +However, this idea has been referred to in multiple ways over the last few decades, including but not limited to: Gaussian Beamlet Tracing (GBT), Fat Ray Tracing (FRT), Parabasal Ray Tracing (PRT), Complex Ray Tracing (CRT), Gauss Beamlet Propagation (GBP) and Beam Synthesis Propagation (BSP). + +## Formalism + +Similar to the Gauss model presented in the [Stigmatic beamlets](@ref) chapter, an astigmatic beamlet can represented by a cluster of **9 rays**: + +!!! tip "Ray representation" + 1. **Chief Ray**: a [`PolarizedRay`](@ref) defining the central path and polarization state. + 2. **Waist Rays**: four "positional" rays (waist $x+, x-, y+, y-$) + 3. **Divergence Rays**: four "directional" rays (divergence $x+, x-, y+, y-$) + +These rays can be thought of tracking the complex curvature matrix $\mathbf{Q}(z)$ through the system. The key assumptions made in order for this formalism to hold are: + +!!! info "Key assumptions" + 1. **Paraxiality**: the auxiliary rays must remain within the paraxial regime relative to the chief ray. + 2. **Parabolic interaction**: since only astigmatism can be captured, each surface interaction must be approximately parabolical + 3. **Homogeneous polarization**: the polarization state of the traced field is assumed to be homogeneous over each beamlet + 4. **Matched scale**: the beamlet must be smaller than the optical element it interacts with, see also 2. + +The initial ordering of the geometric beams/rays is shown in the figure below. The colors represent the chief (red), waist (blue) and divergence (green) beams. + +![Astigmatic ray tracing I](agbtest1.png) + +As with the [`GaussianBeamlet`](@ref), tracing these rays through a system allows the reconstruction of the waist envelope and electric field. The reduced complex amplitude of the Gaussian beamlet is computed as + +```math +\psi(\mathbf{r}) = \frac{E_0}{\sqrt{\mathbf{h}_1 \times \mathbf{h}_2}} \cdot \exp \left( i k \frac{(\mathbf{h}_1 \times \mathbf{r})(\mathbf{u}_2 \cdot \mathbf{r}) - (\mathbf{h}_2 \times \mathbf{r})(\mathbf{u}_1 \cdot \mathbf{r})}{2 \mathbf{h}_1 \times \mathbf{h}_2} \right) \,, +``` +where $\mathbf{h}_{1,2}$ and $\mathbf{u}_{1,2}$ are the two-dimensional complex ray height and angle vectors on the plane perpendicular to the chief ray [Greynolds:1986_1, Wilhelm:2001, Greynolds:2014](@cite). By also tracing a 3D-field vector along the chief ray based on the formalism introduced in the [Polarized rays](@ref) section, polarization effects can be considered when calculating $\psi$ [Worku:2017](@cite). For a simple lens setup, the resulting waist is illustrated in the image below. + +![Astigmatic ray tracing II](agbtest2.png) + +While the above beam closely matches the example Gaussian given in the previous section ([Obtaining the beam parameters](@ref)), the real advantage of this extended method lies in the tracing of non-symmetric systems. For a tilted two cylinder lens system, the following result with strong astigmatic effects is obtained. Multiple waist slices are marked with red dots. + +![Astigmatic ray tracing III](agbtest3.png) + +The phase factor due to the optical path length of the central ray ($e^{i k (z + \Delta L)}$) is added to the reduced field $\psi$ during the final field calculation for each beamlet. More information on the mathemathics behind this formalism can be found below in [The Curvature Matrix $\mathbf{Q}$](@ref) section. + +!!! info "Optical invariant" + In order to ensure the correctness of the traced beamlet, the complex ray vectors must satisfy the **vanishing complex optical invariant**: + ```math + \mathbf{h}_1 \times \mathbf{u}_2 - \mathbf{h}_2 \times \mathbf{u}_1 = 0 + ``` + This ensures that the complex curvature matrix $\mathbf{Q}$ is symmetric, since the beamlet formalism can not capture higher-order abberations. + +## Astigmatic beamlets + +You can construct a single astigmatic beamlet with a specified waist and polarization: + +```@docs; canonical=false +AstigmaticGaussianBeamlet(::AbstractArray, ::AbstractArray, ::Real, ::Real) +``` + +The constructor will spawn an `AstigmaticGaussianBeamlet` which is implemented as follows: + +```@docs; canonical=false +AstigmaticGaussianBeamlet +``` + +### Calculating astigmatic beam parameters + +To obtain the physical vector electric field [V/m] at any point: +```julia +# Field at world position (x, y, z) +E_vec = polarized_field(agb, [0.01, 0, 0], 10.0) +``` + +```julia +# Decompose a field from a detector into a new AstigmaticBeamGroup +beams = WavefrontBeamletDecomposition(x, z, amplitude, phase, dir, λ) + +# Solve system (propagate all beamlets to next segment) +solve_system!(system, beams) +``` + +## The Curvature Matrix $\mathbf{Q}$ + +The relationship between the auxiliary rays and the complex curvature of the beam is defined by the matrix equation $\mathbf{Q} = \mathbf{U}\mathbf{H}^{-1}$. By arranging the transverse components of the complex rays into $2 \times 2$ matrices $\mathbf{H} = [\mathbf{h}_1, \mathbf{h}_2]$ and $\mathbf{U} = [\mathbf{u}_1, \mathbf{u}_2]$, we can solve for the individual components of $\mathbf{Q}$: + +```math +\mathbf{Q} = \frac{1}{\mathbf{h}_1 \times \mathbf{h}_2} \begin{bmatrix} +u_{1x} h_{2y} - u_{2x} h_{1y} & u_{2x} h_{1x} - u_{1x} h_{2x} \\ +u_{1y} h_{2y} - u_{2y} h_{1y} & u_{2y} h_{1x} - u_{1y} h_{2x} +\end{bmatrix} +``` + +The diagonal elements $Q_{xx}$ and $Q_{yy}$ describe the phase curvature (and beam width) along the primary axes, while the off-diagonal elements $Q_{xy}$ (which must equal $Q_{yx}$ for a paraxial beam) describe the **general astigmatism** or twist of the wavefront. This representation allows the formalism to track complex, rotating beam profiles as they propagate through non-orthogonal optical systems. It is important to note that this matrix is not directly tracked during beamlet propagation in **BMO**. More information can be found in the works of Kochkina (2013) and Ashcraft et al. (2024) [Kochkina:2013, Ashcraft:2024](@cite). + +!!! note "Analytic Bilinear Form" + All vector operations in the formulas above ($\cdot, \times$) and the matrix product $\mathbf{r}^T \mathbf{Q} \mathbf{r}$ use the **analytic bilinear form** rather than the conjugated dot product. This preservation of analytic continuity is essential for the stability of Gaussian beamlets in the complex domain. + +## Physical Beam Cross-Section + +While the complex curvature matrix $\mathbf{Q}$ determines the phase and amplitude of the field, extracting the physical $1/e^2$ irradiance footprint (the principal axes of the beam ellipse) requires calculating the spot covariance matrix. This relates directly to the internal code of the `waist_parameters` function. + +As explicitly modeled for general astigmatic Gaussian beams [KochkinaAO:2013](@cite), the matrix describing this intensity ellipse is directly derived from $\operatorname{Im}(\mathbf{Q})$. The eigendecomposition of this matrix (or its inverse) yields eigenvalues that correspond exactly to the squared physical semi-axes of the beam. + +The spatial spot matrix $\mathbf{S}$, which describes the boundary of this intensity ellipse, is proportional to $\operatorname{Im}(\mathbf{Q})^{-1}$. A fundamental property of Hamiltonian optics (the symplectic invariant) dictates that for any physically valid, non-twisted Gaussian beam, the imaginary part of the curvature matrix satisfies: +```math +\operatorname{Im}(\mathbf{Q}) = (\mathbf{H} \mathbf{H}^\dagger)^{-1} +``` +This identity implies that the spatial spot covariance matrix $\mathbf{S}$, which defines the beam envelope, is directly proportional to the outer product of the complex ray height matrix: $\mathbf{S} \propto \mathbf{H} \mathbf{H}^\dagger$. + +In **BeamletOptics**, this calculation is mapped directly to the 3D global coordinate system. Using the two complex 3D ray vectors $\mathbf{h}_1$ and $\mathbf{h}_2$, the $3 \times 3$ physical covariance matrix is formed by taking the real part of the tensor product: +```math +\mathbf{S} = \operatorname{Re}(\mathbf{h}_1 \mathbf{h}_1^\dagger + \mathbf{h}_2 \mathbf{h}_2^\dagger) +``` +Expanding the complex vectors into their real and imaginary parts ($\mathbf{h} = \mathbf{h}_r + i \mathbf{h}_i$), this is implemented as: +```math +\mathbf{S} = \mathbf{h}_{1r} \mathbf{h}_{1r}^T + \mathbf{h}_{1i} \mathbf{h}_{1i}^T + \mathbf{h}_{2r} \mathbf{h}_{2r}^T + \mathbf{h}_{2i} \mathbf{h}_{2i}^T +``` +To find the true physical principal axes of the general astigmatic beam, the `waist_parameters` function computes the eigendecomposition of this symmetric matrix $\mathbf{S}$. The resulting eigenvectors provide the orientation, while the square roots of the eigenvalues provide the lengths of the orthogonal major and minor 3D semi-axes. This approach ensures an objective and stable definition of the intensity footprint, even in systems where the beam undergoes rapid rotation, skew, or non-orthogonal transformations [KochkinaAO:2013, Arnaud1968, Worku:2017](@cite). diff --git a/docs/src/basics/beams/beam_groups.md b/docs/src/basics/beams/beam_groups.md new file mode 100644 index 000000000..f636acac6 --- /dev/null +++ b/docs/src/basics/beams/beam_groups.md @@ -0,0 +1,59 @@ +```@setup beam_groups +beam_showcase_dir = joinpath(@__DIR__, "..", "..", "assets", "beam_renders") + +Main.DocUtils.conditional_include(joinpath(beam_showcase_dir, "collimated_sc.jl")) +Main.DocUtils.conditional_include(joinpath(beam_showcase_dir, "pointsource_sc.jl")) +``` + +# Beam groups + +For convenience, the [`BeamletOptics.AbstractBeamGroup`](@ref) offers a container-like interface for groups of [`Beam`](@ref)s as commonly used in other software packages. The following concrete implementations are currently provided: + +```@repl +using BeamletOptics # hide +BeamletOptics.list_subtypes(BeamletOptics.AbstractBeamGroup); +``` + +Refer to the following sections for convenience constructors to generate the sources listed above. + +## Collimated beam source + +The collimated beam source is ideal to model light coming from a focal plane at infinity. This is useful for simulating plane wavefronts. You can define a collimated monochromatic [`Beam`](@ref) source as follows: + +```@docs; canonical=false +CollimatedSource(::AbstractArray{<:Real}, ::AbstractArray{<:Real}, ::Real, ::Real) +``` + +![Collimated group of beams](collimated_beam_source.png) + +A special constructor called [`UniformDiscSource`](@ref) is available, which offers an equal-area +sampling (Fibonnaci-pattern) sampling and is thus favorable in situations where the weighting of the +individual beams becomes important, e.g. for calculating a point spread function using the [`intensity`](@ref) function. + +```@docs; canonical=false +UniformDiscSource +``` + +![Collimated uniform group of beams](collimated_uniform_beam_source.png) + +## Point beam source + +The `PointSource` type is used to model emission from a spatially localized source that radiates [`Beam`](@ref)s in a range of directions. This is commonly used to simulate conical emission patterns, such as light emerging from a fiber tip or a light source for a lens objective with a known focal distance. You can specify the origin and a propagation direction, which are then used to construct the monochromatic `PointSource`. + +```@docs; canonical=false +PointSource(::AbstractArray{<:Real}, ::AbstractArray{<:Real}, ::Real, ::Real) +``` + +Below you can find an exemplary illustration of a `PointSource`. + +![Point source of beams](point_beam_source.png) + +## Astigmatic Beam Groups + +For complex sources, the package provides the [`AstigmaticBeamGroup`](@ref) container. Several constructors are available for different scenarios: + +- [`GaussianBeamletDecomposition`](@ref): Tiling a large Gaussian beam into many small stable beamlets. +- [`WavefrontBeamletDecomposition`](@ref): Importing an arbitrary complex field (e.g. from a phase screen or camera data). +- [`CollimatedGaussianBeamletSource`](@ref): A square grid of parallel beamlets (ideal for aperture diffraction). +- [`SphericalGaussianBeamletSource`](@ref): A point-like source emitting a cone of beamlets (ideal for focused/divergent beams). +- [`EllipticalGaussianBeamletSource`](@ref): A point-like source emitting an elliptical cone of beamlets (ideal for sources with different fast/slow axis divergence). \ No newline at end of file diff --git a/docs/src/basics/beams/beams.md b/docs/src/basics/beams/beams.md new file mode 100644 index 000000000..c62c20188 --- /dev/null +++ b/docs/src/basics/beams/beams.md @@ -0,0 +1,23 @@ +```@setup beams +beam_showcase_dir = joinpath(@__DIR__, "..", "..", "assets", "beam_renders") + +Main.DocUtils.conditional_include(joinpath(beam_showcase_dir, "beam_showcase.jl")) +``` + +# Beams + +As mentioned in the [Rays](@ref) section, a beam within the context of this package serves as a data structure for storing collections of rays, forming the backbone of the simulation framework. Beams are intended to be designed as [AbstractTrees](https://github.com/JuliaCollections/AbstractTrees.jl) to allow for ray bifurcations, e.g. in the case of optical elements such as beamsplitters. The [`solve_system!`](@ref) function relies on this data structure to perform ray tracing computations within optical systems. + +To ensure compatibility and extensibility, beam types must adhere to the [`BeamletOptics.AbstractBeam`](@ref) interface. Refer to its documentation for more information. + +## Basic beam + +A minimal implementation of the [`BeamletOptics.AbstractBeam`](@ref) type is provided by the [`Beam`](@ref). It can be used to store a light path through an optical system. If the beam is split, its children will be recursively traced until all paths are solved. + +```@docs; canonical=false +Beam +``` + +A ray tracing example through an arbitrary system using a [`Beam`](@ref) is shown below. Individual [`Ray`](@ref) segments are marked by their starting position and direction. The [Beam expander](@ref) and [Miniature microscope](@ref) tutorial covers the use of the [`Beam`](@ref) in more detail. + +![Beam structure](beam_showcase.png) \ No newline at end of file diff --git a/docs/src/basics/beams/stigmatic_beam.md b/docs/src/basics/beams/stigmatic_beam.md new file mode 100644 index 000000000..646f5933f --- /dev/null +++ b/docs/src/basics/beams/stigmatic_beam.md @@ -0,0 +1,63 @@ +```@setup stigmatic_beamlet +beam_showcase_dir = joinpath(@__DIR__, "..", "..", "assets", "beam_renders") + +Main.DocUtils.conditional_include(joinpath(beam_showcase_dir, "gb_showcase.jl")) +``` + +# Gaussian beamlet + +Lasers are common devices in modern optical laboratories. Modeling their propagation through an optical setup can be of interest when planning new experiments. Geometrical ray tracing struggles to capture the propagation of a laser beam correctly, since it can not inherently capture the wave nature of e.g. the [Gaussian beam](https://www.rp-photonics.com/gaussian_beams.html). + +The electric field of the ``\text{TEM}_{00}`` spatial Gaussian mode can be calculated analytically using the [`BeamletOptics.electric_field`](@ref) function: + +```@docs; canonical=false +BeamletOptics.electric_field(r::Real, z::Real, E0, w0, w, k, ψ, R) +``` + +The evolution of this field through an optical system can be modeled e.g. by the ray transfer matrix formalism using the complex ``q``-factor [Saleh2019; pp. 27](@cite). A Julia-based implementation of this approach can be found in [ABCDMatrixOptics.jl](https://github.com/JuliaPhysics/ABCDMatrixOptics.jl). However, in the case of this package another approach will be used. + +## Complex ray tracing + +In 1968 an internal publication at Bell Labs by J. Arnaud introduced the concept of complex rays wherein three geometrical beams can be used to model the propagation of a Gaussian in fundamental mode through a symmetric optical system, i.e. without the Gaussian obtaining astigmatism and/or higher-order abberations. This method is analoguos to the ray transfer matrix based ``q``-method [Arnaud1968](@cite). + +Without extensions of the original method, the following key assumptions must be met such that this method can be applied + +- all (complex) beams of the Gaussian in question must intersect the same optical elements +- the optical elements are large compared to the beam (waist) +- the paraxial approximation must hold for each beam +- the Gaussian may not be clipped by hard apertures +- Lagrange invariant must be fulfilled + +Various versions of this approach have been implemented under different names in commercial software, most notably [FRED](https://photonengr.com/fred-software/), [Code V](https://www.synopsys.com/optical-solutions/codev.html) and [QUADOA](https://www.quadoa.com), as well as in open source software, e.g. + +- [Raypier](https://github.com/bryancole/raypier_optics) - based on Cython, maintenance status not known +- [Poke](https://github.com/Jashcraf/poke) - based on Zemax API and Python, maintained by J. Ashcraft et al. [Ashcraft:2022](@cite) +- [IfoCAD](https://www.aei.mpg.de/ifocad-de) - maintenance status not known, refer to Wanner et al. [Wanner:2017](@cite) + +This package implements the above method via the stigmatic [`GaussianBeamlet`](@ref) and the [`AstigmaticGaussianBeamlet`](@ref), the latter of which is presented in more detail in the [Astigmatic polarized beamlets](@ref) chapter. + +## Stigmatic beamlets + +The [`GaussianBeamlet`](@ref) implements the [`BeamletOptics.AbstractBeam`](@ref) interface and can be used to model the propagation of a monochromatic Gaussian (``\text{TEM}_{00}``-mode) through optical system where all optics lie on the optical axis, e.g. no tip and/or tilt dealignment, and abberations can be neglected. It is represented by a `chief` (red), `waist` (blue) and `divergence` (green) beam. See below how these beams are placed in relation to the envelope of the Gaussian beam. + +![Complex ray tracing I](gbtest1.png) + +```@docs; canonical=false +GaussianBeamlet +``` + +A [`GaussianBeamlet`](@ref) can be constructed via: + +```@docs; canonical=false +GaussianBeamlet(::AbstractArray{<:Real}, ::AbstractArray{<:Real}, ::Real, ::Real) +``` + +### Obtaining the beam parameters + +Once a `GaussianBeamlet` has been traced through an optical system, several parameters might be of interest for further analysis. In order to relate the traced geometrical beams/rays to the Gaussian parameters, the publications of Arnaud, Herloski et al. and DeJager et al. are used [Arnaud1968, Herloski1983, DeJager1992](@cite). Consider the following system where a Gaussian beam with arbitrary parameters has been traced through a lens using the approach outlined in the [Complex ray tracing](@ref) section. + +![Complex ray tracing II](gbtest2.png) + +The user can obtain parameters such as the beam waist radius, the radius of curvature and more using the [`gauss_parameters`](@ref) and/or [`waist_parameters`](@ref) functions. Below the local waist radius and curvature ``R = r^{-1}`` have been calculated for the example above. + +![Gauss beam parameters](gauss_parameters.png) \ No newline at end of file diff --git a/docs/src/basics/components/beamsplitters.md b/docs/src/basics/components/beamsplitters.md index bccbcb315..6d3a519dd 100644 --- a/docs/src/basics/components/beamsplitters.md +++ b/docs/src/basics/components/beamsplitters.md @@ -1,10 +1,8 @@ ```@setup beamsplitters -include(joinpath(@__DIR__, "..", "..", "assets", "cond_save.jl")) - bs_showcase_dir = joinpath(@__DIR__, "..", "..", "assets", "bs_assets") -conditional_include(joinpath(bs_showcase_dir, "pbs_showcase.jl")) -conditional_include(joinpath(bs_showcase_dir, "cbs_showcase.jl")) +Main.DocUtils.conditional_include(joinpath(bs_showcase_dir, "pbs_showcase.jl")) +Main.DocUtils.conditional_include(joinpath(bs_showcase_dir, "cbs_showcase.jl")) ``` # Beamsplitters diff --git a/docs/src/basics/components/detectors.md b/docs/src/basics/components/detectors.md index e0db0c08c..41a5a00e0 100644 --- a/docs/src/basics/components/detectors.md +++ b/docs/src/basics/components/detectors.md @@ -1,11 +1,9 @@ ```@setup detectors -include(joinpath(@__DIR__, "..", "..", "assets", "cond_save.jl")) - detector_showcase_dir = joinpath(@__DIR__, "..", "..", "assets", "detector_assets") -conditional_include(joinpath(detector_showcase_dir, "spotdetector_showcase.jl")) -conditional_include(joinpath(detector_showcase_dir, "photodetector_showcase.jl"), use_placeholder=false) -conditional_include(joinpath(detector_showcase_dir, "psfdetector_showcase.jl"), use_placeholder=false) +Main.DocUtils.conditional_include(joinpath(detector_showcase_dir, "spotdetector_showcase.jl")) +Main.DocUtils.conditional_include(joinpath(detector_showcase_dir, "photodetector_showcase.jl")) +Main.DocUtils.conditional_include(joinpath(detector_showcase_dir, "psfdetector_showcase.jl")) ``` # Detectors diff --git a/docs/src/basics/components/lenses.md b/docs/src/basics/components/lenses.md index 2e72c0ed3..a7f34e874 100644 --- a/docs/src/basics/components/lenses.md +++ b/docs/src/basics/components/lenses.md @@ -1,12 +1,10 @@ ```@setup lenses -include(joinpath(@__DIR__, "..", "..", "assets", "cond_save.jl")) - lens_showcase_dir = joinpath(@__DIR__, "..", "..", "assets", "lens_assets") -conditional_include(joinpath(lens_showcase_dir, "lens_constructor_showcase.jl")) -conditional_include(joinpath(lens_showcase_dir, "spherical_lens_showcase.jl")) -conditional_include(joinpath(lens_showcase_dir, "aspherical_lens_showcase.jl")) -conditional_include(joinpath(lens_showcase_dir, "spherical_doublet_showcase.jl")) +Main.DocUtils.conditional_include(joinpath(lens_showcase_dir, "lens_constructor_showcase.jl")) +Main.DocUtils.conditional_include(joinpath(lens_showcase_dir, "spherical_lens_showcase.jl")) +Main.DocUtils.conditional_include(joinpath(lens_showcase_dir, "aspherical_lens_showcase.jl")) +Main.DocUtils.conditional_include(joinpath(lens_showcase_dir, "spherical_doublet_showcase.jl")) ``` # Lenses diff --git a/docs/src/basics/components/mirrors.md b/docs/src/basics/components/mirrors.md index 7abbc40b6..e429fc308 100644 --- a/docs/src/basics/components/mirrors.md +++ b/docs/src/basics/components/mirrors.md @@ -1,10 +1,8 @@ ```@setup mirrors -include(joinpath(@__DIR__, "..", "..", "assets", "cond_save.jl")) - mirror_showcase_dir = joinpath(@__DIR__, "..", "..", "assets", "mirror_renders") -conditional_include(joinpath(mirror_showcase_dir, "plano_mirror_showcase.jl")) -conditional_include(joinpath(mirror_showcase_dir, "spherical_mirror_showcase.jl")) +Main.DocUtils.conditional_include(joinpath(mirror_showcase_dir, "plano_mirror_showcase.jl")) +Main.DocUtils.conditional_include(joinpath(mirror_showcase_dir, "spherical_mirror_showcase.jl")) ``` # Mirrors diff --git a/docs/src/basics/intro.md b/docs/src/basics/intro.md index a417f10a1..d4832dfe5 100644 --- a/docs/src/basics/intro.md +++ b/docs/src/basics/intro.md @@ -5,6 +5,14 @@ This section of the documentation is intended for users that want to dive deeper ## Basics overview ```@contents -Pages = ["rays.md", "beams.md", joinpath("components", "components.md"), "systems.md", "render.md", "components\\test.md"] +Pages = [ + "rays.md", + joinpath("beams", "beams.md"), + joinpath("beams", "stigmatic_beam.md"), + joinpath("beams", "astigmatic_beam.md"), + joinpath("components", "components.md"), + "systems.md", + "render.md", +] Depth = 2 ``` \ No newline at end of file diff --git a/docs/src/basics/rays.md b/docs/src/basics/rays.md index 6cc1554a9..90a787cc5 100644 --- a/docs/src/basics/rays.md +++ b/docs/src/basics/rays.md @@ -1,10 +1,8 @@ ```@setup rays -include(joinpath(@__DIR__, "..", "assets", "cond_save.jl")) - ray_showcase_dir = joinpath(@__DIR__, "..", "assets", "ray_assets") -conditional_include(joinpath(ray_showcase_dir, "ray_showcase.jl")) -conditional_include(joinpath(ray_showcase_dir, "fresnel_coeffs.jl")) +Main.DocUtils.conditional_include(joinpath(ray_showcase_dir, "ray_showcase.jl")) +Main.DocUtils.conditional_include(joinpath(ray_showcase_dir, "fresnel_coeffs.jl")) ``` # Rays diff --git a/docs/src/examples/agb_doubleslit_experiment.png b/docs/src/examples/agb_doubleslit_experiment.png new file mode 100644 index 000000000..558d840a2 Binary files /dev/null and b/docs/src/examples/agb_doubleslit_experiment.png differ diff --git a/docs/src/examples/double_gauss.md b/docs/src/examples/double_gauss.md index d202a6e56..6226acd87 100644 --- a/docs/src/examples/double_gauss.md +++ b/docs/src/examples/double_gauss.md @@ -1,9 +1,7 @@ ```@setup double_gauss -include(joinpath(@__DIR__, "..", "assets", "cond_save.jl")) - dir = joinpath(@__DIR__, "..", "assets", "examples") -conditional_include(joinpath(dir, "double_gauss.jl")) +Main.DocUtils.conditional_include(joinpath(dir, "double_gauss.jl")) ``` # Double Gauss lens diff --git a/docs/src/examples/double_slit.md b/docs/src/examples/double_slit.md new file mode 100644 index 000000000..d523e0c24 --- /dev/null +++ b/docs/src/examples/double_slit.md @@ -0,0 +1,15 @@ +```@setup double_slit +showcase_dir = joinpath(@__DIR__, "..", "assets", "examples") + +Main.DocUtils.prerender_include(joinpath(showcase_dir, "double_slit.jl"), @__FILE__) +``` + +## Double slit diffraction + +One of the most powerful applications of the beamlet tracing method is the simulation of coherent diffraction from complex apertures. The **BMO** package provides the [`AstigmaticGaussianBeamlet`](@ref) as an implementation of this formalism. More information can be found in the [Astigmatic polarized beamlets](@ref) section. By using a [`WavefrontBeamletDecomposition`](@ref), any arbitrary aperture mask (including phase-varying masks) can be decomposed into a set of coherent beamlets. + +In the example below, a classic double-slit mask (10 µm width, 100 µm separation) is decomposed and propagated 0.2 meters. The simulation perfectly reproduces the analytical Fraunhofer diffraction pattern, showcasing both the individual slit diffraction (envelope) and the coherent interference fringes. + +![Double Slit Experiment Visualization](agb_doubleslit_experiment.png) + +This example demonstrates the package's ability to maintain phase coherence across thousands of beamlets. This is, in principle, a prerequisite for high-fidelity modeling of systems like Atmospheric Turbulence or Phase-Modulating SLMs. \ No newline at end of file diff --git a/docs/src/examples/lens_groups.md b/docs/src/examples/lens_groups.md index cf5c63d88..333cf53d0 100644 --- a/docs/src/examples/lens_groups.md +++ b/docs/src/examples/lens_groups.md @@ -1,9 +1,7 @@ ```@setup double_gauss -include(joinpath(@__DIR__, "..", "assets", "cond_save.jl")) - dir = joinpath(@__DIR__, "..", "assets", "examples") -conditional_include(joinpath(dir, "lens_groups.jl")) +Main.DocUtils.conditional_include(joinpath(dir, "lens_groups.jl")) ``` # Lens groups diff --git a/docs/src/index.md b/docs/src/index.md index 331c8b862..32d6ddd05 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -27,7 +27,7 @@ For this purpose, the package implements a traditional ray tracing solver. This ## Installation !!! warning - This package requires Julia ≥ 1.9.4 + This package requires Julia ≥ 1.10 You can add this package to your project by entering the package manager (press `]` in the REPL) and typing `add BeamletOptics`. It is also recommended that you `add GLMakie`. You can include this package into your current scope via `using BeamletOptics`. If a Makie version is loaded before or after the inclusion of this package, the extension provided as part of this package will enable additional visualization functions. @@ -44,6 +44,7 @@ The BeamletOptics package is made available under the MIT license. If you use th A variety of packages and tools exist that implement similar approaches or offer optics modeling capabilities. Within the Julia ecosystem, the following packages need to be mentioned: - [OpticSim.jl](https://github.com/brianguenter/OpticSim.jl) +- [FluxOptics.jl](https://github.com/anscoil/FluxOptics.jl) - [ABCDMatrixOptics.jl](https://github.com/JuliaPhysics/ABCDMatrixOptics.jl) - [WaveOpticsPropagation.jl](https://github.com/JuliaPhysics/WaveOpticsPropagation.jl) @@ -65,9 +66,9 @@ In order to warrant a 1.0.0 release tag, the following features will need to be ### Additional features - 🔳 Beamlet tracing - - 🟩 Implementation of the full polarized astigmatic Gaussian beamlet formalism + - ✅ Implementation of the full polarized astigmatic Gaussian beamlet formalism - refer to Worku et al. (2017/2020), Greynolds (1985) - - 🔳 Support for (trivial) forms of 2D-field decomposition, e.g. tophat + - ✅ Support for (trivial) forms of 2D-field decomposition, e.g. tophat - 🔳 Modeling of the coherence length and contrast influence - 🔳 Components - 🟩 Polarizing optics (based on Jones formalism) diff --git a/docs/src/reference.md b/docs/src/reference.md index f89e21e32..dd6dfbe71 100644 --- a/docs/src/reference.md +++ b/docs/src/reference.md @@ -15,5 +15,5 @@ Depth = 5 # Index ```@autodocs -Modules = [BeamletOptics] +Modules = [BeamletOptics, BeamletOptics.Config] ``` \ No newline at end of file diff --git a/docs/src/refs.bib b/docs/src/refs.bib index 0cf5058ad..7c2f8fc2c 100644 --- a/docs/src/refs.bib +++ b/docs/src/refs.bib @@ -248,3 +248,115 @@ @article{McMillan:2022 doi = {10.1117/1.JBO.27.8.083003}, URL = {https://doi.org/10.1117/1.JBO.27.8.083003} } + +@inproceedings{Greynolds:1986_1, + author = {Alan W. Greynolds}, + title = {{Propagation Of Generally Astigmatic Gaussian Beams Along Skew Ray Paths}}, + volume = {0560}, + booktitle = {Diffraction Phenomena in Optical Engineering Applications}, + editor = {Dale M. Byrne and James E. Harvey}, + organization = {International Society for Optics and Photonics}, + publisher = {SPIE}, + pages = {33 -- 51}, + year = {1986}, + doi = {10.1117/12.949614}, + URL = {https://doi.org/10.1117/12.949614} +} + + +@inproceedings{Greynolds:1986_2, + author = {Alan W. Greynolds}, + title = {{Vector Formulation Of The Ray-Equivalent Method For General Gaussian Beam Propagation}}, + volume = {0679}, + booktitle = {Current Developments in Optical Engineering and Diffraction Phenomena}, + editor = {Robert E. Fischer and James E. Harvey and Warren J. Smith}, + organization = {International Society for Optics and Photonics}, + publisher = {SPIE}, + pages = {129 -- 133}, + year = {1986}, + doi = {10.1117/12.939577}, + URL = {https://doi.org/10.1117/12.939577} +} + +@inproceedings{Greynolds:2014, + author = {Alan W. Greynolds}, + booktitle = {Classical Optics 2014}, + journal = {Classical Optics 2014}, + keywords = {Propagation methods ; Diffraction theory; Wave propagation ; Geometric optics; Optical systems; Physical optics; Ray tracing; Spatial filtering; Spherical aberration}, + pages = {ITu1A.3}, + publisher = {Optica Publishing Group}, + title = {Fat Rays Revisited: A Synthesis of Physical and Geometrical Optics with Gau{\ss}lets}, + year = {2014}, + url = {https://opg.optica.org/abstract.cfm?URI=IODC-2014-ITu1A.3}, + doi = {10.1364/IODC.2014.ITu1A.3}, + abstract = {Decomposed into Gau{\ss}lets (Gaussian beamlets or ``fat rays''), a diffracting wavefield can be propagated through an optical system by simple ray tracing. As an update to a 1990 ILDC presentation, the method's progress since then is covered along with new comparisons against more precise solutions.}, +} + + +@inproceedings{Wilhelm:2001, + author = {Rainer Wilhelm}, + title = {{Comparing geometrical and wave-optical algorithms of a novel propagation code applied to the VLTI}}, + volume = {4436}, + booktitle = {Wave-Optical Systems Engineering}, + editor = {Frank Wyrowski}, + organization = {International Society for Optics and Photonics}, + publisher = {SPIE}, + pages = {89 -- 100}, + keywords = {geometrical optics, ray tracing, physical optics, wave propagation, beam decomposition, Gaussian bea}, + year = {2001}, + doi = {10.1117/12.451287}, + URL = {https://doi.org/10.1117/12.451287} +} + +@inproceedings{Worku:2017, + author = {N. Worku and H. Gross}, + title = {{Vectorial field propagation through high NA objectives using polarized Gaussian beam decomposition}}, + volume = {10347}, + booktitle = {Optical Trapping and Optical Micromanipulation XIV}, + editor = {Kishan Dholakia and Gabriel C. Spalding}, + organization = {International Society for Optics and Photonics}, + publisher = {SPIE}, + pages = {103470W}, + keywords = {Gaussian, beam decomposition, polarization, complex ray tracing, three dimensional polarization ray tracing, vectorial field, high NA objective}, + year = {2017}, + doi = {10.1117/12.2273919}, + URL = {https://doi.org/10.1117/12.2273919} +} + +@phdthesis{Kochkina:2013, + author = "Kochkina, Evgenia", + title = "{Stigmatic and astigmatic Gaussian beams in fundamental mode : impact of beam model choice on interferometric pathlength signal estimates}", + doi = "10.15488/8105", + school = "Leibniz U., Hannover", + year = "2013" +} + +@article{Ashcraft:2024, + author = {Jaren N. Ashcraft and Ewan S. Douglas and Ramya Anche and Brandon D. Dube and Kevin Z. Derby and Lars Furenlid and Maggie Kautz and Daewook Kim and Kian Milani and A. J. Eldorado Riggs}, + journal = {Opt. Express}, + keywords = {Diffraction theory; Fourier transforms; Gaussian beams; Imaging systems; Optical elements; Optical systems}, + number = {10}, + pages = {18068--18086}, + publisher = {Optica Publishing Group}, + title = {A generalized expression for accelerating beamlet decomposition simulations}, + volume = {32}, + month = {May}, + year = {2024}, + url = {https://opg.optica.org/oe/abstract.cfm?URI=oe-32-10-18068}, + doi = {10.1364/OE.524434}, +} + +@article{KochkinaAO:2013, + author = {Evgenia Kochkina and Gudrun Wanner and Dennis Schmelzer and Michael Tr\"{o}bs and Gerhard Heinzel}, + journal = {Appl. Opt.}, + keywords = {Mathematical methods in physics; Propagation; First-order optics; Laser beam characterization ; Cylindrical lenses; Gaussian beams; Laser beams; Optical signals; Optical systems; Phase matching}, + number = {24}, + pages = {6030--6040}, + publisher = {Optica Publishing Group}, + title = {Modeling of the general astigmatic Gaussian beam and its propagation through 3D optical systems}, + volume = {52}, + month = {Aug}, + year = {2013}, + url = {https://opg.optica.org/ao/abstract.cfm?URI=ao-52-24-6030}, + doi = {10.1364/AO.52.006030}, +} \ No newline at end of file diff --git a/docs/src/tutorials/michelson.md b/docs/src/tutorials/michelson.md index caeddfc78..1ed45015b 100644 --- a/docs/src/tutorials/michelson.md +++ b/docs/src/tutorials/michelson.md @@ -1,11 +1,9 @@ ```@setup michelson using BeamletOptics -include(joinpath(@__DIR__, "..", "assets", "cond_save.jl")) - michelson_dir = joinpath(@__DIR__, "..", "assets", "mi_assets") -conditional_include(joinpath(michelson_dir, "michelson_showcase.jl")) +Main.DocUtils.conditional_include(joinpath(michelson_dir, "michelson_showcase.jl")) ``` # Michelson interferometer diff --git a/docs/src/tutorials/microscope.md b/docs/src/tutorials/microscope.md index f09f61383..00959c609 100644 --- a/docs/src/tutorials/microscope.md +++ b/docs/src/tutorials/microscope.md @@ -1,9 +1,7 @@ ```@setup miniscope -include(joinpath(@__DIR__, "..", "assets", "cond_save.jl")) - tutorial_dir = joinpath(@__DIR__, "..", "assets", "ms_assets") -conditional_include(joinpath(tutorial_dir, "miniscope_showcase.jl")) +Main.DocUtils.conditional_include(joinpath(tutorial_dir, "miniscope_showcase.jl")) ``` # Miniature microscope diff --git a/ext/BeamletOpticsMakieExt.jl b/ext/BeamletOpticsMakieExt.jl index d613e2807..95945bc34 100644 --- a/ext/BeamletOpticsMakieExt.jl +++ b/ext/BeamletOpticsMakieExt.jl @@ -9,10 +9,11 @@ using Makie: Axis3, LScene, mesh!, surface!, lines!, RGBf, RGBAf, scatter! using GeometryBasics: Point2, Point3 using AbstractTrees: PreOrderDFS using MarchingCubes: MC, march +using LinearAlgebra: dot, cross, normalize const _RenderEnv = Union{ Axis3, - LScene, + LScene } struct InvalidAxisError <: RenderException @@ -28,7 +29,7 @@ struct RenderNotImplementedError <: RenderException msg::String t::Type function RenderNotImplementedError(t::Type) - if !(t<:_RenderTypes) + if !(t <: _RenderTypes) throw(ErrorException("Type $t not supported")) end msg = "Render function not implemented for type $t" @@ -36,13 +37,16 @@ struct RenderNotImplementedError <: RenderException end end -render!(::A, ::_RenderTypes; kwargs...) where A<:Any = throw(InvalidAxisError(A)) +render!(::A, ::_RenderTypes; kwargs...) where {A <: Any} = throw(InvalidAxisError(A)) -render!(::_RenderEnv, ::T; kwargs...) where T<:_RenderTypes = throw(RenderNotImplementedError(T)) +function render!(::_RenderEnv, ::T; kwargs...) where {T <: _RenderTypes} + throw(RenderNotImplementedError(T)) +end # include order dependant! include("RenderBeam.jl") include("RenderGaussian.jl") +include("RenderAstigmaticGaussian.jl") include("RenderSDF.jl") include("RenderMesh.jl") include("RenderObjects.jl") @@ -80,6 +84,6 @@ end Hides the axis markers in the `LScene`. Can be toggled via `hide`. """ -hide_axis(ls::LScene, hide::Bool=true) = (ls.show_axis[] = !hide) +hide_axis(ls::LScene, hide::Bool = true) = (ls.show_axis[] = !hide) -end \ No newline at end of file +end diff --git a/ext/RenderAstigmaticGaussian.jl b/ext/RenderAstigmaticGaussian.jl new file mode 100644 index 000000000..badb0c7fd --- /dev/null +++ b/ext/RenderAstigmaticGaussian.jl @@ -0,0 +1,142 @@ +""" + render!(ax, agb::AstigmaticGaussianBeamlet; kwargs...) + +Render the 1/e² envelope of the [`AstigmaticGaussianBeamlet`](@ref) as a smooth 3D surface. + +With `show_beams = true` the generating rays are overlayed into the axis as follows: + +- `chief` beam: red +- `divergence` beam: green +- `waist` beam: blue + +# Keyword args + +- `show_beams = false`: plot the generating rays (chief, waist, divergence) +- `flen = 0.1`: length of the final beam segment in case of no intersection [m] +- `z_res::Int = 100`: longitudinal resolution +- `r_res::Int = 64`: radial (angular) resolution + +# Makie kwargs + +- `color = :red` +- `transparency = true` +""" +function render!( + axis::_RenderEnv, + agb::BMO.AstigmaticGaussianBeamlet{T}; + # kwargs + show_beams = false, + show_pos = false, + r_res = 64, + z_res = 100, + flen = 0.1, + show_waist = false, + # Makie kwargs + color = :red, + transparency = true, + markersize = 10, + kwargs... +) where {T} + vs = LinRange(0, 2π, r_res) + for child in PreOrderDFS(agb) + # Length tracking variable + p = child.parent + if isnothing(p) + l = zero(T) + else + l = length(p) + end + + for ray in BMO.rays(child.c) + # Calculate local segment length + if isnothing(BMO.intersection(ray)) + l_local = flen + else + l_local = length(ray) + end + us = LinRange(0, l_local, z_res) .+ l + # Precompute waist parameters at each z + params = [BMO.waist_parameters(child, u) for u in us] + + # sort params b and c + ps = getindex.(params, 1) + bs = getindex.(params, 2) + cs = getindex.(params, 3) + + # Ensure elliptical basis vectors (bs, cs) vary smoothly along the segment + # to prevent mesh twisting/flips, especially when passing through a focus. + for j in 2:length(bs) + b_new = bs[j] + c_new = cs[j] + b_old = bs[j - 1] + c_old = cs[j - 1] + + # preserve handedness (prevent inside-out mesh flips) + cross_old = cross(b_old, c_old) + cross_new = cross(b_new, c_new) + if dot(cross_new, cross_old) < 0 + b_new = -b_new + end + + # optimal rotation to align with previous slice (Parallel Transport) + # MUST normalize to prevent magnitude-bias from twisting the mesh when major/minor axes swap! + bn = normalize(b_new) + cn = normalize(c_new) + bo = normalize(b_old) + co = normalize(c_old) + + X = dot(bn, bo) + dot(cn, co) + Y = dot(cn, bo) - dot(bn, co) + phi = atan(Y, X) + + cos_phi = cos(phi) + sin_phi = sin(phi) + + bs[j] = b_new * cos_phi + c_new * sin_phi + cs[j] = -b_new * sin_phi + c_new * cos_phi + end + + # Build surface mesh matrices + pts = Matrix{Point3{T}}(undef, length(params), length(vs)) + + for i in eachindex(params) + pts[i, :] = [BMO.ellipse(v, ps[i], bs[i], cs[i]) for v in vs] + end + + Xt = getindex.(pts, 1) + Yt = getindex.(pts, 2) + Zt = getindex.(pts, 3) + + # Render the envelope as a smooth surface + surface!(axis, Xt, Yt, Zt; + color = fill(color, size(Xt)), + transparency, + kwargs... + ) + + # Optionally, plot waist ellipse + if show_waist + scatter!.(axis, pts; color, markersize) + end + + # Bump length tracker + if !isnothing(BMO.intersection(ray)) + l += length(ray) + end + end + + # Optionally, plot generating rays + if show_beams + render!(axis, child.c; show_pos, flen, color = :red) + render!(axis, child.dxp; show_pos, flen, color = :green) + render!(axis, child.dyp; show_pos, flen, color = :green) + render!(axis, child.dxm; show_pos, flen, color = :green) + render!(axis, child.dym; show_pos, flen, color = :green) + render!(axis, child.wxp; show_pos, flen, color = :blue) + render!(axis, child.wyp; show_pos, flen, color = :blue) + render!(axis, child.wxm; show_pos, flen, color = :blue) + render!(axis, child.wym; show_pos, flen, color = :blue) + end + end + return axis +end diff --git a/src/AbstractTypes/AbstractBeam.jl b/src/AbstractTypes/AbstractBeam.jl index c9026558f..52ef88e7c 100644 --- a/src/AbstractTypes/AbstractBeam.jl +++ b/src/AbstractTypes/AbstractBeam.jl @@ -113,6 +113,10 @@ abstract type AbstractBeamGroup{T <: Real, R <: AbstractRay{T}} end beams(bg::AbstractBeamGroup) = bg.beams +Base.length(bg::AbstractBeamGroup) = length(beams(bg)) +Base.iterate(bg::AbstractBeamGroup, state...) = iterate(beams(bg), state...) +Base.getindex(bg::AbstractBeamGroup, i::Int) = getindex(beams(bg), i) + Base.position(bg::AbstractBeamGroup) = position(first(rays(first(beams(bg))))) direction(bg::AbstractBeamGroup) = direction(first(rays(first(beams(bg))))) diff --git a/src/AbstractTypes/AbstractGaussian.jl b/src/AbstractTypes/AbstractGaussian.jl new file mode 100644 index 000000000..ac698445c --- /dev/null +++ b/src/AbstractTypes/AbstractGaussian.jl @@ -0,0 +1,2 @@ +"""From Wilhelm (2001)""" +isparaxial(w0, λ; margin::Int=100) = w0 / λ > margin ? true : false diff --git a/src/AbstractTypes/AbstractRay.jl b/src/AbstractTypes/AbstractRay.jl index 5ba1f88c5..0fa15c5a6 100644 --- a/src/AbstractTypes/AbstractRay.jl +++ b/src/AbstractTypes/AbstractRay.jl @@ -79,7 +79,13 @@ abstract type AbstractRay{T <: Real} end Base.position(ray::AbstractRay) = ray.pos position!(ray::AbstractRay, pos) = (ray.pos = pos) +""" + direction(ray::AbstractRay) + +Returns the direction vector of the `ray`. +""" direction(ray::AbstractRay) = ray.dir + function direction!(ray::AbstractRay, dir) ray.dir = normalize(dir) return nothing diff --git a/src/AbstractTypes/AbstractTypes.jl b/src/AbstractTypes/AbstractTypes.jl index 737bbd178..951ff6dc6 100644 --- a/src/AbstractTypes/AbstractTypes.jl +++ b/src/AbstractTypes/AbstractTypes.jl @@ -33,5 +33,6 @@ include("AbstractObject.jl") include("AbstractShapeTrait.jl") include("AbstractRay.jl") include("AbstractBeam.jl") +include("AbstractGaussian.jl") include("AbstractSystem.jl") include("AbstractUtils.jl") diff --git a/src/AstigmaticGaussian.jl b/src/AstigmaticGaussian.jl new file mode 100644 index 000000000..86404441a --- /dev/null +++ b/src/AstigmaticGaussian.jl @@ -0,0 +1,834 @@ +""" + AstigmaticGaussianBeamlet{T} <: AbstractBeam{T, PolarizedRay{T}} + +Complex ray representation of a general **astigmatic** Gaussian beam as per the formalism described by A. Greynolds (1986) and N. Worku (2017). +The beam is described by a chief [`PolarizedRay`](@ref) and 8 auxiliary [`Ray`](@ref)s that encode the waist radius and divergence in two orthogonal transverse axes. +The beam quality `M2` is considered via the divergence angle. All equations are based on the following publications: + +**Alan Greynolds, "Vector formulation of the ray-equivalent method for general Gaussian beam propagation." Curr. Dev. Opt. Eng. Diffraction Phenom. Vol. 679. SPIE, 1986** + +and + +**Norman Worku and Herbert Gross, "Vectorial field propagation through high NA objectives using polarized Gaussian beam decomposition." OTOM XIV. Vol. 10347. SPIE, 2017** + +# Fields + +- `c`: chief [`Beam`](@ref) of [`PolarizedRay`](@ref)s +- `wxp`: waist x-positive [`Beam`](@ref) of [`Ray`](@ref)s +- `wxm`: waist x-negative [`Beam`](@ref) of [`Ray`](@ref)s +- `wyp`: waist y-positive [`Beam`](@ref) of [`Ray`](@ref)s +- `wym`: waist y-negative [`Beam`](@ref) of [`Ray`](@ref)s +- `dxp`: divergence x-positive [`Beam`](@ref) of [`Ray`](@ref)s +- `dxm`: divergence x-negative [`Beam`](@ref) of [`Ray`](@ref)s +- `dyp`: divergence y-positive [`Beam`](@ref) of [`Ray`](@ref)s +- `dym`: divergence y-negative [`Beam`](@ref) of [`Ray`](@ref)s +- `parent`: reference to the parent beam (or `nothing`) +- `children`: vector of child beams (e.g. after beam-splitting) + +# Additional information + +!!! info "Waist and field calculation" + For a given beamlet the Gaussian beam parameters can be obtained via the [`gauss_parameters`](@ref) function. +""" +mutable struct AstigmaticGaussianBeamlet{T} <: AbstractBeam{T, PolarizedRay{T}} + c::Beam{T, PolarizedRay{T}} # chief + wxp::Beam{T, Ray{T}} # waist x + + wxm::Beam{T, Ray{T}} # waist x - + wyp::Beam{T, Ray{T}} # waist y + + wym::Beam{T, Ray{T}} # waist y - + dxp::Beam{T, Ray{T}} # div. x + + dxm::Beam{T, Ray{T}} # div. x - + dyp::Beam{T, Ray{T}} # div. y + + dym::Beam{T, Ray{T}} # div. y - + parent::Nullable{AstigmaticGaussianBeamlet{T}} + children::Vector{AstigmaticGaussianBeamlet{T}} +end + +function AstigmaticGaussianBeamlet( + c::Beam{T, PolarizedRay{T}}, + wxp::Beam{T, Ray{T}}, + wxm::Beam{T, Ray{T}}, + wyp::Beam{T, Ray{T}}, + wym::Beam{T, Ray{T}}, + dxp::Beam{T, Ray{T}}, + dxm::Beam{T, Ray{T}}, + dyp::Beam{T, Ray{T}}, + dym::Beam{T, Ray{T}} +) where {T <: Real} + return AstigmaticGaussianBeamlet{T}(c, wxp, wxm, wyp, wym, dxp, dxm, dyp, dym, + nothing, + Vector{AstigmaticGaussianBeamlet{T}}()) +end + +""" + AstigmaticGaussianBeamlet(position, direction, λ, w0; kwargs...) + +Constructs an astigmatic Gaussian beamlet at its waist with the specified beam parameters. +In the 4-argument version, the beam has circular symmetry with waist radius `w0`. +In the 5-argument version, independent waists `w0_x` and `w0_y` can be specified. + +# Arguments + +## Inputs + +- `position`: origin of the beamlet +- `direction`: direction of the beamlet +- `λ`: wavelength of the beamlet in [m]. Default value is 1000 nm. +- `w0`: beam waist (radius) in [m]. Default value is 1 mm. +- `w0_x`, `w0_y`: independent beam waists in [m]. + +## Keyword Arguments + +- `M2`, `M2_x`, `M2_y`: beam quality factors. Default is 1 +- `P0`: beam total power in [W]. Default is 1 mW. +- `E0`: electric field vector in [V/m]. Default is `nothing` (aligned with support axes, scaled by `P0`). +- `support`: optional support vector for basis construction +- `z0`: beam waist offset in [m]. Default is 0 m + +# Additional information + +!!! warning "Optical invariant check" + When using the `solve_system!` function, the beamlet invariant will be checked for each interaction. If the invariant is violated, tracing will be stopped. +""" +function AstigmaticGaussianBeamlet( + position::AbstractArray, + direction::AbstractArray, + λ::Real = get_default_wavelength(), + w0::Real = get_default_waist(); + # kwargs + M2::Real = 1, + P0::Real = get_default_power(), + E0::Union{Nothing, AbstractArray{<:Number}} = nothing, + support::Union{Nothing, AbstractArray{<:Real}} = nothing, + z0::Real = 0 +) + return AstigmaticGaussianBeamlet(position, direction, λ, w0, w0; + M2_x = M2, M2_y = M2, P0, E0, support, z0) +end + +""" + AstigmaticGaussianBeamlet(position, direction, λ, w0_x, w0_y; kwargs...) + +Constructs an astigmatic Gaussian beamlet with independent waists `w0_x` and `w0_y`. +This constructor supports modeling astigmatic sources where the waists in X and Y are at different locations along the beam axis. + +# Arguments +- `position`: Global reference point of the beamlet. +- `direction`: Propagation direction vector. +- `λ`: Wavelength. +- `w0_x`: Waist radius in the X direction (defined by the support vector). +- `w0_y`: Waist radius in the Y direction. + +# Keyword Arguments +- `z0_x`: Position of the X waist relative to `position` along the propagation axis. Defaults to `z0`. +- `z0_y`: Position of the Y waist relative to `position` along the propagation axis. Defaults to `z0`. +- `z0`: Default waist position if `z0_x` and `z0_y` are not specified. Also defines the starting point of the chief ray as `position + z0 * direction`. +- `M2_x`, `M2_y`: Beam quality factors. Default is 1. +- `P0`: Total power in [W]. +- `E0`: Optional Jones vector for polarization. +- `support`: Optional vector orthogonal to `direction` to define the X axis. + +# Additional information + +!!! warning "Optical invariant check" + When using the `solve_system!` function, the beamlet invariant will be checked for each interaction. If the invariant is violated, tracing will be stopped. +""" +function AstigmaticGaussianBeamlet( + position::AbstractArray, + direction::AbstractArray, + λ::Real, + w0_x::Real, + w0_y::Real; + # kwargs + M2_x::Real = 1, + M2_y::Real = 1, + P0::Real = get_default_power(), + E0::Union{Nothing, AbstractArray{<:Number}} = nothing, + support::Union{Nothing, AbstractArray{<:Real}} = nothing, + z0::Real = 0, + z0_x::Real = z0, + z0_y::Real = z0 +) + # Create orthogonal vectors for construction purposes (right-handed) + direction = normalize(direction) + if isnothing(support) + s1 = normal3d(direction) + else + if !isorthogonal3d(direction, support) + error("Ray direction and support vector must be orthogonal!") + end + s1 = normalize(support) + end + s2 = cross(direction, s1) + + # Handle polarization and power + if isnothing(E0) + # Calculate E0 magnitude based on P0 + I0 = (2 * P0) / (π * w0_x * w0_y) + E_phasor = electric_field(I0) + E0 = s1 .* E_phasor # Default to linear polarization along first transverse axis + else + if !isorthogonal3d(direction, E0) + # If user provided E0 but it's not orthogonal, project it. + # This is a convenience for tilted setups. + E0 = E0 .- dot(E0, direction) .* direction + end + end + + # Divergence angles + θx = divergence_angle(λ, w0_x, M2_x) + θy = divergence_angle(λ, w0_y, M2_y) + # Waist rays + wxp = Ray(position + s1 * w0_x + z0_x * direction, direction, λ) + wxm = Ray(position - s1 * w0_x + z0_x * direction, direction, λ) + wyp = Ray(position + s2 * w0_y + z0_y * direction, direction, λ) + wym = Ray(position - s2 * w0_y + z0_y * direction, direction, λ) + # Divergence rays + div_dir_xp = normalize(direction + s1 * tan(θx)) + div_dir_xm = normalize(direction - s1 * tan(θx)) + div_dir_yp = normalize(direction + s2 * tan(θy)) + div_dir_ym = normalize(direction - s2 * tan(θy)) + # Corrected divergence ray positions to ensure waist is at z0_x and z0_y + dxp = Ray(position - z0_x * s1 * tan(θx), div_dir_xp, λ) + dxm = Ray(position + z0_x * s1 * tan(θx), div_dir_xm, λ) + dyp = Ray(position - z0_y * s2 * tan(θy), div_dir_yp, λ) + dym = Ray(position + z0_y * s2 * tan(θy), div_dir_ym, λ) + # Chief ray + c = PolarizedRay(position + z0 * direction, direction, λ, E0) + return AstigmaticGaussianBeamlet( + Beam(c), + Beam(wxp), + Beam(wxm), + Beam(wyp), + Beam(wym), + Beam(dxp), + Beam(dxm), + Beam(dyp), + Beam(dym) + ) +end + +"""Return a tuple of all 9 component beams of the [`AstigmaticGaussianBeamlet`](@ref).""" +@inline _component_beams(agb::AstigmaticGaussianBeamlet) = ( + agb.c, agb.wxp, agb.wxm, agb.wyp, agb.wym, agb.dxp, agb.dxm, agb.dyp, agb.dym) + +"""Return a tuple of the 8 auxiliary (parabasal) beams.""" +@inline _aux_beams(agb::AstigmaticGaussianBeamlet) = ( + agb.wxp, agb.wxm, agb.wyp, agb.wym, agb.dxp, agb.dxm, agb.dyp, agb.dym) + +# Implementation of AbstractBeam interface +rays(agb::AstigmaticGaussianBeamlet) = rays(agb.c) + +Base.length(agb::AstigmaticGaussianBeamlet) = length(agb.c) +optical_path_length(agb::AstigmaticGaussianBeamlet) = optical_path_length(agb.c) + +isentering(agb::AstigmaticGaussianBeamlet, id::Int) = isentering(rays(agb.c)[id]) + +_last_beam_intersection(agb::AstigmaticGaussianBeamlet) = intersection(last(rays(agb.c))) + +point_on_beam(agb::AstigmaticGaussianBeamlet, t::Real) = point_on_beam(agb.c, t) + +wavelength(agb::AstigmaticGaussianBeamlet) = wavelength(first(rays(agb.c))) +direction(agb::AstigmaticGaussianBeamlet) = direction(first(rays(agb.c))) +position(agb::AstigmaticGaussianBeamlet) = position(first(rays(agb.c))) +polarization(agb::AstigmaticGaussianBeamlet) = polarization(first(rays(agb.c))) + +electric_field(agb::AstigmaticGaussianBeamlet) = polarization(agb) +function electric_field!(agb::AstigmaticGaussianBeamlet, new_E0) + polarization!(first(rays(agb.c)), new_E0) +end + +function refractive_index(agb::AstigmaticGaussianBeamlet, id::Int) + return refractive_index(rays(agb.c)[id]) +end + +function refractive_index!(agb::AstigmaticGaussianBeamlet, id::Int, n_new::Real) + for beam in _component_beams(agb) + refractive_index!(rays(beam)[id], n_new) + end + return nothing +end + +""" + parent!(child::AstigmaticGaussianBeamlet, parent::AstigmaticGaussianBeamlet) + +Links parent for tree navigation and ensures the chief beam parent is also linked. +""" +function parent!(child::AstigmaticGaussianBeamlet, parent::AstigmaticGaussianBeamlet) + child.parent = parent + child.c.parent = parent.c + return nothing +end + +function Base.show(io::IO, agb::AstigmaticGaussianBeamlet) + p0 = position(first(rays(agb.c))) + d0 = direction(first(rays(agb.c))) + λ = wavelength(agb) + _, w1, w2 = waist_parameters(agb, 0.0) + print(io, + "AstigmaticGaussianBeamlet(pos: $p0, dir: $d0, λ: $λ, w_x: $(norm(w1)), w_y: $(norm(w2)))") +end + +# AbstractTrees integration +AbstractTrees.children(agb::AstigmaticGaussianBeamlet) = agb.children +AbstractTrees.nodevalue(agb::AstigmaticGaussianBeamlet) = agb + +""" + AstigmaticGaussianBeamletInteraction <: AbstractInteraction + +Stores the interaction result for all 9 component beams of an +[`AstigmaticGaussianBeamlet`](@ref). Uses the hint from the chief beam interaction. + +# Fields + +- `chief`: [`BeamInteraction`](@ref) for the chief ray +- `wxp`, `wxm`, `wyp`, `wym`: waist beam interactions +- `dxp`, `dxm`, `dyp`, `dym`: divergence beam interactions +""" +struct AstigmaticGaussianBeamletInteraction{R <: Real} <: AbstractInteraction + chief::BeamInteraction{R} + wxp::BeamInteraction{R} + wxm::BeamInteraction{R} + wyp::BeamInteraction{R} + wym::BeamInteraction{R} + dxp::BeamInteraction{R} + dxm::BeamInteraction{R} + dyp::BeamInteraction{R} + dym::BeamInteraction{R} +end + +hint(i::AstigmaticGaussianBeamletInteraction) = hint(i.chief) +function hint!(i::AstigmaticGaussianBeamletInteraction, new_hint::Nullable{Hint}) + hint!(i.chief, new_hint) +end + +""" + interact3d(system, object, agb::AstigmaticGaussianBeamlet, ray_id) + +Generic dispatch: traces each component beam's ray through `object` independently. +Returns `nothing` if any interaction fails; otherwise returns an +[`AstigmaticGaussianBeamletInteraction`](@ref). +""" +function interact3d(system::AbstractSystem, + object::AbstractObject, + agb::AstigmaticGaussianBeamlet{R}, + ray_id::Int) where {R} + i_c = interact3d(system, object, agb.c, rays(agb.c)[ray_id]) + i_wxp = interact3d(system, object, agb.wxp, rays(agb.wxp)[ray_id]) + i_wxm = interact3d(system, object, agb.wxm, rays(agb.wxm)[ray_id]) + i_wyp = interact3d(system, object, agb.wyp, rays(agb.wyp)[ray_id]) + i_wym = interact3d(system, object, agb.wym, rays(agb.wym)[ray_id]) + i_dxp = interact3d(system, object, agb.dxp, rays(agb.dxp)[ray_id]) + i_dxm = interact3d(system, object, agb.dxm, rays(agb.dxm)[ray_id]) + i_dyp = interact3d(system, object, agb.dyp, rays(agb.dyp)[ray_id]) + i_dym = interact3d(system, object, agb.dym, rays(agb.dym)[ray_id]) + if any(isnothing, (i_c, i_wxp, i_wxm, i_wyp, i_wym, i_dxp, i_dxm, i_dyp, i_dym)) + return nothing + end + return AstigmaticGaussianBeamletInteraction{R}( + i_c, i_wxp, i_wxm, i_wyp, i_wym, i_dxp, i_dxm, i_dyp, i_dym) +end + +function Base.push!(agb::AstigmaticGaussianBeamlet{T}, + interaction::AstigmaticGaussianBeamletInteraction{T}) where {T} + push!(agb.c, interaction.chief) + push!(agb.wxp, interaction.wxp) + push!(agb.wxm, interaction.wxm) + push!(agb.wyp, interaction.wyp) + push!(agb.wym, interaction.wym) + push!(agb.dxp, interaction.dxp) + push!(agb.dxm, interaction.dxm) + push!(agb.dyp, interaction.dyp) + push!(agb.dym, interaction.dym) + return nothing +end + +function Base.replace!(agb::AstigmaticGaussianBeamlet{T}, + interaction::AstigmaticGaussianBeamletInteraction{T}, + index::Int) where {T} + replace!(agb.c, interaction.chief, index) + replace!(agb.wxp, interaction.wxp, index) + replace!(agb.wxm, interaction.wxm, index) + replace!(agb.wyp, interaction.wyp, index) + replace!(agb.wym, interaction.wym, index) + replace!(agb.dxp, interaction.dxp, index) + replace!(agb.dxm, interaction.dxm, index) + replace!(agb.dyp, interaction.dyp, index) + replace!(agb.dym, interaction.dym, index) + return nothing +end + +function _modify_beam_head!(old::AstigmaticGaussianBeamlet{T}, + new::AstigmaticGaussianBeamlet{T}) where {T <: Real} + _modify_beam_head!(old.c, new.c) + _modify_beam_head!(old.wxp, new.wxp) + _modify_beam_head!(old.wxm, new.wxm) + _modify_beam_head!(old.wyp, new.wyp) + _modify_beam_head!(old.wym, new.wym) + _modify_beam_head!(old.dxp, new.dxp) + _modify_beam_head!(old.dxm, new.dxm) + _modify_beam_head!(old.dyp, new.dyp) + _modify_beam_head!(old.dym, new.dym) +end + +""" + _beams_hits_same_shape(agb, id) + +Tests if all 9 component rays at section `id` hit the same object shape. +""" +@inline function _beams_hits_same_shape(agb::AstigmaticGaussianBeamlet, id::Int)::Bool + i1 = intersection(rays(agb.c)[id]) + if isnothing(i1) + isnothing(intersection(rays(agb.wxp)[id])) || return false + isnothing(intersection(rays(agb.wxm)[id])) || return false + isnothing(intersection(rays(agb.wyp)[id])) || return false + isnothing(intersection(rays(agb.wym)[id])) || return false + isnothing(intersection(rays(agb.dxp)[id])) || return false + isnothing(intersection(rays(agb.dxm)[id])) || return false + isnothing(intersection(rays(agb.dyp)[id])) || return false + isnothing(intersection(rays(agb.dym)[id])) || return false + return true + else + s0 = shape(i1) + _check = b -> begin + int = intersection(rays(b)[id]) + !isnothing(int) && shape(int) === s0 + end + _check(agb.wxp) || return false + _check(agb.wxm) || return false + _check(agb.wyp) || return false + _check(agb.wym) || return false + _check(agb.dxp) || return false + _check(agb.dxm) || return false + _check(agb.dyp) || return false + _check(agb.dym) || return false + return true + end +end + +function isparentbeam(beam::AstigmaticGaussianBeamlet, ray::AbstractRay) + for b in _component_beams(beam) + isparentbeam(b, ray) && return true + end + return false +end + +""" + _ray_to_plane_projection(plane_pos, plane_normal, ray) + +Projects a ray onto a plane defined by `plane_pos` and `plane_normal`. +Returns the offset vector `h` (from plane_pos to projected point) +and the projected ray slope `u`. +""" +function _ray_to_plane_projection(plane_pos, plane_normal, ray) + ray_pos = position(ray) + ray_dir = direction(ray) + d = line_plane_distance3d(plane_pos, plane_normal, ray_pos, ray_dir) + p = ray_pos + ray_dir * d + h = p - plane_pos + u = ray_dir - dot(ray_dir, plane_normal) * plane_normal + return h, u +end + +""" + parabasal_ray_parameters(agb, p0, i) + +Compute the complex parabasal ray parameters (h1, u1, h2, u2) at the transverse +plane defined by the chief ray's position `p0` and direction at segment `i`. + +The real parts of `h` and `u` come from the divergence rays (dxp, dyp), +while the imaginary parts come from the waist rays (wxp, wyp). +""" +function parabasal_ray_parameters(agb::AstigmaticGaussianBeamlet, p0, i) + chief = rays(agb.c)[i] + pn = direction(chief) + + # A Gaussian beam must model the local wavefront strictly up to its quadratic Taylor term. + # Since ray direction is the local wavefront slope (u(x) = dW/dx = W_x + W_xx*x + 0.5*W_xxx*x^2), + # the central difference (p - m)/2 perfectly isolates the pure paraxial curvature (W_xx) + # and mathematically cancels out asymmetric higher-order aberrations like cubic coma (W_xxx). + + # X-axis Waist (Real Part) + h1_real_p, u1_real_p = _ray_to_plane_projection(p0, pn, rays(agb.wxp)[i]) + h1_real_m, u1_real_m = _ray_to_plane_projection(p0, pn, rays(agb.wxm)[i]) + h1_real = (h1_real_p - h1_real_m) / 2 + u1_real = (u1_real_p - u1_real_m) / 2 + + # X-axis Divergence (Imaginary Part) + h1_imag_p, u1_imag_p = _ray_to_plane_projection(p0, pn, rays(agb.dxp)[i]) + h1_imag_m, u1_imag_m = _ray_to_plane_projection(p0, pn, rays(agb.dxm)[i]) + h1_imag = (h1_imag_p - h1_imag_m) / 2 + u1_imag = (u1_imag_p - u1_imag_m) / 2 + + h1 = h1_real + im * h1_imag + u1 = u1_real + im * u1_imag + + # Y-axis Waist (Real Part) + h2_real_p, u2_real_p = _ray_to_plane_projection(p0, pn, rays(agb.wyp)[i]) + h2_real_m, u2_real_m = _ray_to_plane_projection(p0, pn, rays(agb.wym)[i]) + h2_real = (h2_real_p - h2_real_m) / 2 + u2_real = (u2_real_p - u2_real_m) / 2 + + # Y-axis Divergence (Imaginary Part) + h2_imag_p, u2_imag_p = _ray_to_plane_projection(p0, pn, rays(agb.dyp)[i]) + h2_imag_m, u2_imag_m = _ray_to_plane_projection(p0, pn, rays(agb.dym)[i]) + h2_imag = (h2_imag_p - h2_imag_m) / 2 + u2_imag = (u2_imag_p - u2_imag_m) / 2 + + h2 = h2_real + im * h2_imag + u2 = u2_real + im * u2_imag + + return h1, u1, h2, u2, p0 +end + +""" + check_optical_invariant(agb, i; threshold = get_invariant_threshold()) + +Evaluate the complex optical invariant `h1 . u2 - h2 . u1 = 0` at segment `i`. +Returns `true` if the invariant holds (within `threshold`), and `false` otherwise. +""" +function check_optical_invariant(agb::AstigmaticGaussianBeamlet, i::Int; + threshold::Real = get_invariant_threshold()) + chief = rays(agb.c)[i] + p0 = position(chief) + λ = wavelength(chief) + n = refractive_index(agb, i) + + h1, u1, h2, u2, _ = parabasal_ray_parameters(agb, p0, i) + + all_pass = true + + # Check Coupling Invariant: h1 . u2 - h2 . u1 = 0 + inv_val = sum(h1 .* u2) - sum(h2 .* u1) + if abs(inv_val) > threshold + @warn lazy"Parabasal coupling invariant violation at segment $i: |h1.u2 - h2.u1| = $(abs(inv_val)). The paraxial astigmatic Gaussian beam tracing assumptions have broken down." + all_pass = false + end + + # Check Lagrange Invariant (Area Invariant): n * Im(h* . u) = λ/π + # This ensures that each axis individually behaves like a valid Gaussian. + H_target = λ / π + sets = ( + (h1, u1, "x"), + (h2, u2, "y") + ) + for (h, u, label) in sets + H = n * imag(sum(conj(h) .* u)) + if !isapprox(H, H_target, atol = threshold) + @warn lazy"Lagrange invariant violation ($label) at segment $i: H=$H, target=$H_target. The beamlet has likely encountered an object that violates the paraxial assumption." + all_pass = false + end + end + + return all_pass +end + +""" + parabasal_ray_parameters(agb, z) + +Compute the parabasal ray parameters at distance `z` along the beam. +""" +function parabasal_ray_parameters(agb::AstigmaticGaussianBeamlet, z::Real) + p0, i = point_on_beam(agb, z) + return parabasal_ray_parameters(agb, p0, i) +end + +""" + shift_phase!(agb, Δϕ) + +Apply a global phase shift `Δϕ` to the `AstigmaticGaussianBeamlet` by rotating the chief ray's polarization. +""" +function shift_phase!(agb::AstigmaticGaussianBeamlet, Δϕ::Real) + for ray in rays(agb.c) + E = polarization(ray) + polarization!(ray, E * exp(im * Δϕ)) + end + return nothing +end + +""" + optical_power(agb) + +Compute the total integrated optical power of the beamlet. For a Gaussian beamlet, +this is typically constant through lossless propagation. +""" +function optical_power(agb::AstigmaticGaussianBeamlet) + p0n, in_ = point_on_beam(agb, 0.0) + chiefn = rays(agb.c)[in_] + dirn = direction(chiefn) + h1n, _, h2n, _, _ = parabasal_ray_parameters(agb, p0n, in_) + area_ref = abs(_pseudo_cross2d(h1n, h2n, dirn)) + E_ref_amp = norm(polarization(chiefn)) + # Corrected power: P = I_peak * π * w0x * w0y / 2 + # We use the built-in intensity function to account for wave impedance + I_ref = intensity(E_ref_amp) + return 0.5 * π * area_ref * I_ref +end + +""" + waist_parameters(agb, z) + +Compute the position and elliptical waist axes at distance `z` along the beam. +Returns `(p0, w1, w2, w01, w02)` where `w1` and `w2` are 3D vectors describing the semi-axes +of the beam cross-section ellipse. +""" +function waist_parameters(agb::AstigmaticGaussianBeamlet, z::Real) + p0, i = point_on_beam(agb, z) + + # Extract the complex vectors h1 and h2 representing the amplitude matrix H from the paraxial rays. + h1, _, h2, _, _ = parabasal_ray_parameters(agb, p0, i) + + # Physical axis estimation using the complex ray height h. + # The true orthogonal principal axes of the beam cross-section are + # the eigenvectors of the spot covariance matrix S. + + # Split the complex vectors into real and imaginary parts to compute the outer product. + h1r, h1i = real(h1), imag(h1) + h2r, h2i = real(h2), imag(h2) + + # Compute the real part of the outer tensor product H * H^dagger, yielding the spatial covariance matrix of the beam intensity. + S = h1r * h1r' + h1i * h1i' + h2r * h2r' + h2i * h2i' + + # Perform an eigendecomposition to find the principal axes (eigenvectors) and variances (eigenvalues) of the beam cross-section. + F = eigen(Symmetric(S)) + + # F.values are sorted in ascending order. Rank is 2 (plane orthogonal to propagation direction). + # The 3x3 matrix has rank 2 in the transverse plane, so we discard the zero eigenvalue and take the two positive variances (squared radii). + v1 = max(zero(eltype(S)), F.values[2]) + v2 = max(zero(eltype(S)), F.values[3]) + + # Scale the normalized eigenvectors by the square root of the eigenvalues to obtain the physical half-axis vectors of the elliptical spot. + w1 = sqrt(v1) * F.vectors[:, 2] + w2 = sqrt(v2) * F.vectors[:, 3] + + # Get waist sizes for unification + _, _, _, _, _, w01, w02 = gauss_parameters(agb, z) + + return p0, w1, w2, w01, w02 +end + +""" + _pseudo_cross2d(a, b, c) + +Calculates the triple product `(a × b) ⋅ c` using a non-conjugating dot product. +""" +@inline function _pseudo_cross2d(a, b, c) + # Scalar triple product (a × b) ⋅ c + return (a[2] * b[3] - a[3] * b[2]) * c[1] + + (a[3] * b[1] - a[1] * b[3]) * c[2] + + (a[1] * b[2] - a[2] * b[1]) * c[3] +end + +""" + _pseudo_dot(a, b) + +Calculates the non-conjugating dot product `a ⋅ b = Σ aᵢbᵢ`. +""" +@inline function _pseudo_dot(a, b) + return a[1] * b[1] + a[2] * b[2] + a[3] * b[3] +end + +""" + parabasal_field(agb, r, z; E_ref_amp, area_ref, z_norm) + +Compute the complex scalar electric field of the [`AstigmaticGaussianBeamlet`](@ref) +at a transverse offset `r` (a 3D vector in the plane perpendicular to the chief ray) +and longitudinal position `z`. + +Uses the built-in normalization `√(area_ref / area(z))` so that the result is +physical [V/m] when `E_ref_amp` matches the initial polarization amplitude. + +# Arguments + +- `agb`: the astigmatic Gaussian beamlet +- `r`: transverse offset vector (must be orthogonal to the chief ray direction at `z`) +- `z`: distance along the beam +- `E_ref_amp`: reference field amplitude (auto-computed from `z_norm` if `nothing`) +- `area_ref`: reference area (auto-computed from `z_norm` if `nothing`). +- `z_norm`: longitudinal position for reference normalization (default: 0). + +# Formalism +The field is computed using the **Parabasal Gaussian Beamlet** formalism: +ψ(r, z) = √(area_ref / area(z)) * exp(i * k * [z + 1/2 * rᵀ * Q(z) * r]) +where area(z) = (h1 × h2) · dir is the complex beam area. +""" +function parabasal_field( + agb::AstigmaticGaussianBeamlet, + r::AbstractArray, + z::Real; + E_ref_amp::Union{Nothing, Number} = nothing, + area_ref::Union{Nothing, Complex} = nothing, + z_norm::Real = 0.0 +) + p0, i = point_on_beam(agb, z) + chief = rays(agb.c)[i] + dir = direction(chief) + + if !isorthogonal3d(dir, r; atol = Config.get_orthogonality_threshold()) + error("r must lie in plane at p0/dir (dot product: $(dot(dir, r)))") + end + + # Lazy init of reference normalization (computed once if not supplied) + if area_ref === nothing || E_ref_amp === nothing + p0n, in_ = point_on_beam(agb, z_norm) + chiefn = rays(agb.c)[in_] + if area_ref === nothing + dirn = direction(chiefn) + h1n, _, h2n, _, _ = parabasal_ray_parameters(agb, p0n, in_) + area_ref = _pseudo_cross2d(h1n, h2n, dirn) + end + if E_ref_amp === nothing + # Extract complex amplitude (scalar projection) to preserve phase + E_vec = polarization(chiefn) + max_idx = argmax(abs.(E_vec)) + E_ref_amp = Complex(norm(E_vec) * cis(angle(E_vec[max_idx]))) + end + end + + h1, u1, h2, u2, _ = parabasal_ray_parameters(agb, p0, i) + + area = _pseudo_cross2d(h1, h2, dir) + # Regularization to prevent division by zero at caustics or NaN propagation + if isnan(area) || abs(area) < 1e-25 + area = Complex(1e-25, 1e-25) + end + ξ1 = _pseudo_cross2d(h1, r, dir) + ξ2 = _pseudo_cross2d(h2, r, dir) + + # Complex quadratic phase term w = r^T Q r / 2 + # We use _pseudo_dot to compute the non-conjugating dot product r^T u. + w = (ξ1 * _pseudo_dot(u2, r) - ξ2 * _pseudo_dot(u1, r)) / (2 * area) + + # Phase correction for refractive index (OPL - geometric length) + p_parent = agb.parent + l_parent = isnothing(p_parent) ? 0.0 : length(p_parent) + opl_parent = isnothing(p_parent) ? 0.0 : optical_path_length(p_parent) + + Δl = opl_parent - l_parent + z_sum = l_parent + for j in 1:(i - 1) + ray_j = rays(agb.c)[j] + Δl += optical_path_length(ray_j) - length(ray_j) + z_sum += length(ray_j) + end + Δl += (refractive_index(chief) - 1) * (z - z_sum) + + k0 = 2π / wavelength(chief) + + # area_ref / area is essentially (1 / (1 + i*z/zr))^2 for stigmatic beams. + # The sqrt gives the standard -atan(z/zr) Gouy phase natively. + # The phase includes the OPL correction Δl to ensure coherence in media. + ψ = sqrt(area_ref / area) * exp(im * k0 * (z + w + Δl)) + return E_ref_amp * ψ +end + +""" + electric_field(agb, r, z) + +Convenience wrapper for [`parabasal_field`](@ref) using the beamlet's starting position (z=0) +as the reference normalization. +""" +function electric_field(agb::AstigmaticGaussianBeamlet, r::AbstractArray, z::Real) + return parabasal_field(agb, r, z; z_norm = 0.0) +end + +""" + polarized_field(agb, r, z) + +Compute the complex **vector** electric field [V/m] of the [`AstigmaticGaussianBeamlet`](@ref) +at position `(r, z)`. Returns a 3D vector. +""" +function polarized_field(agb::AstigmaticGaussianBeamlet, r::AbstractArray, z::Real) + p0, i = point_on_beam(agb, z) + chief = rays(agb.c)[i] + E_vec = polarization(chief) + # The complex scalar field already includes the propagation phase and Gouy phase. + # We normalize to the chief ray's polarization magnitude to avoid double-counting amplitude. + ψ = parabasal_field(agb, r, z; E_ref_amp = 1.0) + return E_vec * ψ +end + +""" + intensity(agb::AstigmaticGaussianBeamlet, r, z) + +Compute the optical intensity [W/m²] of the beamlet at position `(r, z)`. +""" +function intensity(agb::AstigmaticGaussianBeamlet, r::AbstractArray, z::Real) + E = electric_field(agb, r, z) + return intensity(E) +end + +""" + rayleigh_range(agb::AstigmaticGaussianBeamlet) + +Returns the Rayleigh range for the x and y axes of the beamlet as a tuple `(z_rx, z_ry)`. +""" +function rayleigh_range(agb::AstigmaticGaussianBeamlet) + λ = wavelength(agb) + _, w1, w2 = waist_parameters(agb, 0.0) + return (rayleigh_range(λ, norm(w1)), rayleigh_range(λ, norm(w2))) +end + +""" + gauss_parameters(agb::AstigmaticGaussianBeamlet, z::Real) + +Compute the scalar Gaussian beam parameters at distance `z`. +Returns a tuple `(w1, w2, R1, R2, ψ, w01, w02)` where: +- `w1`, `w2`: beam radii along the principal axes +- `R1`, `R2`: radii of curvature along the principal axes +- `ψ`: total Gouy phase shift +- `w01`, `w02`: waist radii along the principal axes +""" +function gauss_parameters(agb::AstigmaticGaussianBeamlet, z::Real) + p0, i = point_on_beam(agb, z) + h1, u1, h2, u2, _ = parabasal_ray_parameters(agb, p0, i) + n = refractive_index(agb, i) + λ = wavelength(agb) + T = typeof(λ) + dir = direction(rays(agb.c)[i]) + + # Axis 1 + w1 = norm(h1) + # real(sum(u1 .* conj.(h1))) + invR1 = (real(u1[1]) * real(h1[1]) + imag(u1[1]) * imag(h1[1]) + + real(u1[2]) * real(h1[2]) + imag(u1[2]) * imag(h1[2]) + + real(u1[3]) * real(h1[3]) + imag(u1[3]) * imag(h1[3])) / w1^2 + R1 = isapprox(invR1, 0, atol = 1e-20) ? T(Inf) : 1 / invR1 + # imag(sum(h1 .* conj.(u1))) + H1 = abs(n * (imag(h1[1]) * real(u1[1]) - real(h1[1]) * imag(u1[1]) + + imag(h1[2]) * real(u1[2]) - real(h1[2]) * imag(u1[2]) + + imag(h1[3]) * real(u1[3]) - real(h1[3]) * imag(u1[3]))) + w01 = H1 / (n * norm(u1)) + + # Axis 2 + w2 = norm(h2) + # real(sum(u2 .* conj.(h2))) + invR2 = (real(u2[1]) * real(h2[1]) + imag(u2[1]) * imag(h2[1]) + + real(u2[2]) * real(h2[2]) + imag(u2[2]) * imag(h2[2]) + + real(u2[3]) * real(h2[3]) + imag(u2[3]) * imag(h2[3])) / w2^2 + R2 = isapprox(invR2, 0, atol = 1e-20) ? T(Inf) : 1 / invR2 + # imag(sum(h2 .* conj.(u2))) + H2 = abs(n * (imag(h2[1]) * real(u2[1]) - real(h2[1]) * imag(u2[1]) + + imag(h2[2]) * real(u2[2]) - real(h2[2]) * imag(u2[2]) + + imag(h2[3]) * real(u2[3]) - real(h2[3]) * imag(u2[3]))) + w02 = H2 / (n * norm(u2)) + + # Total Gouy phase + area = _pseudo_cross2d(h1, h2, dir) + ψ = -0.5 * angle(area) + + return (w1, w2, R1, R2, ψ, w01, w02) +end + +function waist_parameters(agb::AstigmaticGaussianBeamlet{G}, zs::AbstractArray) where {G} + n = length(zs) + p0 = Vector{Point3{G}}(undef, n) + w1 = Vector{Point3{G}}(undef, n) + w2 = Vector{Point3{G}}(undef, n) + w01 = Vector{G}(undef, n) + w02 = Vector{G}(undef, n) + @inbounds for i in 1:n + p0[i], w1[i], w2[i], w01[i], w02[i] = waist_parameters(agb, zs[i]) + end + return (p0, w1, w2, w01, w02) +end diff --git a/src/Beam.jl b/src/Beam.jl index d3dcd8690..c89ace5d8 100644 --- a/src/Beam.jl +++ b/src/Beam.jl @@ -16,8 +16,14 @@ mutable struct Beam{T, R <: AbstractRay{T}} <: AbstractBeam{T, R} children::Vector{Beam{T, R}} end +""" + rays(beam::Beam) + +Returns the vector of rays that make up the `beam`. +""" rays(b::Beam) = b.rays + Base.push!(b::Beam, ray::AbstractRay) = push!(b.rays, ray) function Beam(ray::R) where {T, R <: AbstractRay{T}} @@ -262,4 +268,4 @@ function Base.show(io::IO, ::MIME"text/plain", beam::Beam) end end return nothing -end \ No newline at end of file +end diff --git a/src/BeamGroups.jl b/src/BeamGroups.jl index 6c01c012e..60dc5c4ab 100644 --- a/src/BeamGroups.jl +++ b/src/BeamGroups.jl @@ -12,7 +12,7 @@ Represents a cone of [`Beam`](@ref)s being emitted from a single point in space. - `numerical_aperture`: returns the NA of the source """ -struct PointSource{T, R<:AbstractRay{T}} <: AbstractBeamGroup{T,R} +struct PointSource{T, R <: AbstractRay{T}} <: AbstractBeamGroup{T, R} beams::Vector{Beam{T, R}} NA::T end @@ -53,11 +53,11 @@ function PointSource( dir::AbstractArray{D}, θ::H, λ::L = 1e-6; - num_rings::Int=10, - num_rays::Int=100*num_rings, - ) where {P<:Real, D<:Real, H<:Real, L<:Real} + num_rings::Int = 10, + num_rays::Int = 100 * num_rings +) where {P <: Real, D <: Real, H <: Real, L <: Real} T = promote_type(P, D, H, L) - if num_rays < num_rings*20 + if num_rays < num_rings * 20 throw(ErrorException("No. of rays should be atleast 20x no. of rings (passed: $num_rays, req: $(num_rings*20))")) end if θ ≥ pi @@ -73,7 +73,7 @@ function PointSource( push!(beams, Beam(Ray(pos, dir, λ))) num_rays -= 1 # calculate total accumulated circumference of all rings - ndirs = [rotate3d(b2, step(θ_NA)*i) * dir for i in eachindex(θ_NA[2:end])] + ndirs = [rotate3d(b2, step(θ_NA) * i) * dir for i in eachindex(θ_NA[2:end])] circm = norm.(ndirs .- dot.(ndirs, Ref(dir)) .* Ref(dir)) .* Ref(2π) total = sum(circm) ds = total / num_rays @@ -89,7 +89,7 @@ function PointSource( dphi = 2π / numEl RotMat = rotate3d(dir, dphi) cdir = ndir - for _ = 1:numEl + for _ in 1:numEl push!(beams, Beam(pos, cdir, λ)) # rotate vector (not-thread safe!) cdir = RotMat * cdir @@ -113,7 +113,7 @@ Represents a parallel bundle of [`Beam`](@ref)s being emitted from a disk in spa - `diameter`: returns the diameter of the source """ -struct CollimatedSource{T, R<:AbstractRay{T}} <: AbstractBeamGroup{T,R} +struct CollimatedSource{T, R <: AbstractRay{T}} <: AbstractBeamGroup{T, R} beams::Vector{Beam{T, R}} diameter::T end @@ -154,11 +154,11 @@ function CollimatedSource( dir::AbstractArray{D1}, diameter::D2, λ::L = 1e-6; - num_rings::Int=10, - num_rays::Int=100*num_rings, - ) where {P<:Real, D1<:Real, D2<:Real, L<:Real} + num_rings::Int = 10, + num_rays::Int = 100 * num_rings +) where {P <: Real, D1 <: Real, D2 <: Real, L <: Real} T = promote_type(P, D1, D2, L) - if num_rays < num_rings*20 + if num_rays < num_rings * 20 throw(ErrorException("No. of rays should be atleast 20x no. of rings (passed: $num_rays, req: $(num_rings*20))")) end # define buffer @@ -167,10 +167,10 @@ function CollimatedSource( num_rays -= 1 # setup concentric beam ring radii b1 = normal3d(dir) # random seed - r_max = diameter/2 + r_max = diameter / 2 radii = LinRange(0, r_max, num_rings)[2:end] # calculate total accumulated circumference of all rings - circm = radii*2π + circm = radii * 2π total = sum(circm) ds = total / num_rays # calculate number of rays per ring @@ -186,7 +186,7 @@ function CollimatedSource( dphi = 2π / numEl RotMat = rotate3d(dir, dphi) helper = b1 * r - for _ = 1:numEl + for _ in 1:numEl push!(beams, Beam(pos + helper, dir, λ)) helper = RotMat * helper end @@ -223,23 +223,567 @@ function UniformDiscSource( pos::AbstractArray{P}, dir::AbstractArray{D1}, diameter::D2, - λ::L=1e-6; + λ::L = 1e-6; # kwargs - num_rays::Int=1_000 - ) where {P<:Real, D1<:Real, D2<:Real, L<:Real} - T = promote_type(P, D1, D2, L) - R = diameter / 2 + num_rays::Int = 1_000 +) where {P <: Real, D1 <: Real, D2 <: Real, L <: Real} + T = promote_type(P, D1, D2, L) + R = diameter / 2 φ0 = 2π / (1 + √5) # golden angle - beams = Vector{Beam{T,Ray{T}}}(undef, num_rays) + beams = Vector{Beam{T, Ray{T}}}(undef, num_rays) # orthogonal basis in the pupil plane e1 = normal3d(dir) e2 = normalize(cross(dir, e1)) - for k in 0:num_rays-1 - ρ = √((k + 0.5)/num_rays) # equal-area radius - φ = k * φ0 - r = R * ρ - x = r * cos(φ) * e1 + r * sin(φ) * e2 - beams[k+1] = Beam(pos + x, dir, λ) + for k in 0:(num_rays - 1) + ρ = √((k + 0.5) / num_rays) # equal-area radius + φ = k * φ0 + r = R * ρ + x = r * cos(φ) * e1 + r * sin(φ) * e2 + beams[k + 1] = Beam(pos + x, dir, λ) end return CollimatedSource(beams, T(diameter)) end + +""" + AstigmaticBeamGroup{T, R} <: AbstractBeamGroup{T, R} + +A generic container for groups of [`AstigmaticGaussianBeamlet`](@ref)s. +""" +struct AstigmaticBeamGroup{T, R <: AbstractRay{T}} <: AbstractBeamGroup{T, R} + beams::Vector{AstigmaticGaussianBeamlet{T}} +end + +function AstigmaticBeamGroup(beams::Vector{AstigmaticGaussianBeamlet{T}}) where {T} + return AstigmaticBeamGroup{T, PolarizedRay{T}}(beams) +end + +""" + CollimatedGaussianBeamletSource(pos, dir, D, λ, w0s; n_grid=20) + + +Generates an `n_grid × n_grid` square array of `AstigmaticGaussianBeamlet`s, all pointing +in the same `dir`ection and having the same uniform amplitude. This is used to model +macroscopic plane waves or flat-top beams passing through hard apertures (e.g., for +Fraunhofer or Fresnel diffraction). + +# Arguments +- `pos`: Center position of the source plane. +- `dir`: Propagation direction. +- `D`: Total width/height of the square aperture. +- `λ`: Wavelength. +- `w0s`: Sub-waist of each individual beamlet. For smooth overlap, `w0s ≈ D / n_grid`. +- `n_grid`: Number of beamlets along one axis (default `20` yields `400` total beamlets). +- `basis`: Orientation of the macroscopic sampling grid. Determines the 3D directions corresponding to the `x` and `y` grid axes. +- `randomize_axes`: If `true`, the internal principal axes of each individual beamlet are randomly rotated. This averages out numerical grid-alignment biases and is essential for preserving rotational symmetry in focused spots (e.g. Airy disks). +- `rng`: Random number generator to use for `randomize_axes`. +""" +function CollimatedGaussianBeamletSource( + pos::AbstractArray{P}, + dir::AbstractArray{D1}, + D::D2, + λ::L, + w0s::W; + n_grid::Int = 20, + basis::Union{Nothing, Tuple{AbstractVector, AbstractVector}} = nothing, + randomize_axes::Bool = false, + rng = Random.GLOBAL_RNG +) where {P <: Real, D1 <: Real, D2 <: Real, L <: Real, W <: Real} + T = promote_type(P, D1, D2, L, W) + dir_n = normalize(dir) + # Use provided basis or fallback to automatic orthogonal basis + e1 = isnothing(basis) ? normal3d(dir_n) : normalize(basis[1]) + e2 = isnothing(basis) ? normalize(cross(dir_n, e1)) : normalize(basis[2]) + + beams = Vector{AstigmaticGaussianBeamlet{T}}() + Δ = D / n_grid + + xs = LinRange(-D / 2 + Δ / 2, D / 2 - Δ / 2, n_grid) + ys = LinRange(-D / 2 + Δ / 2, D / 2 - Δ / 2, n_grid) + + for x in xs + for y in ys + offset = x * e1 + y * e2 + # Support vector for the beamlet axes + if randomize_axes + base_s = normal3d(dir_n) + ortho_s = cross(dir_n, base_s) + phi = 2π * rand(rng) + local_support = base_s * cos(phi) + ortho_s * sin(phi) + else + local_support = nothing + end + b = AstigmaticGaussianBeamlet(pos + offset, dir_n, λ, w0s; support = local_support) + push!(beams, b) + end + end + return AstigmaticBeamGroup(beams) +end + +""" + GaussianBeamletDecomposition(pos, dir, λ, w0; n_grid=20) + +Decomposes a macroscopic Gaussian beam of waist `w0` into an `n_grid × n_grid` +array of microscopic `AstigmaticGaussianBeamlet`s. This allows the accurate +tracing of large Gaussian beams through highly aberrative or non-paraxial +optical systems, perfectly preserving higher-order phase aberrations via the +coherent superposition of the sub-beamlets. + +# Arguments +- `pos`: Waist center position of the macroscopic beam. +- `dir`: Propagation direction. +- `λ`: Wavelength. +- `w0`: Macroscopic beam waist. +- `n_grid`: Number of beamlets along one axis (default `20` yields `400` total beamlets). +- `overlap`: Scaling factor for the sub-waist relative to grid spacing (default `1.2` ensures smooth overlap). +- `basis`: Orientation of the macroscopic sampling grid. Determines the 3D directions corresponding to the `x` and `y` grid axes. +- `randomize_axes`: If `true`, the internal principal axes of each individual beamlet are randomly rotated. This averages out numerical grid-alignment biases and is essential for preserving rotational symmetry in focused spots. +- `rng`: Random number generator to use for `randomize_axes`. +- `P0`: Total power of the macroscopic Gaussian beam in [W]. +- `E0`: Optional Jones vector defining the polarization and initial phase of the beam. If `nothing`, defaults to linear polarization along the first grid axis. +- `threshold`: Relative amplitude below which beamlets are not spawned (default `1e-4`). +""" +function GaussianBeamletDecomposition( + pos::AbstractArray{P}, + dir::AbstractArray{D1}, + λ::L, + w0::W; + n_grid::Int = 20, + overlap::Float64 = 1.2, + basis::Union{Nothing, Tuple{AbstractVector, AbstractVector}} = nothing, + randomize_axes::Bool = false, + rng = Random.GLOBAL_RNG, + P0::Real = get_default_power(), + E0 = nothing, + threshold::Float64 = 1e-4 +) where {P <: Real, D1 <: Real, W <: Real, L <: Real} + T = promote_type(P, D1, W, L) + dir_n = normalize(dir) + # Use provided basis or fallback to automatic orthogonal basis + e1 = isnothing(basis) ? normal3d(dir_n) : normalize(basis[1]) + e2 = isnothing(basis) ? normalize(cross(dir_n, e1)) : normalize(basis[2]) + + # Determine macroscopic peak amplitude + if isnothing(E0) + I0 = (2 * P0) / (π * w0^2) + E_phasor = T(electric_field(I0)) + pol = e1 + else + E_phasor = one(T) + pol = E0 + end + + # We tile over a 4*w0 x 4*w0 area to capture the macroscopic Gaussian tails + D = 4 * w0 + Δ = D / n_grid + + # The sub-waist should be slightly larger than grid spacing to ensure smooth overlap + w0s = Δ * overlap + + beams = Vector{AstigmaticGaussianBeamlet{T}}() + xs = LinRange(-D / 2 + Δ / 2, D / 2 - Δ / 2, n_grid) + ys = LinRange(-D / 2 + Δ / 2, D / 2 - Δ / 2, n_grid) + + for x in xs + for y in ys + offset = x * e1 + y * e2 + # Macroscopic Gaussian envelope amplitude weighting + amp = exp(-(x^2 + y^2) / w0^2) + # Threshold to avoid tracing zero-amplitude beamlets + if amp > threshold + # Normalization factor for coherent superposition + norm_factor = (Δ^2) / (π * w0s^2) + # Standard linear polarization along e1 + # Support vector for the beamlet axes + if randomize_axes + base_s = normal3d(dir_n) + ortho_s = cross(dir_n, base_s) + phi = 2π * rand(rng) + local_support = base_s * cos(phi) + ortho_s * sin(phi) + else + local_support = nothing + end + b = AstigmaticGaussianBeamlet( + pos + offset, dir_n, λ, w0s; E0 = (amp * norm_factor * E_phasor) .* pol, support = local_support) + push!(beams, b) + end + end + end + return AstigmaticBeamGroup(beams) +end + +""" + SphericalGaussianBeamletSource(pos, dir, θ, λ; num_rings=10, num_rays=100*num_rings) + +Decomposes a macroscopic spherical wave (or a highly divergent/focused beam) into a cone +of `AstigmaticGaussianBeamlet`s originating from a single point `pos`. + +The angular spread of the beamlets is bounded by the half-angle `θ`. To ensure a smooth +far-field interference pattern without speckle, the sub-waist `w0s` of each beamlet is +automatically calculated such that their far-field divergence perfectly overlaps with +adjacent beamlets in the grid. + +# Arguments +- `pos`: Origin point of the spherical wave. +- `dir`: Central propagation direction. +- `θ`: Half spread angle in radians. +- `λ`: Wavelength. +- `num_rings`: Number of concentric angular rings. +- `num_rays`: Total number of beamlets to generate. +- `overlap`: Scaling factor for the sub-waist divergence (default `1.2` ensures smooth overlap). +- `basis`: Optional reference vector (e.g. `[1,0,0]`) to define the starting azimuthal angle for the source rings. +- `randomize_axes`: If `true`, the internal principal axes of each individual beamlet are randomly rotated. This averages out numerical artifacts in the far-field focus. +- `rng`: Random number generator to use for `randomize_axes`. +- `P0`: Total power of the spherical source in [W]. +- `E0`: Optional Jones vector defining the polarization and phase of the spherical wave. +""" +function SphericalGaussianBeamletSource( + pos::AbstractArray{P}, + dir::AbstractArray{D}, + θ::H, + λ::L; + num_rings::Int = 10, + num_rays::Int = 100 * num_rings, + overlap::Float64 = 1.2, + basis::Union{Nothing, AbstractVector} = nothing, + randomize_axes::Bool = false, + rng = Random.GLOBAL_RNG, + P0::Real = get_default_power(), + E0 = nothing +) where {P <: Real, D <: Real, H <: Real, L <: Real} + T = promote_type(P, D, H, L) + if num_rays < num_rings * 20 + throw(ErrorException("No. of beamlets should be atleast 20x no. of rings (passed: $num_rays, req: $(num_rings*20))")) + end + if θ ≥ pi + throw(ErrorException("Spherical source opening half-angle θ must be ≤ π")) + end + + # Calculate optimal sub-waist for smooth far-field overlap + # Angular spacing between rings: + Δθ = θ / num_rings + # We want beamlet divergence θ_div = λ / (π * w0s) to be approx overlap * Δθ + w0s = λ / (π * overlap * Δθ) + + dir_n = normalize(dir) + b1 = isnothing(basis) ? normal3d(dir_n) : normalize(basis - dot(basis, dir_n) * dir_n) + b2 = normalize(cross(dir_n, b1)) + θ_NA = LinRange(0, θ, num_rings) + + # Initial ray count for power distribution + total_rays = num_rays + P_sub = P0 / total_rays + + beams = Vector{AstigmaticGaussianBeamlet{T}}() + + # Central beamlet + push!(beams, AstigmaticGaussianBeamlet(pos, dir_n, λ, w0s; P0 = P_sub, E0 = E0)) + num_rays -= 1 + + # Calculate circumference weights + ndirs = [rotate3d(b2, step(θ_NA) * i) * dir_n for i in eachindex(θ_NA[2:end])] + circm = norm.(ndirs .- dot.(ndirs, Ref(dir_n)) .* Ref(dir_n)) .* Ref(2π) + total = sum(circm) + ds = total / num_rays + + n_rays = round.(Int, circm / ds) + n_rays[end] += (num_rays - sum(n_rays)) + + for (i, ndir) in enumerate(ndirs) + numEl = n_rays[i] + if iszero(numEl) + continue + end + dphi = 2π / numEl + RotMat = rotate3d(dir_n, dphi) + cdir = ndir + for _ in 1:numEl + # Polarization is set via the E0 kwarg. We could try to project it properly, + # but default linear works for paraxial-ish cones. + # Support vector for the beamlet axes + if randomize_axes + base_s = normal3d(cdir) + ortho_s = cross(cdir, base_s) + phi = 2π * rand(rng) + local_support = base_s * cos(phi) + ortho_s * sin(phi) + else + local_support = nothing + end + push!(beams, AstigmaticGaussianBeamlet(pos, cdir, λ, w0s; P0 = P_sub, E0 = E0, support = local_support)) + cdir = RotMat * cdir + end + end + + return AstigmaticBeamGroup(beams) +end + +""" + EllipticalGaussianBeamletSource(pos, dir, θ_x, θ_y, λ; num_rings=10, num_rays=100*num_rings, ...) + +Spawns a coherent array of `AstigmaticGaussianBeamlet`s distributed on an elliptical cap. +This is ideal for modelling sources with different divergences in the fast and slow axes, +such as tapered amplifiers or edge-emitting laser diodes. + +# Arguments +- `pos`: Origin point of the spherical wave. +- `dir`: Central propagation direction. +- `θ_x`, `θ_y`: Half spread angles in radians for the two principal axes. +- `λ`: Wavelength. +- `num_rings`: Number of concentric angular rings. +- `num_rays`: Total number of beamlets to generate. +- `overlap`: Scaling factor for the sub-waist divergence (default `1.2` ensures smooth overlap). +- `basis`: Optional reference vector (e.g. `[1,0,0]`) to define the starting azimuthal angle for the source rings. +- `randomize_axes`: If `true`, the internal principal axes of each individual beamlet are randomly rotated. +- `rng`: Random number generator to use for `randomize_axes`. +- `P0`: Total power of the source in [W]. +- `E0`: Optional Jones vector defining the polarization and phase of the wave. +""" +function EllipticalGaussianBeamletSource( + pos::AbstractArray{P}, + dir::AbstractArray{D}, + θ_x::H1, + θ_y::H2, + λ::L; + num_rings::Int = 10, + num_rays::Int = 100 * num_rings, + overlap::Float64 = 1.2, + basis::Union{Nothing, AbstractVector} = nothing, + randomize_axes::Bool = false, + rng = Random.GLOBAL_RNG, + P0::Real = get_default_power(), + E0 = nothing +) where {P <: Real, D <: Real, H1 <: Real, H2 <: Real, L <: Real} + T = promote_type(P, D, H1, H2, L) + if num_rays < num_rings * 20 + throw(ErrorException("No. of beamlets should be atleast 20x no. of rings (passed: $num_rays, req: $(num_rings*20))")) + end + if θ_x ≥ pi/2 || θ_y ≥ pi/2 + throw(ErrorException("Elliptical source opening half-angles θ_x and θ_y must be < π/2")) + end + + # Calculate optimal sub-waist + # We use the geometric mean of the angles to estimate the average ring spacing + θ_avg = sqrt(θ_x * θ_y) + Δθ = θ_avg / num_rings + w0s = λ / (π * overlap * Δθ) + + dir_n = normalize(dir) + b1 = isnothing(basis) ? normal3d(dir_n) : normalize(basis - dot(basis, dir_n) * dir_n) + b2 = normalize(cross(dir_n, b1)) + + # We use tangent space to define the elliptical rings + tx = tan(θ_x) + ty = tan(θ_y) + + total_rays = num_rays + P_sub = P0 / total_rays + + beams = Vector{AstigmaticGaussianBeamlet{T}}() + + # Central beamlet + push!(beams, AstigmaticGaussianBeamlet(pos, dir_n, λ, w0s; P0 = P_sub, E0 = E0)) + num_rays -= 1 + + # Ring normalized radii + ρs = LinRange(0, 1, num_rings + 1)[2:end] + + # Calculate approximate circumference of each elliptical ring to distribute rays + # Ramanujan's approximation for ellipse circumference: C ≈ π [3(a+b) - sqrt((3a+b)(a+3b))] + circm = zeros(num_rings) + for (i, ρ) in enumerate(ρs) + a = ρ * tx + b = ρ * ty + circm[i] = π * (3*(a+b) - sqrt((3a+b)*(a+3b))) + end + + total_circm = sum(circm) + ds = total_circm / num_rays + + n_rays = round.(Int, circm / ds) + n_rays[end] += (num_rays - sum(n_rays)) + + for (i, ρ) in enumerate(ρs) + numEl = n_rays[i] + if iszero(numEl) + continue + end + + a = ρ * tx + b = ρ * ty + + # We use equal steps in the parametric angle t. + # This ensures perfect symmetry and robust coverage. + ts = LinRange(0, 2π, numEl + 1)[1:end-1] + for t in ts + # Parametric equation of ellipse in tangent plane + u = a * cos(t) + v = b * sin(t) + + # The 3D direction vector + cdir = normalize(dir_n + u * b1 + v * b2) + + # Support vector for the beamlet axes + if randomize_axes + base_s = normal3d(cdir) + ortho_s = cross(cdir, base_s) + phi = 2π * rand(rng) + local_support = base_s * cos(phi) + ortho_s * sin(phi) + else + local_support = nothing + end + push!(beams, AstigmaticGaussianBeamlet(pos, cdir, λ, w0s; P0 = P_sub, E0 = E0, support = local_support)) + end + end + + return AstigmaticBeamGroup(beams) +end + +""" + WavefrontBeamletDecomposition(x, y, amplitude, phase, dir, λ; threshold=1e-4) + +Decomposes an arbitrary complex scalar field (defined by a spatial `amplitude` and `phase` +distribution on a 2D grid `x` and `y`) into a collection of `AstigmaticGaussianBeamlet`s. + +This function uses the Eikonal approximation to map the local phase gradient into a +local propagation direction for each beamlet. It allows users to import arbitrary, +aberrated, or custom beam profiles (e.g. from a camera or a wavefront sensor) and +propagate them through a `BeamletOptics` system. + +# Arguments +- `x`, `y`: Vectors defining the 1D spatial coordinates of the 2D field grid. +- `amplitude`: 2D array of field amplitudes `(length(x) × length(y))`. +- `phase`: 2D array of phase values in radians. +- `dir`: The macroscopic reference propagation direction (e.g., `[0, 1, 0]`). +- `λ`: Wavelength. +- `threshold`: Relative amplitude threshold below which beamlets are not spawned (saves computation). +- `overlap`: Scaling factor for the sub-waist relative to grid spacing (default `1.2` ensures smooth overlap). +- `basis`: Orientation of the macroscopic sampling grid. Determines the 3D directions corresponding to the `x` and `y` input axes. +- `randomize_axes`: If `true`, the internal principal axes of each individual beamlet are randomly rotated. This averages out numerical grid-alignment biases and helps preserve rotational symmetry in focused patterns. +- `rng`: Random number generator to use for `randomize_axes`. +- `E0`: Optional reference polarization vector or Jones vector. If `nothing`, defaults to linear polarization along the first grid axis. +""" +function WavefrontBeamletDecomposition( + x::AbstractVector{P1}, + y::AbstractVector{P2}, + amplitude::AbstractMatrix{A}, + phase::AbstractMatrix{Ph}, + dir::AbstractArray{D}, + λ::L; + threshold::Float64 = 1e-4, + overlap::Float64 = 1.2, + basis::Union{Nothing, Tuple{AbstractVector, AbstractVector}} = nothing, + randomize_axes::Bool = false, + rng = Random.GLOBAL_RNG, + E0 = nothing +) where {P1 <: Real, P2 <: Real, A <: Real, Ph <: Real, D <: Real, L <: Real} + T = promote_type(P1, P2, A, Ph, D, L) + + nx, ny = length(x), length(y) + if size(amplitude) != (nx, ny) || size(phase) != (nx, ny) + throw(DimensionMismatch("Amplitude and phase arrays must match the dimensions of x and y.")) + end + + dir_n = normalize(dir) + # Use provided basis or fallback to automatic orthogonal basis + e1_v = isnothing(basis) ? normal3d(dir_n) : normalize(basis[1]) + e2_v = isnothing(basis) ? normalize(cross(dir_n, e1_v)) : normalize(basis[2]) + + dx = nx > 1 ? (x[2] - x[1]) : 1.0 + dy = ny > 1 ? (y[2] - y[1]) : 1.0 + + # Per-axis sub-waists for correct overlap on non-square grids + w0s_x = T(dx * overlap) + w0s_y = T(dy * overlap) + k = 2π / λ + + beams = Vector{AstigmaticGaussianBeamlet{T}}() + sizehint!(beams, ceil(Int, nx * ny * 0.1)) # Conservative estimate + beams_lock = ReentrantLock() + max_amp = maximum(amplitude) + + Threads.@threads for i in 1:nx + for j in 1:ny + amp = amplitude[i, j] + if isnan(amp) || amp < max_amp * threshold + continue + end + ph = phase[i, j] + if isnan(ph) + continue + end + + # Compute local phase gradients using central differences + # Use mod2pi wrap to avoid slow angle(exp(im*x)) + _wrap = Δ -> mod2pi(Δ + π) - π + + if i > 1 && i < nx + dφ_dx = (_wrap(phase[i + 1, j] - ph) + + _wrap(ph - phase[i - 1, j])) / (2dx) + elseif i == 1 + dφ_dx = _wrap(phase[i + 1, j] - ph) / dx + else + dφ_dx = _wrap(ph - phase[i - 1, j]) / dx + end + + if j > 1 && j < ny + dφ_dy = (_wrap(phase[i, j + 1] - ph) + + _wrap(ph - phase[i, j - 1])) / (2dy) + elseif j == 1 + dφ_dy = _wrap(phase[i, j + 1] - ph) / dy + else + dφ_dy = _wrap(ph - phase[i, j - 1]) / dy + end + + # Convert phase gradient to angular deviation (Eikonal equation: ∇φ = k * sin(θ)) + sin_θx = dφ_dx / k + sin_θy = dφ_dy / k + + # Ensure valid angles and handle NaNs + if isnan(sin_θx) || isnan(sin_θy) || (sin_θx^2 + sin_θy^2 > 1.0) + @warn lazy"Phase gradient too steep or NaN at ($i, $j); skipping." + continue + end + + cos_θz = sqrt(1.0 - sin_θx^2 - sin_θy^2) + + # Construct the local direction vector + local_dir = sin_θx * e1_v + sin_θy * e2_v + cos_θz * dir_n + local_dir = normalize(local_dir) + + # Position + pos = x[i] * e1_v + y[j] * e2_v + + # Complex amplitude (E0 vector) + # The E0 vector MUST be orthogonal to local_dir. + # We project the macroscopic polarization (E0 or e1_v) onto the plane orthogonal to local_dir: + base_pol = isnothing(E0) ? e1_v : E0 + pol_axis = base_pol .- dot(base_pol, local_dir) .* local_dir + if norm(pol_axis) < 1e-6 + pol_axis = e2_v .- dot(e2_v, local_dir) .* local_dir + end + + # Normalization factor for power conservation: + # Each sub-beamlet represents a cell of area dx*dy. The Gaussian overlap + # integral is π*w0_x*w0_y, so we scale by 1/S = (dx*dy) / (π*w0_x*w0_y). + norm_factor = (dx * dy) / (π * w0s_x * w0s_y) + E0_complex = normalize(pol_axis) * (amp * exp(im * ph) * norm_factor) + + # Support vector for the beamlet axes + if randomize_axes + # Randomly rotate the basis around the local direction + base_s = normal3d(local_dir) + ortho_s = cross(local_dir, base_s) + phi = 2π * rand(rng) + local_support = base_s * cos(phi) + ortho_s * sin(phi) + else + local_support = nothing + end + + b = AstigmaticGaussianBeamlet(pos, local_dir, λ, w0s_x, w0s_y; E0 = E0_complex, support = local_support) + lock(beams_lock) do + push!(beams, b) + end + end + end + + return AstigmaticBeamGroup(beams) +end diff --git a/src/BeamletOptics.jl b/src/BeamletOptics.jl index 2c8161655..b3c69f250 100644 --- a/src/BeamletOptics.jl +++ b/src/BeamletOptics.jl @@ -1,30 +1,40 @@ module BeamletOptics -using LinearAlgebra: norm, normalize, normalize!, dot, cross, I, tr +using LinearAlgebra: norm, normalize, normalize!, dot, cross, I, tr, eigen, Symmetric using MarchingCubes: MC, march using Trapz: trapz using PrecompileTools: @setup_workload, @compile_workload using StaticArrays: @SArray, @SVector, SMatrix, SArray, SVector using GeometryBasics: Point3, Point2, Mat -using AbstractTrees: AbstractTrees, parent, children, NodeType, nodetype, nodevalue, print_tree, HasNodeType, Leaves, StatelessBFS, PostOrderDFS, PreOrderDFS, TreeIterator +using AbstractTrees: AbstractTrees, parent, children, NodeType, nodetype, nodevalue, + print_tree, HasNodeType, Leaves, StatelessBFS, PostOrderDFS, + PreOrderDFS, TreeIterator using InteractiveUtils: subtypes using FileIO: load using MeshIO using ForwardDiff: gradient +using Random import Base: length, push!, empty!, position # Do not change order of inclusion! include("Constants.jl") +include("Config.jl") +using .Config: get_invariant_threshold, set_invariant_threshold!, + get_sdf_surface_threshold, get_sdf_raymarch_eps, get_sdf_inside_step, + get_internal_reflection_threshold, get_line_plane_intersection_threshold, + get_orthogonality_threshold, get_default_r_max, get_default_depth_max, + get_default_wavelength, get_default_waist, get_default_power include("Utils/Utils.jl") include("AbstractTypes/AbstractTypes.jl") include("Rays.jl") include("PolarizedRays.jl") include("Beam.jl") +include("Gaussian.jl") +include("AstigmaticGaussian.jl") include("BeamGroups.jl") include("Mesh.jl") include("SDFs/SDF.jl") -include("Gaussian.jl") include("System.jl") include("OpticalComponents/Components.jl") include("ObjectGroups.jl") diff --git a/src/Config.jl b/src/Config.jl new file mode 100644 index 000000000..1b1375a74 --- /dev/null +++ b/src/Config.jl @@ -0,0 +1,140 @@ +""" + Config + +Global configuration settings for the BeamletOptics package using Preferences.jl. +""" +module Config + +using Preferences + +# --- Paraxial Invariants --- +const INVARIANT_THRESHOLD = @load_preference("invariant_threshold", 1e-6) +""" + get_invariant_threshold() + +Returns the global configuration threshold for the paraxial optical invariant check. +""" +get_invariant_threshold() = INVARIANT_THRESHOLD + + +# --- SDF & Ray Marching --- +const SDF_SURFACE_THRESHOLD = @load_preference("sdf_surface_threshold", 1e-9) +const SDF_RAYMARCH_EPS = @load_preference("sdf_raymarch_eps", 1e-10) +const SDF_INSIDE_STEP = @load_preference("sdf_inside_step", 1.0) + +""" + get_sdf_surface_threshold() + +Returns the global configuration threshold for the Signed Distance Field (SDF) surface detection. +""" +get_sdf_surface_threshold() = SDF_SURFACE_THRESHOLD + +""" + get_sdf_raymarch_eps() + +Returns the global configuration epsilon for the SDF ray marching algorithm. +""" +get_sdf_raymarch_eps() = SDF_RAYMARCH_EPS + +""" + get_sdf_inside_step() + +Returns the global configuration step size when inside an SDF volume. +""" +get_sdf_inside_step() = SDF_INSIDE_STEP + + +# --- Numerical Thresholds --- +const INTERNAL_REFLECTION_THRESHOLD = @load_preference("internal_reflection_threshold", 1e-6) +const LINE_PLANE_INTERSECTION_THRESHOLD = @load_preference("line_plane_intersection_threshold", 1e-6) +const ORTHOGONALITY_THRESHOLD = @load_preference("orthogonality_threshold", 1e-10) + +""" + get_internal_reflection_threshold() + +Returns the global configuration threshold for total internal reflection detection. +""" +get_internal_reflection_threshold() = INTERNAL_REFLECTION_THRESHOLD + +""" + get_line_plane_intersection_threshold() + +Returns the global configuration threshold for line-plane intersection calculations. +""" +get_line_plane_intersection_threshold() = LINE_PLANE_INTERSECTION_THRESHOLD + +""" + get_orthogonality_threshold() + +Returns the global configuration threshold for orthogonality checks (e.g., beam support axes). +""" +get_orthogonality_threshold() = ORTHOGONALITY_THRESHOLD + + +# --- Tracing Defaults --- +const DEFAULT_R_MAX = @load_preference("default_r_max", 100) +const DEFAULT_DEPTH_MAX = @load_preference("default_depth_max", typemax(Int)) + +""" + get_default_r_max() + +Returns the default maximum number of segments for ray tracing. +""" +get_default_r_max() = DEFAULT_R_MAX + +""" + get_default_depth_max() + +Returns the default maximum depth for recursive ray tracing (e.g., reflections/refractions). +""" +get_default_depth_max() = DEFAULT_DEPTH_MAX + + +# --- Physical Defaults --- +const DEFAULT_WAVELENGTH = @load_preference("default_wavelength", 1e-6) +const DEFAULT_WAIST = @load_preference("default_waist", 1e-3) +const DEFAULT_POWER = @load_preference("default_power", 1e-3) + +""" + get_default_wavelength() + +Returns the default wavelength in meters. +""" +get_default_wavelength() = DEFAULT_WAVELENGTH + +""" + get_default_waist() + +Returns the default beam waist radius in meters. +""" +get_default_waist() = DEFAULT_WAIST + +""" + get_default_power() + +Returns the default beam total power in Watts. +""" +get_default_power() = DEFAULT_POWER + + +""" + set_preference!(key::String, val; persistent=true) + +Helper to set preferences. Default is persistent. +""" +function set_preference!(key::String, val) + @set_preferences!(key => val) + @info "Preference '$key' updated to $val. Please restart Julia for this to take effect." +end + +# Keep the old setter for compatibility +""" + set_invariant_threshold!(val::Real) + +Sets the global configuration threshold for the paraxial optical invariant check. +This preference is persistent. Please restart Julia for this to take effect. +""" +set_invariant_threshold!(val::Real) = set_preference!("invariant_threshold", Float64(val)) + + +end # module diff --git a/src/Exports.jl b/src/Exports.jl index 48fa0687e..88ce01d5e 100644 --- a/src/Exports.jl +++ b/src/Exports.jl @@ -1,9 +1,14 @@ # kinematic export -export translate3d!, translate_to3d!, rotate3d!, xrotate3d!, yrotate3d!, zrotate3d!, align3d!, reset_translation3d!, reset_rotation3d! -export position, orientation +export translate3d!, translate_to3d!, rotate3d!, xrotate3d!, yrotate3d!, zrotate3d!, + align3d!, reset_translation3d!, reset_rotation3d! +export position, direction, orientation # ray and beam type export -export Ray, PolarizedRay, Beam, PointSource, CollimatedSource, UniformDiscSource, GaussianBeamlet +export Ray, PolarizedRay, Beam, PointSource, CollimatedSource, UniformDiscSource, + GaussianBeamlet, AstigmaticGaussianBeamlet, rayleigh_range, rays, point_on_beam, + normal3d +export CollimatedGaussianBeamletSource, GaussianBeamletDecomposition, + SphericalGaussianBeamletSource, EllipticalGaussianBeamletSource, WavefrontBeamletDecomposition, AstigmaticBeamGroup # system export System, StaticSystem, solve_system! @@ -19,22 +24,26 @@ components =# # mirrors -export Mirror, SquarePlanoMirror2D, RectangularPlanoMirror, SquarePlanoMirror, RoundPlanoMirror, ConcaveSphericalMirror, RightAnglePrismMirror +export Mirror, SquarePlanoMirror2D, RectangularPlanoMirror, SquarePlanoMirror, + RoundPlanoMirror, ConcaveSphericalMirror, RightAnglePrismMirror # lenses export Lens, DoubletLens, ThinLens, SphericalLens, SphericalDoubletLens, thickness # surfaces -export CircularFlatSurface, RectangularFlatSurface, SphericalSurface, EvenAsphericalSurface, CylindricalSurface, AcylindricalSurface +export CircularFlatSurface, RectangularFlatSurface, SphericalSurface, EvenAsphericalSurface, + CylindricalSurface, AcylindricalSurface # prisms export Prism, RightAnglePrism # detectors -export Detector, electric_field, intensity, spot_diagram, optical_power, Centroid, MinMax +export Detector, electric_field, intensity, spot_diagram, optical_power, gauss_parameters, + waist_parameters, Centroid, MinMax # splitters -export ThinBeamsplitter, RoundThinBeamsplitter, RectangularPlateBeamsplitter, RoundPlateBeamsplitter, CubeBeamsplitter, RectangularCompensatorPlate +export ThinBeamsplitter, RoundThinBeamsplitter, RectangularPlateBeamsplitter, + RoundPlateBeamsplitter, CubeBeamsplitter, RectangularCompensatorPlate # polarizing components export PolarizationFilter @@ -43,7 +52,11 @@ export PolarizationFilter export NonInteractableObject, MeshDummy, IntersectableObject # misc -export Retroreflector +export Retroreflector, get_invariant_threshold, set_invariant_threshold!, + get_sdf_surface_threshold, get_sdf_raymarch_eps, get_sdf_inside_step, + get_internal_reflection_threshold, get_line_plane_intersection_threshold, + get_orthogonality_threshold, get_default_r_max, get_default_depth_max, + get_default_wavelength, get_default_waist, get_default_power # render export render! diff --git a/src/Gaussian.jl b/src/Gaussian.jl index fcd4b33c5..4543f66f5 100644 --- a/src/Gaussian.jl +++ b/src/Gaussian.jl @@ -4,7 +4,7 @@ Ray representation of the **stigmatic** Gaussian beam as per J. Arnaud (1985). The beam quality `M2` is fully considered via the divergence angle. The formalism for the beam parameter calculation is based on the following publications: -**Jacques Arnaud, "Representation of Gaussian beams by complex rays," Appl. Opt. 24, 538-543 (1985)** +**Jacques Arnaud, "Representation of Gaussian beams by complex rays." Appl. Opt. 24, 538-543 (1985)** and @@ -84,7 +84,7 @@ wavelength(beam::GaussianBeamlet) = beam.λ wavelength!(beam::GaussianBeamlet, new) = (beam.λ = new) beam_waist(beam::GaussianBeamlet) = beam.w0 electric_field(beam::GaussianBeamlet) = beam.E0 -electric_field!(beam::GaussianBeamlet{T}, new) where T = (beam.E0 = Complex{T}(new)) +electric_field!(beam::GaussianBeamlet{T}, new) where {T} = (beam.E0 = Complex{T}(new)) refractive_index(beam::GaussianBeamlet, id::Int) = refractive_index(rays(beam.chief)[id]) function refractive_index!(beam::GaussianBeamlet, id::Int, n_new::Real) refractive_index!(rays(beam.chief)[id], n_new) @@ -213,15 +213,15 @@ The following inputs and arguments can be used to configure the beamlet: If results fluctuate due to the randomness of this vector, make sure to specify a fixed orthogonal `support` vector. """ function GaussianBeamlet( - position::AbstractArray{P}, - direction::AbstractArray{D}, - λ::L = 1e-6, - w0::Real = 1e-3; - M2::Real = 1, - P0::Real = 1e-3, - z0::Real = 0, - support::Nullable{AbstractArray} = nothing - ) where {P<:Real, D<:Real, L<:Real} + position::AbstractArray{P}, + direction::AbstractArray{D}, + λ::L = get_default_wavelength(), + w0::Real = get_default_waist(); + M2::Real = 1, + P0::Real = get_default_power(), + z0::Real = 0, + support::Nullable{AbstractArray} = nothing +) where {P <: Real, D <: Real, L <: Real} # T = promote_type(P, D, L) dir = normalize(direction) # Create orthogonal vector for construction purposes (right-handed) @@ -255,26 +255,6 @@ function GaussianBeamlet( ) end -global gb_constructor_warn = true - -#FIXME remove deprecated constructor until end of 2025 -function GaussianBeamlet(chief::Ray{T}, λ=1e-6, w0=1e-3; M2=1, P0=1e-3, support = [0,0,1]) where T - if gb_constructor_warn - @warn "The GaussianBeamlet(::Ray, ...) constructor will be deprecated in the future" - global gb_constructor_warn = false - end - s1 = normal3d(direction(chief), support) - return GaussianBeamlet( - position(chief), - direction(chief), - λ, - w0; - M2, - P0, - support = s1 - ) -end - point_on_beam(gauss::GaussianBeamlet, t::Real) = point_on_beam(gauss.chief, t) """ @@ -299,7 +279,7 @@ function gauss_parameters( gauss::GaussianBeamlet, z::Real; hint = point_on_beam(gauss, z) - ) +) p0, index = hint chief = gauss.chief.rays[index] div = gauss.divergence.rays[index] @@ -333,7 +313,7 @@ function gauss_parameters( H = abs(n * (y_w * m_d - y_d * m_w)) # Test optical invariant λ = wavelength(gauss) - if !isapprox(H, λ / π, atol = 1e-6) + if !isapprox(H, λ / π, atol = Config.get_invariant_threshold()) H = λ / π # println("H not fulfilled at z=$z") end @@ -349,7 +329,50 @@ function gauss_parameters( isnan(ψ) && (ψ = zero(ψ)) isnan(w0) && (w0 = w) R < 0 && (ψ = -ψ) - return w, R, ψ, w0 + return (w, R, ψ, w0) +end + +""" + waist_parameters(gb, z) + +Compute the position and cross-section axes at distance `z` along the beam. +For a stigmatic `GaussianBeamlet`, the cross-section is circular, and the axes are +determined by the orientation of the auxiliary waist ray. +Returns the vectors `(p0, w1, w2)` and scalar waist radii `(w0, w0)`. +""" +function waist_parameters(gb::GaussianBeamlet, z::Real) + p0, i = point_on_beam(gb, z) + w, _, _, _ = gauss_parameters(gb, z, hint = (p0, i)) + chief = rays(gb.chief)[i] + waist = rays(gb.waist)[i] + dir = direction(chief) + # Recover the basis vector from the auxiliary waist ray + # p_waist = p_chief + w * s1 + vec = position(waist) - p0 + # Project to transverse plane to be sure + vec = vec - dot(vec, dir) * dir + if norm(vec) < 1e-12 + s1 = normal3d(dir) + else + s1 = normalize(vec) + end + s2 = cross(dir, s1) + # Get waist size for unification + _, _, _, w0 = gauss_parameters(gb, z) + return p0, w * s1, w * s2, w0, w0 +end + +function waist_parameters(gauss::GaussianBeamlet{G}, zs::AbstractArray) where {G} + n = length(zs) + p0 = Vector{Point3{G}}(undef, n) + w1 = Vector{Point3{G}}(undef, n) + w2 = Vector{Point3{G}}(undef, n) + w01 = Vector{G}(undef, n) + w02 = Vector{G}(undef, n) + @inbounds for i in 1:n + p0[i], w1[i], w2[i], w01[i], w02[i] = waist_parameters(gauss, zs[i]) + end + return (p0, w1, w2, w01, w02) end """ @@ -378,20 +401,22 @@ This function also considers phase changes due to changes in the [`optical_path_ !!! warning Note that `z` and `r` must be specified as cartesian distances. Using the optical path length for `z` can lead to false results. """ -function electric_field(gauss::GaussianBeamlet, r, z) - point, index = point_on_beam(gauss, z) +function electric_field(gauss::GaussianBeamlet, r, z; hint = point_on_beam(gauss, z)) + point, index = hint w, R, ψ, w0 = gauss_parameters(gauss, z, hint = (point, index)) k = wavenumber(wavelength(gauss)) # Calculate new local field strength based on E0*w0 = const. E0 = electric_field(gauss) * (beam_waist(gauss) / w0) # Calculate phase change due to optical path length Δl = optical_path_length(gauss) - length(gauss) - # Note: geometrical length changes considered in `electric_field` call below + # Note: geometrical length changes considered in `electric_field` call below ref_ϕ = Δl / wavelength(gauss) * 2π - return electric_field(r, z, E0, w0, w, k, ψ, R) * exp(im*ref_ϕ) + return electric_field(r, z, E0, w0, w, k, ψ, R) * exp(im * ref_ϕ) end -optical_power(gauss::GaussianBeamlet) = intensity(electric_field(gauss)) / 2 * π * beam_waist(gauss)^2 +function optical_power(gauss::GaussianBeamlet) + intensity(electric_field(gauss)) / 2 * π * beam_waist(gauss)^2 +end """ isparaxial(system, gb::GaussianBeamlet, threshold=π/4) diff --git a/src/OpticalComponents/Beamsplitters/CubeBeamsplitter.jl b/src/OpticalComponents/Beamsplitters/CubeBeamsplitter.jl index 3942a9f4d..0bd81ba38 100644 --- a/src/OpticalComponents/Beamsplitters/CubeBeamsplitter.jl +++ b/src/OpticalComponents/Beamsplitters/CubeBeamsplitter.jl @@ -118,4 +118,33 @@ function interact3d( hint!(interaction, Hint(cbs, shape(cbs.coating))) return interaction end +end + +function interact3d( + system::AbstractSystem, + cbs::CubeBeamsplitter, + agb::AstigmaticGaussianBeamlet, + id::Int) + _shape = shape(intersection(rays(agb.c)[id])) + # Front prism interaction + if _shape === shape(cbs.front) + interaction = interact3d(system, cbs.front, agb, id) + hint!(interaction, Hint(cbs, shape(cbs.coating))) + return interaction + end + # Splitter "coating" interaction + if _shape === shape(cbs.coating) + interact3d(system, cbs.coating, agb, id) + # Update refractive index + _n = refractive_index(cbs, wavelength(agb)) + refractive_index!(agb.children[1], 1, _n) + refractive_index!(agb.children[2], 1, _n) + return nothing + end + # Back prism interaction + if _shape === shape(cbs.back) + interaction = interact3d(system, cbs.back, agb, id) + hint!(interaction, Hint(cbs, shape(cbs.coating))) + return interaction + end end \ No newline at end of file diff --git a/src/OpticalComponents/Beamsplitters/PlateBeamsplitter.jl b/src/OpticalComponents/Beamsplitters/PlateBeamsplitter.jl index b9d7fa59e..43d075e0c 100644 --- a/src/OpticalComponents/Beamsplitters/PlateBeamsplitter.jl +++ b/src/OpticalComponents/Beamsplitters/PlateBeamsplitter.jl @@ -266,4 +266,48 @@ function interact3d( end # if nothing worked, return nothing return nothing -end \ No newline at end of file +end + +function interact3d( + system::AbstractSystem, + pbs::AbstractPlateBeamsplitter, + agb::AstigmaticGaussianBeamlet, + id::Int + ) + _shape = shape(intersection(rays(agb.c)[id])) + # Substrate interaction + if _shape === shape(substrate(pbs)) + interaction = interact3d(system, substrate(pbs), agb, id) + hint!(interaction, Hint(pbs, shape(coating(pbs)))) + return interaction + end + # Splitter interaction + if _shape === shape(coating(pbs)) + interact3d(system, coating(pbs), agb, id) + # Update refractive index and calculate refraction + λ = wavelength(rays(agb.c)[id]) + n_optics = refractive_index(pbs, λ) + n_system = refractive_index(system, λ) + if isentering(agb, id) + # transmitted ray is refracted into substrate + _nt = n_optics + _nr = n_system + else + # transmitted ray is refracted into environment + _nt = n_system + _nr = n_optics + end + # Update children ref. index + refractive_index!(agb.children[1], 1, _nt) + refractive_index!(agb.children[2], 1, _nr) + # Calculate refracted directions for transmitted child's component beams + n_target = isentering(agb, id) ? n_optics : n_system + for (beam, pbeam) in zip(_component_beams(agb.children[1]), _component_beams(agb)) + n_d, _ = refraction3d(rays(pbeam)[id], n_target) + direction!(first(rays(beam)), n_d) + end + return nothing + end + # if nothing worked, return nothing + return nothing +end diff --git a/src/OpticalComponents/Beamsplitters/ThinBeamsplitter.jl b/src/OpticalComponents/Beamsplitters/ThinBeamsplitter.jl index e893079c5..11d99d6ab 100644 --- a/src/OpticalComponents/Beamsplitters/ThinBeamsplitter.jl +++ b/src/OpticalComponents/Beamsplitters/ThinBeamsplitter.jl @@ -1,7 +1,7 @@ """ ThinBeamsplitter <: AbstractBeamsplitter -Represents a 2D beam-splitting device. +Represents a 2D beam-splitting device. # Fields @@ -60,13 +60,15 @@ function RoundThinBeamsplitter(diameter::Real; reflectance::Real = 0.5) if reflectance ≥ 1 || reflectance ≈ 0 error("Splitting ratio ∈ (0, 1)!") end - shape = CircularFlatMesh(diameter/2) + shape = CircularFlatMesh(diameter / 2) R = sqrt(reflectance) T = sqrt(1 - R^2) return ThinBeamsplitter(shape, R, T) end -ThinBeamsplitter(width::Real; reflectance::Real=0.5) = ThinBeamsplitter(width, width; reflectance) +function ThinBeamsplitter(width::Real; reflectance::Real = 0.5) + ThinBeamsplitter(width, width; reflectance) +end Base.isvalid(bs::AbstractBeamsplitter) = reflectance(bs)^2 + transmittance(bs)^2 ≈ 1 @@ -95,7 +97,7 @@ end end @inline function _beamsplitter_reflected_beam(bs::AbstractBeamsplitter, ::Beam{T, R}, - ray::R) where {T <: Real, R <: PolarizedRay{T}} + ray::R) where {T <: Real, R <: PolarizedRay{T}} J = SPBasis(-reflectance(bs), 0, 0, reflectance(bs)) normal = normal3d(intersection(ray)) pos = position(ray) + length(ray) * direction(ray) @@ -109,27 +111,32 @@ function interact3d(::AbstractSystem, bs::ThinBeamsplitter, beam::Beam{T, R}, ray::R) where {T <: Real, R <: AbstractRay{T}} # Push transmitted and reflected beams to system children!(beam, - [_beamsplitter_transmitted_beam(bs, beam, ray), _beamsplitter_reflected_beam(bs, beam, ray)]) + [_beamsplitter_transmitted_beam(bs, beam, ray), + _beamsplitter_reflected_beam(bs, beam, ray)]) # Stop for beam spawning return nothing end -@inline function _beamsplitter_transmitted_beam(bs::AbstractBeamsplitter, gauss::GaussianBeamlet, ray_id::Int) +@inline function _beamsplitter_transmitted_beam( + bs::AbstractBeamsplitter, gauss::GaussianBeamlet, ray_id::Int) # Transmitted Gaussian (no phase flip) chief = _beamsplitter_transmitted_beam(bs, gauss.chief, rays(gauss.chief)[ray_id]) waist = _beamsplitter_transmitted_beam(bs, gauss.waist, rays(gauss.waist)[ray_id]) - divergence = _beamsplitter_transmitted_beam(bs, gauss.divergence, rays(gauss.divergence)[ray_id]) + divergence = _beamsplitter_transmitted_beam( + bs, gauss.divergence, rays(gauss.divergence)[ray_id]) λ = wavelength(gauss) w0 = gauss_parameters(gauss, length(gauss))[4] E0 = transmittance(bs) * electric_field(gauss) * (beam_waist(gauss) / w0) return GaussianBeamlet(chief, waist, divergence, λ, w0, E0) end -@inline function _beamsplitter_reflected_beam(bs::AbstractBeamsplitter, gauss::GaussianBeamlet, ray_id::Int) +@inline function _beamsplitter_reflected_beam( + bs::AbstractBeamsplitter, gauss::GaussianBeamlet, ray_id::Int) # Reflected Gaussian (no phase flip) chief = _beamsplitter_reflected_beam(bs, gauss.chief, rays(gauss.chief)[ray_id]) waist = _beamsplitter_reflected_beam(bs, gauss.waist, rays(gauss.waist)[ray_id]) - divergence = _beamsplitter_reflected_beam(bs, gauss.divergence, rays(gauss.divergence)[ray_id]) + divergence = _beamsplitter_reflected_beam( + bs, gauss.divergence, rays(gauss.divergence)[ray_id]) λ = wavelength(gauss) w0 = gauss_parameters(gauss, length(gauss))[4] E0 = reflectance(bs) * electric_field(gauss) * (beam_waist(gauss) / w0) @@ -147,7 +154,8 @@ The reflection phase jump is modeled here as θᵣ = π for simplicity. This is The phase jump is applied to the reflected portion of any incoming beam that faces the [`ThinBeamsplitter`](@ref) normal vector, which assumes that the splitter has an unambigous normal, i.e. a 2D mesh. This is intended to model the effect of the Fresnel equations without full polarization calculus. """ -function interact3d(::AbstractSystem, bs::ThinBeamsplitter, gauss::GaussianBeamlet, ray_id::Int) +function interact3d( + ::AbstractSystem, bs::ThinBeamsplitter, gauss::GaussianBeamlet, ray_id::Int) # Phase flip ray = gauss.chief.rays[ray_id] df = dot(direction(ray), normal3d(intersection(ray))) @@ -161,8 +169,61 @@ function interact3d(::AbstractSystem, bs::ThinBeamsplitter, gauss::GaussianBeaml r = _beamsplitter_reflected_beam(bs, gauss, ray_id) # Add conditional phase flip to reflected beam - electric_field!(r, electric_field(r) * exp(im*ϕ)) + electric_field!(r, electric_field(r) * exp(im * ϕ)) children!(gauss, [t, r]) return nothing end + +@inline function _beamsplitter_transmitted_beam( + bs::AbstractBeamsplitter, agb::AstigmaticGaussianBeamlet, ray_id::Int) + c = _beamsplitter_transmitted_beam(bs, agb.c, rays(agb.c)[ray_id]) + wxp = _beamsplitter_transmitted_beam(bs, agb.wxp, rays(agb.wxp)[ray_id]) + wxm = _beamsplitter_transmitted_beam(bs, agb.wxm, rays(agb.wxm)[ray_id]) + wyp = _beamsplitter_transmitted_beam(bs, agb.wyp, rays(agb.wyp)[ray_id]) + wym = _beamsplitter_transmitted_beam(bs, agb.wym, rays(agb.wym)[ray_id]) + dxp = _beamsplitter_transmitted_beam(bs, agb.dxp, rays(agb.dxp)[ray_id]) + dxm = _beamsplitter_transmitted_beam(bs, agb.dxm, rays(agb.dxm)[ray_id]) + dyp = _beamsplitter_transmitted_beam(bs, agb.dyp, rays(agb.dyp)[ray_id]) + dym = _beamsplitter_transmitted_beam(bs, agb.dym, rays(agb.dym)[ray_id]) + return AstigmaticGaussianBeamlet(c, wxp, wxm, wyp, wym, dxp, dxm, dyp, dym) +end + +@inline function _beamsplitter_reflected_beam( + bs::AbstractBeamsplitter, agb::AstigmaticGaussianBeamlet, ray_id::Int) + c = _beamsplitter_reflected_beam(bs, agb.c, rays(agb.c)[ray_id]) + wxp = _beamsplitter_reflected_beam(bs, agb.wxp, rays(agb.wxp)[ray_id]) + wxm = _beamsplitter_reflected_beam(bs, agb.wxm, rays(agb.wxm)[ray_id]) + wyp = _beamsplitter_reflected_beam(bs, agb.wyp, rays(agb.wyp)[ray_id]) + wym = _beamsplitter_reflected_beam(bs, agb.wym, rays(agb.wym)[ray_id]) + dxp = _beamsplitter_reflected_beam(bs, agb.dxp, rays(agb.dxp)[ray_id]) + dxm = _beamsplitter_reflected_beam(bs, agb.dxm, rays(agb.dxm)[ray_id]) + dyp = _beamsplitter_reflected_beam(bs, agb.dyp, rays(agb.dyp)[ray_id]) + dym = _beamsplitter_reflected_beam(bs, agb.dym, rays(agb.dym)[ray_id]) + return AstigmaticGaussianBeamlet(c, wxp, wxm, wyp, wym, dxp, dxm, dyp, dym) +end + +""" + interact3d(::AbstractSystem, bs::ThinBeamsplitter, agb::AstigmaticGaussianBeamlet, ray_id::Int) + +Models the interaction between a [`ThinBeamsplitter`](@ref) and an [`AstigmaticGaussianBeamlet`](@ref). +The reflection phase jump θᵣ = π is applied to the reflected child beam. +""" +function interact3d( + ::AbstractSystem, bs::ThinBeamsplitter, agb::AstigmaticGaussianBeamlet, ray_id::Int) + # Phase flip + ray = rays(agb.c)[ray_id] + df = dot(direction(ray), normal3d(intersection(ray))) + ϕ = df < 0 ? π : 0 + + t = _beamsplitter_transmitted_beam(bs, agb, ray_id) + r = _beamsplitter_reflected_beam(bs, agb, ray_id) + + # Add conditional phase flip to reflected beam chief polarization + chief_ray = first(rays(r.c)) + E_new = polarization(chief_ray) * exp(im * ϕ) + polarization!(chief_ray, E_new) + + children!(agb, [t, r]) + return nothing +end diff --git a/src/OpticalComponents/Detectors/Detector.jl b/src/OpticalComponents/Detectors/Detector.jl index a4b90e4b2..b8296cdb2 100644 --- a/src/OpticalComponents/Detectors/Detector.jl +++ b/src/OpticalComponents/Detectors/Detector.jl @@ -36,7 +36,7 @@ abstract type AbstractDetector{T} <: AbstractObject{T} end Resets the field data of the `detector`. Must be implemented for each concrete subtype of [`AbstractDetector`](@ref). """ -function empty!(::D) where D <: AbstractDetector +function empty!(::D) where {D <: AbstractDetector} @warn "Detector reset logic for $D not implemented" return nothing end @@ -46,8 +46,8 @@ end Abstract supertype for all [`Detector`](@ref) hit records. -A hit of this type encapsulates the interaction of a ray or beamlet with the [`Detector`](@ref) -surface. Instead of directly accumulating values (e.g. optical power), the hit +A hit of this type encapsulates the interaction of a ray or beamlet with the [`Detector`](@ref) +surface. Instead of directly accumulating values (e.g. optical power), the hit object stores all relevant information about the incident field for a posteriori evaluation (such as plotting, power integration, or polarization analysis). @@ -66,8 +66,8 @@ abstract type AbstractDetectorHit end """ AbstractRayHit{T} <: AbstractDetectorHit -Abstract supertype for detector hits produced by [`AbstractRay`](@ref)s. -Provides a common interface for extracting positional and optical path +Abstract supertype for detector hits produced by [`AbstractRay`](@ref)s. +Provides a common interface for extracting positional and optical path information from rays stored in a detector hit. Currently the following concrete types are implemented: @@ -106,7 +106,9 @@ wavenumber(hit::AbstractRayHit) = wavenumber(hit.ray) hit_point(hit::AbstractRayHit) = position(hit) + length(hit.ray) * direction(hit) -projection_factor(hit::AbstractRayHit) = abs(dot(direction(hit), normal3d(intersection(hit.ray)))) +function projection_factor(hit::AbstractRayHit) + abs(dot(direction(hit), normal3d(intersection(hit.ray)))) +end "Stores a [`Ray`](@ref) hit" struct RayHit{T} <: AbstractRayHit{T} @@ -140,15 +142,59 @@ up until the current beam section, identified by the `id` index. struct GaussianBeamletHit{T} <: AbstractBeamletHit{T} gauss::GaussianBeamlet{T} l0::T - id::Int + id::Int + # Cache + p0::Point3{T} + d0::Point3{T} + sqrt_proj::T + w_max::T +end + +""" + AstigmaticGaussianBeamletHit{T} <: AbstractBeamletHit{T} + +Stores an [`AstigmaticGaussianBeamlet`], where `l0` represents the length of the parent beam +up until the current beam section, identified by the `id` index. +""" +struct AstigmaticGaussianBeamletHit{T} <: AbstractBeamletHit{T} + agb::AstigmaticGaussianBeamlet{T} + l0::T + id::Int + # Cache + p0::Point3{T} + d0::Point3{T} + h1::Point3{Complex{T}} + u1::Point3{Complex{T}} + h2::Point3{Complex{T}} + u2::Point3{Complex{T}} + area_ref::Complex{T} + k0::T + Δl::T + n_eff::T + E_ref_amp::Complex{T} + sqrt_proj::T + w_max::T end position(hit::GaussianBeamletHit) = position(hit.gauss.chief.rays[hit.id]) direction(hit::GaussianBeamletHit) = direction(hit.gauss.chief.rays[hit.id]) -hit_point(hit::GaussianBeamletHit) = position(hit) + length(hit.gauss.chief.rays[hit.id]) * direction(hit) +position(hit::AstigmaticGaussianBeamletHit) = position(hit.agb.c.rays[hit.id]) +direction(hit::AstigmaticGaussianBeamletHit) = direction(hit.agb.c.rays[hit.id]) + +function hit_point(hit::GaussianBeamletHit) + position(hit) + length(hit.gauss.chief.rays[hit.id]) * direction(hit) +end +function hit_point(hit::AstigmaticGaussianBeamletHit) + position(hit) + length(hit.agb.c.rays[hit.id]) * direction(hit) +end -projection_factor(hit::GaussianBeamletHit) = abs(dot(direction(hit), normal3d(intersection(hit.gauss.chief.rays[hit.id])))) +function projection_factor(hit::GaussianBeamletHit) + abs(dot(direction(hit), normal3d(intersection(hit.gauss.chief.rays[hit.id])))) +end +function projection_factor(hit::AstigmaticGaussianBeamletHit) + abs(dot(direction(hit), normal3d(intersection(hit.agb.c.rays[hit.id])))) +end """ Detector <: AbstractDetector @@ -158,9 +204,9 @@ The detector surface is a detection screen that captures incoming ray or beamlet The active surface is discretized in the local R² x-y-coordinate system. If configured, beams or beamlets can continue tracing after hitting the detector. -# Hits +# Hits -Hits are represented via the [`AbstractDetectorHit`](@ref) interface. An empty detector is able to +Hits are represented via the [`AbstractDetectorHit`](@ref) interface. An empty detector is able to detect any kind of incoming hit, but as soon as the initial hit type has been determined, all following hits must share the same type, i.e. no cross-interaction between hit types is allowed. @@ -177,7 +223,7 @@ Refer to the respective function documentation. In general, the detection surface is represented by a flat [`Mesh`](@ref) that has been rotated such that the surface normals point towards the negative y-axis for the initial positioning. This allows for the definition -of a **left-handed** (x, z) surface coordinate system, where incoming beams intersect against the detector surface normal. +of a **left-handed** (x, z) surface coordinate system, where incoming beams intersect against the detector surface normal. !!! warning "Reset behavior" The `Detector` must be reset between each call of [`solve_system!`](@ref) in order to @@ -208,7 +254,8 @@ mutable struct Detector{T, S <: AbstractShape{T}} <: AbstractDetector{T} Nothing, Vector{RayHit{T}}, Vector{PolarizedRayHit{T}}, - Vector{GaussianBeamletHit{T}} + Vector{GaussianBeamletHit{T}}, + Vector{AstigmaticGaussianBeamletHit{T}} } stop::Bool lock::ReentrantLock @@ -222,9 +269,9 @@ The detector edge length can be configured via `edge_length`. Additionally, continued tracing can be configured via the `stop` flag where - `true` indicates continued tracing -- `false` stops the incoming beams as with any hard target +- `false` stops the incoming beams as with any hard target """ -function Detector(edge_length::Real, stop::Bool=true) +function Detector(edge_length::Real, stop::Bool = true) shape = QuadraticFlatMesh(edge_length) # rotate surface normal along neg. y-axis zrotate3d!(shape, π) @@ -241,18 +288,19 @@ stop(d::Detector) = d.stop function push!(d::Detector, new::AbstractDetectorHit) # Lock d to avoid race conditions - lock(d.lock) do + lock(d.lock) do # set data type on first push if isnothing(hits(d)) hits!(d, [new]) return nothing end - # if new<:AbstractData does not match, throws push! error + # if new<:AbstractData does not match, throws push! error push!(hits(d), new) end end -function interact3d(::AbstractSystem, d::Detector, beam::Beam{T, R}, ray::R) where {T <: Real, R <: Ray{T}} +function interact3d(::AbstractSystem, d::Detector, beam::Beam{T, R}, + ray::R) where {T <: Real, R <: Ray{T}} # Optical path length and wavenumber opl = optical_path_length(beam) # Push hit data into detector, determine stop @@ -264,7 +312,7 @@ function interact3d(::AbstractSystem, d::Detector, beam::Beam{T, R}, ray::R) whe else # Continue tracing with hit pos. as starting return BeamInteraction{T, R}( - nothing, + nothing, Ray{T}( position(hit), direction(hit), @@ -276,7 +324,8 @@ function interact3d(::AbstractSystem, d::Detector, beam::Beam{T, R}, ray::R) whe end end -function interact3d(::AbstractSystem, d::Detector, beam::Beam{T, R}, ray::R) where {T <: Real, R <: PolarizedRay{T}} +function interact3d(::AbstractSystem, d::Detector, beam::Beam{T, R}, + ray::R) where {T <: Real, R <: PolarizedRay{T}} # Optical path length and wavenumber opl = optical_path_length(beam) # Push hit data into detector, determine stop @@ -303,7 +352,17 @@ end function interact3d(::AbstractSystem, d::Detector, g::GaussianBeamlet{R}, id::Int) where {R} l0 = length(g) - length(g.chief.rays[id]) - push!(d, GaussianBeamletHit(g, l0, id)) + # Pre-calculate cache + ray = g.chief.rays[id] + p0 = position(ray) + d0 = direction(ray) + sqrt_proj = sqrt(abs(dot(d0, normal3d(intersection(ray))))) + + # Calculate actual beam radius at detector for auto-limits + w_at_detector, _, _, _ = gauss_parameters(g, length(g)) + w_max = w_at_detector + + push!(d, GaussianBeamletHit(g, l0, id, p0, d0, sqrt_proj, w_max)) if stop(d) # Stop solver (hard target) return nothing @@ -313,7 +372,65 @@ function interact3d(::AbstractSystem, d::Detector, g::GaussianBeamlet{R}, id::In end end +function interact3d(system::AbstractSystem, d::Detector, + agb::AstigmaticGaussianBeamlet{R}, id::Int) where {R} + l0 = length(agb) - length(agb.c.rays[id]) + + # Pre-calculate cache + chief = rays(agb.c)[id] + p0 = position(chief) + d0 = direction(chief) + k0 = 2π / wavelength(chief) + sqrt_proj = sqrt(abs(dot(d0, normal3d(intersection(chief))))) + + # Parabasal parameters at segment start (p0) + h1, u1, h2, u2, _ = parabasal_ray_parameters(agb, p0, id) + + # Reference normalization at z=0 + p0n, in_ = point_on_beam(agb, 0.0) + dirn = direction(rays(agb.c)[in_]) + h1n, _, h2n, _, _ = parabasal_ray_parameters(agb, p0n, in_) + area_ref = _pseudo_cross2d(h1n, h2n, dirn) + + # Extract complex reference amplitude + E_vec = polarization(rays(agb.c)[in_]) + max_idx = argmax(abs.(E_vec)) + E_ref_amp = Complex{R}(norm(E_vec) * cis(angle(E_vec[max_idx]))) + + # OPL correction (Δl) + p_parent = agb.parent + l_parent = isnothing(p_parent) ? 0.0 : length(p_parent) + opl_parent = isnothing(p_parent) ? 0.0 : optical_path_length(p_parent) + + Δl = opl_parent - l_parent + z_sum = l_parent + for j in 1:(id - 1) + ray_j = rays(agb.c)[j] + Δl += optical_path_length(ray_j) - length(ray_j) + z_sum += length(ray_j) + end + # Note: the (n-1)*z term in parabasal_field depends on (z - z_sum). + # Propagate semi-axes to detector for w_max (auto-limits) + H1 = h1 + length(chief) * u1 + H2 = h2 + length(chief) * u2 + w_max = max(norm(H1), norm(H2)) + n_eff = refractive_index(agb, id) + + push!(d, + AstigmaticGaussianBeamletHit( + agb, l0, id, p0, d0, h1, u1, h2, u2, area_ref, k0, Δl, + n_eff, E_ref_amp, sqrt_proj, w_max + )) + if stop(d) + # Stop solver (hard target) + return nothing + else + # Continue tracing # FIXME + throw(ErrorException("Continued tracing for AstigmaticGaussianBeamlet not yet implemented.")) + end +end + # include eval and helper functions include("DetectorUtils.jl") include("SpotDiagram.jl") -include("FieldCalculation.jl") \ No newline at end of file +include("FieldCalculation.jl") diff --git a/src/OpticalComponents/Detectors/DetectorUtils.jl b/src/OpticalComponents/Detectors/DetectorUtils.jl index db2067c5c..b4b8ef8f6 100644 --- a/src/OpticalComponents/Detectors/DetectorUtils.jl +++ b/src/OpticalComponents/Detectors/DetectorUtils.jl @@ -107,25 +107,87 @@ function calc_local_pos( ey = orientation(pd)[:,2] ez = orientation(pd)[:,3] pts_2D = Vector{Point2{T}}() - # Caclulate spots + sizehint!(pts_2D, length(hits) * num_spots) + + # Pre-calculate trig + sin_t = sin.(ts) + cos_t = cos.(ts) + + # Calculate spots for hit in hits - # Determine waist radius at intersection point - waist_radius, ~, ~, ~ = gauss_parameters(hit.gauss, length(hit.gauss)) - waist_radius *= crop_factor + # Use cached w_max (radius at detector) + waist_radius = hit.w_max * crop_factor + # build basis vectors - dir = direction(hit) + dir = hit.d0 nd1 = normal3d(dir) nd2 = cross(dir, nd1) origin = hit_point(hit) - # Calculate 3D waist circle of points - pts_3D = ellipse(ts, origin, waist_radius*nd1, waist_radius*nd2) - # Project 3D points onto plane, calculate local (x, z) coords - for (i, pt) in enumerate(pts_3D) + + # Calculate spots and project + for k in 1:num_spots + # 3D waist point + pt = origin + waist_radius * (cos_t[k] * nd1 + sin_t[k] * nd2) + # Project onto detector plane along ray direction dist = line_plane_distance3d(p0, ey, pt, dir) - pts_3D[i] = pt + dist * dir + isnothing(dist) && continue + p_proj = pt + dist * dir + + # Local coordinates + v = p_proj - p0 + push!(pts_2D, Point2{T}(dot(v, ex), dot(v, ez))) + end + end + return pts_2D +end + +""" + calc_local_pos(pd::Detector, hits::Vector{AstigmaticGaussianBeamletHit}; crop_factor=1, num_spots=50) + +Calculates a projected ellipse of 2D hit spots for each hit of an [`AstigmaticGaussianBeamlet`](@ref) +on the [`Detector`](@ref). +""" +function calc_local_pos( + pd::Detector, + hits::Vector{AstigmaticGaussianBeamletHit{T}}; + # kwargs + crop_factor::Real=one(T), + num_spots::Int=50 + ) where T + # Calculate waist projections in local (x, z) coordinates + ts = LinRange(0, 2pi, num_spots) + p0 = position(pd) + # Left-handed coord. sys. due to pd mesh rotation + ex = -orientation(pd)[:,1] + ey = orientation(pd)[:,2] + ez = orientation(pd)[:,3] + pts_2D = Vector{Point2{T}}() + sizehint!(pts_2D, length(hits) * num_spots) + + sin_t = sin.(ts) + cos_t = cos.(ts) + + for hit in hits + # Use cached parabasal parameters at segment start + # Propagate to detector (end of segment) + # chief segment length + l_seg = length(rays(hit.agb.c)[hit.id]) + h1 = (hit.h1 + l_seg * hit.u1) * crop_factor + h2 = (hit.h2 + l_seg * hit.u2) * crop_factor + + dir = hit.d0 + origin = hit_point(hit) + + for k in 1:num_spots + pt = origin + cos_t[k] * h1 + sin_t[k] * h2 + # Project onto detector plane along ray direction + dist = line_plane_distance3d(p0, ey, pt, dir) + isnothing(dist) && continue + p_proj = pt + dist * dir + + v = p_proj - p0 + push!(pts_2D, Point2{T}(real(dot(v, ex)), real(dot(v, ez)))) end - new_pts = calc_local_pos(p0, ex, ez, pts_3D) - append!(pts_2D, new_pts) end return pts_2D end @@ -160,8 +222,8 @@ function calc_local_lims( crop_factor::Real=one(T), center::AbstractCenterAlgorithm=Centroid() ) where T - # get all hit‐points in local (x,y) - local_hits = calc_local_pos(pd) + # get provided hit‐points in local (x,y) + local_hits = calc_local_pos(pd, hits) xs = getindex.(local_hits, 1) zs = getindex.(local_hits, 2) # calculate center @@ -186,14 +248,40 @@ For available keyword args., refer to the corresponding [`calc_local_pos`](@ref) """ function calc_local_lims( pd::Detector, - ::Vector{GaussianBeamletHit{G}}; - # kwargs - crop_factor::Real=one(G), - num_spots::Int=50 - ) where G - local_hits = calc_local_pos(pd; crop_factor, num_spots) - xs = getindex.(local_hits, 1) - zs = getindex.(local_hits, 2) - # min/max limits - return minimum(xs), maximum(xs), minimum(zs), maximum(zs) + hits::Vector{H}; + crop_factor::Real=1.5, + kwargs... + ) where {T, H <: AbstractBeamletHit{T}} + + pos_pd = position(pd) + ex = -orientation(pd)[:, 1] + ez = orientation(pd)[:, 3] + + xmin = T(Inf) + xmax = T(-Inf) + zmin = T(Inf) + zmax = T(-Inf) + + for hit in hits + # Center in local coords + p_hit = hit_point(hit) - pos_pd + x = dot(p_hit, ex) + z = dot(p_hit, ez) + + # Conservative bounding box using cached w_max + # w_max is the maximum semi-axis at the detector plane + w = hit.w_max * crop_factor + + xmin = min(xmin, x - w) + xmax = max(xmax, x + w) + zmin = min(zmin, z - w) + zmax = max(zmax, z + w) + end + + # Handle empty or invalid hits + if xmin > xmax + return (T(0), T(0), T(0), T(0)) + end + + return (xmin, xmax, zmin, zmax) end diff --git a/src/OpticalComponents/Detectors/FieldCalculation.jl b/src/OpticalComponents/Detectors/FieldCalculation.jl index ac7a684b1..b8a8d768a 100644 --- a/src/OpticalComponents/Detectors/FieldCalculation.jl +++ b/src/OpticalComponents/Detectors/FieldCalculation.jl @@ -2,7 +2,7 @@ electric_field(pd::Detector; kwargs...) Compute a two‐dimensional electric field based on incoming rays or beams as captured by a [`Detector`](@ref). -The returned E-field map is sampled on a regular `n×n` grid in the detector’s local (x,z)-plane. +The returned E-field map is sampled on a regular `n×n` grid in the detector's local (x,z)-plane. Note that the `pd` local coordinates are given in a (x, z) basis where the normal vector forms a left-handed system. !!! note "Resetting detectors" @@ -45,27 +45,30 @@ The following generic kwargs can be used for all hit types: A tuple `(xs, zs, E)` where - `xs::LinRange{T}` and `zs::LinRange{T}` are the sampled coordinates - in the detector’s local x and z axes, + in the detector's local x and z axes, - `E::Matrix{Complex{T}}` is the corresponding raw/unscaled intensity map """ electric_field(d::Detector; kwargs...) = electric_field(d, hits(d); kwargs...) -electric_field(d::Detector, ::Nothing; kwargs...) = throw(ErrorException("No hits available on detector.")) +function electric_field(d::Detector, ::Nothing; kwargs...) + throw(ErrorException("No hits available on detector.")) +end function electric_field( pd::Detector, hits::Vector{GaussianBeamletHit{G}}; # kwargs - n::Int=100, - crop_factor::Real=1.5, - num_spots::Int=50, + n::Int = 100, + crop_factor::Real = 1.5, + num_spots::Int = 50, x_min = Inf, x_max = Inf, z_min = Inf, z_max = Inf, - x0_shift::Real=0, - z0_shift::Real=0 - ) where G + x0_shift::Real = 0, + z0_shift::Real = 0, + kwargs... +) where {G} # Calculate autolims _x_min, _x_max, _z_min, _z_max = calc_local_lims(pd; crop_factor, num_spots) if x_min != Inf && x_max != Inf @@ -81,31 +84,108 @@ function electric_field( # Preallocate e-field matrix field = zeros(Complex{G}, n, n) # PD local coordinate axes (left-handed coords.) - local_x = Point3(-orientation(pd)[:,1]) # flipped sign due to rotated pd mesh - local_z = Point3(orientation(pd)[:,3]) + local_x = Point3(-orientation(pd)[:, 1]) # flipped sign due to rotated pd mesh + local_z = Point3(orientation(pd)[:, 3]) origin = position(pd) # Calculate field superposition - Threads.@threads for j in eachindex(zs) # FIXME row column major order? - z = zs[j] + Threads.@threads for j in eachindex(zs) + z_grid = zs[j] + # Hoist z-grid math out of inner loop + p_row = origin + z_grid * local_z + + @inbounds for i in eachindex(xs) + x_grid = xs[i] + p1 = p_row + x_grid * local_x + + acc = Complex{G}(0.0) + for hit in hits + v = p1 - hit.p0 + l1 = _pseudo_dot(v, hit.d0) + + # Transverse distance r + r_vec = v - l1 * hit.d0 + r = norm(r_vec) + + # Distance along beam + z = hit.l0 + l1 + + acc += electric_field(hit.gauss, r, z; hint = (hit.p0 + l1 * hit.d0, hit.id)) * hit.sqrt_proj + end + field[i, j] = acc + end + end + return xs, zs, field +end + +function electric_field( + pd::Detector, + hits::Vector{AstigmaticGaussianBeamletHit{G}}; + # kwargs + n::Int = 100, + crop_factor::Real = 3.0, + num_spots::Int = 50, + x_min = Inf, + x_max = Inf, + z_min = Inf, + z_max = Inf, + x0_shift::Real = 0, + z0_shift::Real = 0, + kwargs... +) where {G} + # Calculate autolims + _x_min, _x_max, _z_min, _z_max = calc_local_lims(pd; crop_factor, num_spots) + if x_min != Inf && x_max != Inf + _x_min = x_min + _x_max = x_max + end + if z_min != Inf && z_max != Inf + _z_min = z_min + _z_max = z_max + end + xs = LinRange(_x_min, _x_max, n) .+ x0_shift + zs = LinRange(_z_min, _z_max, n) .+ z0_shift + # Preallocate e-field matrix + field = zeros(Complex{G}, n, n) + # PD local coordinate axes (left-handed coords.) + local_x = Point3(-orientation(pd)[:, 1]) + local_z = Point3(orientation(pd)[:, 3]) + origin = position(pd) + # Calculate field superposition + Threads.@threads for j in eachindex(zs) + z_grid = zs[j] + # Hoist z-grid math out of inner loop + p_row = origin + z_grid * local_z + @inbounds for i in eachindex(xs) - x = xs[i] - # Transform point p on PD into world coordinates - p1 = origin + x * local_x + z * local_z - # Add E-field contribution for each hit + x_grid = xs[i] + p1 = p_row + x_grid * local_x + + acc = Complex{G}(0.0) for hit in hits - p0 = position(hit) - d0 = direction(hit) - # important: calculate l0 with geometric length for local r, z - l0 = hit.l0 - proj = projection_factor(hit) - # Find projection of p1 onto Gaussian optical axis, i.e. local r and z - l1 = dot(p1 - p0, d0) - p2 = p0 + l1 * d0 - r_gb = norm(p1 - p2) - z_gb = l0 + l1 - # Add field contribution, projection factor accounts for beam spot stretching - field[i, j] += electric_field(hit.gauss, r_gb, z_gb) * sqrt(proj) + v = p1 - hit.p0 + l1 = _pseudo_dot(v, hit.d0) + r_vec = v - l1 * hit.d0 + + h1_z = hit.h1 + l1 * hit.u1 + h2_z = hit.h2 + l1 * hit.u2 + area_z = _pseudo_cross2d(h1_z, h2_z, hit.d0) + if abs(area_z) < 1e-25 + area_z = Complex{G}(1e-25, 1e-25) + end + + ξ1 = _pseudo_cross2d(h1_z, r_vec, hit.d0) + ξ2 = _pseudo_cross2d(h2_z, r_vec, hit.d0) + w = (ξ1 * _pseudo_dot(hit.u2, r_vec) - + ξ2 * _pseudo_dot(hit.u1, r_vec)) / (2 * area_z) + + phase_corr = (hit.n_eff - 1) * l1 + z_total = hit.l0 + l1 + ψ = sqrt(hit.area_ref / area_z) * + cis(hit.k0 * (z_total + w + hit.Δl + phase_corr)) + + acc += (hit.E_ref_amp * ψ) * hit.sqrt_proj end + field[i, j] = acc end end return xs, zs, field @@ -115,16 +195,17 @@ function electric_field( pd::Detector, hits::Vector{RayHit{R}}; # kwargs - n::Int=100, - crop_factor::Real=1, - center::AbstractCenterAlgorithm=Centroid(), + n::Int = 100, + crop_factor::Real = 1, + center::AbstractCenterAlgorithm = Centroid(), x_min = Inf, x_max = Inf, z_min = Inf, z_max = Inf, - x0_shift::Real=0, - z0_shift::Real=0 - ) where R + x0_shift::Real = 0, + z0_shift::Real = 0, + kwargs... +) where {R} # automatically calculate limits _x_min, _x_max, _z_min, _z_max = calc_local_lims(pd; crop_factor, center) if x_min != Inf && x_max != Inf @@ -145,6 +226,15 @@ function electric_field( @views e1, e2 = Point3(-orient[:, 1]), Point3(orient[:, 3]) origin_pd = position(pd) + hit_data = map(hits) do hit + dir = direction(hit) + p_hit = position(hit) + length(hit) * dir + proj = projection_factor(hit) + k = wavenumber(hit) + opl = optical_path_length(hit) + (p_hit, dir, proj, k, opl) + end + Threads.@threads for j in eachindex(zs) z = zs[j] @inbounds for i in eachindex(xs) @@ -153,11 +243,11 @@ function electric_field( p = origin_pd + x * e1 + z * e2 # Add all field contributions acc = zero(complex(R)) - @inbounds @simd for hit in hits - l = dot(p - hit_point(hit), direction(hit)) - acc += projection_factor(hit) * cis(wavenumber(hit) * (optical_path_length(hit) + l)) + for (p_hit, dir, proj, k, opl) in hit_data + l = dot(p - p_hit, dir) + acc += proj * cis(k * (opl + l)) end - field[i,j] = acc + field[i, j] = acc end end @@ -191,4 +281,4 @@ For more information on keyword argument options, refer to the [`electric_field` function optical_power(pd::Detector; kwargs...) x, y, I = intensity(pd; kwargs...) return trapz((x, y), I) -end \ No newline at end of file +end diff --git a/src/OpticalComponents/NonInteractable.jl b/src/OpticalComponents/NonInteractable.jl index 1c7aff6a6..752e75b9e 100644 --- a/src/OpticalComponents/NonInteractable.jl +++ b/src/OpticalComponents/NonInteractable.jl @@ -19,4 +19,10 @@ set_new_origin3d!(d::NonInteractableObject) = set_new_origin3d!(d.shape) intersect3d(::NonInteractableObject, ::AbstractRay) = nothing interact3d(::AbstractSystem, ::NonInteractableObject, ::AbstractBeam, ::AbstractRay) = nothing +""" + MeshDummy(loadpath::String) + +Creates a [`NonInteractableObject`](@ref) with a [`Mesh`](@ref) loaded from the specified file path. +Useful for rendering background objects or geometry that does not interact with rays. +""" MeshDummy(loadpath::String) = NonInteractableObject(Mesh(load(loadpath))) \ No newline at end of file diff --git a/src/OpticalComponents/Polarizers/PolarizationFilter.jl b/src/OpticalComponents/Polarizers/PolarizationFilter.jl index 144b8f46c..6912d4fb7 100644 --- a/src/OpticalComponents/Polarizers/PolarizationFilter.jl +++ b/src/OpticalComponents/Polarizers/PolarizationFilter.jl @@ -46,3 +46,24 @@ function interact3d(::AbstractSystem, return BeamInteraction{T, R}(nothing, PolarizedRay{T}(npos, ndir, nothing, wavelength(ray), refractive_index(ray), E0)) end + +function interact3d(system::AbstractSystem, + polfilter::PolarizationFilter, + agb::AstigmaticGaussianBeamlet{T}, + id::Int) where {T <: Real} + # Chief ray interaction (handles polarization change) + i_c = interact3d(system, polfilter, agb.c, rays(agb.c)[id]) + isnothing(i_c) && return nothing + + # Auxiliary rays only undergo geometric interaction with the filter shape. + # They hit at their own transverse locations, preserving beam width/divergence. + aux_ints = map(b -> begin + interact3d(system, polfilter.shape, b, rays(b)[id]) + end, _aux_beams(agb)) + + if any(isnothing, aux_ints) + return nothing + end + + return AstigmaticGaussianBeamletInteraction{T}(i_c, aux_ints...) +end diff --git a/src/PolarizedRays.jl b/src/PolarizedRays.jl index 9c8326084..18dbd1efc 100644 --- a/src/PolarizedRays.jl +++ b/src/PolarizedRays.jl @@ -3,7 +3,7 @@ A ray type to model the propagation of an electric field vector based on the publication: -**Yun, Garam, Karlton Crabtree, and Russell A. Chipman. "Three-dimensional polarization ray-tracing calculus I: definition and diattenuation." Applied optics 50.18 (2011): 2855-2865.** +**Yun, Garam, Karlton Crabtree, and Russell A. Chipman. "Three-dimensional polarization ray-tracing calculus I: definition and diattenuation." Applied Optics 50.18 (2011): 2855-2865.** The geometrical ray description is identical to the standard [`Ray`](@ref). The polarization interaction can be described in local s-p-coordinates but must be transformed into global coordinates using the method described in the publication above, see also [`_calculate_global_E0`](@ref). @@ -54,12 +54,12 @@ mutable struct PolarizedRay{T} <: AbstractRay{T} throw(ErrorException("Direction vector to short for normalization.")) end # This test is very important and must be performed for each pol. ray - if !isorthogonal3d(dir, E0; atol=1e-14) - throw(ErrorException("Ray dir. and E0 must be orthogonal.")) + if !isorthogonal3d(dir, E0; atol=1e-10) + error("Ray dir. and E0 must be orthogonal (dot product: $(dot(dir, E0)))") end return new{M}( Point3{M}(pos), - Point3{M}(dir), + normalize(Point3{M}(dir)), int, M(λ), M(n), diff --git a/src/SDFs/AbstractSDF.jl b/src/SDFs/AbstractSDF.jl index cc8adf7dd..6faf9e180 100644 --- a/src/SDFs/AbstractSDF.jl +++ b/src/SDFs/AbstractSDF.jl @@ -1,6 +1,3 @@ -const eps_srf = 1e-9 # helps to decide if on SDF surface -const eps_ray = 1e-10 # helps to terminate outside ray marching routine -const eps_ins = 1e-0 # internal ray marching length step """ AbstractSDF <: AbstractShape @@ -103,7 +100,7 @@ function _raymarch_outside(shape::AbstractSDF{S}, pos::AbstractArray{R}, dir::AbstractArray{R}, num_iter = 1000, - eps = eps_ray) where {S, R} + eps = Config.get_sdf_raymarch_eps()) where {S, R} T = promote_type(S, R) dist = sdf(shape, pos) t0 = zero(T) @@ -145,7 +142,7 @@ function _raymarch_inside(object::AbstractSDF{S}, pos::AbstractArray{R}, dir::AbstractArray{R}, num_iter = 1000, - dl = eps_ins) where {S, R} + dl = Config.get_sdf_inside_step()) where {S, R} # this method assumes semi-concave objects, i.e. might fail depending on the choice of dl T = promote_type(S, R) t0::T = 0 @@ -180,7 +177,7 @@ function intersect3d(object::AbstractSDF, ray::AbstractRay) dir = direction(ray) d = sdf(object, pos) # Test if outside of sdf, else inside - if d > eps_srf + if d > Config.get_sdf_surface_threshold() return _raymarch_outside(object, pos, dir) end # Test if normal and ray dir oppose or align to determine if ray exits object diff --git a/src/SDFs/AbstractSurface.jl b/src/SDFs/AbstractSurface.jl index df0242c2c..a610495af 100644 --- a/src/SDFs/AbstractSurface.jl +++ b/src/SDFs/AbstractSurface.jl @@ -101,4 +101,7 @@ struct CircularFlatSurface{T} <: AbstractRotationallySymmetricSurface{T} diameter::T end +radius(::CircularFlatSurface{T}) where {T} = T(Inf) +edge_sag(::CircularFlatSurface{T}, ::AbstractSDF) where {T} = zero(T) + sdf(::CircularFlatSurface, ::AbstractOrientationType) = nothing diff --git a/src/System.jl b/src/System.jl index 3e8795297..1d5ade609 100644 --- a/src/System.jl +++ b/src/System.jl @@ -40,7 +40,9 @@ struct StaticSystem{T <: Tuple} <: AbstractSystem end StaticSystem(object::AbstractObject) = StaticSystem((object)) StaticSystem(object::AbstractObjectGroup) = StaticSystem([object]) -StaticSystem(objects::AbstractArray{<:AbstractObject}) = StaticSystem(tuple(collect(Leaves(objects))...)) +function StaticSystem(objects::AbstractArray{<:AbstractObject}) + StaticSystem(tuple(collect(Leaves(objects))...)) +end objects(system::StaticSystem) = system.objects @@ -71,9 +73,11 @@ end return result end -@inline function trace_one(system::AbstractSystem, ray::AbstractRay{R}, hint::Hint) where {R} +@inline function trace_one( + system::AbstractSystem, ray::AbstractRay{R}, hint::Hint) where {R} # Trace against hinted shape of object - intersection::Nullable{Intersection{R}} = intersect3d(shape(hint)::AbstractShape{R}, ray) + intersection::Nullable{Intersection{R}} = intersect3d( + shape(hint)::AbstractShape{R}, ray) if isnothing(intersection) # If hinted object is not intersected, trace the entire system intersection = trace_all(system, ray) @@ -97,37 +101,44 @@ An optional [`Hint`](@ref) can be provided to test against a specific object (an If a hint is provided and the object intersection is valid, the intersection will be returned immediately. However, it is not guaranteed that this is the true closest intersection. """ -@inline function tracing_step!(system::AbstractSystem, ray::AbstractRay{R}, hint::Hint) where {R <: Real} +@inline function tracing_step!( + system::AbstractSystem, ray::AbstractRay{R}, hint::Hint) where {R <: Real} # Test against hinted object intersection!(ray, trace_one(system, ray, hint)) return nothing end -@inline function tracing_step!(system::AbstractSystem, ray::AbstractRay{R}, ::Nothing) where {R <: Real} +@inline function tracing_step!( + system::AbstractSystem, ray::AbstractRay{R}, ::Nothing) where {R <: Real} # Test against all objects in system intersection!(ray, trace_all(system, ray)) return nothing end - """ - trace_system!(system::AbstractSystem, beam::Beam{T}; r_max::Int = 20) where {T <: Real} + trace_system!(system::AbstractSystem, beam::Beam{T}; r_max = get_default_r_max()) where {T <: Real} Trace a [`Beam`](@ref) through an optical `system`. Maximum number of tracing steps can be capped by `r_max`. # Tracing logic The intersection of the last ray of the `beam` with any objects contained within the `system` is tested. -If an object is hit, the optical interaction is calculated. If no interaction occurs or no +If an object is hit, the optical interaction is calculated. If no interaction occurs or no further objects are hit, the tracing procedure is stopped. # Arguments - `system:`: The optical system through which the [`Beam`](@ref) is traced. - `beam`: The [`Beam`](@ref) object to be traced. -- `r_max`: Maximum number of tracing iterations. Default is 20. +- `r_max`: Maximum number of tracing iterations. """ -function trace_system!(system::AbstractSystem, beam::Beam{T, R}; r_max::Int = 20) where {T <: Real, R <: AbstractRay{T}} +function trace_system!( + system::AbstractSystem, + beam::Beam{T, R}; + # kwargs + r_max::Int = get_default_r_max(), + kwargs... +) where {T <: Real, R <: AbstractRay{T}} # Test until max. number of rays in beam reached interaction::Nullable{BeamInteraction{T, R}} = nothing while length(rays(beam)) < r_max @@ -143,7 +154,8 @@ function trace_system!(system::AbstractSystem, beam::Beam{T, R}; r_max::Int = 20 break end obj = object(ray_intersection) - interaction = interact3d(system, obj, beam, ray)::Union{Nothing, BeamInteraction{T, R}} + interaction = interact3d( + system, obj, beam, ray)::Union{Nothing, BeamInteraction{T, R}} if isnothing(interaction) break end @@ -190,7 +202,12 @@ The retracing logic for an already solved `beam` loops over the rays and childre If this kind of situation must be modeled, e.g. in the case of an optical chopper wheel, retracing should be disabled. """ -function retrace_system!(system::AbstractSystem, beam::Beam{T, R}) where {T <: Real, R <: AbstractRay{T}} +function retrace_system!( + system::AbstractSystem, + beam::Beam{T, R}; + # kwargs + kwargs... +) where {T <: Real, R <: AbstractRay{T}} # Cleanup flags cleanup_children = false cleanup_tail = false @@ -260,7 +277,7 @@ function retrace_system!(system::AbstractSystem, beam::Beam{T, R}) where {T <: R end """ - trace_system!(system::System, gauss::GaussianBeamlet{T}; r_max::Int = 20) where {T <: Real} + trace_system!(system::System, gauss::GaussianBeamlet{T}; r_max = get_default_r_max()) where {T <: Real} Trace a [`GaussianBeamlet`](@ref) through an optical `system`. Maximum number of tracing steps can be capped by `r_max`. @@ -274,11 +291,15 @@ If all rays hit the same target, the optical interaction is analyzed, else the t - `system`: The optical system through which the [`GaussianBeamlet`](@ref) is traced. - `gauss`: The [`GaussianBeamlet`](@ref) object to be traced. -- `r_max`: Maximum number of tracing iterations. Default is 20. +- `r_max`: Maximum number of tracing iterations. """ -function trace_system!(system::AbstractSystem, +function trace_system!( + system::AbstractSystem, gauss::GaussianBeamlet{T}; - r_max::Int = 20) where {T <: Real} + # kwargs... + r_max::Int = get_default_r_max(), + kwargs... +) where {T <: Real} # Test until bundle is stopped interaction::Nullable{GaussianBeamletInteraction{T}} = nothing # Buffer variable @@ -328,7 +349,12 @@ end Retrace the beam stored in `GaussianBeamlet` through the optical `system`. Chief, waist and divergence ray intersections and interactions are recalculated. All rays must hit the same object, or the retracing step is aborted. If retracing is stopped before the end of the beam is reached, further rays are dropped. """ -function retrace_system!(system::AbstractSystem, gauss::GaussianBeamlet{T}) where {T <: Real} +function retrace_system!( + system::AbstractSystem, + gauss::GaussianBeamlet{T}; + # kwargs + kwargs... +) where {T <: Real} # Cleanup flags cleanup_children = false cleanup_tail = false @@ -420,9 +446,9 @@ function retrace_system!(system::AbstractSystem, gauss::GaussianBeamlet{T}) wher end # Drop all disconnected rays after last valid intersection, reset tail intersection to nothing if cleanup_tail - deleteat!(rays(gauss.chief), (cutoff + 1):n_c) - deleteat!(rays(gauss.waist), (cutoff + 1):n_w) - deleteat!(rays(gauss.divergence), (cutoff + 1):n_d) + deleteat!(rays(gauss.chief), (cutoff + 1):length(rays(gauss.chief))) + deleteat!(rays(gauss.waist), (cutoff + 1):length(rays(gauss.waist))) + deleteat!(rays(gauss.divergence), (cutoff + 1):length(rays(gauss.divergence))) end if reset_intersection intersection!(last(rays(gauss.chief)), nothing) @@ -432,6 +458,203 @@ function retrace_system!(system::AbstractSystem, gauss::GaussianBeamlet{T}) wher return nothing end +""" + trace_system!(system, agb::AstigmaticGaussianBeamlet; r_max = get_default_r_max(), check_invariant = true, threshold = get_invariant_threshold()) + +Trace an [`AstigmaticGaussianBeamlet`](@ref) through an optical `system`. +All 9 component beams (chief + 8 parabasal) are traced in lockstep: +the chief ray is traced first for each intersection, followed by the auxiliary rays. +All rays must hit the same shape; otherwise tracing stops. +""" +function trace_system!( + system::AbstractSystem, + agb::AstigmaticGaussianBeamlet{T}; + # kwargs + r_max::Int = get_default_r_max(), + check_invariant::Bool = true, + threshold::Real = get_invariant_threshold() +) where {T <: Real} + interaction::Nullable{AstigmaticGaussianBeamletInteraction{T}} = nothing + seg_counter::Int = length(rays(agb.c)) + aux = _aux_beams(agb) + while seg_counter < r_max + # Trace chief ray first + ray = last(rays(agb.c)) + tracing_step!(system, ray, hint(interaction)) + isnothing(intersection(ray)) && break + _object = object(intersection(ray)) + # Follow up with all auxiliary rays + stopped = false + for beam in aux + ray = last(rays(beam)) + tracing_step!(system, ray, hint(interaction)) + if isnothing(intersection(ray)) + stopped = true + break + end + end + stopped && break + # If beams do not hit same target stop tracing + if !_beams_hits_same_shape(agb, seg_counter) + # Ensure that no intersection artifacts remain + intersection!(last(rays(agb.c)), nothing) + for beam in aux + intersection!(last(rays(beam)), nothing) + end + break + end + # Calculate interaction + interaction = interact3d(system, _object, agb, seg_counter) + if isnothing(interaction) + break + end + # Add rays to beamlet + push!(agb, interaction) + seg_counter += 1 + + # Verify that the paraxial assumptions still hold for the new segment + if check_invariant && + !check_optical_invariant(agb, seg_counter; threshold = threshold) + break + end + end + return nothing +end + +""" + retrace_system!(system, agb::AstigmaticGaussianBeamlet; check_invariant=true, threshold = get_invariant_threshold()) + +Retrace the beam stored in [`AstigmaticGaussianBeamlet`](@ref) through the optical +`system`. All 9 component ray intersections and interactions are recalculated. +All rays must hit the same object, or the retracing step is aborted. +""" +function retrace_system!( + system::AbstractSystem, + agb::AstigmaticGaussianBeamlet{T}; + # kwargs + check_invariant::Bool = true, + threshold::Real = get_invariant_threshold() +) where {T <: Real} + # Cleanup flags + cleanup_children = false + cleanup_tail = false + reset_intersection = false + cutoff = 0 + # Buffer variables + _interaction::Nullable{AstigmaticGaussianBeamletInteraction{T}} = nothing + _hint::Nullable{Hint} = nothing + + all_beams = _component_beams(agb) + aux = _aux_beams(agb) + + # Test if beam is healthy + n_c = length(rays(agb.c)) + n_lens = map(b -> length(rays(b)), all_beams) + if !all(==(n_c), n_lens) + error("Astigmatic Gaussian beamlet is broken") + end + + # Iterate over chief rays + for (i, c_ray) in enumerate(rays(agb.c)) + # Test if intersection is valid + _intersection = intersection(c_ray) + if isnothing(_intersection) + cleanup_children = true + cleanup_tail = true + reset_intersection = true + cutoff = i + break + end + # Recalculate current intersection (use shape of hint if available) + if isnothing(_hint) + _object = object(_intersection) + intersection!(c_ray, intersect3d(_object, c_ray)) + for beam in aux + intersection!(rays(beam)[i], intersect3d(_object, rays(beam)[i])) + end + else + _object = object(_hint) + _shape = BeamletOptics.shape(_hint) + intersection!(c_ray, intersect3d(_shape, c_ray)) + for beam in aux + intersection!(rays(beam)[i], intersect3d(_shape, rays(beam)[i])) + end + end + # Test if all beams still hit the same target + if !_beams_hits_same_shape(agb, i) + cleanup_children = true + cleanup_tail = true + reset_intersection = true + cutoff = i + break + end + # Test if valid intersection + if isnothing(intersection(c_ray)) + cleanup_children = true + cleanup_tail = true + reset_intersection = true + cutoff = i + break + end + # Update object field + object!(intersection(c_ray), _object) + for beam in aux + r_int = intersection(rays(beam)[i]) + !isnothing(r_int) && object!(r_int, _object) + end + # Test if interaction is still valid + _interaction = interact3d(system, _object, agb, i) + # Catch hint + _hint = hint(_interaction) + if isnothing(_interaction) + # Do not set cleanup since nothing is a valid interaction + if n_c > i + cleanup_tail = true + cutoff = i + end + break + end + # Update next beamlet section + if i < n_c + # NOT THREAD-SAFE + replace!(agb, _interaction, i + 1) + else + # Valid new interaction, drop children and add new ray + cleanup_children = true + push!(agb, _interaction) + end + + # Verify that the paraxial assumptions still hold for the new segment + if check_invariant && !check_optical_invariant(agb, i + 1; threshold = threshold) + cleanup_tail = true + cutoff = i + break + end + + if i >= n_c + break + end + end + # Drop current branch since path has been altered + if cleanup_children + _drop_beams!(agb) + end + # Drop all disconnected rays after last valid intersection, reset tail intersection + if cleanup_tail + deleteat!(rays(agb.c), (cutoff + 1):length(rays(agb.c))) + for beam in aux + deleteat!(rays(beam), (cutoff + 1):length(rays(beam))) + end + end + if reset_intersection + intersection!(last(rays(agb.c)), nothing) + for beam in aux + intersection!(last(rays(beam)), nothing) + end + end + return nothing +end + """ solve_system!(system::System, beam::AbstractBeam; r_max=100, retrace=true, depth_max=typemax(Int)) @@ -443,30 +666,38 @@ A maximum number of rays per `beam` (`r_max`) can be specified in order to avoid - `system::System`: The optical system in which the beam will be traced. - `beam::AbstractBeam`: The beam object to be traced through the system. -- `r_max::Int=100` (optional): Maximum number of tracing iterations for each leaf. Default is 100. -- `retrace::Bool=true` (optional): Flag to indicate if the system should be retraced. Default is true. -- `depth_max::Int=typemax(Int)` (optional): Maximum number of branching levels explored from the root beam. Default allows unlimited depth. + +## Keyword Arguments + +- `r_max = get_default_r_max()`: Maximum number of tracing iterations for each leaf. +- `retrace = true`: Flag to indicate if the system should be retraced. Default is true. +- `depth_max = get_default_depth_max()`: Maximum number of branching levels explored from the root beam. +- `check_invariant = true`: enables or disables optical invariant checks where applicable +- `threshold = get_invariant_threshold()`: threshold for paraxial invariant checks """ function solve_system!( system::AbstractSystem, beam::B; - r_max::Int = 100, + # kwargs + r_max::Int = get_default_r_max(), retrace::Bool = true, - depth_max::Int = typemax(Int), - ) where {B <: AbstractBeam} + depth_max::Int = get_default_depth_max(), + check_invariant::Bool = true, + threshold::Real = get_invariant_threshold() +) where {B <: AbstractBeam} queue = Tuple{B, Int}[(beam, 1)] while !isempty(queue) - # Process beams in FIFO order. + # Process beams in FIFO order. current, depth = popfirst!(queue) - # Optionally retrace the current beam. + # Optionally retrace the current beam. if retrace - retrace_system!(system, current) + retrace_system!(system, current; check_invariant, threshold) end # Process the current leaf beam. - solve_leaf!(system, current; r_max=r_max) + solve_leaf!(system, current; r_max, check_invariant, threshold) # Check if the maximum branching depth has been reached. if depth <= depth_max - # Enqueue all child beams for subsequent processing. + # Enqueue all child beams for subsequent processing. for child in children(current) # 'children' returns an iterable of sub-beams. push!(queue, (child, depth + 1)) end @@ -480,26 +711,27 @@ function solve_system!( end function solve_system!(system::AbstractSystem, bg::AbstractBeamGroup; kwargs...) - for _beam in beams(bg) + Threads.@threads for _beam in beams(bg) solve_system!(system, _beam; kwargs...) end return nothing end -@inline function solve_leaf!(system::AbstractSystem, beam::AbstractBeam; r_max = 100) +@inline function solve_leaf!( + system::AbstractSystem, beam::AbstractBeam; r_max = get_default_r_max(), kwargs...) if isnothing(_last_beam_intersection(beam)) - trace_system!(system, beam, r_max = r_max) + trace_system!(system, beam; r_max, kwargs...) end return nothing end function AbstractTrees.printnode(io::IO, node::B; kw...) where {B <: AbstractObject} - show(io, B) + show(io, node) end function AbstractTrees.printnode(io::IO, node::B; kw...) where {B <: AbstractObjectGroup} - show(io, B) + show(io, node) end Base.show(::IO, ::MIME"text/plain", system::System) = diff --git a/src/Utils/LinearAlgebraUtils.jl b/src/Utils/LinearAlgebraUtils.jl index b8fd8e431..0bd3d81f9 100644 --- a/src/Utils/LinearAlgebraUtils.jl +++ b/src/Utils/LinearAlgebraUtils.jl @@ -162,9 +162,10 @@ end Returns the distance between a line and an infinitely large plane which are characterized by their `position` and `normal`/`direction`. """ -function line_plane_distance3d(plane_position::AbstractArray, plane_normal::AbstractArray, line_position::AbstractArray, line_direction::AbstractArray) +function line_plane_distance3d(plane_position::AbstractArray, plane_normal::AbstractArray, + line_position::AbstractArray, line_direction::AbstractArray) denom = dot(plane_normal, line_direction) - if abs(denom) > 1e-6 + if abs(denom) > Config.get_line_plane_intersection_threshold() # explicit dot product for perfomance c = dot(plane_position - line_position, plane_normal) t = c / denom diff --git a/src/Utils/OpticUtils.jl b/src/Utils/OpticUtils.jl index 8a8435e34..6bdc7e747 100644 --- a/src/Utils/OpticUtils.jl +++ b/src/Utils/OpticUtils.jl @@ -142,7 +142,8 @@ function fresnel_coefficients(θ::AbstractArray{T}, n::Number) where {T} end function is_internally_reflected(rp::Number, rs::Number) - isapprox(abs2(rs), 1, atol = 1e-6) && isapprox(abs2(rp), 1, atol = 1e-6) + isapprox(abs2(rs), 1, atol = Config.get_internal_reflection_threshold()) && + isapprox(abs2(rp), 1, atol = Config.get_internal_reflection_threshold()) end """ @@ -174,7 +175,7 @@ numerical_aperture(θ::Real, n::Real = 1.0) = n * sin(θ) Calculates e.g. the interferometric contrast from a series of optical power measurements. For more information go [here](https://en.wikipedia.org/wiki/Interferometric_visibility). """ -visibility(I_min::Real, I_max::Real) = (I_max - I_min) / (I_max + I_min) +visibility(I_min::Real, I_max::Real) = (I_max - I_min) / (I_max + I_min) function visibility(opt_pwr::AbstractArray) I_max = maximum(opt_pwr) I_min = minimum(opt_pwr) diff --git a/test/Components/TestDetectorUtils.jl b/test/Components/TestDetectorUtils.jl new file mode 100644 index 000000000..20e507966 --- /dev/null +++ b/test/Components/TestDetectorUtils.jl @@ -0,0 +1,113 @@ +module TestDetectorUtils + +using BeamletOptics +using Test + +const BMO = BeamletOptics + +const mm = 1e-3 + +@testset "DetectorUtils" begin + @testset "Testing calc_center_point with Centroid" begin + @testset "Uniform weights" begin + xs = [1.0, 2.0, 3.0] + zs = [4.0, 5.0, 6.0] + projection_factor = [1.0, 1.0, 1.0] + x0, z0 = BMO.calc_center_point(BMO.Centroid(), xs, zs, projection_factor) + @test x0 ≈ 2.0 + @test z0 ≈ 5.0 + end + + @testset "Biased weights" begin + # biased weights + xs = [1.0, 2.0, 3.0] + zs = [4.0, 5.0, 6.0] + projection_factor = [10.0, 1.0, 1.0] + x0, z0 = BMO.calc_center_point(BMO.Centroid(), xs, zs, projection_factor) + @test x0 ≈ 1.25 + @test z0 ≈ 4.25 + end + + @testset "iszero fallback" begin + xs = [1.0, 10.0, 100.0] + zs = [2.0, 20.0, 200.0] + projection_factor = [0.0, 0.0, 0.0] + x0, z0 = BMO.calc_center_point(BMO.Centroid(), xs, zs, projection_factor) + @test x0 ≈ 50.5 + @test z0 ≈ 101.0 + end + end + @testset "Testing calc_local_pos with GaussianBeamlet" begin + # setup test beam + offset = 50mm + gb = GaussianBeamlet([0,0,0], [0,1,0]) + w, ~, ~, ~ = gauss_parameters(gb, offset) + # setup untilted detector + pd = Detector(5mm) + translate_to3d!(pd, [0, offset, 0]) + system = System([pd]) + @testset "Untilted detector projection" begin + solve_system!(system, gb) + crop_factor = 2 + num_spots = 1000 + pts = BMO.calc_local_pos(pd; num_spots, crop_factor) + # find local bounding box + xmin = minimum(getindex.(pts, 1)) + xmax = maximum(getindex.(pts, 1)) + ymin = minimum(getindex.(pts, 2)) + ymax = maximum(getindex.(pts, 2)) + # test num spots and correct circle dims + @test length(pts) == num_spots + @test isapprox(w * crop_factor, -xmin, atol=1e-8) + @test isapprox(w * crop_factor, xmax, atol=1e-8) + @test isapprox(w * crop_factor, -ymin, atol=1e-8) + @test isapprox(w * crop_factor, ymax, atol=1e-8) + end + @testset "Tilted detector projection" begin + zrotate3d!(pd, deg2rad(45)) + solve_system!(system, gb) + crop_factor = 1.5 + num_spots = 980 + pts = BMO.calc_local_pos(pd; num_spots, crop_factor) + xmin = minimum(getindex.(pts, 1)) + xmax = maximum(getindex.(pts, 1)) + ymin = minimum(getindex.(pts, 2)) + ymax = maximum(getindex.(pts, 2)) + @test isapprox(w * crop_factor * sqrt(2), -xmin, atol=1e-8) + @test isapprox(w * crop_factor * sqrt(2), xmax, atol=1e-8) + @test isapprox(w * crop_factor, -ymin, atol=1e-8) + @test isapprox(w * crop_factor, ymax, atol=1e-8) + end + end + + @testset "Testing calc_local_pos with AstigmaticGaussianBeamlet" begin + # setup test beam + offset = 150mm + agb = AstigmaticGaussianBeamlet([0,0,0], [0,1,0]) + w, ~, ~, ~ = gauss_parameters(agb, offset) + # setup untilted detector + pd = Detector(5mm) + translate_to3d!(pd, [0, offset, 0]) + xrotate3d!(pd, deg2rad(45)) + system = System([pd]) + @testset "Untilted detector projection" begin + solve_system!(system, agb) + crop_factor = 2 + num_spots = 1000 + pts = BMO.calc_local_pos(pd; num_spots, crop_factor) + # find local bounding box + xmin = minimum(getindex.(pts, 1)) + xmax = maximum(getindex.(pts, 1)) + ymin = minimum(getindex.(pts, 2)) + ymax = maximum(getindex.(pts, 2)) + # test num spots and correct circle dims + @test length(pts) == num_spots + @test isapprox(w * crop_factor, -xmin, atol=5e-6) + @test isapprox(w * crop_factor, xmax, atol=5e-6) + @test isapprox(w * crop_factor * sqrt(2), -ymin, atol=5e-6) + @test isapprox(w * crop_factor * sqrt(2), ymax, atol=5e-6) + end + end +end + +end # MODULE \ No newline at end of file diff --git a/test/E2E/TestFraunhofer.jl b/test/E2E/TestFraunhofer.jl new file mode 100644 index 000000000..3826375f2 --- /dev/null +++ b/test/E2E/TestFraunhofer.jl @@ -0,0 +1,66 @@ +module TestFraunhofer + +using BeamletOptics +using Test +using LinearAlgebra + +const BMO = BeamletOptics +const mm = 1e-3 +const nm = 1e-9 + +@testset "Fraunhofer Diffraction (Astigmatic Gaussian Beamlets)" begin + # D = 2 mm, λ = 632.8 nm, evaluated at 100 m + D = 2mm + λ = 632.8nm + L = 100.0 # meters + + # We represent the square aperture by an array of 15 x 15 Gaussian beamlets for speed + n_beams = 15 + Δ = D / n_beams + w0s = Δ + + beams = CollimatedGaussianBeamletSource([0.0, 0.0, 0.0], [0.0, 1.0, 0.0], D, λ, w0s; n_grid=n_beams) + + # Set electric field amplitude to point along z-axis to match previous test + for b in beams + BeamletOptics.polarization!(b.c.rays[1], [0.0, 0.0, 1.0]) + end + + # Physical detector large enough to catch all divergence rays + pd = Detector(3000mm) + translate_to3d!(pd, [0, L, 0]) + + system = System([pd]) + + # Trace all beams to the detector + solve_system!.(Ref(system), beams) + + # All beams should have hit the detector + @test length(pd.hits) == n_beams^2 + + # Use a low resolution grid (n=50) for fast testing + x, z, I = BMO.intensity( + pd, n = 50, x_min = -100mm, x_max = 100mm, z_min = -100mm, z_max = 100mm) + + # Compare with analytical solution: I(x,z) ∝ sinc²(D*x/(λ*L)) * sinc²(D*z/(λ*L)) + x_norm = x .* D ./ (λ * L) + z_norm = z .* D ./ (λ * L) + sinc_sq(u) = (u == 0) ? 1.0 : (sin(π * u) / (π * u))^2 + analy_I = [sinc_sq(u_x) * sinc_sq(u_z) for u_x in x_norm, u_z in z_norm] + + # Normalize numerical intensity to match analytical peak (1.0) + I_norm = I ./ maximum(I) + + # Calculate mean absolute error between normalized numerical and analytical intensities + mae = sum(abs.(I_norm .- analy_I)) / length(I_norm) + + # With a 15x15 beamlet grid, the MAE should be very small (< 0.05) + @test mae < 0.05 + + # Check peak is exactly at the center + mid_idx_x = argmin(abs.(x)) + mid_idx_z = argmin(abs.(z)) + @test I_norm[mid_idx_x, mid_idx_z] ≈ 1.0 +end + +end # MODULE diff --git a/test/TestAstigmaticGaussianBeamlet.jl b/test/TestAstigmaticGaussianBeamlet.jl new file mode 100644 index 000000000..47c2a8080 --- /dev/null +++ b/test/TestAstigmaticGaussianBeamlet.jl @@ -0,0 +1,206 @@ +module TestAstigmaticGaussianBeamlet + +using BeamletOptics +using Test +using LinearAlgebra + +const BMO = BeamletOptics + +@testset "AstigmaticGaussianBeamlet" begin + λ0 = 1000e-9 + w0 = 1e-4 + + @testset "Construction" begin + beam = AstigmaticGaussianBeamlet([0.0, 0, 0], [0, 1, 0], λ0, w0; E0=[0,0,1], support=[0,0,1]) + @test isa(beam, AstigmaticGaussianBeamlet{Float64}) + @test BMO.wavelength(beam) == λ0 + @test BMO.direction(beam) ≈ [0, 1, 0] + @test length(BMO.rays(beam.c)) == 1 + @test length(BMO.rays(beam.wxp)) == 1 + @test length(BMO.rays(beam.dyp)) == 1 + @test isnothing(beam.parent) + @test isempty(beam.children) + end + + @testset "Component beam consistency" begin + beam = AstigmaticGaussianBeamlet([0.0, 0, 0], [0, 1, 0], λ0, w0; E0=[0,0,1], support=[0,0,1]) + all_beams = BMO._component_beams(beam) + @test length(all_beams) == 9 + aux_beams = BMO._aux_beams(beam) + @test length(aux_beams) == 8 + for b in all_beams + @test length(BMO.rays(b)) == 1 + end + end + + @testset "Free-space field matches analytic Gaussian" begin + beam = AstigmaticGaussianBeamlet([0.0, 0, 0], [0, 1, 0], λ0, w0; E0=[0,0,1], support=[0,0,1]) + dir = normalize([0, 1, 0]) + ex = normalize(cross(dir, [0,0,1])) + z_eval = 0.08 + + rs = LinRange(-5e-3, 5e-3, 201) + E_num = [BMO.parabasal_field(beam, ex * r, z_eval) for r in rs] + E_ana = BMO.electric_field.(rs, z_eval, 1.0, w0, λ0) + + mid = (length(rs) + 1) ÷ 2 + phase = angle(E_num[mid] / E_ana[mid]) + E_ana_aligned = E_ana .* exp(im * phase) + + @test all(isapprox.(E_num, E_ana_aligned; atol=1e-5, rtol=1e-3)) + end + + @testset "Waist parameters" begin + beam = AstigmaticGaussianBeamlet([0.0, 0, 0], [0, 1, 0], λ0, w0; E0=[0,0,1], support=[0,0,1]) + p0, w1, w2 = BMO.waist_parameters(beam, 0.0) + @test p0 ≈ [0, 0, 0] + # At the waist, the beam size should be ~w0 + @test norm(w1) ≈ w0 atol=1e-6 + @test norm(w2) ≈ w0 atol=1e-6 + end + + @testset "Waist parameters with offsets" begin + z0_x = 0.05 + z0_y = 0.10 + beam = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ0, w0, 2*w0; + z0_x = z0_x, z0_y = z0_y, + E0=[0,0,1], support=[1,0,0] + ) + + # X waist should be at z0_x + _, wx_waist, _ = BMO.waist_parameters(beam, z0_x) + @test norm(wx_waist) ≈ w0 atol=1e-6 + + # Y waist should be at z0_y + _, _, wy_waist = BMO.waist_parameters(beam, z0_y) + @test norm(wy_waist) ≈ 2*w0 atol=1e-6 + + # Verify invariants hold + @test BMO.check_optical_invariant(beam, 1; threshold=1e-12) + end + + @testset "Lens interaction" begin + s1 = BMO.CylinderSDF(BMO.inch / 2, BMO.inch) + l1 = BMO.Lens(s1, n -> 1.5) + BMO.translate3d!(l1, [0, 0.1, 0.0]) + BMO.zrotate3d!(l1, deg2rad(90)) + + system = BMO.System([l1]) + beam = AstigmaticGaussianBeamlet([0.0, 0, 0], [0, 1, 0], λ0, w0; E0=[0,0,1], support=[0,0,1]) + solve_system!(system, beam) + + # Should have 3 segments: initial → enter lens → exit lens → free + n_rays = length(BMO.rays(beam.c)) + @test n_rays == 3 + for b in BMO._aux_beams(beam) + @test length(BMO.rays(b)) == n_rays + end + end + + @testset "Mirror interaction" begin + m = BMO.SquarePlanoMirror(0.05, 0.01) + BMO.translate3d!(m, [0, 0.05, 0]) + system = BMO.System([m]) + beam = AstigmaticGaussianBeamlet([0.0, 0, 0], [0, 1, 0], λ0, w0; E0=[0,0,1], support=[0,0,1]) + solve_system!(system, beam) + + # Should have 2 segments: initial → reflected + n_rays = length(BMO.rays(beam.c)) + @test n_rays == 2 + for b in BMO._aux_beams(beam) + @test length(BMO.rays(b)) == n_rays + end + # Check reflected direction is approximately [0, -1, 0] + last_chief = last(BMO.rays(beam.c)) + @test isapprox(BMO.direction(last_chief)[2], -1.0, atol=0.01) + end + + @testset "ThinBeamsplitter interaction" begin + bs = BMO.ThinBeamsplitter(0.05) + BMO.translate3d!(bs, [0, 0.03, 0]) + BMO.zrotate3d!(bs, deg2rad(45)) + + system = BMO.System([bs]) + beam = AstigmaticGaussianBeamlet([0.0, 0, 0], [0, 1, 0], λ0, w0; E0=[0,0,1], support=[0,0,1]) + solve_system!(system, beam) + + # Should create 2 children (transmitted + reflected) + @test length(beam.children) == 2 + t_child = beam.children[1] + r_child = beam.children[2] + @test isa(t_child, AstigmaticGaussianBeamlet) + @test isa(r_child, AstigmaticGaussianBeamlet) + # Both children should have consistent component beams + for child in beam.children + n = length(BMO.rays(child.c)) + for b in BMO._aux_beams(child) + @test length(BMO.rays(b)) == n + end + end + end + + @testset "Two-lens astigmatic system" begin + s1 = BMO.CylinderSDF(BMO.inch / 2, BMO.inch) + s2 = BMO.CylinderSDF(BMO.inch / 2, BMO.inch) + l1 = BMO.Lens(s1, n -> 1.5) + l2 = BMO.Lens(s2, n -> 1.5) + BMO.translate3d!(l1, [0, 0.1, 0.0]) + BMO.translate3d!(l2, [0, 0.15, 0.0]) + BMO.zrotate3d!(l1, deg2rad(90)) + BMO.xrotate3d!(l2, deg2rad(60)) + + system = BMO.System([l1, l2]) + beam = AstigmaticGaussianBeamlet([0.0, 0, 0], [0, 1, 0], λ0, w0; E0=[0,0,1], support=[0,0,1]) + solve_system!(system, beam) + + # 2 lenses × 2 surfaces + 1 initial = 5 segments + n_rays = length(BMO.rays(beam.c)) + @test n_rays == 5 + for b in BMO._aux_beams(beam) + @test length(BMO.rays(b)) == n_rays + end + end + + @testset "Retracing" begin + s1 = BMO.CylinderSDF(BMO.inch / 2, BMO.inch) + l1 = BMO.Lens(s1, n -> 1.5) + BMO.translate3d!(l1, [0, 0.1, 0.0]) + BMO.zrotate3d!(l1, deg2rad(90)) + + system = BMO.System([l1]) + beam = AstigmaticGaussianBeamlet([0.0, 0, 0], [0, 1, 0], λ0, w0; E0=[0,0,1], support=[0,0,1]) + solve_system!(system, beam) + + n_initial = length(BMO.rays(beam.c)) + + # Move lens slightly and retrace + BMO.translate3d!(l1, [0, 0.005, 0]) + BMO.retrace_system!(system, beam) + + # Should still have same number of segments + @test length(BMO.rays(beam.c)) == n_initial + for b in BMO._aux_beams(beam) + @test length(BMO.rays(b)) == n_initial + end + end + + @testset "Detector interaction" begin + pd = BMO.Detector(0.05) + BMO.translate3d!(pd, [0, 0.1, 0]) + system = BMO.System([pd]) + beam = AstigmaticGaussianBeamlet([0.0, 0, 0], [0, 1, 0], λ0, w0) + solve_system!(system, beam) + + @test !isnothing(BMO.hits(pd)) + @test length(BMO.hits(pd)) == 1 + @test isa(BMO.hits(pd)[1], BMO.AstigmaticGaussianBeamletHit) + + # Test field calculation + xs, zs, E = BMO.electric_field(pd; n=20) + @test size(E) == (20, 20) + @test any(!iszero, E) + end +end + +end # MODULE diff --git a/test/TestAstigmaticGaussianPhysical.jl b/test/TestAstigmaticGaussianPhysical.jl new file mode 100644 index 000000000..1538434b0 --- /dev/null +++ b/test/TestAstigmaticGaussianPhysical.jl @@ -0,0 +1,426 @@ +module TestAstigmaticGaussianPhysical + +using BeamletOptics +using Test +using LinearAlgebra + +const BMO = BeamletOptics +const mm = 1e-3 +const nm = 1e-9 + +@testset "AGB Physical Validation" begin + + # Use support=[1,0,0] so that w0_x → X-axis, w0_y → Z-axis + @testset "Free-space field — elliptical profile (wx ≠ wy)" begin + λ = 633e-9 + w0_x = 1e-4 + w0_y = 2e-4 + beam = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, w0_x, w0_y; + E0 = [0, 0, 1], support = [1, 0, 0]) + + z_eval = 0.05 + zRx = π * w0_x^2 / λ + zRy = π * w0_y^2 / λ + wx_z = w0_x * sqrt(1 + (z_eval / zRx)^2) + wy_z = w0_y * sqrt(1 + (z_eval / zRy)^2) + + I0 = BMO.intensity(beam, [0, 0, 0], z_eval) + + # X-axis profile → w0_x direction (s1=[1,0,0]) + rs_x = LinRange(-3wx_z, 3wx_z, 51) + Ix = [BMO.intensity(beam, [r, 0, 0], z_eval) for r in rs_x] + Ix_ana = [I0 * exp(-2 * r^2 / wx_z^2) for r in rs_x] + @test all(isapprox.(Ix, Ix_ana; rtol = 1e-3)) + + # Z-axis profile → w0_y direction (s2=[0,0,-1]) + rs_z = LinRange(-3wy_z, 3wy_z, 51) + Iz = [BMO.intensity(beam, [0, 0, r], z_eval) for r in rs_z] + Iz_ana = [I0 * exp(-2 * r^2 / wy_z^2) for r in rs_z] + @test all(isapprox.(Iz, Iz_ana; rtol = 1e-3)) + end + + @testset "Energy conservation during propagation" begin + λ = 633e-9 + w0 = 1e-4 + beam = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, w0; + E0 = [0, 0, 1], support = [1, 0, 0]) + + # I_peak(z) * |area(z)| should be constant (energy conservation) + function peak_times_area(beam, z) + I_peak = BMO.intensity(beam, [0, 0, 0], z) + p0, i = BMO.point_on_beam(beam, z) + h1, _, h2, _, _ = BMO.parabasal_ray_parameters(beam, p0, i) + dir = BMO.direction(BMO.rays(beam.c)[i]) + area = abs(BMO._pseudo_cross2d(h1, h2, dir)) + return I_peak * area + end + + P0 = peak_times_area(beam, 0.0) + P1 = peak_times_area(beam, 0.1) + P2 = peak_times_area(beam, 0.5) + @test isapprox(P0, P1; rtol = 1e-6) + @test isapprox(P0, P2; rtol = 1e-6) + end + + @testset "Optical power invariant" begin + λ = 633e-9 + w0_x = 1e-4 + w0_y = 3e-4 + beam = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, w0_x, w0_y; + E0 = [0, 0, 1], support = [1, 0, 0]) + P = BMO.optical_power(beam) + @test P > 0 + @test isfinite(P) + end + + @testset "Peak intensity scaling with beam area" begin + λ = 633e-9 + w0_x = 1e-4 + w0_y = 2e-4 + beam = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, w0_x, w0_y; + E0 = [0, 0, 1], support = [1, 0, 0]) + + I0 = BMO.intensity(beam, [0, 0, 0], 0.0) + p0_0, i0 = BMO.point_on_beam(beam, 0.0) + h1_0, _, h2_0, _, _ = BMO.parabasal_ray_parameters(beam, p0_0, i0) + dir0 = BMO.direction(BMO.rays(beam.c)[i0]) + area0 = abs(BMO._pseudo_cross2d(h1_0, h2_0, dir0)) + + for z in [0.02, 0.05, 0.1, 0.2] + Iz = BMO.intensity(beam, [0, 0, 0], z) + p0_z, iz = BMO.point_on_beam(beam, z) + h1_z, _, h2_z, _, _ = BMO.parabasal_ray_parameters(beam, p0_z, iz) + dir_z = BMO.direction(BMO.rays(beam.c)[iz]) + area_z = abs(BMO._pseudo_cross2d(h1_z, h2_z, dir_z)) + expected_ratio = area0 / area_z + @test isapprox(Iz / I0, expected_ratio; rtol = 1e-4) + end + end + + @testset "Astigmatic Gouy phase" begin + λ = 633e-9 + w0_x = 1e-4 + w0_y = 2e-4 + beam = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, w0_x, w0_y; + E0 = [0, 0, 1], support = [1, 0, 0]) + + zRx = π * w0_x^2 / λ + zRy = π * w0_y^2 / λ + k = 2π / λ + + for z_eval in [0.01, 0.03, 0.05] + E = BMO.electric_field(beam, [0, 0, 0], z_eval) + actual_phase = angle(E * exp(-im * k * z_eval)) + # AGB now matches standard convention → negative Gouy phase + expected_gouy = -(0.5 * atan(z_eval / zRx) + 0.5 * atan(z_eval / zRy)) + @test isapprox(actual_phase, expected_gouy; atol = 1e-3) + end + end + + @testset "Transverse phase curvature" begin + λ = 633e-9 + w0_x = 1e-4 + w0_y = 2e-4 + beam = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, w0_x, w0_y; + E0 = [0, 0, 1], support = [1, 0, 0]) + + z_eval = 0.1 + k = 2π / λ + E_center = BMO.electric_field(beam, [0, 0, 0], z_eval) + + # X direction → w0_x → zRx + x_off = 1e-5 + E_x = BMO.electric_field(beam, [x_off, 0, 0], z_eval) + Δϕ_x = angle(E_x / E_center) + zRx = π * w0_x^2 / λ + Rx = z_eval * (1 + (zRx / z_eval)^2) + expected_Δϕ_x = k * x_off^2 / (2 * Rx) + @test isapprox(Δϕ_x, expected_Δϕ_x; rtol = 5e-2) + + # Z direction → w0_y → zRy + z_off = 1e-5 + E_z = BMO.electric_field(beam, [0, 0, z_off], z_eval) + Δϕ_z = angle(E_z / E_center) + zRy = π * w0_y^2 / λ + Ry = z_eval * (1 + (zRy / z_eval)^2) + expected_Δϕ_z = k * z_off^2 / (2 * Ry) + @test isapprox(Δϕ_z, expected_Δϕ_z; rtol = 5e-2) + end + + # ── Polarization ── + + @testset "Polarization preserved in free-space" begin + λ = 633e-9 + w0 = 1e-4 + beam = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, w0; + E0 = [0, 0, 1], support = [1, 0, 0]) + chief = first(BMO.rays(beam.c)) + E = BMO.polarization(chief) + @test isapprox(normalize(real.(E)), [0, 0, 1]; atol = 1e-10) + end + + @testset "Polarization rotated by mirror reflection" begin + λ = 633e-9 + w0 = 1e-4 + m = BMO.SquarePlanoMirror(0.05, 0.01) + BMO.translate3d!(m, [0, 0.05, 0]) + system = BMO.System([m]) + beam = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, w0; + E0 = [0, 0, 1], support = [1, 0, 0]) + solve_system!(system, beam) + reflected_chief = last(BMO.rays(beam.c)) + @test isapprox(BMO.direction(reflected_chief)[2], -1.0; atol = 0.01) + E = BMO.polarization(reflected_chief) + d = BMO.direction(reflected_chief) + @test abs(dot(real.(E), d)) < 1e-10 + end + + @testset "Auto-E0 orthogonality for tilted beams" begin + for dir in [[1, 1, 0], [0, 1, 1], [1, 1, 1], [1, 0, 0]] + beam = AstigmaticGaussianBeamlet( + [0.0, 0, 0], Float64.(dir), 633e-9, 1e-4) + chief = first(BMO.rays(beam.c)) + E = BMO.polarization(chief) + d = BMO.direction(chief) + @test abs(dot(real.(E), d)) < 1e-10 + # Ensure magnitude corresponds to the default P0 = 1e-3 + @test isapprox(BMO.optical_power(beam), 1e-3; atol = 1e-10) + end + end + + @testset "Detector integrated power" begin + λ = 633e-9 + w0 = 0.5mm + pd = BMO.Detector(10mm) + BMO.translate3d!(pd, [0, 0.05, 0]) + system = BMO.System([pd]) + beam = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, w0; + E0 = [0, 0, 1], support = [1, 0, 0]) + solve_system!(system, beam) + + xs, zs, E = BMO.electric_field(pd; n = 50) + @test size(E) == (50, 50) + @test any(!iszero, E) + + I = abs2.(E) + max_idx = argmax(I) + mid = size(I, 1) ÷ 2 + 1 + @test abs(max_idx[1] - mid) < 5 + @test abs(max_idx[2] - mid) < 5 + end + + @testset "Detector power self-consistency" begin + # Detector power at two different distances should scale with beam area + λ = 633e-9 + w0 = 0.5mm + pd_size = 10mm + + pd1 = BMO.Detector(pd_size) + BMO.translate3d!(pd1, [0, 0.05, 0]) + s1 = BMO.System([pd1]) + b1 = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, w0; + E0 = [0, 0, 1], support = [1, 0, 0]) + solve_system!(s1, b1) + P1 = BMO.optical_power(pd1; + n = 80, x_min = -pd_size / 2, x_max = pd_size / 2, + z_min = -pd_size / 2, z_max = pd_size / 2) + + pd2 = BMO.Detector(pd_size) + BMO.translate3d!(pd2, [0, 0.10, 0]) + s2 = BMO.System([pd2]) + b2 = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, w0; + E0 = [0, 0, 1], support = [1, 0, 0]) + solve_system!(s2, b2) + P2 = BMO.optical_power(pd2; + n = 80, x_min = -pd_size / 2, x_max = pd_size / 2, + z_min = -pd_size / 2, z_max = pd_size / 2) + + # Power should be conserved (both detectors capture full beam) + @test isapprox(P1, P2; rtol = 0.05) + end + + @testset "Beamsplitter power conservation" begin + λ = 633e-9 + w0 = 0.5mm + bs = BMO.ThinBeamsplitter(10mm; reflectance = 0.5) + BMO.zrotate3d!(bs, deg2rad(45)) + + pd_t = BMO.Detector(10mm) + pd_r = BMO.Detector(10mm) + BMO.translate3d!(pd_t, [0, 0.1, 0]) + BMO.zrotate3d!(pd_t, deg2rad(180)) + BMO.translate3d!(pd_r, [0.1, 0, 0]) + BMO.zrotate3d!(pd_r, deg2rad(90)) + + # Reference: single beam straight to detector (no BS) + pd_ref = BMO.Detector(10mm) + BMO.translate3d!(pd_ref, [0, 0.1, 0]) + BMO.zrotate3d!(pd_ref, deg2rad(180)) + + pd_size = 10mm + kw = (n = 80, x_min = -pd_size / 2, x_max = pd_size / 2, + z_min = -pd_size / 2, z_max = pd_size / 2) + + # Measure reference power (no BS) + sys_ref = BMO.System([pd_ref]) + b_ref = AstigmaticGaussianBeamlet( + [0.0, -0.1, 0], [0, 1, 0], λ, w0; + E0 = [0, 0, 1], support = [1, 0, 0]) + solve_system!(sys_ref, b_ref) + P_ref = BMO.optical_power(pd_ref; kw...) + + # Measure split power + system = BMO.System([bs, pd_t, pd_r]) + beam = AstigmaticGaussianBeamlet( + [0.0, -0.1, 0], [0, 1, 0], λ, w0; + E0 = [0, 0, 1], support = [1, 0, 0]) + solve_system!(system, beam) + @test length(beam.children) == 2 + + P_t = BMO.optical_power(pd_t; kw...) + P_r = BMO.optical_power(pd_r; kw...) + + # P_t + P_r ≈ P_ref (lossless beamsplitter) + @test isapprox(P_t + P_r, P_ref; rtol = 0.15) + end + + @testset "Michelson fringe contrast" begin + λ = 633e-9 + w0 = 0.5mm + l0 = 0.1 + + m1 = BMO.SquarePlanoMirror2D(BMO.inch) + m2 = BMO.SquarePlanoMirror2D(BMO.inch) + bs = BMO.ThinBeamsplitter(BMO.inch; reflectance = 0.5) + pd = BMO.Detector(10mm) + + BMO.translate3d!(m1, [l0, 0, 0]) + BMO.translate3d!(m2, [0, l0, 0]) + BMO.translate3d!(pd, [-l0, 0, 0]) + BMO.zrotate3d!(bs, deg2rad(45)) + BMO.zrotate3d!(m1, deg2rad(90)) + BMO.zrotate3d!(pd, deg2rad(90)) + + system = BMO.System([m1, m2, bs, pd]) + + pd_size = 10mm + Npts = 9 + offsets = LinRange(0, λ, Npts) + powers = zeros(Npts) + + for (i, δ) in enumerate(offsets) + BMO.translate_to3d!(m2, [0, l0 + δ, 0]) + beam = AstigmaticGaussianBeamlet( + [0.0, -l0, 0], [0, 1, 0], λ, w0; + E0 = [0, 0, 1], support = [1, 0, 0]) + BMO.empty!(pd) + solve_system!(system, beam) + powers[i] = BMO.optical_power(pd; + n = 60, x_min = -pd_size / 2, x_max = pd_size / 2, + z_min = -pd_size / 2, z_max = pd_size / 2) + end + + # Signal periodic with period λ + @test isapprox(powers[1], powers[end]; rtol = 0.1, atol = 1e-10) + + # Fringe contrast > 50% + P_max = maximum(powers) + P_min = minimum(powers) + contrast = (P_max - P_min) / (P_max + P_min) + @test contrast > 0.5 + end + + @testset "Field symmetry" begin + λ = 633e-9 + w0 = 1e-4 + beam = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, w0; + E0 = [0, 0, 1], support = [1, 0, 0]) + + z_eval = 0.05 + for r in [1e-5, 3e-5, 5e-5] + Ep_x = BMO.electric_field(beam, [r, 0, 0], z_eval) + Em_x = BMO.electric_field(beam, [-r, 0, 0], z_eval) + @test isapprox(Ep_x, Em_x; rtol = 1e-10) + + Ep_z = BMO.electric_field(beam, [0, 0, r], z_eval) + Em_z = BMO.electric_field(beam, [0, 0, -r], z_eval) + @test isapprox(Ep_z, Em_z; rtol = 1e-10) + end + end + + @testset "Stigmatic AGB matches standard GaussianBeamlet" begin + λ = 1000e-9 + w0 = 1e-4 + # Both use same support direction + agb = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, w0; + E0 = [0, 0, 1], support = [1, 0, 0]) + gb = GaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, w0; + support = [1, 0, 0]) + + z_eval = 0.08 + rs = LinRange(-3e-3, 3e-3, 51) + + E_agb = [BMO.electric_field(agb, [r, 0, 0], z_eval) for r in rs] + E_gb = [BMO.electric_field(gb, abs(r), z_eval) for r in rs] + + # Compare intensity profiles (normalized to peak) + I_agb = abs2.(E_agb) + I_gb = abs2.(E_gb) + I_agb_norm = I_agb / maximum(I_agb) + I_gb_norm = I_gb / maximum(I_gb) + @test all(isapprox.(I_agb_norm, I_gb_norm; rtol = 1e-3)) + end + + @testset "Invariant Violation Test" begin + λ = 532nm + w0 = 0.1mm + + # Create a highly non-paraxial setup: + # A flat plate tilted at an extreme angle (80 degrees) + surf1 = BMO.CircularFlatSurface(10.0mm) + surf2 = BMO.CircularFlatSurface(10.0mm) + + # n=2.0 (high index) + lens = BMO.Lens(surf1, surf2, 1.0mm, λ -> 2.0) + + # Tilt the lens by 80 degrees + BMO.zrotate3d!(lens, deg2rad(80)) + BMO.translate3d!(lens, [0, 1.0mm, 0]) + + # Set threshold very low to trigger violation (central diffs are very accurate) + strict_threshold = 1e-13 + + system = BMO.System([lens]) + + # Create a beamlet pointing at the lens + beam = AstigmaticGaussianBeamlet( + [0.0, 0, 0], [0, 1, 0], λ, 0.05mm; support = [1, 0, 0]) + + # Reset beam for the actual test + beam = AstigmaticGaussianBeamlet( + [0.4mm, 0, 0], [0, 1, 0], λ, 0.05mm; support = [1, 0, 0]) + + @test_logs (:warn, r"Lagrange invariant violation") match_mode=:any BMO.solve_system!( + system, beam; threshold = strict_threshold) + + # Verify that the beam stopped tracing once the invariant failed + # (solve_system calls trace_system! which has a break on invariant failure) + @test length(BMO.rays(beam.c)) < 10 # It should stop early + end +end # outer testset + +end # MODULE diff --git a/test/TestAstigmaticGaussianSources.jl b/test/TestAstigmaticGaussianSources.jl new file mode 100644 index 000000000..68a854d0f --- /dev/null +++ b/test/TestAstigmaticGaussianSources.jl @@ -0,0 +1,186 @@ +module TestAstigmaticGaussianSources + +using BeamletOptics +using Test +using LinearAlgebra + +const BMO = BeamletOptics +const mm = 1e-3 +const nm = 1e-9 + +@testset "Astigmatic Gaussian Beamlet Sources" begin + λ = 532nm + dir = [0.0, 1.0, 0.0] + pos = [0.0, 0.0, 0.0] + + @testset "CollimatedGaussianBeamletSource" begin + D = 2mm + w0s = D / 10 + bg = CollimatedGaussianBeamletSource(pos, dir, D, λ, w0s; n_grid = 10) + @test bg isa AstigmaticBeamGroup + beams = BMO.beams(bg) + + @test length(beams) == 100 + # Check all point in the right direction + @test all(normalize(BMO.direction(b)) ≈ dir for b in bg) + # Check all have the correct sub-waist + for b in beams + _, w1, _ = BMO.waist_parameters(b, 0.0) + @test norm(w1) ≈ w0s + end + end + + @testset "GaussianBeamletDecomposition" begin + w0 = 1mm + # A 21x21 grid will trim beamlets with amp < 1e-4, so length will be < 441 + bg = GaussianBeamletDecomposition(pos, dir, λ, w0; n_grid = 21) + @test bg isa AstigmaticBeamGroup + beams = BMO.beams(bg) + + @test length(beams) > 0 + @test length(beams) <= 441 + + # Find the beamlet with the maximum amplitude + center_beam = argmax([norm(BMO.polarization(b)) for b in bg]) + + # The peak amplitude beamlet should be at the center (0, 0, 0) + @test norm(BMO.position(bg[center_beam]) - pos)≈0.0 atol=1e-5 + end + + @testset "SphericalGaussianBeamletSource" begin + θ = 0.1 # radians + bg = SphericalGaussianBeamletSource(pos, dir, θ, λ; num_rings = 5, num_rays = 500) + @test bg isa AstigmaticBeamGroup + + @test length(bg) == 500 + # Check they all originate from pos + @test all(BMO.position(b) ≈ pos for b in bg) + end + + @testset "EllipticalGaussianBeamletSource" begin + θ_x = 0.2 + θ_y = 0.1 + bg = EllipticalGaussianBeamletSource(pos, dir, θ_x, θ_y, λ; num_rings = 5, num_rays = 500) + @test bg isa AstigmaticBeamGroup + + @test length(bg) == 500 + # Check they all originate from pos + @test all(BMO.position(b) ≈ pos for b in bg) + + # Check directions are within the elliptical cone + dir_n = normalize(dir) + b1 = BMO.normal3d(dir_n) + b2 = cross(dir_n, b1) + + for b in bg + d = BMO.direction(b) + # project on tangent plane using local basis + u = dot(d, b1) / dot(d, dir_n) + v = dot(d, b2) / dot(d, dir_n) + @test (u / tan(θ_x))^2 + (v / tan(θ_y))^2 <= 1.05 + end + end + + @testset "WavefrontBeamletDecomposition" begin + # Generate a synthetic wavefront (a tilted plane wave) + nx, ny = 11, 11 + x = LinRange(-1mm, 1mm, nx) + y = LinRange(-1mm, 1mm, ny) + + amp = ones(nx, ny) + # Tilt in x by angle alpha + alpha = 0.001 + k = 2π / λ + phase = [k * xi * alpha for xi in x, yi in y] + + bg = WavefrontBeamletDecomposition(x, y, amp, phase, dir, λ) + @test bg isa AstigmaticBeamGroup + + @test length(bg) == nx * ny + + # We check the direction of the beamlets + # The true local propagation direction should be tilted by alpha + for b in bg + d = normalize(BMO.direction(b)) + # Projection onto the original dir should be approximately cos(alpha) + @test dot(d, dir)≈cos(alpha) atol=1e-3 + end + end + + @testset "WavefrontBeamletDecomposition Energy Conservation" begin + # Define a simple Gaussian wavefront + λ = 1e-6 + w0_input = 1.0e-3 # 1 mm + k = 2π / λ + + # Grid + L = 5.0e-3 # 5 mm total width + N = 41 + x = LinRange(-L / 2, L / 2, N) + y = LinRange(-L / 2, L / 2, N) + dx = x[2] - x[1] + dy = y[2] - y[1] + + X = [xi for xi in x, yi in y] + Y = [yi for xi in x, yi in y] + R2 = X .^ 2 .+ Y .^ 2 + + # Input field: A = exp(-r^2/w0^2) + # Total power P = integral |A|^2 dA / (2Z) = pi * w0^2 / 4Z + amplitude = exp.(-R2 / w0_input^2) + phase = zeros(size(amplitude)) # Flat wavefront + + dir = [0.0, 0.0, 1.0] + + # Decomposition + overlap = 1.2 + w0_beamlet = dx * overlap + + # The normalization in the code is for AMPLITUDE reconstruction. + # E0 = A * (dx * dy) / (pi * w0s^2) + # Let's see if this leads to power conservation. + + bg = WavefrontBeamletDecomposition( + x, y, amplitude, phase, dir, λ; overlap = overlap, threshold = 1e-6) + + # Total power of beamlets (sum of individual powers) + P_beamlets_sum = sum(optical_power(b) for b in bg.beams) + + # Total power of input field (discrete integral) + # Using Z_vacuum to match library defaults + P_input = sum(abs2.(amplitude)) * (dx * dy) / (2 * BeamletOptics.Z_vacuum) + + if length(bg.beams) > 0 + b1 = bg.beams[1] + params1 = BeamletOptics.gauss_parameters(b1, 0.0) + end + + # Reconstructed field power at z=0 + # Sample on a finer grid to check field reconstruction + N_fine = 81 + x_fine = LinRange(-L / 2, L / 2, N_fine) + y_fine = LinRange(-L / 2, L / 2, N_fine) + dx_f = x_fine[2] - x_fine[1] + dy_f = y_fine[2] - y_fine[1] + + E_rec = zeros(ComplexF64, N_fine, N_fine) + for (ii, xf) in enumerate(x_fine) + for (jj, yf) in enumerate(y_fine) + r_vec = [xf, yf, 0.0] + # Sum up contributions from all beamlets (coherent superposition) + for b in bg.beams + p0 = BeamletOptics.position(b) + # For flat wavefront at z=0, the polarized field is appropriate + E_rec[ii, jj] += norm(BeamletOptics.polarized_field(b, r_vec - p0, 0.0)) + end + end + end + + P_rec = sum(abs2.(E_rec)) * (dx_f * dy_f) / (2 * BeamletOptics.Z_vacuum) + + # The coherent reconstruction should ideally match the input power + @test isapprox(P_rec / P_input, 1.0, atol = 0.05) + end +end + +end # MODULE diff --git a/test/TestBugFixes.jl b/test/TestBugFixes.jl index fb998b255..0629421e5 100644 --- a/test/TestBugFixes.jl +++ b/test/TestBugFixes.jl @@ -3,6 +3,7 @@ module TestBugFixes using BeamletOptics using LinearAlgebra using Test +using Logging const BMO = BeamletOptics @@ -21,57 +22,58 @@ const mm = 1e-3 system = BMO.System([pd]) empty!(pd) BMO.solve_system!(system, beam) - + pd_pwr = optical_power( pd; # restore pre-v0.11 behavior, e.g. no autolims - n=pd_res, - x_min=-pd_size/2, - x_max=pd_size/2, - z_min=-pd_size/2, - z_max=pd_size/2 + n = pd_res, + x_min = -pd_size / 2, + x_max = pd_size / 2, + z_min = -pd_size / 2, + z_max = pd_size / 2 ) - + @test pd_pwr≈10e-3 atol=1e-5 end @testset "Issue#22 and Issue#23" begin # https://github.com/JuliaPhysics/BeamletOptics.jl/issues/22 # https://github.com/JuliaPhysics/BeamletOptics.jl/issues/23 - - mutable struct TestSubstrate{T, S <: BMO.AbstractShape{T}, N} <: BMO.AbstractRefractiveOptic{T, N} + + mutable struct TestSubstrate{T, S <: BMO.AbstractShape{T}, N} <: + BMO.AbstractRefractiveOptic{T, N} const shape::S n::N end - + BMO.refractive_index(ts::TestSubstrate, ::Real) = ts.n set_index(ts::TestSubstrate, new) = (ts.n = new) get_index(ts::TestSubstrate) = ts.n - + "Shifts the phase of the beamlet by a specific amount in [rad]." function shift_phase(gb::BMO.GaussianBeamlet, phase::Real) - BMO.electric_field!(gb, BMO.electric_field(gb) * exp(im*phase)) + BMO.electric_field!(gb, BMO.electric_field(gb) * exp(im * phase)) return nothing end - - ref_signal(ϕ, A) = (cos(ϕ)+1)/2 * A - + + ref_signal(ϕ, A) = (cos(ϕ) + 1) / 2 * A + # setup system for tests below - splitter = CubeBeamsplitter(10mm, n->1) + splitter = CubeBeamsplitter(10mm, n -> 1) substrate_length = 10mm - substrate = TestSubstrate(BMO.CylinderSDF(5mm, substrate_length/2), 1.5) - + substrate = TestSubstrate(BMO.CylinderSDF(5mm, substrate_length / 2), 1.5) + pd_size = 10mm pd_res = 250 detector = Detector(pd_size) - + translate3d!(substrate, [0, -25mm, 0]) translate3d!(detector, [0, 40mm, 0]) - + system = System([substrate, splitter, detector]) - + start_offset = 50mm - + @testset "Testing electric_field calculation - non-imaging ref. index change" begin indices = (1, 10, 100, 1000) for index in indices @@ -79,43 +81,43 @@ end phi = LinRange(0, 2pi, 30) int = zeros(length(phi)) for (i, p) in enumerate(phi) - gb_prb = GaussianBeamlet([0, -start_offset, 0], [0, 1, 0], 1e-6, .5mm) - gb_ref = GaussianBeamlet([start_offset, 0, 0], [-1, 0, 0], 1e-6, .5mm) + gb_prb = GaussianBeamlet([0, -start_offset, 0], [0, 1, 0], 1e-6, 0.5mm) + gb_ref = GaussianBeamlet([start_offset, 0, 0], [-1, 0, 0], 1e-6, 0.5mm) empty!(detector) shift_phase(gb_ref, p) solve_system!(system, gb_prb) solve_system!(system, gb_ref) int[i] = BMO.optical_power(detector) end - @test isapprox(BMO.visibility(int), 1, atol=1e-2) + @test isapprox(BMO.visibility(int), 1, atol = 1e-2) end end - + @testset "Testing electric_field calculation - ref. index based phase shift" begin λ = 1e-6 - gb_prb = GaussianBeamlet([0, -start_offset, 0], [0, 1, 0], λ, .5mm) - gb_ref = GaussianBeamlet([start_offset, 0, 0], [-1, 0, 0], λ, .5mm) - + gb_prb = GaussianBeamlet([0, -start_offset, 0], [0, 1, 0], λ, 0.5mm) + gb_ref = GaussianBeamlet([start_offset, 0, 0], [-1, 0, 0], λ, 0.5mm) + n_lambdas = substrate_length / BMO.wavelength(gb_prb) - + n_factors = LinRange(0, 1, 50) pwr = zeros(length(n_factors)) # Increase ref. index of substrate until one additional λ of OPL has been introduced for (i, nf) in enumerate(n_factors) - set_index(substrate, 1 + 1/n_lambdas * nf) + set_index(substrate, 1 + 1 / n_lambdas * nf) empty!(detector) solve_system!(system, gb_prb) solve_system!(system, gb_ref) pd_pwr = optical_power( detector; # restore pre-v0.11 behavior, e.g. no autolims - n=pd_res, - x_min=-pd_size/2, - x_max=pd_size/2, - z_min=-pd_size/2, - z_max=pd_size/2 + n = pd_res, + x_min = -pd_size / 2, + x_max = pd_size / 2, + z_min = -pd_size / 2, + z_max = pd_size / 2 ) - @test isapprox(pd_pwr, ref_signal(2pi*nf, 2e-3), atol=1e-8) + @test isapprox(pd_pwr, ref_signal(2pi * nf, 2e-3), atol = 1e-8) end # Test if opl difference is indeed one λ delta = BMO.optical_path_length(gb_prb) @@ -123,13 +125,13 @@ end delta /= λ @test delta ≈ 1 end - - @testset "Testing electric_field mutation during retracing" begin - gb_prb = GaussianBeamlet([0, -start_offset, 0], [0, 1, 0], 1e-6, .5mm) - gb_ref = GaussianBeamlet([start_offset, 0, 0], [-1, 0, 0], 1e-6, .5mm) + + @testset "Testing electric_field mutation during retracing" begin + gb_prb = GaussianBeamlet([0, -start_offset, 0], [0, 1, 0], 1e-6, 0.5mm) + gb_ref = GaussianBeamlet([start_offset, 0, 0], [-1, 0, 0], 1e-6, 0.5mm) phis = LinRange(0, 2pi, 50) pwr = zeros(length(phis)) - # Vary starting phase by 0...2pi via retracing + # Vary starting phase by 0...2pi via retracing for (i, phi) in enumerate(phis) empty!(detector) solve_system!(system, gb_prb) @@ -137,13 +139,13 @@ end pd_pwr = optical_power( detector; # restore pre-v0.11 behavior, e.g. no autolims - n=pd_res, - x_min=-pd_size/2, - x_max=pd_size/2, - z_min=-pd_size/2, - z_max=pd_size/2 + n = pd_res, + x_min = -pd_size / 2, + x_max = pd_size / 2, + z_min = -pd_size / 2, + z_max = pd_size / 2 ) - @test isapprox(pd_pwr, ref_signal(phi, 2e-3), atol=1e-8) + @test isapprox(pd_pwr, ref_signal(phi, 2e-3), atol = 1e-8) shift_phase(gb_prb, step(phis)) end end @@ -151,7 +153,7 @@ end @testset "Issue#51" begin # https://github.com/JuliaPhysics/BeamletOptics.jl/issues/51 - mirror = BeamletOptics.ConcaveSphericalMirror(0.1,0.01,0.2) + mirror = BeamletOptics.ConcaveSphericalMirror(0.1, 0.01, 0.2) system = StaticSystem([mirror]) beam = Beam([0, -0.19, 0.07], [0.0, 1, 0]) solve_system!(system, beam) @@ -167,4 +169,64 @@ end end end -end # MODULE \ No newline at end of file +@testset "PlateBeamsplitter BoundsError" begin + # Issue: Newborn child beams only contain one ray. Indexing rays(beam)[id] + # where id > 1 throws a BoundsError in interact3d for AstigmaticGaussianBeamlet. + + # 1 lens followed by 1 plate beamsplitter + lens = ThinLens(Inf, 50mm, 25mm, 1.5) + BMO.translate3d!(lens, [0, 50mm, 0]) + + pbs = RoundPlateBeamsplitter(25mm, 5mm, λ -> 1.5) + BMO.translate3d!(pbs, [0, 100mm, 0]) + + system = System([lens, pbs]) + + # Astigmatic beamlet starting at origin + agb = AstigmaticGaussianBeamlet([0, 0, 0], [0, 1, 0], 1e-6, 1mm) + + # This should not throw BoundsError + @test_nowarn solve_system!(system, agb) + + # Verify we have children (splitting happened) + @test length(BMO.children(agb)) == 2 +end + +@testset "Retrace Tail Trimming Consistency" begin + # Issue: When retracing reaches the old tail (i == n_c), a new segment + # can be pushed and then rejected by check_optical_invariant. + # Stale n_c caused inconsistent trimming between chief and aux beams. + + # We need a system where we can trigger an invariant violation during retrace. + # We'll use a very small invariant threshold to make it easy to trigger. + strict_threshold = 1e-15 + + # A simple plane surface + surf = RoundPlanoMirror(50mm, 5mm) + BMO.translate3d!(surf, [0, 50mm, 0]) + system = System([surf]) + + # Initial trace: 1 segment (2 rays) + agb = AstigmaticGaussianBeamlet([0, 0, 0], [0, 1, 0], 1e-6, 1mm) + + with_logger(NullLogger()) do + # Use strict threshold for this call + solve_system!(system, agb; threshold = strict_threshold) + + n_initial = length(BMO.rays(agb.c)) + @test n_initial == 2 + + # Now move the surface further away such that retracing will + # reach the old tail and try to push a new segment. + BMO.translate3d!(surf, [0, 10mm, 0]) + + # Also tilt it or change parameters to trigger invariant violation if possible. + BMO.retrace_system!(system, agb; threshold = strict_threshold) + end + + # Verification of consistency + lengths = map(b -> length(BMO.rays(b)), BMO._component_beams(agb)) + @test all(==(lengths[1]), lengths) +end + +end # MODULE diff --git a/test/TestPolarizedRays.jl b/test/TestPolarizedRays.jl index ef485ae65..ec0221a69 100644 --- a/test/TestPolarizedRays.jl +++ b/test/TestPolarizedRays.jl @@ -70,7 +70,7 @@ const BMO = BeamletOptics @test BMO.polarization(beam.rays[2]) ≈ [0, 0, -I0_1] @test BMO.polarization(beam.rays[3]) ≈ [0, 0, I0_1] @test BMO.polarization(beam.rays[4]) ≈ [0, -I0_1, 0] - @test length(beam) == 6.0 + @test length(beam) ≈ 6.0 end @testset "y-Polarization" begin @@ -82,7 +82,7 @@ const BMO = BeamletOptics @test BMO.polarization(beam.rays[2]) ≈ [0, -I0_2, 0] @test BMO.polarization(beam.rays[3]) ≈ [I0_2, 0, 0] @test BMO.polarization(beam.rays[4]) ≈ [-I0_2, 0, 0] - @test length(beam) == 8.0 + @test length(beam) ≈ 8.0 end end diff --git a/test/runtests.jl b/test/runtests.jl index 0834fd352..a79d9c3d6 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -8,6 +8,9 @@ include(joinpath(@__DIR__, "TestPolarizedRays.jl")) include(joinpath(@__DIR__, "TestBeams.jl")) include(joinpath(@__DIR__, "TestBeamGroups.jl")) include(joinpath(@__DIR__, "TestGaussianBeamlet.jl")) +include(joinpath(@__DIR__, "TestAstigmaticGaussianBeamlet.jl")) +include(joinpath(@__DIR__, "TestAstigmaticGaussianPhysical.jl")) +include(joinpath(@__DIR__, "TestAstigmaticGaussianSources.jl")) # Test geometry representation include(joinpath(@__DIR__, "Geometry", "TestMesh.jl")) @@ -25,6 +28,7 @@ include(joinpath(@__DIR__, "Lenses", "TestCylindricalLenses.jl")) # Test component models include(joinpath(@__DIR__, "Components", "TestDummies.jl")) +include(joinpath(@__DIR__, "Components", "TestDetectorUtils.jl")) include(joinpath(@__DIR__, "Components", "TestDetector.jl")) include(joinpath(@__DIR__, "Components", "TestBeamsplitters.jl")) include(joinpath(@__DIR__, "Components", "TestPolarizers.jl")) @@ -33,6 +37,7 @@ include(joinpath(@__DIR__, "Components", "TestPolarizers.jl")) include(joinpath(@__DIR__, "E2E", "TestDoubleGaussLens.jl")) include(joinpath(@__DIR__, "E2E", "TestMichelson.jl")) include(joinpath(@__DIR__, "E2E", "TestMachZehnder.jl")) +include(joinpath(@__DIR__, "E2E", "TestFraunhofer.jl")) # Test regressions include(joinpath(@__DIR__, "TestBugFixes.jl"))