diff --git a/Project.toml b/Project.toml index f7a289301..832916f11 100644 --- a/Project.toml +++ b/Project.toml @@ -17,7 +17,6 @@ Preferences = "21216c6a-2e73-6563-6e65-726566657250" ProgressMeter = "92933f4c-e287-5a05-a399-4b506db050ca" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" -Trapz = "592b5752-818d-11e9-1e9a-2b8ca4a44cd1" [weakdeps] Makie = "ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a" @@ -43,7 +42,6 @@ Preferences = "1.5.2" ProgressMeter = "1.11" Random = "1" StaticArrays = "1" -Trapz = "2" julia = "1.12" [workspace] diff --git a/docs/src/api/api.md b/docs/src/api/api.md index d36ea1036..c50f9d49f 100644 --- a/docs/src/api/api.md +++ b/docs/src/api/api.md @@ -12,4 +12,4 @@ Depth = 2 ## Public API for dependent packages -Besides the exported names, a few names are declared `public` in `src/Exports.jl` without being exported, e.g. `BeamletOptics.is_static`, `BeamletOptics.hit_count`, the progress interface `BeamletOptics.ProgressSink`, the sampling of the sources `BeamletOptics.AbstractSampling`, the optional `BeamletOptics.bounding_sphere_of` of a shape (see [Bounding sphere pretest](@ref)), `BeamletOptics.AbstractObjectGroup` for own assembly types of separate parts (see [Assemblies: group or multi-shape object](@ref)), or `BeamletOptics.relaunch!` and the beamlet hit records (`BeamletOptics.AstigmaticGaussianBeamletHit(agb, id)`, `BeamletOptics.beamlet_hit_field`) for components that re-emit light, e.g. solvers coupled through a field (see [Re-emitting components](@ref)). Packages built on BMO, such as [BeamletOpticsGUI](https://github.com/StackEnjoyer/BeamletOpticsGUI.jl), may rely on them like on the exported API; other unexported names are internal and may change in any release. Whether a name is public can be checked with `Base.ispublic(BeamletOptics, name)`. Their docstrings are listed in the [Reference](@ref), the render handle protocol is described on the [Live rendering](@ref "Render handle protocol") page. A new `AbstractObject` subtype can add a method of [`properties`](@ref) to list its own parameters, see [Inspecting components](@ref). +Besides the exported names, a few names are declared `public` in `src/Exports.jl` without being exported, e.g. `BeamletOptics.is_static`, `BeamletOptics.hit_count`, the progress interface `BeamletOptics.ProgressSink`, the sampling of the sources `BeamletOptics.AbstractSourceSampling` and the samplings of a detector `BeamletOptics.AbstractDetectorSampling` with `BeamletOptics.sample_points` (see [Sampling](@ref)), the optional `BeamletOptics.bounding_sphere_of` of a shape (see [Bounding sphere pretest](@ref)), `BeamletOptics.AbstractObjectGroup` for own assembly types of separate parts (see [Assemblies: group or multi-shape object](@ref)), or `BeamletOptics.relaunch!` and the beamlet hit records (`BeamletOptics.AstigmaticGaussianBeamletHit(agb, id)`, `BeamletOptics.beamlet_hit_field`) for components that re-emit light, e.g. solvers coupled through a field (see [Re-emitting components](@ref)). Packages built on BMO, such as [BeamletOpticsGUI](https://github.com/StackEnjoyer/BeamletOpticsGUI.jl), may rely on them like on the exported API; other unexported names are internal and may change in any release. Whether a name is public can be checked with `Base.ispublic(BeamletOptics, name)`. Their docstrings are listed in the [Reference](@ref), the render handle protocol is described on the [Live rendering](@ref "Render handle protocol") page. A new `AbstractObject` subtype can add a method of [`properties`](@ref) to list its own parameters, see [Inspecting components](@ref). diff --git a/docs/src/assets/detector_assets/photodetector_showcase.jl b/docs/src/assets/detector_assets/photodetector_showcase.jl index 4d4ded971..683973535 100644 --- a/docs/src/assets/detector_assets/photodetector_showcase.jl +++ b/docs/src/assets/detector_assets/photodetector_showcase.jl @@ -18,7 +18,7 @@ g2 = GaussianBeamlet([0,-20e-3,0], [0,1,0], 532e-9, 5e-4) solve_system!(system, g1) solve_system!(system, g2) -x, y, I = intensity(pd, n=1000) +x, y, I = intensity(pd, RegularGrid(n=1000)) spots = spot_diagram(pd) ## render fringes diff --git a/docs/src/assets/detector_assets/spotdetector_showcase.jl b/docs/src/assets/detector_assets/spotdetector_showcase.jl index 35890f0c1..244d810cc 100644 --- a/docs/src/assets/detector_assets/spotdetector_showcase.jl +++ b/docs/src/assets/detector_assets/spotdetector_showcase.jl @@ -54,7 +54,7 @@ b2_spots = spot_diagram(pd) empty!(pd) solve_system!(system, b3) -x, z, I = intensity(pd; n=300, crop_factor=1) +x, z, I = intensity(pd, RegularGrid(n=300, crop_factor=1)) empty!(pd) ## diff --git a/docs/src/assets/examples/double_slit.jl b/docs/src/assets/examples/double_slit.jl index 4432c604b..f6836855a 100644 --- a/docs/src/assets/examples/double_slit.jl +++ b/docs/src/assets/examples/double_slit.jl @@ -57,8 +57,8 @@ solve_system!(system, beams) @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) +xs_eval, zs_eval, I = intensity(target_pd, + RegularGrid(n = n_eval, x_min = -15e-3, x_max = 15e-3, z_min = -15e-3, z_max = 15e-3)) ## # Visualization diff --git a/docs/src/assets/examples/polarized_psf_showcase.jl b/docs/src/assets/examples/polarized_psf_showcase.jl index e5136886b..56c997db1 100644 --- a/docs/src/assets/examples/polarized_psf_showcase.jl +++ b/docs/src/assets/examples/polarized_psf_showcase.jl @@ -30,7 +30,7 @@ solve_system!(system, beam) ## NA = sin(2 * atan(D / (4f))) R = 1.5λ / NA -xs, zs, E = electric_field(pd; n = 201, x_min = -R, x_max = R, z_min = -R, z_max = R) +xs, zs, E = electric_field(pd, RegularGrid(n = 201, x_min = -R, x_max = R, z_min = -R, z_max = R)) I = intensity.(E) I0 = maximum(I) diff --git a/docs/src/assets/examples/psfdetector_showcase.jl b/docs/src/assets/examples/psfdetector_showcase.jl index 176805e53..a478e23ab 100644 --- a/docs/src/assets/examples/psfdetector_showcase.jl +++ b/docs/src/assets/examples/psfdetector_showcase.jl @@ -22,7 +22,7 @@ sys = System([lens, psfd]) solve_system!(sys, cs) -x, z, I_num = intensity(psfd; n=500, crop_factor=10) +x, z, I_num = intensity(psfd, RegularGrid(n=500, crop_factor=10)) fringes_fig = Figure() srf = Axis3(fringes_fig[1, 1], xlabel="x [µm]", ylabel="z [µm]", elevation=0.9, azimuth=2.372) @@ -57,7 +57,7 @@ solve_system!(system, ps) asph_fig = Figure(size=(800, 500)) -xs, ys, _intensity = intensity(pd, n=801, x_min=-25e-6, x_max=25e-6, z_min=-25e-6, z_max=25e-6, z0_shift=-50e-6) +xs, ys, _intensity = intensity(pd, RegularGrid(n=801, x_min=-25e-6, x_max=25e-6, z_min=-25e-6, z_max=25e-6, z0_shift=-50e-6)) ax = Axis(asph_fig[1,1], xlabel="x [µm]", ylabel="z [µm]", aspect=1) diff --git a/docs/src/assets/mi_assets/michelson_showcase.jl b/docs/src/assets/mi_assets/michelson_showcase.jl index 8f1e2d37b..23b68b8f3 100644 --- a/docs/src/assets/mi_assets/michelson_showcase.jl +++ b/docs/src/assets/mi_assets/michelson_showcase.jl @@ -216,11 +216,7 @@ save("mi_pd.png", fig; px_per_unit=8, update = false) ## fringe plot x, y, I = intensity( pd, - n=200, - x_min=-pd_size/2, - x_max= pd_size/2, - z_min=-pd_size/2, - z_max= pd_size/2, + RegularGrid(n=200, x_min=-pd_size/2, x_max=pd_size/2, z_min=-pd_size/2, z_max=pd_size/2), ) spots = spot_diagram(pd) @@ -240,11 +236,7 @@ solve_system!(system, beam) x, y, I = intensity( pd, - n=200, - x_min=-pd_size/2, - x_max= pd_size/2, - z_min=-pd_size/2, - z_max= pd_size/2, + RegularGrid(n=200, x_min=-pd_size/2, x_max=pd_size/2, z_min=-pd_size/2, z_max=pd_size/2), ) spots = spot_diagram(pd) diff --git a/docs/src/basics/components/detectors.md b/docs/src/basics/components/detectors.md index 70f25b2c7..179a060b5 100644 --- a/docs/src/basics/components/detectors.md +++ b/docs/src/basics/components/detectors.md @@ -66,12 +66,28 @@ The following image shows the spot diagram of a Sonnar lens. Two [`CollimatedSou Alternatively, the detector data can also be used to reconstruct electric field distributions of incoming beams on its surface using coherent addition. Three readouts build on each other: [`electric_field`](@ref) is the coherent sum of the fields of all hits, [`intensity`](@ref) the flux of the Poynting vector of that field through the detector, and [`optical_power`](@ref) the integral of the intensity. Their definitions follow. ```@docs; canonical=false -electric_field(::Detector) -electric_field(::Detector, ::AbstractVector, ::AbstractVector) +electric_field(::Detector, ::BeamletOptics.AbstractDetectorSampling) electric_field(::BeamletOptics.AbstractDetectorHit, ::AbstractVector) -intensity(::Detector) -intensity(::Detector, ::AbstractVector, ::AbstractVector) -optical_power(::Detector) +intensity(::Detector, ::BeamletOptics.AbstractDetectorSampling) +optical_power(::Detector, ::BeamletOptics.AbstractDetectorSampling) +``` + +### Sampling + +Where on the detector the readouts are evaluated is set by a sampling, the second argument of each readout. It chooses its window, the points in local detector coordinates and the weights with which [`optical_power`](@ref) integrates the intensity. The default is a [`RegularGrid`](@ref) around the hits; a [`RectilinearGrid`](@ref) is a grid of one's own with any spacing. + +```julia +x, z, I = intensity(pd, RegularGrid(n = 200, crop_factor = 5)) +P = optical_power(pd, RectilinearGrid(xs, zs)) +``` + +```@docs; canonical=false +RegularGrid +RectilinearGrid +BeamletOptics.AbstractDetectorSampling +BeamletOptics.sample_points +electric_field(::Detector, ::AbstractArray{<:AbstractVector}) +intensity(::Detector, ::AbstractArray{<:AbstractVector}) ``` ### Gaussian beamlet interference diff --git a/docs/src/examples/psf.md b/docs/src/examples/psf.md index 7e2d7e452..0698b1864 100644 --- a/docs/src/examples/psf.md +++ b/docs/src/examples/psf.md @@ -47,7 +47,7 @@ sys = System([lens, detector]) solve_system!(sys, cs) # retrieve intensity -x, z, I_num = intensity(detector; n=500, crop_factor=10) +x, z, I_num = intensity(detector, RegularGrid(n=500, crop_factor=10)) ``` Visualizing the result yields the expected Airy-disk pattern. @@ -123,7 +123,7 @@ solve_system!(System([mirror, pd]), pol_src) NA = sin(2 * atan(D / (4f))) R = 1.5λ / NA -xs, zs, E = electric_field(pd; n = 201, x_min = -R, x_max = R, z_min = -R, z_max = R) +xs, zs, E = electric_field(pd, RegularGrid(n = 201, x_min = -R, x_max = R, z_min = -R, z_max = R)) I = intensity.(E) # |E|²/(2Z₀) per point, not projected onto the detector Ey = map(e -> abs2(e[2]), E) # longitudinal component diff --git a/docs/src/tutorials/michelson.md b/docs/src/tutorials/michelson.md index bd47bdfe9..d5fe23938 100644 --- a/docs/src/tutorials/michelson.md +++ b/docs/src/tutorials/michelson.md @@ -219,11 +219,7 @@ You can recreate this figure by running the following code: # evaluate intensity, overwrite autlims x, y, I = intensity( pd, - n=200, - x_min=-pd_size/2, - x_max= pd_size/2, - z_min=-pd_size/2, - z_max= pd_size/2, + RegularGrid(n=200, x_min=-pd_size/2, x_max=pd_size/2, z_min=-pd_size/2, z_max=pd_size/2), ) spots = spot_diagram(pd) @@ -244,11 +240,7 @@ solve_system!(system, beam) # reevaluate intensity, overwrite autlims x, y, I = intensity( pd, - n=200, - x_min=-pd_size/2, - x_max= pd_size/2, - z_min=-pd_size/2, - z_max= pd_size/2, + RegularGrid(n=200, x_min=-pd_size/2, x_max=pd_size/2, z_min=-pd_size/2, z_max=pd_size/2), ) spots = spot_diagram(pd) diff --git a/skills/beamletoptics/API.md b/skills/beamletoptics/API.md index a3dcfdcce..04d69f4e5 100644 --- a/skills/beamletoptics/API.md +++ b/skills/beamletoptics/API.md @@ -44,7 +44,7 @@ Use `scripts/api_lookup.jl NAME` to print the docstring and signatures of any na | Splitters | `ThinBeamsplitter`, `RoundThinBeamsplitter`, `RectangularPlateBeamsplitter`, `RoundPlateBeamsplitter`, `CubeBeamsplitter`, `RectangularCompensatorPlate` | | Prisms | `Prism`, `RightAnglePrism`, `EquilateralPrism`, `DovePrism` | | Polarizers | `PolarizationFilter`, `RoundPolarizationFilter`, `LinearPolarizer`, `RoundLinearPolarizer`, `transmission_axis` | -| Detectors | `Detector`, `spot_diagram`, `intensity`, `electric_field`, `optical_power`, `gauss_parameters`, `waist_parameters`, `Centroid`, `MinMax` | +| Detectors | `Detector`, `RegularGrid`, `RectilinearGrid`, `spot_diagram`, `intensity`, `electric_field`, `optical_power`, `gauss_parameters`, `waist_parameters`, `Centroid`, `MinMax` | | Dummies | `NonInteractableObject`, `IntersectableObject` | | Config | `get_default_wavelength`, `get_default_waist`, `get_default_power`, `get_default_r_max`, `get_default_depth_max`, `get_invariant_threshold`, `set_invariant_threshold!`, `get_internal_reflection_threshold`, `get_line_plane_intersection_threshold`, `get_orthogonality_threshold`, `get_sdf_surface_threshold`, `get_sdf_raymarch_eps`, `get_sdf_inside_step`, `get_progress_threshold`, `set_progress_threshold!` | | Render (Makie)| `wavelength_color`, `render!`, `get_view`, `set_view`, `hide_axis`, `set_orthographic`, `look_at!`, `arrow!`, `render_lcs!`, `render_bounding_sphere!`, `set_render_look`, `studio_lighting!` | @@ -119,16 +119,19 @@ initialize!(system) # empties all detectors of the system (nested groups inclu ```julia solve_system!(system, source; initialize = true) # empties the detectors first (or initialize!(system), empty!(det)) pts = spot_diagram(det) # Vector{Point2}: local (x, z) in m -x, z, E = electric_field(det; n = 200) # complex field on an n×n grid (3-vectors for polarized rays and astigmatic beamlets) -x, z, I = intensity(det; n = 200) # W/m², power per detector area (Poynting flux) +x, z, E = electric_field(det) # complex field on a 100×100 RegularGrid (3-vectors for polarized rays and astigmatic beamlets) +x, z, I = intensity(det, RegularGrid(n = 200)) # W/m², power per detector area (Poynting flux) P = optical_power(det) # W, beam power for any angle of incidence -E = electric_field(det, xs, zs) # on a grid of one's own: local x, z vectors in m -I = intensity(det, xs, zs) +s = RectilinearGrid(xs, zs) # a grid of one's own: local x, z vectors in m, any spacing +x, z, E = electric_field(det, s) +x, z, I = intensity(det, s) +P = optical_power(det, s) # trapezoidal rule on xs × zs ``` -Grid keywords for `electric_field`/`intensity`/`optical_power`: `n`, `crop_factor`, `x_min`, `x_max`, -`z_min`, `z_max`, `x0_shift`, `z0_shift`, `center = Centroid() | MinMax()` (rays). -They also take `progress = true` (see Solving). See `components/detectors.md`. +The second argument of `electric_field`/`intensity`/`optical_power` is a sampling (default +`RegularGrid()`). Keywords of `RegularGrid`: `n`, `crop_factor`, `x_min`, `x_max`, `z_min`, `z_max`, +`x0_shift`, `z0_shift`, `center = Centroid() | MinMax()` (rays). The readouts take `progress = true` +(see Solving). See `components/detectors.md`. ## Coupling to other solvers (OpticsBase) diff --git a/skills/beamletoptics/VISUALIZATION.md b/skills/beamletoptics/VISUALIZATION.md index 9fd528776..824840cbf 100644 --- a/skills/beamletoptics/VISUALIZATION.md +++ b/skills/beamletoptics/VISUALIZATION.md @@ -99,7 +99,7 @@ not part of BeamletOptics. It is the package BeamletOpticsGUI ## Detector data plots ```julia -x, z, I = intensity(det; n = 301, crop_factor = 5) +x, z, I = intensity(det, RegularGrid(n = 301, crop_factor = 5)) fig = Figure() ax = Axis(fig[1, 1], aspect = 1, xlabel = "x [µm]", ylabel = "z [µm]") heatmap!(ax, x * 1e6, z * 1e6, I) diff --git a/skills/beamletoptics/WORKFLOW.md b/skills/beamletoptics/WORKFLOW.md index e69b36c3b..118890c6e 100644 --- a/skills/beamletoptics/WORKFLOW.md +++ b/skills/beamletoptics/WORKFLOW.md @@ -57,7 +57,7 @@ end ## PSFs from rays - Use `UniformDiscSource` (equal-area sampling) with thousands of rays and a `Detector` near focus; - read `intensity(det; n, crop_factor)` or give explicit `x_min/x_max/z_min/z_max` windows. + read `intensity(det, RegularGrid(n = ..., crop_factor = ...))` or give explicit `x_min/x_max/z_min/z_max` windows in the `RegularGrid`. - For unpolarized PSFs, trace two orthogonal polarizations (polarized beams wrapped in a `CollimatedSource(beams, diameter, pos, dir)`) and add the intensities incoherently. diff --git a/skills/beamletoptics/components/detectors.md b/skills/beamletoptics/components/detectors.md index 518078b47..58591b6fe 100644 --- a/skills/beamletoptics/components/detectors.md +++ b/skills/beamletoptics/components/detectors.md @@ -19,25 +19,31 @@ Detector(edge_length, stop = true) | Call | Returns | |------|---------| | `spot_diagram(det)` | `Vector{Point2}` of local `(x, z)` hit points (beamlets: projected 1/e² contour, kwargs `num_spots`, `crop_factor`) | -| `electric_field(det; kwargs...)` | `(xs, zs, E)`: complex field on an `n×n` grid (hits of `PolarizedRay`s and `AstigmaticGaussianBeamlet`s: a matrix of complex 3-vectors, use `sum(abs2, e)` per element) | -| `intensity(det; kwargs...)` | `(xs, zs, I)`: power per detector area in W/m², the Poynting flux through the detector; a single hit gives `n\|E\|² cos θ / (2Z₀)` | -| `optical_power(det; kwargs...)` | integrated power in W, the beam power for any angle of incidence | -| `electric_field(det, xs, zs)`, `intensity(det, xs, zs)` | the same on a grid of one's own (local `x`, `z` vectors in m) | +| `electric_field(det, s = RegularGrid())` | `(xs, zs, E)`: complex field on the sampling `s`, by default an `n×n` grid (hits of `PolarizedRay`s and `AstigmaticGaussianBeamlet`s: a matrix of complex 3-vectors, use `sum(abs2, e)` per element) | +| `intensity(det, s = RegularGrid())` | `(xs, zs, I)`: power per detector area in W/m², the Poynting flux through the detector; a single hit gives `n\|E\|² cos θ / (2Z₀)` | +| `optical_power(det, s = RegularGrid())` | power in W, `Σ wᵢ Iᵢ` with the quadrature weights of the sampling, the beam power for any angle of incidence | -Grid keywords: +The sampling `s` decides where the readouts are evaluated, its window and the weights of `optical_power`: + +- `RegularGrid(; kwargs...)`: `n×n` equidistant points in a window around the hits (keywords below), trapezoidal rule +- `RectilinearGrid(xs, zs)`: a grid of one's own (local `x`, `z` vectors in m, any spacing), the window is `xs × zs` as given, trapezoidal rule; use `optical_power(det, RectilinearGrid(xs, zs))` for the power on it +- `electric_field(det, points)`, `intensity(det, points)`: the values only, at an array of local `(x, z)` points (e.g. `Point2`) in m, in the shape of `points` + +Keywords of `RegularGrid` (not of the readouts): - `n = 100`: grid points per axis - `crop_factor`: scales the automatic window around the hits; default `1` for rays (box around the hit points) and `3` for beamlets (three beam radii around each hit) - `center = Centroid()` or `MinMax()`: how the automatic window is centered - `x_min, x_max, z_min, z_max`: explicit window in local coordinates (m) - `x0_shift, z0_shift`: shift the window -- `num_spots`: beamlet contour resolution used for the automatic limits -`progress = true` shows a progress bar in the terminal once the readout has run for +A given bound replaces only its own side of the automatic window. + +`progress = true` (keyword of the readout) shows a progress bar in the terminal once the readout has run for `get_progress_threshold()` s (default 5 s). Local `(x, z)` form a left-handed frame with the normal, as seen by the incoming beam. -`intensity.(E)` turns a field matrix into `|E|²/(2Z₀)` per point (vacuum, not projected onto the detector); the irradiance on the detector, with `n` and `cos θ` of each hit, is `intensity(det)` or `intensity(det, xs, zs)`. +`intensity.(E)` turns a field matrix into `|E|²/(2Z₀)` per point (vacuum, not projected onto the detector); the irradiance on the detector, with `n` and `cos θ` of each hit, is `intensity(det)` or `intensity(det, RectilinearGrid(xs, zs))`. Ray-based PSFs are not normalized: compare shapes and positions, not absolute Strehl values. If nothing reaches the detector, readout throws "No hits available on detector." diff --git a/skills/beamletoptics/templates/03_psf_airy.jl b/skills/beamletoptics/templates/03_psf_airy.jl index d20376100..71d2761c1 100644 --- a/skills/beamletoptics/templates/03_psf_airy.jl +++ b/skills/beamletoptics/templates/03_psf_airy.jl @@ -15,7 +15,7 @@ system = System([lens, det]) source = UniformDiscSource([0, -10mm, 0], [0, 1, 0], 15mm, λ; num_rays = 5000) solve_system!(system, source) -x, z, I = intensity(det; n = 201, crop_factor = 10) # grid around the spot, I in W/m² +x, z, I = intensity(det, RegularGrid(n = 201, crop_factor = 10)) # grid around the spot, I in W/m² imax = argmax(I) println("peak at x = ", round(x[imax[1]] / µm; digits = 2), " µm, z = ", round(z[imax[2]] / µm; digits = 2), " µm") diff --git a/src/BeamGroups/BeamGroups.jl b/src/BeamGroups/BeamGroups.jl index 5a3f8ab88..020f3fcb3 100644 --- a/src/BeamGroups/BeamGroups.jl +++ b/src/BeamGroups/BeamGroups.jl @@ -82,7 +82,7 @@ end The fewest rays with which [`set_num_rays!`](@ref) regenerates the source `src`: `20 num_rings` for ring sources, `1` for sunflower, line and fan sources, and `nothing` if the rays of `src` can not be regenerated, e.g. a source built from given beams or any other beam or beam group. Also -defined for the [`BeamletOptics.AbstractSampling`](@ref) of a source. +defined for the [`BeamletOptics.AbstractSourceSampling`](@ref) of a source. """ min_num_rays(src) = nothing min_num_rays(src::Union{CollimatedSource, PointSource}) = min_num_rays(src.sampling) diff --git a/src/BeamGroups/CollimatedSource.jl b/src/BeamGroups/CollimatedSource.jl index 96d9f47e6..4e771c08d 100644 --- a/src/BeamGroups/CollimatedSource.jl +++ b/src/BeamGroups/CollimatedSource.jl @@ -22,7 +22,7 @@ mutable struct CollimatedSource{T, R <: AbstractRay{T}} <: AbstractBeamGroup{T, diameter::T center::Point3{T} orientation::SMatrix{3, 3, T, 9} - sampling::AbstractSampling + sampling::AbstractSourceSampling end """ @@ -45,7 +45,7 @@ CollimatedSource(beams::Vector{<:Beam}, diameter, pos, orientation::AbstractMatr CollimatedSource(beams, diameter, pos, orientation, NoSampling()) function CollimatedSource(beams::Vector{Beam{T, R}}, diameter, pos, orientation::AbstractMatrix, - sampling::AbstractSampling) where {T, R <: AbstractRay{T}} + sampling::AbstractSourceSampling) where {T, R <: AbstractRay{T}} _check_kinematic_members(beams) return CollimatedSource{T, R}(beams, T(diameter), Point3{T}(pos), _check_orientation(orientation, T), sampling) end diff --git a/src/BeamGroups/PointSource.jl b/src/BeamGroups/PointSource.jl index 14c513335..d7e7233e9 100644 --- a/src/BeamGroups/PointSource.jl +++ b/src/BeamGroups/PointSource.jl @@ -22,7 +22,7 @@ mutable struct PointSource{T, R <: AbstractRay{T}} <: AbstractBeamGroup{T, R} NA::T center::Point3{T} orientation::SMatrix{3, 3, T, 9} - sampling::AbstractSampling + sampling::AbstractSourceSampling end """ @@ -45,7 +45,7 @@ PointSource(beams::Vector{<:Beam}, NA, pos, orientation::AbstractMatrix) = PointSource(beams, NA, pos, orientation, NoSampling()) function PointSource(beams::Vector{Beam{T, R}}, NA, pos, orientation::AbstractMatrix, - sampling::AbstractSampling) where {T, R <: AbstractRay{T}} + sampling::AbstractSourceSampling) where {T, R <: AbstractRay{T}} _check_kinematic_members(beams) return PointSource{T, R}(beams, T(NA), Point3{T}(pos), _check_orientation(orientation, T), sampling) end diff --git a/src/BeamGroups/Sampling.jl b/src/BeamGroups/Sampling.jl index e7de06a37..f86664b87 100644 --- a/src/BeamGroups/Sampling.jl +++ b/src/BeamGroups/Sampling.jl @@ -37,7 +37,7 @@ The golden angle `π(3 - √5) ≈ 2.39996` rad, i.e. the azimuthal increment of const _GOLDEN_ANGLE = π * (3 - √5) """ - AbstractSampling + AbstractSourceSampling How the rays of a [`CollimatedSource`](@ref) or [`PointSource`](@ref) are sampled. The source stores its sampling in the field `sampling`, such that [`set_num_rays!`](@ref) can regenerate its @@ -46,7 +46,7 @@ same methods. # Implementation reqs. -A subtype `S <: AbstractSampling` implements: +A subtype `S <: AbstractSourceSampling` implements: - `source_beams(s::S, pos, dir, b1, args..., λ, num_rays::Int, T) -> Vector{<:Beam}`: the beams of the source, see [`BeamletOptics.source_beams`](@ref). `args` are the arguments of the source @@ -68,7 +68,7 @@ half spread angle) are fields of the subtype. - [`BeamletOptics.ConeRings`](@ref), [`BeamletOptics.ConeSunflower`](@ref), [`BeamletOptics.ConeFan`](@ref): `PointSource` """ -abstract type AbstractSampling end +abstract type AbstractSourceSampling end """ NoSampling() @@ -77,7 +77,7 @@ The beams of the source were given to its constructor, e.g. `CollimatedSource(beams, diameter, pos, dir)`. They can not be regenerated: [`set_num_rays!`](@ref) throws an `ArgumentError` and `min_num_rays` returns `nothing`. """ -struct NoSampling <: AbstractSampling end +struct NoSampling <: AbstractSourceSampling end """ DiscRings(num_rings::Int) @@ -90,7 +90,7 @@ it for the outermost ring, which represents only the inner half of its annulus. represents about the same area (trapezoidal rule), e.g. for spot sizes or point spread functions, which weight every ray equally. Needs at least `20 num_rings` rays. """ -struct DiscRings <: AbstractSampling +struct DiscRings <: AbstractSourceSampling num_rings::Int end @@ -101,7 +101,7 @@ Sunflower (Fibonacci) sampling of the disc of a [`UniformDiscSource`](@ref): eve represents the same area of the disc. The spiral starts with the center ray. Needs at least one ray. """ -struct DiscSunflower <: AbstractSampling end +struct DiscSunflower <: AbstractSourceSampling end """ DiscLine() @@ -111,7 +111,7 @@ along the sampling reference vector. The center ray comes first, followed by the one end of the line to the other, both ends included. An even number of rays has a second ray at the center, see [`UniformLineSource`](@ref). Needs at least one ray. """ -struct DiscLine <: AbstractSampling end +struct DiscLine <: AbstractSourceSampling end """ ConeRings(num_rings::Int, θ::Float64) @@ -123,7 +123,7 @@ angle each cone represents, i.e. to its circumference, but half of it for the ou which represents only the inner half of its band. Every ray then represents about the same solid angle (trapezoidal rule). Needs at least `20 num_rings` rays. """ -struct ConeRings <: AbstractSampling +struct ConeRings <: AbstractSourceSampling num_rings::Int θ::Float64 end @@ -135,7 +135,7 @@ Sunflower (Fibonacci) sampling of the spherical cap with the half spread angle ` [`UniformPointSource`](@ref): every ray represents the same solid angle. The spiral starts with the center ray. Needs at least one ray. """ -struct ConeSunflower <: AbstractSampling +struct ConeSunflower <: AbstractSourceSampling θ::Float64 end @@ -148,7 +148,7 @@ to the source direction. The center ray comes first, followed by the other rays the fan to the other, both edges included. An even number of rays has a second ray at the center, see [`UniformFanSource`](@ref). Needs at least one ray. """ -struct ConeFan <: AbstractSampling +struct ConeFan <: AbstractSourceSampling θ::Float64 end @@ -179,7 +179,7 @@ function _fan_coordinates(n::Int) end """ - source_beams(sampling::AbstractSampling, pos, dir, b1, args..., λ, num_rays, T) -> Vector{<:Beam} + source_beams(sampling::AbstractSourceSampling, pos, dir, b1, args..., λ, num_rays, T) -> Vector{<:Beam} The beams of a source at `pos` [m] along the unit vector `dir`, sampled by `sampling` with `num_rays` rays of the wavelength `λ` [m] and the number type `T`. `b1` is the unit sampling @@ -355,4 +355,4 @@ end # The fewest rays of a sampling, see `min_num_rays` min_num_rays(::NoSampling) = nothing min_num_rays(s::Union{DiscRings, ConeRings}) = 20 * s.num_rings -min_num_rays(::AbstractSampling) = 1 +min_num_rays(::AbstractSourceSampling) = 1 diff --git a/src/BeamletOptics.jl b/src/BeamletOptics.jl index e1b9985c7..37e78d2a9 100644 --- a/src/BeamletOptics.jl +++ b/src/BeamletOptics.jl @@ -14,7 +14,6 @@ module BeamletOptics using LinearAlgebra: norm, normalize, normalize!, dot, cross, I, eigen, Symmetric, Hermitian, svd 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 diff --git a/src/Exports.jl b/src/Exports.jl index d25b0c03e..a5e65a4b0 100644 --- a/src/Exports.jl +++ b/src/Exports.jl @@ -49,7 +49,7 @@ export Prism, RightAnglePrism, EquilateralPrism, DovePrism # detectors export Detector, electric_field, intensity, spot_diagram, optical_power, gauss_parameters, - waist_parameters, Centroid, MinMax + waist_parameters, Centroid, MinMax, RegularGrid, RectilinearGrid # splitters export ThinBeamsplitter, RoundThinBeamsplitter, RectangularPlateBeamsplitter, @@ -83,11 +83,13 @@ public is_static, hit_count, wavelength, min_num_rays, ProgressSink, PROGRESS_SI progress_state, is_cancelled # re-emitting components (e.g. solvers coupled through a field) public relaunch!, beamlet_hit_field, GaussianBeamletHit, AstigmaticGaussianBeamletHit +# own detector samplings, see AbstractDetectorSampling +public AbstractDetectorSampling, sample_points # optional part of the shape interface, see AbstractShape public bounding_sphere_of, AbstractBoundingSphere, NoBoundingSphere, SingleBoundingSphere, MultiBoundingSphere # own assembly types of separate parts, see AbstractObjectGroup public AbstractObjectGroup # element type of path_segments public PathSegment -public AbstractSampling, NoSampling, DiscRings, DiscSunflower, DiscLine, ConeRings, ConeSunflower, +public AbstractSourceSampling, NoSampling, DiscRings, DiscSunflower, DiscLine, ConeRings, ConeSunflower, ConeFan, source_beams, sampling_basis diff --git a/src/OpticalComponents/Detectors/Detectors.jl b/src/OpticalComponents/Detectors/Detectors.jl index a2d59a2ec..b29f9beea 100644 --- a/src/OpticalComponents/Detectors/Detectors.jl +++ b/src/OpticalComponents/Detectors/Detectors.jl @@ -7,4 +7,5 @@ include("HitBuffers.jl") # eval and helper functions include("DetectorUtils.jl") include("SpotDiagram.jl") +include("Sampling.jl") include("FieldCalculation.jl") diff --git a/src/OpticalComponents/Detectors/FieldCalculation.jl b/src/OpticalComponents/Detectors/FieldCalculation.jl index c16558486..dec7247f4 100644 --- a/src/OpticalComponents/Detectors/FieldCalculation.jl +++ b/src/OpticalComponents/Detectors/FieldCalculation.jl @@ -1,9 +1,10 @@ """ - electric_field(pd::Detector; kwargs...) + electric_field(pd::Detector, s::AbstractDetectorSampling = RegularGrid(); progress = true) -Samples the electric field of the hits of the [`Detector`](@ref) `pd` on a regular `n×n` grid in -its local (x, z) plane, in a window around the hits. The field at the local point `(x, z)` is the -coherent sum of the fields `Eⱼ` of all hits `j`, +Samples the electric field of the hits of the [`Detector`](@ref) `pd` at the points of the +sampling `s` in its local (x, z) plane, by default a [`RegularGrid`](@ref) in a window around +the hits. The field at the local point `(x, z)` is the coherent sum of the fields `Eⱼ` of all +hits `j`, ```math \\mathbf{E}(x, z) = \\sum_j \\mathbf{E}_j(\\mathbf{p}), \\qquad \\mathbf{p} = \\mathbf{p}_d + x\\,\\hat{\\mathbf{x}} + z\\,\\hat{\\mathbf{z}}, @@ -14,8 +15,8 @@ system with the detector normal. `Eⱼ` is defined per hit type in [`electric_field(::BeamletOptics.AbstractDetectorHit, ::AbstractVector)`](@ref). The field is not projected onto the detector: it is the field that is there, for any angle of incidence. The power per detector area follows from [`intensity`](@ref), which takes the angle of incidence -of each hit into account. To sample on a grid of one's own, use -[`electric_field(::Detector, ::AbstractVector, ::AbstractVector)`](@ref). +of each hit into account. To sample on a grid of one's own, pass a [`RectilinearGrid`](@ref); +other samplings are subtypes of [`BeamletOptics.AbstractDetectorSampling`](@ref). !!! warning "Coherent sum" All hits are summed as one monochromatic, mutually coherent field, also hits of different @@ -25,33 +26,13 @@ of each hit into account. To sample on a grid of one's own, use !!! note "Resetting detectors" Be sure to call `empty!(pd)` (or [`initialize!`](@ref)`(system)` for all detectors) before each new measurement if reusing the same detector. -# Keyword Arguments - -The following generic kwargs can be used for all hit types: - -- `n::Int=100` - Number of sample points per axis. -- `crop_factor::Real` - Scales the width of the sampling window returned by - [`calc_local_lims`](@ref); values >1 expand, <1 shrink. The default is `1` for ray hits - (the box around the hit points) and `3` for beamlet hits (three beam radii around each - hit, which holds the power of a Gaussian beam except for a part of `10⁻⁸`). -- `x_min, x_max, z_min, z_max` - Manually override the sampling bounds in the local x or z directions. - If left as `Inf`, the bounds from `calc_local_lims` are used. -- `x0_shift::Real=0, z0_shift::Real=0` - Applies a constant offset to the entire x or z coordinate arrays, - useful for recentring or testing alignment. -- `progress::Bool=true` - Shows a progress bar once the calculation has run for `get_progress_threshold()` - seconds (default 5 s). It is only drawn if `stderr` is a terminal. - -## Ray specific keyword arguments - -- `center::AbstractCenterAlgorithm=Centroid()` - How the sampling window is centred. - `Centroid()` uses the projection‑weighted centroid, - `MinMax()` uses the geometric mid‑point of the bounding box. +# Keyword arguments + +- `progress::Bool = true`: shows a progress bar once the calculation has run for + `get_progress_threshold()` seconds (default 5 s). It is only drawn if `stderr` is a terminal. + +The grid, its window and its resolution are set by the sampling, e.g. +`electric_field(pd, RegularGrid(n = 200, crop_factor = 5))`, see [`RegularGrid`](@ref). !!! note "Scaling" The returned values for ray hits correspond to the E-field of the point spread function. @@ -61,33 +42,33 @@ The following generic kwargs can be used for all hit types: # Returns -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, -- `E` is the field at `(xs[i], zs[j])`: a `Matrix{Complex{T}}` for [`Ray`](@ref)s and - [`GaussianBeamlet`](@ref)s, a `Matrix{Point3{Complex{T}}}` of 3D vectors in global coordinates - for [`PolarizedRay`](@ref)s and [`AstigmaticGaussianBeamlet`](@ref)s, which carry a polarization. +The coordinates of the sampling followed by the field at its points, for the grids +`(xs, zs, E)` with `E[i, j]` at `(xs[i], zs[j])`, see [`sample_points`](@ref). The values are +complex scalars for [`Ray`](@ref)s and [`GaussianBeamlet`](@ref)s, `Point3{Complex{T}}` 3D vectors +in global coordinates for [`PolarizedRay`](@ref)s and [`AstigmaticGaussianBeamlet`](@ref)s, +which carry a polarization. !!! note "Unpolarized light" An unpolarized PSF is **not** obtained from a single coherent trace. Instead, trace twice with orthogonal input polarizations (e.g. `E0 = [1,0,0]` and `E0 = [0,0,1]`), evaluate - [`intensity`](@ref)`(pd, xs, zs)` on the same grid after each trace and add the results. + [`intensity`](@ref)`(pd, s)` with the same [`RectilinearGrid`](@ref) `s` after each trace + and add the results. """ -function electric_field(pd::Detector; progress::Bool = true, kwargs...) - xs, zs = _sampling_grid(pd; kwargs...) - return xs, zs, electric_field(pd, xs, zs; progress) +function electric_field(pd::Detector, s::AbstractDetectorSampling = RegularGrid(); + progress::Bool = true) + grid = sample_points(pd, s) + return (grid.coordinates..., electric_field(pd, grid.points; progress)) end """ - electric_field(pd::Detector, xs::AbstractVector, zs::AbstractVector; progress = true) + electric_field(pd::Detector, points::AbstractArray{<:AbstractVector}; progress = true) -Samples the electric field of the hits of the [`Detector`](@ref) `pd` on the grid `xs × zs` of -its local coordinates in \\[m\\]: `E[i, j]` is the field at `(xs[i], zs[j])`. The type of `E` and -the meaning of its values are those of [`electric_field`](@ref)`(pd; kwargs...)`, which picks -the grid automatically. +The field of the hits of the [`Detector`](@ref) `pd` at the local detector coordinates +`points` in \\[m\\], an array of vectors `(x, z)` (e.g. `Point2`s), see +[`electric_field`](@ref)`(pd, s)`. Returns the values only, in the shape of `points`. """ -electric_field(pd::Detector, xs::AbstractVector, zs::AbstractVector; progress::Bool = true) = - _sample(electric_field, pd, xs, zs, progress) +electric_field(pd::Detector, points::AbstractArray{<:AbstractVector}; progress::Bool = true) = + _sample(electric_field, pd, points, progress) """ electric_field(hits::AbstractVector{<:AbstractDetectorHit}, p::AbstractVector) @@ -132,7 +113,7 @@ detector and the optical path length `L` from the source to the hit point `p_hit [Astigmatic polarized beamlets](@ref). Beamlet hits give the physical field in \\[V/m\\]. Ray hits are raw and unscaled: `|E|²` does not -carry the power of the ray, see the note on scaling in [`electric_field`](@ref)`(pd; kwargs...)`. +carry the power of the ray, see the note on scaling in [`electric_field`](@ref)`(pd, s)`. A new hit type implements this method, `direction(hit)` and `refractive_index(hit)`; the readouts of a [`Detector`](@ref) on a grid ([`electric_field`](@ref), [`intensity`](@ref), @@ -157,12 +138,12 @@ _ray_phasor(hit::AbstractRayHit, p) = cis(wavenumber(hit) * (optical_path_length(hit) + refractive_index(hit) * dot(p - hit_point(hit), direction(hit)))) """ - intensity(pd::Detector; kwargs...) + intensity(pd::Detector, s::AbstractDetectorSampling = RegularGrid(); progress = true) Samples the irradiance on the [`Detector`](@ref) `pd`, the power per detector area in \\[W/m²\\], -on the grid of [`electric_field`](@ref)`(pd; kwargs...)`, with the same keyword arguments. -Returns a tuple `(xs, zs, I)`. To sample on a grid of one's own, use -[`intensity(::Detector, ::AbstractVector, ::AbstractVector)`](@ref). +at the points of the sampling `s`, by default a [`RegularGrid`](@ref) around the hits. Returns +the coordinates of the sampling followed by the irradiance at its points, for the grids +`(xs, zs, I)`; `progress` as for [`electric_field`](@ref)`(pd, s)`. `I` is the flux of the coherent sum of all hits through the detector: the time-averaged Poynting vector along the detector normal `n̂`, which points along the incoming beams. Hits with a @@ -194,29 +175,31 @@ mean of their `n cos θ`. `I` is in \\[W/m²\\] for beamlet hits. For ray hits, whose fields are unscaled, it has the same form but no absolute unit. """ -function intensity(pd::Detector; progress::Bool = true, kwargs...) - xs, zs = _sampling_grid(pd; kwargs...) - return xs, zs, intensity(pd, xs, zs; progress) +function intensity(pd::Detector, s::AbstractDetectorSampling = RegularGrid(); + progress::Bool = true) + grid = sample_points(pd, s) + return (grid.coordinates..., intensity(pd, grid.points; progress)) end """ - intensity(pd::Detector, xs::AbstractVector, zs::AbstractVector; progress = true) + intensity(pd::Detector, points::AbstractArray{<:AbstractVector}; progress = true) -Samples the irradiance on the [`Detector`](@ref) `pd` in \\[W/m²\\] on the grid `xs × zs` of its -local coordinates in \\[m\\]: `I[i, j]` is the irradiance at `(xs[i], zs[j])`, see -[`intensity`](@ref)`(pd; kwargs...)`. +The irradiance on the [`Detector`](@ref) `pd` in \\[W/m²\\] at the local detector coordinates +`points` in \\[m\\], an array of vectors `(x, z)` (e.g. `Point2`s), see +[`intensity`](@ref)`(pd, s)`. Returns the values only, in the shape of `points`. """ -function intensity(pd::Detector, xs::AbstractVector, zs::AbstractVector; progress::Bool = true) +function intensity(pd::Detector, points::AbstractArray{<:AbstractVector}; + progress::Bool = true) # downstream normal: the detector normal points against the incoming beams n̂ = Point3(-orientation(pd)[:, 2]) - return _sample((hs, p) -> intensity(hs, p, n̂), pd, xs, zs, progress) + return _sample((hs, p) -> intensity(hs, p, n̂), pd, points, progress) end """ intensity(hits::AbstractVector{<:AbstractDetectorHit}, p::AbstractVector, n̂::AbstractVector) Irradiance \\[W/m²\\] of the coherent sum of the detector `hits` at the global point `p` through -a plane with the unit normal `n̂`, see [`intensity`](@ref)`(pd; kwargs...)`. +a plane with the unit normal `n̂`, see [`intensity`](@ref)`(pd, s)`. """ intensity(::AbstractVector{<:AbstractDetectorHit}, ::AbstractVector, ::AbstractVector) @@ -245,64 +228,54 @@ function intensity(hits::AbstractVector{<:Union{RayHit, GaussianBeamletHit}}, end """ - optical_power(pd::Detector; kwargs...) + optical_power(pd::Detector, s::AbstractDetectorSampling = RegularGrid(); progress = true) Calculates the total optical power on `pd` in \\[W\\] as the integral of its [`intensity`](@ref) -over the sampling window in the local detector coordinates, +over the window of the sampling `s` in the local detector coordinates, ```math -P = \\int_{x_\\mathrm{min}}^{x_\\mathrm{max}} \\int_{z_\\mathrm{min}}^{z_\\mathrm{max}} I(x, z)\\, \\mathrm{d}z\\, \\mathrm{d}x, +P = \\iint I(x, z)\\, \\mathrm{d}x\\, \\mathrm{d}z \\approx \\sum_i w_i\\, I(x_i, z_i), ``` -evaluated with the trapezoidal rule on the `n×n` grid of [`electric_field`](@ref)`(pd; kwargs...)`, -with the same keyword arguments. Since `I` is the flux through the detector, `P` is the power of -the beams for any angle of incidence. +with the points `(xᵢ, zᵢ)` and the weights `wᵢ` \\[m²\\] of the sampling, see +[`sample_points`](@ref): the trapezoidal rule for [`RegularGrid`](@ref) and +[`RectilinearGrid`](@ref). Since `I` is the flux through the detector, `P` is the power of the +beams for any angle of incidence. -The integral runs over the sampling window, not over the active area of the detector: the -window is not cut at the edges of the detector. The default window of beamlet hits holds the -power of each beamlet except for a part of `10⁻⁸`, see `crop_factor`. For ray hits, `P` has no -absolute unit, see [`intensity`](@ref). +The integral runs over the window of the sampling, not over the active area of the detector: +the window is not cut at the edges of the detector. The default window of beamlet hits holds +the power of each beamlet except for a part of `10⁻⁸`, see `crop_factor` of +[`RegularGrid`](@ref). For ray hits, `P` has no absolute unit, see [`intensity`](@ref). """ -function optical_power(pd::Detector; kwargs...) - x, y, I = intensity(pd; kwargs...) - return trapz((x, y), I) -end - -# The local grid of `electric_field(pd; kwargs...)`: `n` points per axis in the window of -# `calc_local_lims`, or within the given bounds -function _sampling_grid(pd::Detector; n::Int = 100, x_min = Inf, x_max = Inf, z_min = Inf, - z_max = Inf, x0_shift::Real = 0, z0_shift::Real = 0, kwargs...) - _x_min, _x_max, _z_min, _z_max = calc_local_lims(pd, _detector_hits(pd); kwargs...) - 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 - return xs, zs +function optical_power(pd::Detector, s::AbstractDetectorSampling = RegularGrid(); + progress::Bool = true) + grid = sample_points(pd, s) + I = intensity(pd, grid.points; progress) + # lazy: neither the weights nor their product with I are materialized + return sum(Broadcast.instantiate(Broadcast.broadcasted(*, grid.weights, I))) end -# Samples `f(hits, p)` at the global points `p` of the local detector coordinates `xs × zs`, -# threaded over `zs`. All readouts of a detector on a grid share this loop. -function _sample(f, pd::Detector, xs::AbstractVector, zs::AbstractVector, progress::Bool) +# Samples `f(hits, p)` at the global points `p` of the local detector coordinates `points`, +# threaded over chunks of the points. All readouts of a detector share this loop. +function _sample(f, pd::Detector, points::AbstractArray, progress::Bool) # PD local coordinate axes (left-handed coords.), flipped x due to the rotated pd mesh local_x = Point3(-orientation(pd)[:, 1]) local_z = Point3(orientation(pd)[:, 3]) - return _sample(f, _detector_hits(pd), position(pd), local_x, local_z, xs, zs, progress) + return _sample(f, _detector_hits(pd), position(pd), local_x, local_z, points, progress) end # function barrier: `hits` has a concrete type here -function _sample(f, hits::AbstractVector, origin, local_x, local_z, xs, zs, progress::Bool) - point(i, j) = origin + xs[i] * local_x + zs[j] * local_z - values = Matrix{typeof(f(hits, point(1, 1)))}(undef, length(xs), length(zs)) - _with_progress(progress, length(zs), "Detector field: ") do prog - Threads.@threads for j in eachindex(zs) - @inbounds for i in eachindex(xs) - values[i, j] = f(hits, point(i, j)) +function _sample(f, hits::AbstractVector, origin, local_x, local_z, points::AbstractArray, + progress::Bool) + point(q) = origin + q[1] * local_x + q[2] * local_z + values = similar(points, typeof(f(hits, point(first(points))))) + # equal chunks of consecutive points, independent of the shape; one tick per chunk + nparts = min(length(points), max(100, 4 * Threads.nthreads())) + parts = collect(Iterators.partition(eachindex(values, points), cld(length(points), nparts))) + _with_progress(progress, length(parts), "Detector field: ") do prog + Threads.@threads for part in parts + @inbounds for k in part + values[k] = f(hits, point(points[k])) end _tick!(prog) end diff --git a/src/OpticalComponents/Detectors/Sampling.jl b/src/OpticalComponents/Detectors/Sampling.jl new file mode 100644 index 000000000..8e9b4a5e0 --- /dev/null +++ b/src/OpticalComponents/Detectors/Sampling.jl @@ -0,0 +1,146 @@ +""" + AbstractDetectorSampling + +Abstract supertype of the samplings of a [`Detector`](@ref): a sampling decides where on the +detector the readouts [`electric_field`](@ref), [`intensity`](@ref) and [`optical_power`](@ref) +are evaluated, in which window, and with which weights the power is integrated. + +# Implementation reqs. + +A subtype `S <: AbstractDetectorSampling` implements + + sample_points(pd::Detector, s::S) -> (; coordinates, points, weights) + +see [`sample_points`](@ref). The window is the business of the sampling: it may look at the +hits of `pd`, e.g. as [`RegularGrid`](@ref) does, or take a fixed one, as +[`RectilinearGrid`](@ref) does. All readouts then work for the new sampling. + +Concrete subtypes include: + +- [`RegularGrid`](@ref) — `n×n` points in a window around the hits +- [`RectilinearGrid`](@ref) — the grid `xs × zs` of one's own, with any spacing +""" +abstract type AbstractDetectorSampling end + +""" + sample_points(pd::Detector, s::AbstractDetectorSampling) -> (; coordinates, points, weights) + +The points at which the readouts of the [`Detector`](@ref) `pd` are evaluated for the sampling +`s`: + +- `points`: an array of local detector coordinates `(x, z)` in \\[m\\], each a vector + (e.g. a `Point2`). The readouts return their values in the shape of `points`. +- `weights`: the detector area in \\[m²\\] each point stands for, in the shape of `points`, as + an array or a lazy broadcast (`Broadcast.broadcasted`), which is only evaluated by + [`optical_power`](@ref). It is `Σ wᵢ Iᵢ` with the irradiance `Iᵢ` at the points, so the + weights are the quadrature rule of the sampling. +- `coordinates`: a tuple that the readouts return in front of the values, e.g. `(xs, zs)` for + a grid. + +The local coordinates `(x, z)` form a left-handed system with the detector normal, see +[`electric_field`](@ref)`(pd, s)`. +""" +function sample_points end + +""" + RectilinearGrid(xs::AbstractVector, zs::AbstractVector) + +A [`Detector`](@ref) sampling on the grid `xs × zs` of local detector coordinates in \\[m\\], +with any spacing: the readouts return `(xs, zs, values)` with `values[i, j]` at +`(xs[i], zs[j])`. [`optical_power`](@ref) integrates with the trapezoidal rule along both axes. +The window is `xs × zs` as given, independent of the hits. Both axes must be non-empty and +ascending, otherwise an `ArgumentError` is thrown: a descending axis would integrate to a +negative power. +""" +struct RectilinearGrid{X <: AbstractVector{<:Real}, Z <: AbstractVector{<:Real}} <: + AbstractDetectorSampling + xs::X + zs::Z + function RectilinearGrid(xs::X, zs::Z) where {X <: AbstractVector{<:Real}, + Z <: AbstractVector{<:Real}} + (isempty(xs) || isempty(zs)) && + throw(ArgumentError("RectilinearGrid needs at least one point per axis")) + (issorted(xs) && issorted(zs)) || + throw(ArgumentError("RectilinearGrid needs ascending xs and zs")) + return new{X, Z}(xs, zs) + end +end + +function sample_points(::Detector, g::RectilinearGrid) + points = [Point2(x, z) for x in g.xs, z in g.zs] + # the outer product of the 1D weights stays lazy until optical_power needs it + weights = Broadcast.instantiate(Broadcast.broadcasted(*, + _trapezoid_weights(g.xs), transpose(_trapezoid_weights(g.zs)))) + return (; coordinates = (g.xs, g.zs), points, weights) +end + +# Weights of the trapezoidal rule on the nodes `xs`, zero for a single node +function _trapezoid_weights(xs::AbstractVector) + w = zeros(float(eltype(xs)), length(xs)) + for i in firstindex(xs):(lastindex(xs) - 1) + h = (xs[i + 1] - xs[i]) / 2 + w[i - firstindex(xs) + 1] += h + w[i - firstindex(xs) + 2] += h + end + return w +end + +""" + RegularGrid(; n = 100, crop_factor, center = Centroid(), x_min, x_max, z_min, z_max, + x0_shift = 0, z0_shift = 0) + +The default sampling of a [`Detector`](@ref): `n×n` equidistant points in a window around its +hits, in local detector coordinates. The readouts return `(xs, zs, values)` with +`values[i, j]` at `(xs[i], zs[j])`; [`optical_power`](@ref) integrates with the trapezoidal +rule. The window follows from the hits when the readout is evaluated, see +[`calc_local_lims`](@ref). + +# Keyword arguments + +- `n::Int = 100`: number of points per axis. +- `crop_factor::Real`: scales the width of the window around the hits; values >1 expand, <1 + shrink. The default is `1` for ray hits (the box around the hit points) and `3` for beamlet + hits (three beam radii around each hit, which holds the power of a Gaussian beam except for + a part of `10⁻⁸`). +- `center::AbstractCenterAlgorithm = Centroid()`: for ray hits, how the window is centred: + `Centroid()` uses the projection-weighted centroid, `MinMax()` the mid-point of the bounding + box. +- `x_min, x_max, z_min, z_max`: bounds of the window in \\[m\\]. A given bound replaces its side + of the window around the hits, the others stay automatic. If a lower bound ends up above its + upper one, the readout throws an `ArgumentError`. +- `x0_shift = 0, z0_shift = 0`: shift the whole window along `x` or `z` in \\[m\\]. +""" +struct RegularGrid{C <: AbstractCenterAlgorithm} <: AbstractDetectorSampling + n::Int + crop_factor::Union{Nothing, Real} + center::C + x_min::Union{Nothing, Real} + x_max::Union{Nothing, Real} + z_min::Union{Nothing, Real} + z_max::Union{Nothing, Real} + x0_shift::Real + z0_shift::Real +end + +function RegularGrid(; n::Integer = 100, crop_factor::Union{Nothing, Real} = nothing, + center::AbstractCenterAlgorithm = Centroid(), x_min = nothing, x_max = nothing, + z_min = nothing, z_max = nothing, x0_shift::Real = 0, z0_shift::Real = 0) + n ≥ 1 || throw(ArgumentError("RegularGrid needs at least one point per axis, got n = $n")) + return RegularGrid(Int(n), crop_factor, center, x_min, x_max, z_min, z_max, x0_shift, z0_shift) +end + +function sample_points(pd::Detector, g::RegularGrid) + x_lo, x_hi, z_lo, z_hi = calc_local_lims(pd, _detector_hits(pd); + _window_kwargs(g.crop_factor)..., center = g.center) + x_lo, x_hi = something(g.x_min, x_lo), something(g.x_max, x_hi) + z_lo, z_hi = something(g.z_min, z_lo), something(g.z_max, z_hi) + x_lo ≤ x_hi || throw(ArgumentError("RegularGrid: x_min = $x_lo lies above x_max = $x_hi")) + z_lo ≤ z_hi || throw(ArgumentError("RegularGrid: z_min = $z_lo lies above z_max = $z_hi")) + xs = LinRange(x_lo, x_hi, g.n) .+ g.x0_shift + zs = LinRange(z_lo, z_hi, g.n) .+ g.z0_shift + return sample_points(pd, RectilinearGrid(xs, zs)) +end + +# Without a `crop_factor`, `calc_local_lims` uses its default of the hit type +_window_kwargs(::Nothing) = (;) +_window_kwargs(crop_factor::Real) = (; crop_factor) diff --git a/test/Components/TestDetector.jl b/test/Components/TestDetector.jl index 7a992413c..31c243c9b 100644 --- a/test/Components/TestDetector.jl +++ b/test/Components/TestDetector.jl @@ -88,7 +88,7 @@ end solve_system!(sys, cs) # get PSF - x, y, I_num = intensity(psfd; n=500, crop_factor=5, center=MinMax()) + x, y, I_num = intensity(psfd, RegularGrid(n=500, crop_factor=5, center=MinMax())) # walk from the peak to the first local minimum through the centre column ix_ctr, jx_ctr = Tuple(argmax(I_num)) @@ -168,8 +168,8 @@ end # Compare solutions I_analytical = intensity.(screen) - ~, ~, I_numerical = intensity(pd_l; n, x_min=-l/2, x_max=l/2, z_min=-l/2, z_max=l/2) - Pt = optical_power(pd_l; n, x_min=-l/2, x_max=l/2, z_min=-l/2, z_max=l/2) + ~, ~, I_numerical = intensity(pd_l, RegularGrid(; n, x_min=-l/2, x_max=l/2, z_min=-l/2, z_max=l/2)) + Pt = optical_power(pd_l, RegularGrid(; n, x_min=-l/2, x_max=l/2, z_min=-l/2, z_max=l/2)) @test all(isapprox.(I_analytical, I_numerical, atol = 2e-1)) @test isapprox(Pt, 2 * P0, atol = 3e-5) end @@ -496,14 +496,14 @@ end ("AstigmaticGaussianBeamlet", agb)), θd in (0, 30, 60) pd = tilted(deg2rad(θd)) solve_system!(System([pd]), beam()) - @test optical_power(pd; n = 300, progress = false) ≈ P0 rtol = 1e-4 + @test optical_power(pd, RegularGrid(n = 300); progress = false) ≈ P0 rtol = 1e-4 end @testset "The field is not projected onto the detector" begin pd = tilted(deg2rad(60)) beam = gb() solve_system!(System([pd]), beam) - E = electric_field(pd, [0.0], [0.0]; progress = false)[1] + E = electric_field(pd, RectilinearGrid([0.0], [0.0]); progress = false)[3][1] @test abs(E) ≈ abs(BMO.electric_field(beam, 0.0, 100mm)) rtol = 1e-9 end @@ -513,7 +513,7 @@ end function irradiance(ray) pd = tilted(0) solve_system!(System([pd]), Beam(ray)) - return intensity(pd, [0.0], [0.0]; progress = false)[1] + return intensity(pd, RectilinearGrid([0.0], [0.0]); progress = false)[3][1] end # a ray has the amplitude 1, a polarized ray that of its field vector @test irradiance(Ray(p, d, λ)) ≈ cos(θ) / (2 * BMO.Z_vacuum) @@ -540,16 +540,16 @@ end dir = [s * sin(α), cos(α), 0] solve_system!(system, gb(-100mm / cos(α) * dir + [0, 100mm, 0], dir)) end - @test optical_power(pd; n = 800, progress = false) ≈ 2P0 rtol = 1e-3 + @test optical_power(pd, RegularGrid(n = 800); progress = false) ≈ 2P0 rtol = 1e-3 end @testset "The grid methods sample the automatic grid" begin pd = tilted(deg2rad(30)) solve_system!(System([pd]), agb()) - xs, zs, E = electric_field(pd; n = 20, progress = false) - @test electric_field(pd, xs, zs; progress = false) == E - xs, zs, I = intensity(pd; n = 20, progress = false) - @test intensity(pd, xs, zs; progress = false) == I + xs, zs, E = electric_field(pd, RegularGrid(n = 20); progress = false) + @test electric_field(pd, RectilinearGrid(xs, zs); progress = false)[3] == E + xs, zs, I = intensity(pd, RegularGrid(n = 20); progress = false) + @test intensity(pd, RectilinearGrid(xs, zs); progress = false)[3] == I end end diff --git a/test/Components/TestDetectorSampling.jl b/test/Components/TestDetectorSampling.jl new file mode 100644 index 000000000..538cf722f --- /dev/null +++ b/test/Components/TestDetectorSampling.jl @@ -0,0 +1,114 @@ +module TestDetectorSampling + +using BeamletOptics +using Test + +const BMO = BeamletOptics + +const mm = 1e-3 + +# A sampling of one's own: points of any arrangement and their weights, as in #168 +struct PointCloud{P, W} <: BMO.AbstractDetectorSampling + points::P + weights::W +end + +BMO.sample_points(::Detector, s::PointCloud) = + (; coordinates = (s.points,), points = s.points, weights = s.weights) + +# A Gaussian beam of 1 mW on a detector tilted by 30° +function tilted_detector() + pd = Detector(50mm) + zrotate3d!(pd, deg2rad(30)) + translate3d!(pd, [0, 100mm, 0]) + solve_system!(System([pd]), GaussianBeamlet([0.0, 0, 0], [0.0, 1, 0], 1e-6, 1mm; P0 = 1e-3)) + return pd +end + +@testset "Detector sampling" begin + pd = tilted_detector() + + @testset "RegularGrid gives the values of the former keyword readouts" begin + # recorded with `intensity(pd; n = 50)`, `optical_power(pd; ...)` before the samplings + x, z, I = intensity(pd, RegularGrid(n = 50); progress = false) + @test sum(I) ≈ 49970.20330881326 rtol = 1e-12 + @test I[20, 27] ≈ 203.20885922342407 rtol = 1e-12 + @test first(x) ≈ -0.0034658561053307387 rtol = 1e-12 + @test last(x) ≈ 0.0034658561053307387 rtol = 1e-12 + @test optical_power(pd, RegularGrid(n = 50); progress = false) ≈ 0.0010000000061118099 rtol = 1e-12 + @test optical_power(pd; progress = false) ≈ 0.0010000000063770916 rtol = 1e-12 + s = RegularGrid(n = 31, crop_factor = 2, x_min = -1e-3, x_max = 2e-3) + x, z, I = intensity(pd, s; progress = false) + @test sum(I) ≈ 62674.78458469183 rtol = 1e-12 + @test (first(x), last(x)) == (-1e-3, 2e-3) + @test last(z) ≈ 0.002310570736887159 rtol = 1e-12 + end + + @testset "A single bound replaces only its side" begin + x_auto, z_auto, _ = electric_field(pd, RegularGrid(n = 11); progress = false) + x, z, _ = electric_field(pd, RegularGrid(n = 11, x_min = -1mm); progress = false) + @test first(x) == -1mm + @test last(x) == last(x_auto) + @test z == z_auto + x, z, _ = electric_field(pd, RegularGrid(n = 11, z_max = 2mm, x0_shift = 1mm); progress = false) + @test x ≈ x_auto .+ 1mm + @test (first(z), last(z)) == (first(z_auto), 2mm) + end + + @testset "RectilinearGrid" begin + # non-uniform: dense at the edges, coarse in the center + xs = 4mm .* sinpi.(range(-0.5, 0.5, length = 601)) + zs = 3mm .* sinpi.(range(-0.5, 0.5, length = 401)) + g = RectilinearGrid(xs, zs) + x, z, E = electric_field(pd, g; progress = false) + @test x === xs && z === zs + @test size(E) == (601, 401) + @test optical_power(pd, g; progress = false) ≈ 1e-3 rtol = 1e-4 + # a single node has no area + @test optical_power(pd, RectilinearGrid([0.0], [0.0]); progress = false) == 0 + # the weights stay lazy and add up to the area of the window + w = BMO.sample_points(pd, g).weights + @test !(w isa AbstractArray) + @test sum(w) ≈ 8mm * 6mm rtol = 1e-12 + # a wide and a tall grid give the same values as their transposes + xs1, zs1 = range(-3mm, 3mm, length = 3), range(-2mm, 2mm, length = 301) + I_tall = intensity(pd, RectilinearGrid(zs1, xs1); progress = false)[3] + I_wide = intensity(pd, RectilinearGrid(xs1, zs1); progress = false)[3] + @test size(I_tall) == (301, 3) && size(I_wide) == (3, 301) + end + + @testset "A sampling of one's own" begin + g = RectilinearGrid(range(-3mm, 3mm, length = 41), range(-2mm, 2mm, length = 31)) + grid = BMO.sample_points(pd, g) + cloud = PointCloud(vec(grid.points), vec(copy(grid.weights))) + pts, I = intensity(pd, cloud; progress = false) + @test pts === cloud.points + @test I isa Vector + @test I ≈ vec(intensity(pd, g; progress = false)[3]) + @test optical_power(pd, cloud; progress = false) ≈ sum(cloud.weights .* I) + @test optical_power(pd, cloud; progress = false) ≈ optical_power(pd, g; progress = false) + _, E = electric_field(pd, cloud; progress = false) + @test E ≈ vec(electric_field(pd, g; progress = false)[3]) + # the values at local points alone, without a sampling + @test intensity(pd, cloud.points; progress = false) == I + @test electric_field(pd, cloud.points; progress = false) == E + end + + @testset "Errors" begin + @test_throws ArgumentError RegularGrid(n = 0) + # a bound beyond its opposite side would give a descending grid and a negative power + x_auto, z_auto, _ = intensity(pd, RegularGrid(n = 5); progress = false) + @test_throws ArgumentError intensity(pd, RegularGrid(x_min = last(x_auto) + 1mm)) + @test_throws ArgumentError optical_power(pd, RegularGrid(z_max = first(z_auto) - 1mm)) + @test_throws ArgumentError RectilinearGrid([1.0, 0.0], [0.0, 1.0]) + @test_throws ArgumentError RectilinearGrid(Float64[], [0.0]) + # a single point is not an array of points + @test_throws MethodError intensity(pd, BMO.Point2(0.0, 0.0)) + empty = Detector(10mm) + for s in (RegularGrid(), RectilinearGrid([0.0], [0.0])) + @test_throws "No hits available on detector." intensity(empty, s; progress = false) + end + end +end + +end # module diff --git a/test/E2E/TestAnalyticReferences.jl b/test/E2E/TestAnalyticReferences.jl index ecfaec32d..e83e10f86 100644 --- a/test/E2E/TestAnalyticReferences.jl +++ b/test/E2E/TestAnalyticReferences.jl @@ -227,7 +227,7 @@ end zrotate3d!(pd, π / 2) translate3d!(pd, [-5cm, 23.5cm, 0]) solve_system!(System([cbs, m1, m2, pd]), GaussianBeamlet([0.0, 0, 0], [0.0, 1, 0], λ, 0.5mm)) - return optical_power(pd; progress = false, n = 60) + return optical_power(pd, RegularGrid(n = 60); progress = false) end # one fringe over λ/2 of the mirror position, sampled finely enough for its contrast xs = range(0, λ / 2, 33) diff --git a/test/E2E/TestFraunhofer.jl b/test/E2E/TestFraunhofer.jl index 3826375f2..a90627154 100644 --- a/test/E2E/TestFraunhofer.jl +++ b/test/E2E/TestFraunhofer.jl @@ -40,7 +40,7 @@ const nm = 1e-9 # 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) + pd, RegularGrid(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) diff --git a/test/E2E/TestMichelson.jl b/test/E2E/TestMichelson.jl index daa45845a..202ae7130 100644 --- a/test/E2E/TestMichelson.jl +++ b/test/E2E/TestMichelson.jl @@ -49,13 +49,15 @@ const mm = 1e-3 # Moving mirror path length path_length_numerical[i] = length(beam.children[1].children[2]) optical_pwr_numerical[i] = BMO.optical_power( - pd; + pd, # restore pre-v0.11 behavior, e.g. no autolims - n=pd_resolution, - x_min=-pd_size/2, - x_max=pd_size/2, - z_min=-pd_size/2, - z_max=pd_size/2 + RegularGrid( + n=pd_resolution, + x_min=-pd_size/2, + x_max=pd_size/2, + z_min=-pd_size/2, + z_max=pd_size/2 + ) ) end path_length_analytical = @. 2 * lambdas + 4l_0 @@ -85,7 +87,7 @@ const mm = 1e-3 empty!(pd) solve_system!(system, beam) - xs, ys, Efield = electric_field(pd; n=pd_resolution) + xs, ys, Efield = electric_field(pd, RegularGrid(n=pd_resolution)) # analytical solution short_arm = 4l_0 diff --git a/test/TestAstigmaticGaussianBeamlet.jl b/test/TestAstigmaticGaussianBeamlet.jl index 5a5ba96cf..3f7e5029a 100644 --- a/test/TestAstigmaticGaussianBeamlet.jl +++ b/test/TestAstigmaticGaussianBeamlet.jl @@ -230,7 +230,7 @@ const BMO = BeamletOptics @test isa(BMO.hits(pd)[1], BMO.AstigmaticGaussianBeamletHit) # Test field calculation - xs, zs, E = BMO.electric_field(pd; n=20) + xs, zs, E = BMO.electric_field(pd, RegularGrid(n = 20)) @test size(E) == (20, 20) @test any(!iszero, E) end diff --git a/test/TestAstigmaticGaussianPhysical.jl b/test/TestAstigmaticGaussianPhysical.jl index b02a43242..22c55fc87 100644 --- a/test/TestAstigmaticGaussianPhysical.jl +++ b/test/TestAstigmaticGaussianPhysical.jl @@ -140,7 +140,7 @@ dominant(E) = E[argmax(abs.(E))] isodd(n_mirrors) && zrotate3d!(pd, -π / 2) system = System([mirror.(mirror_pos[1:n_mirrors])..., pd]) solve_system!(system, beam) - _, _, E = BMO.electric_field(pd; n = 1, x_min = 0, x_max = 0, z_min = 0, z_max = 0) + _, _, E = BMO.electric_field(pd, RegularGrid(n = 1, x_min = 0, x_max = 0, z_min = 0, z_max = 0)) return angle(dominant(E[1]) * cis(-k * BMO.optical_path_length(beam))) end for n_mirrors in 0:3 @@ -245,7 +245,7 @@ dominant(E) = E[argmax(abs.(E))] for E0 in E0s solve_system!(system, AstigmaticGaussianBeamlet([0.0, 0, 0], [0.0, 1, 0], 1e-6, 1e-3; E0)) end - return optical_power(pd; progress = false, n = 150) + return optical_power(pd, RegularGrid(n = 150); progress = false) end P1 = power([1.0, 0, 0]) @test power([1.0, 0, 0], [1.0, 0, 0]) ≈ 4P1 rtol = 1e-9 @@ -260,7 +260,7 @@ dominant(E) = E[argmax(abs.(E))] pd = Detector(24e-3) translate3d!(pd, [0, 0.2, 0]) solve_system!(System([pd]), source; progress = false) - return optical_power(pd; progress = false, n = 200) + return optical_power(pd, RegularGrid(n = 200); progress = false) end @test source_power([1, 0, im] / sqrt(2)) ≈ source_power(ComplexF64[1, 0, 0]) rtol = 1e-3 end @@ -276,7 +276,7 @@ dominant(E) = E[argmax(abs.(E))] E0 = [0, 0, 1], support = [1, 0, 0]) solve_system!(system, beam) - xs, zs, E = BMO.electric_field(pd; n = 50) + xs, zs, E = BMO.electric_field(pd, RegularGrid(n = 50)) @test size(E) == (50, 50) @test any(!iszero, E) @@ -301,9 +301,9 @@ dominant(E) = E[argmax(abs.(E))] [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) + P1 = BMO.optical_power(pd1, + RegularGrid(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]) @@ -312,9 +312,9 @@ dominant(E) = E[argmax(abs.(E))] [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) + P2 = BMO.optical_power(pd2, + RegularGrid(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) @@ -339,7 +339,7 @@ dominant(E) = E[argmax(abs.(E))] BMO.zrotate3d!(pd_ref, deg2rad(180)) pd_size = 10mm - kw = (n = 80, x_min = -pd_size / 2, x_max = pd_size / 2, + grid = RegularGrid(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) @@ -348,7 +348,7 @@ dominant(E) = E[argmax(abs.(E))] [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...) + P_ref = BMO.optical_power(pd_ref, grid) # Measure split power system = BMO.System([bs, pd_t, pd_r]) @@ -358,8 +358,8 @@ dominant(E) = E[argmax(abs.(E))] 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 = BMO.optical_power(pd_t, grid) + P_r = BMO.optical_power(pd_r, grid) # P_t + P_r ≈ P_ref (lossless beamsplitter) @test isapprox(P_t + P_r, P_ref; rtol = 0.15) @@ -396,9 +396,9 @@ dominant(E) = E[argmax(abs.(E))] 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) + powers[i] = BMO.optical_power(pd, + RegularGrid(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 λ @@ -511,7 +511,7 @@ dominant(E) = E[argmax(abs.(E))] BMO.align3d!(pd_r, [-1.0, 0, 0]) translate_to3d!(pd_r, [60mm, 80mm, 0]) beam() = AstigmaticGaussianBeamlet([0.0, 0, 0], [0.0, 1, 0], λ, w0; P0, support = [1.0, 0, 0]) - axis_field(pd) = dominant(electric_field(pd; n = 1, x_min = 0, x_max = 0, z_min = 0, z_max = 0)[3][1]) + axis_field(pd) = dominant(electric_field(pd, RegularGrid(n = 1, x_min = 0, x_max = 0, z_min = 0, z_max = 0))[3][1]) function solve(objects...) empty!(pd_t) empty!(pd_r) diff --git a/test/TestAstigmaticGaussianSources.jl b/test/TestAstigmaticGaussianSources.jl index 4444c3e29..893362a9a 100644 --- a/test/TestAstigmaticGaussianSources.jl +++ b/test/TestAstigmaticGaussianSources.jl @@ -226,7 +226,7 @@ end pd = Detector(2half_width) translate3d!(pd, [0, L, 0]) solve_system!(System([pd]), source; progress = false) - return BeamletOptics.optical_power(pd; progress = false, n = 200) + return BeamletOptics.optical_power(pd, RegularGrid(n = 200); progress = false) end P0 = 1e-3 @testset "GaussianBeamletDecomposition is the Gaussian beam of w0 and P0" begin @@ -236,9 +236,10 @@ end pd = Detector(12w0) translate3d!(pd, [0, L, 0]) solve_system!(System([pd]), g; progress = false) - x, z, I = intensity(pd; progress = false, n = 201, x_min = -3w0, x_max = 3w0, z_min = -3w0, z_max = 3w0) + s = RegularGrid(n = 201, x_min = -3w0, x_max = 3w0, z_min = -3w0, z_max = 3w0) + x, z, I = intensity(pd, s; progress = false) w = w0 * sqrt(1 + (L * λ / (π * w0^2))^2) - @test BeamletOptics.trapz((x, z), I) ≈ P0 rtol = 1e-3 + @test optical_power(pd, s; progress = false) ≈ P0 rtol = 1e-3 # the peak intensity 2 P0 / (π w²) of the Gaussian beam, i.e. also its radius @test maximum(I) ≈ 2P0 / (π * w^2) rtol = 1e-3 end diff --git a/test/TestBugFixes.jl b/test/TestBugFixes.jl index a6c813bec..18ec92022 100644 --- a/test/TestBugFixes.jl +++ b/test/TestBugFixes.jl @@ -81,13 +81,15 @@ end BMO.solve_system!(system, beam) pd_pwr = optical_power( - pd; + 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 + RegularGrid( + 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 @@ -166,13 +168,15 @@ end solve_system!(system, gb_prb) solve_system!(system, gb_ref) pd_pwr = optical_power( - detector; + 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 + RegularGrid( + 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) end @@ -194,13 +198,15 @@ end solve_system!(system, gb_prb) solve_system!(system, gb_ref) pd_pwr = optical_power( - detector; + 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 + RegularGrid( + 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) shift_phase(gb_prb, step(phis)) diff --git a/test/TestGaussianBeamlet.jl b/test/TestGaussianBeamlet.jl index 635b787f4..b85dddf83 100644 --- a/test/TestGaussianBeamlet.jl +++ b/test/TestGaussianBeamlet.jl @@ -270,7 +270,7 @@ end function axis_field(system, pd, beam) empty!(pd) solve_system!(system, beam) - _, _, E = electric_field(pd; n = 1, x_min = 0, x_max = 0, z_min = 0, z_max = 0) + _, _, E = electric_field(pd, RegularGrid(n = 1, x_min = 0, x_max = 0, z_min = 0, z_max = 0)) return E[1] * cis(-k * BMO.optical_path_length(beam)) end gouy(args...) = rad2deg(angle(axis_field(args...))) @@ -351,7 +351,7 @@ end @test BMO.hit_count(pd_t) == 1 && BMO.hit_count(pd_r) == 1 @test transmitted ≈ direct / sqrt(2) rtol = 1e-6 # same distance behind the splitter: the reflected field differs by its sign only - _, _, E_r = electric_field(pd_r; n = 1, x_min = 0, x_max = 0, z_min = 0, z_max = 0) + _, _, E_r = electric_field(pd_r, RegularGrid(n = 1, x_min = 0, x_max = 0, z_min = 0, z_max = 0)) reflected = E_r[1] * cis(-k * BMO.optical_path_length(beam.children[2])) @test abs(reflected) ≈ abs(transmitted) rtol = 1e-6 @test abs(sind(rad2deg(angle(reflected / transmitted)))) < 1e-6 diff --git a/test/TestPolarizedRays.jl b/test/TestPolarizedRays.jl index 0f0a53887..f2cdad7fa 100644 --- a/test/TestPolarizedRays.jl +++ b/test/TestPolarizedRays.jl @@ -189,7 +189,7 @@ const BMO = BeamletOptics end # index 101 is x = 0 (crossing point), index 51 is x = -Λ/2 (half a fringe away) - x_scan(pd) = electric_field(pd; n = 201, x_min = -Λ, x_max = Λ, z_min = 0.0, z_max = 0.0) + x_scan(pd) = electric_field(pd, RegularGrid(n = 201, x_min = -Λ, x_max = Λ, z_min = 0.0, z_max = 0.0)) visibility(I) = (maximum(I) - minimum(I)) / (maximum(I) + minimum(I)) @testset "s-polarization: full-contrast fringes" begin @@ -217,7 +217,7 @@ const BMO = BeamletOptics @testset "orthogonal polarizations do not interfere" begin pd = two_ray_detector(s_pol, p_minus) - xs, zs, I = intensity(pd; n = 101, x_min = -Λ, x_max = Λ, z_min = -Λ, z_max = Λ) + xs, zs, I = intensity(pd, RegularGrid(n = 101, x_min = -Λ, x_max = Λ, z_min = -Λ, z_max = Λ)) @test maximum(I) - minimum(I) < 1e-12 * maximum(I) # the flux of each ray through the detector is cos θ of its unit irradiance @@ -227,7 +227,7 @@ const BMO = BeamletOptics @testset "tilted detector: flux falls with cos θ" begin # rays with and without polarization are weighted alike by the angle of incidence tilt = deg2rad(40) - probe(pd) = intensity(pd; n = 1, x_min = 0.0, x_max = 0.0, z_min = 0.0, z_max = 0.0)[3][1, 1] + probe(pd) = intensity(pd, RegularGrid(n = 1, x_min = 0.0, x_max = 0.0, z_min = 0.0, z_max = 0.0))[3][1, 1] pd_pol = Detector(1.0) zrotate3d!(pd_pol, tilt) @@ -284,7 +284,7 @@ const BMO = BeamletOptics W = 1.5λ / NA function normalized_psf(detector) - E = electric_field(detector; n = 101, x_min = -W, x_max = W, z_min = -W, z_max = W)[3] + E = electric_field(detector, RegularGrid(n = 101, x_min = -W, x_max = W, z_min = -W, z_max = W))[3] I = intensity.(E) Ex2 = map(e -> abs2(e[1]), E) Ey2 = map(e -> abs2(e[2]), E) @@ -333,7 +333,7 @@ const BMO = BeamletOptics sys = System([lens, psfd]) solve_system!(sys, pcs) - x, y, I_num = intensity(psfd; n = 500, crop_factor = 5, center = MinMax()) + x, y, I_num = intensity(psfd, RegularGrid(n = 500, crop_factor = 5, center = MinMax())) # walk from the peak to the first local minimum through the centre column ix_ctr, jx_ctr = Tuple(argmax(I_num)) @@ -348,9 +348,9 @@ const BMO = BeamletOptics @test x[i_min] - x[ix_ctr] ≈ airy_radius rtol = 2e-2 # vector field result feeds the scalar intensity/power pipeline - E_map = electric_field(psfd; n = 200, crop_factor = 5, center = MinMax())[3] + E_map = electric_field(psfd, RegularGrid(n = 200, crop_factor = 5, center = MinMax()))[3] @test eltype(E_map) <: BMO.Point3{<:Complex} - @test BMO.optical_power(psfd; n = 100, crop_factor = 5, center = MinMax()) > 0 + @test BMO.optical_power(psfd, RegularGrid(n = 100, crop_factor = 5, center = MinMax())) > 0 # at this NA the PSF stays isotropic and the vector effects vanish row = I_num[ix_ctr, :] diff --git a/test/TestProgress.jl b/test/TestProgress.jl index fcdccc4ee..aab3f5be0 100644 --- a/test/TestProgress.jl +++ b/test/TestProgress.jl @@ -123,8 +123,8 @@ end end @testset "electric_field for beamlet and polarized hits" begin - field_matches(pd) = electric_field(pd; n = 50, progress = true) == - electric_field(pd; n = 50, progress = false) + field_matches(pd) = electric_field(pd, RegularGrid(n = 50); progress = true) == + electric_field(pd, RegularGrid(n = 50); progress = false) @testset "GaussianBeamletHit" begin pd = Detector(20mm) diff --git a/test/runtests.jl b/test/runtests.jl index 72b6713d8..f112acb8f 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -39,6 +39,7 @@ include(joinpath(@__DIR__, "Lenses", "TestCylindricalLenses.jl")) include(joinpath(@__DIR__, "Components", "TestDummies.jl")) include(joinpath(@__DIR__, "Components", "TestDetectorUtils.jl")) include(joinpath(@__DIR__, "Components", "TestDetector.jl")) +include(joinpath(@__DIR__, "Components", "TestDetectorSampling.jl")) include(joinpath(@__DIR__, "Components", "TestBeamsplitters.jl")) include(joinpath(@__DIR__, "Components", "TestPolarizers.jl")) include(joinpath(@__DIR__, "Components", "TestPrisms.jl"))