Reference
This page contains the full source code documentation and the literature referenced througout this website.
Literature
B. A. Madruga, C. C. Dorian, M. Sehgal, A. J. Silva, M. Shtrahman, D. Aharoni and P. Golshani. Open-source, high performance miniature multiphoton microscopy systems for freely behaving animals, bioRxiv (2024).
A. Manny. Simulation of the contrast mechanisms of a heterodyne two-color interferometer. Master's thesis, Faculty of Aerospace Engineering and Geodesy, University of Stuttgart (Dec 2024).
L. Boussemaere. OpenRAMAN: a low-cost, high-performance open-source Raman spectrometer,
https://www.open-raman.org/. Hardware licensed under CERN-OHL-W-v2. Accessed 2026-07-31.B. Richards and E. Wolf. Electromagnetic diffraction in optical systems, II. Structure of the image field in an aplanatic system. Proc. R. Soc. Lond. A 253, 358–379 (1959).
G. Yun, K. Crabtree and R. A. Chipman. Three-dimensional polarization ray-tracing calculus I: definition and diattenuation. Appl. Opt. 50, 2855–2865 (2011).
G. Yun, S. C. McClain and R. A. Chipman. Three-dimensional polarization ray-tracing calculus II: retardance. Appl. Opt. 50, 2866–2874 (2011).
G. Fowles. Introduction to Modern Optics. Dover Books on Physics Series (Dover Publications, 1989).
M. Ware and J. Peatross. Physics of Light and Optics (Black & White) (Brigham Young University, Department of Physics, 2015).
B. Saleh and M. Teich. Fundamentals of Photonics. Wiley Series in Pure and Applied Optics (Wiley, 2019).
J. Arnaud. Representation of Gaussian beams by complex rays. Appl. Opt. 24, 538–543 (1985).
J. Ashcraft, poke v0.1.0, https://zenodo.org/10.5281/zenodo.7117214 (Sep 2022).
G. Wanner, E. Kochkina, C. Mahrdt, V. Müller, S. Schuster, G. Heinzel and K. Danzmann. Simulating laser interferometers for missions such as (E)Lisa, Lisa pathfinder and Grace follow-on. In: International Conference on Space Optics — ICSO 2014, Vol. 10563, edited by Z. Sodnik, B. Cugny and N. Karafolas (International Society for Optics and Photonics, SPIE, 2017); p. 105632G.
R. Herloski, S. Marshall and R. Antos. Gaussian beam ray-equivalent modeling and optical design. Appl. Opt. 22, 1168–1174 (1983).
D. DeJager and M. Noethen. Gaussian beam parameters that use Coddington-based Y–NU paraprincipal ray tracing. Appl. Opt. 31, 2199–2205 (1992).
A. W. Greynolds. Propagation Of Generally Astigmatic Gaussian Beams Along Skew Ray Paths. In: Diffraction Phenomena in Optical Engineering Applications, Vol. 0560, edited by D. M. Byrne and J. E. Harvey (International Society for Optics and Photonics, SPIE, 1986); pp. 33–51.
A. W. Greynolds. Vector Formulation Of The Ray-Equivalent Method For General Gaussian Beam Propagation. In: Current Developments in Optical Engineering and Diffraction Phenomena, Vol. 0679, edited by R. E. Fischer, J. E. Harvey and W. J. Smith (International Society for Optics and Photonics, SPIE, 1986); pp. 129–133.
R. Wilhelm. Comparing geometrical and wave-optical algorithms of a novel propagation code applied to the VLTI. In: Wave-Optical Systems Engineering, Vol. 4436, edited by F. Wyrowski (International Society for Optics and Photonics, SPIE, 2001); pp. 89–100.
A. W. Greynolds. Fat Rays Revisited: A Synthesis of Physical and Geometrical Optics with Gaußlets. In: Classical Optics 2014 (Optica Publishing Group, 2014); p. ITu1A.3.
N. Worku and H. Gross. Vectorial field propagation through high NA objectives using polarized Gaussian beam decomposition. In: Optical Trapping and Optical Micromanipulation XIV, Vol. 10347, edited by K. Dholakia and G. C. Spalding (International Society for Optics and Photonics, SPIE, 2017); p. 103470W.
E. Kochkina. Stigmatic and astigmatic Gaussian beams in fundamental mode : impact of beam model choice on interferometric pathlength signal estimates. Ph.D. Thesis, Leibniz U., Hannover (2013).
J. N. Ashcraft, E. S. Douglas, R. Anche, B. D. Dube, K. Z. Derby, L. Furenlid, M. Kautz, D. Kim, K. Milani and A. J. Riggs. A generalized expression for accelerating beamlet decomposition simulations. Opt. Express 32, 18068–18086 (2024).
E. Kochkina, G. Wanner, D. Schmelzer, M. Tröbs and G. Heinzel. Modeling of the general astigmatic Gaussian beam and its propagation through 3D optical systems. Appl. Opt. 52, 6030–6040 (2013).
International Organization for Standardization. ISO 10110-12:2019 Optics and photonics – Preparation of drawings for optical elements and systems – Part 12: Aspheric surfaces (2019).
J. Sasián. Aspheric Surfaces. In: Introduction to Lens Design (Cambridge University Press, 2019); pp. 21–29.
J. Korger, T. Kolb, P. Banzer, A. Aiello, C. Wittmann, C. Marquardt and G. Leuchs. The polarization properties of a tilted polarizer. Opt. Express 21, 27032–27042 (2013).
E. Hecht. Optik (De Gruyter, Berlin, Boston, 2018).
P. Hanrahan. A survey of ray-surface intersection algorithms. In: An Introduction to Ray Tracing (Academic Press Ltd., GBR, 1989); pp. 79–119.
T. Möller and B. Trumbore. Fast, minimum storage ray/triangle intersection. In: ACM SIGGRAPH 2005 Courses, SIGGRAPH '05 (Association for Computing Machinery, New York, NY, USA, 2005); p. 7–es.
S. Osher and R. Fedkiw. Signed Distance Functions. In: Level Set Methods and Dynamic Implicit Surfaces (Springer New York, New York, NY, 2003); pp. 17–22.
L. McMillan, G. D. Bruce and K. Dholakia. Meshless Monte Carlo radiation transfer method for curved geometries using signed distance functions. Journal of Biomedical Optics 27, 083003 (2022).
Index
BeamletOptics.BeamletOptics Module
BeamletOpticsNon-sequential 3D ray and Gaussian beamlet tracing for optical setups ("BMO"). Documentation: https://stackenjoyer.github.io/BeamletOptics.jl/stable/
AI coding assistants
The package ships an agent skill that teaches assistants such as Claude Code how to use BMO. Install the copy matching this package version into a project with BeamletOptics.install_agent_skill.
BeamletOptics.Nullable Type
Nullable{T}An alias which results in Union{T, Nothing} to provide a shorter notation for struct fields which can containing nothing.
BeamletOptics.NullableVector Type
NullableVector{T}An alias which results in Union{Vector{T}, Nothing} to provide a shorter notation for struct fields which can containing nothing.
BeamletOptics.ObjectOrGroup Type
ObjectOrGroupUnion of AbstractObject and AbstractObjectGroup: what a System or a group stores and what render! draws.
BeamletOptics.PROGRESS_SINK Constant
PROGRESS_SINKScoped ProgressSink of the running code, nothing (terminal bars) by default. Set it with Base.ScopedValues.with(PROGRESS_SINK => sink) do … end.
BeamletOptics._RenderTypes Type
A collection of all types from BMO which might be renderable in principle.
sourceBeamletOptics.golden_angle Constant
golden_angleThe golden angle π(3 - √5) ≈ 2.39996 rad, the azimuthal increment of the sunflower samplings.
BeamletOptics.AbstractBeam Type
AbstractBeam{T <: Real, R <: AbstractRay{T}}A generic type for a container type which holds rays, beams etc.
Parametrization
A subtype of AbstractBeam is parameterized by its main data type T <: Real, as well as the underlying ray representation R <: AbstractRay{T}. If a beam is to be compatible with different AbstractRay implementations, it must be parameterized by T and R. However, it can also be set to a fixed type for T and R, i.e. MyBeam <: AbstractBeam{Float32, MyRay}.
Implementation reqs.
Subtypes of AbstractBeam must implement the following:
Fields
parent: aNullablefield that holds the same type as the subtype, used for tree navigationchildren: a vector that holds the same type as the subtype, used for sub-beam tracking, i.e. beamsplitting
Getters/setters
The tree functions parent, children and isroot (from AbstractTrees) work via the parent/children fields.
Functions
trace_system!(system, beam; r_max, kwargs...): traces the beam from its last ray through thesystemuntil no object is hit or an interaction returnsnothingpush!(beam, interaction): appends the result of an interaction to the beam_component_beams(beam): returns a tuple of the beams that store the rays ofbeam, chief beam first. A beam that stores its rays itself (e.g.Beam) returns(beam,)
A beam that stores its rays itself must also implement rays and empty!, otherwise the generic methods recurse. Everything else (rays, first_ray, empty!, position, direction, the lengths and the kinematic API) has generic methods built on _component_beams.
Kinematic
AbstractBeams are BeamletOptics.Movable with a BeamletOptics.Directed frame, see BeamletOptics.AbstractKinematicTrait. A subtype needs no move methods of its own: the generic translate3d!/rotate3d! move the start ray of every component beam. Rotations are applied about the position of the beam, i.e. the start of first_ray. reset_rotation3d! throws an ArgumentError, since a beam has no orientation.
Warning
Only root beams can be moved. Every move resets the beam to its untraced start state via empty!; moving a child beam throws an ArgumentError.
BeamletOptics.AbstractBeamGroup Type
AbstractBeamGroupProvides a generic container type interface for bundles of Beams. This interface assumes that there exists a central beam around which the bundle propagates, e.g. akin to an optical axis.
Implementation reqs.
Subtypes of AbstractBeamGroup must implement the following:
Fields
beams: a vector or tuple of rootAbstractBeams, e.g.Beams orAstigmaticGaussianBeamletscenter: aPoint3{T}which is regarded as the source position, i.e. the reference origin (pivot) of the groupdir: aSMatrix{3,3,T,9}that describes the local coordinate system of the group
The columns of dir are the local x-, y- and z-axis. They must form a right-handed orthonormal basis, like the dir of an ObjectGroup. The local y-axis (second column) is the central source direction, i.e. the optical axis of the group. The local x-axis (first column) is the reference vector of the azimuthal sampling (the basis of the source constructors). Unlike a direction vector, the orientation therefore also tracks a roll of the group about its own optical axis.
Since the kinematic API modifies center and dir, the subtype must be a mutable struct.
Getters/setters
If the fields above do not exist, the following getters/setters must be dispatched:
beams: getter for thebeamsfield or equivalent return typeposition/position!: gets or sets the source position (pivot)orientation/orientation!: gets or sets the orientation matrixwavelength: getter for the common wavelength of the beam bundle
The central source direction is derived from the orientation via direction.
Functions
None required; the kinematic primitives below are generic.
Kinematic
An AbstractBeamGroup is a container: it takes the kinematic class of its beams, i.e. BeamletOptics.Movable with an BeamletOptics.Oriented frame for movable beams, see BeamletOptics.AbstractKinematicTrait. The constructors check that the beams are either all static or all movable. The following logic is applied to
translate3d!: all beams and the groupcenterare translated by the offset vectorrotate3d!: all beams are rotated around thecenterpoint with respect to their relative position,orientationis rotatedreset_translation3d!/reset_rotation3d!: moves the group back to the origin or its standard orientation (identity: the central source direction/optical axis is the global +y-axis and the azimuthal sampling reference vectorbasisis the global +x-axis); the beams are always reset, even if the group is already at the identityset_pivot3d!: moves the groupcenter(the pivot used above) without moving or resetting thebeams
Except for set_pivot3d!, every command resets each beam to its untraced start state.
BeamletOptics.AbstractBeamRenderHandle Type
Handle of a ray, beam or beam group, returned by live_render!(ax, beam). Implements rendered, render_plots, render_settings and render_settings!. update_render! draws the current rays of the beam, e.g. after solve_system!. Keep the handle on a root beam or a beam group: child beams and all rays after the first are new objects after every solve, so a handle on one of them does not follow the solved beam.
BeamletOptics.AbstractBeamletHit Type
AbstractBeamletHitStores beamlet hits. Currently implemented:
sourceBeamletOptics.AbstractBeamsplitter Type
AbstractBeamsplitter <: AbstractObjectA generic type to represent an AbstractObject that splits incoming beams by reflection and transmission.
Implementation reqs.
Subtypes of AbstractBeamsplitter should implement all supertype requirements.
Interaction logic
After intersection with the AbstractShape at which the beam splitting occurs, the interact3d function should appended the transmitted and reflected sub-beams to the parent beam via the children! function. The interact3d function should then return nothing in order to stop the tracing of the parent beam.
Appending convention
As a convention, when splitting an incoming beam, the order of children appended to the parent beam should be
transmitted beam
reflected beam
Functions
interact3d: see above_beamsplitter_transmitted_beam: optional helper function_beamsplitter_reflected_beam: optical helper function
BeamletOptics.AbstractBoundingSphere Type
Supertype of the results of bounding_sphere_of: a SingleBoundingSphere for a shape, a MultiBoundingSphere for several shapes or objects, or NoBoundingSphere for anything without one. Like a trait, bounding_sphere_of(x) selects by the type of x how x is tested against a ray, see intersect3d(sphere, x, ray); in contrast to a trait, a sphere also holds data of x, its center and radius.
Implementation reqs.
Fields
pos: the center in world coordinates [m]radius: the radius [m]
Getters/setters
position(sphere): readsposradius(sphere): readsradius
Functions
None required. The generic intersect3d(sphere, x, ray) and bounding_box use the getters. NoBoundingSphere has no fields. It has methods of its own wherever no sphere is a valid input, and its position and radius throw an ArgumentError.
BeamletOptics.AbstractCompositeSDF Type
AbstractCompositeSDF{T} <: AbstractSDF{T}Generic supertype for boolean composite SDFs, i.e. SDFs that combine two or more AbstractSDF operands into a single shape. Owns the field layout and pivot-aware kinematics shared by all boolean composites; concrete subtypes only need to define the boolean combination semantics (sdf, normal3d, thickness).
Implementation reqs.
Subtypes of AbstractCompositeSDF should implement all reqs. of AbstractSDF as well as the following:
Fields
dir::SMatrix{3, 3, T, 9}: the composite's own orientation matrixtransposed_dir::SMatrix{3, 3, T, 9}: transpose ofdirpos::Point3{T}: the composite's own position, in that field order, and the struct must bemutablesince every setter inAbstractShape.jl/AbstractSDF.jlassigns fields directly
Getters/setters
The AbstractShape getters and setters read these fields, so the composite needs no getters of its own.
Functions
operands: returns aTupleof every childAbstractSDF, in any ordersdf,normal3dandthicknessspecific to the boolean combination
BeamletOptics.AbstractCylindricalSurfaceSDF Type
AbstractCylindricalSurfaceSDF <: AbstractLensSDF{T}A class of AbstractSDFs that can be used to represent cylindric non-rotationally symmetric lens surfaces. It is implicity assumed that all surfaces are represented by closed volumes for ray-tracing correctness.
Implementation reqs.
Subtypes of AbstractCylindricalSurfaceSDF must implement the following additional methods.
Functions:
height: this function returns the height of the cylinder part of the surfaceradius: this function returns the radius of the cylinder surface curvature
BeamletOptics.AbstractDetector Type
AbstractDetector <: AbstractObjectA generic representation of a detector that evaluates AbstractBeam data during and/or after interaction. Refer to e.g. Detector for more information.
Implementation reqs.
Subtypes of AbstractDetector should implement all supertype requirements as well as:
Functions
interact3d: see e.g.Detectorfor referenceempty!: resets data stored in the detector, see below.initialize!calls it for all detectors of a system
Additional information
The information provided below applies to the standard functional implementation of this type and may be overwritten by specialized subtypes.
Data mutability
In order to model field superposition effects, the concrete implementation of an AbstractDetector should be a mutable struct with a constant shape field. This is necessary, since (sub-)beams will interact sequentially with the detector during solve_system!. Only if the data can be accumulated sequentially, multiple beam interactions can be captured for a complex system, e.g. an interferometer.
Data reset
Since e.g. E-field data is supposed to be accumulated by mutability of the detector data, the burden of resetting the data for a new solver call is placed on the user. This function should be called empty!. A single detector is reset with empty!(detector), all detectors of a System or ObjectGroup with initialize!, which calls empty! on every AbstractDetector. The solver does not reset detectors unless asked to (keyword initialize of solve_system!), since the beams of a beam group and several sources solved one after another are meant to superpose.
Every kinematic function empties a detector, since the stored data belong to the pose of the detector during the solve, see translate3d!(::Movable, ::AbstractDetector, offset). A subtype gets this from its empty! method without further code.
BeamletOptics.AbstractDetectorHit Type
AbstractDetectorHitAbstract supertype for all Detector hit records.
A hit of this type encapsulates the interaction of a ray or beamlet with the Detector 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).
Implementation reqs.
Functions
Subtypes of AbstractDetectorHit must implement the following functions:
electric_field(hit, p): the field of the hit at a global pointp, seeelectric_field(::BeamletOptics.AbstractDetectorHit, ::AbstractVector)direction(hit): the direction of propagation at the hithit_point(hit): the global point where the ray or chief ray crossed the detector, forray_hitsrefractive_index(hit): the refractive index in front of the detectorintensity(hits, p, n̂): the irradiance of a vector of such hits at a global pointpthrough a plane with the normaln̂, seeintensitycalc_local_lims(pd, hits, crop_factor::Real; center::AbstractCenterAlgorithm = Centroid()): the window of the defaultRegularGridaround the hitscalc_local_lims(pd, hits, ::Nothing; center::AbstractCenterAlgorithm = Centroid()): the same window with the defaultcrop_factorof the hit typecalc_local_pos(pd, hits): the local (x, z) positions of the hits forspot_diagram
The readouts of a Detector (electric_field, intensity, optical_power) need all of them except hit_point and calc_local_pos.
Info
Note that new subtypes of AbstractDetectorHit must be manually added to the Detector definition to be eligible.
Concrete subtypes include:
RayHit— unpolarized geometric rayPolarizedRayHit— ray carrying a polarization stateGaussianBeamletHit— single Gaussian beamletAstigmaticGaussianBeamletHit— single astigmatic Gaussian beamlet with a vector field
BeamletOptics.AbstractDetectorSampling Type
Abstract supertype of the samplings of a Detector: a sampling decides where on the detector the readouts electric_field, intensity and optical_power are evaluated, in which window, and with which weights the power is integrated.
Implementation reqs.
Functions
sample_points(pd::Detector, sampling::S) -> DetectorSamples: the points, weights and coordinates of the sampling onpd, seesample_points. The window is the business of the sampling: it may look at the hits ofpd, e.g. asRegularGriddoes, or take a fixed one, asRectilinearGriddoes. All readouts then work for the new sampling.
Concrete subtypes include:
RegularGrid—num_points×num_pointspoints in a window around the hitsRectilinearGrid— the gridxs × zsof one's own, with any spacing
BeamletOptics.AbstractInteraction Type
AbstractInteractionDescribes how an AbstractBeam and an AbstractObject interact with each other. This data type stores information from the interact3d function and provides it to the solver. The solver can use this data to extend the AbstractBeam.
Implementation reqs.
Subtypes of AbstractInteraction must implement the following:
Fields
hint: a nullableHintfor the solver. The field is required, since the solver reads it for every interaction, but it may benothing
Beam data
It is required that concrete implementations of this type provide some form of data on how to extend the beam. For instance, refer to theBeamInteraction and GaussianBeamletInteraction.
BeamletOptics.AbstractJonesPolarizer Type
AbstractJonesPolarizer <: AbstractObjectRepresents infinitesimally thin components that change the polarization state of incoming PolarizedRays via global Jones matrix calculus. Rather than using the generic Yun ray tracing scheme as referred to in the PolarizedRay docs, this element interacts with the global E-field vector E0 by using a GlobalJonesBasis and projecting the entries into the transverse plane defined by the incoming ray direction and orthogonal E-field vector. This approach is partially inspired by the publication:
Jan Korger et al., "The polarization properties of a tilted polarizer," Opt. Express 21, 27032-27042 (2013)
Warning
It is assumed that the ray direction of propagation is not changed during the interaction.
Implementation reqs.
Subtypes of AbstractJonesPolarizer should implement all supertype requirements.
Interaction logic
The GlobalJonesBasis tracks the rotation in 3D-space via the orientation of the attached AbstractShape. The polarization matrix P is calculated by projecting the previous matrix into the incoming orthogonal plane of polarization. Refer to the _calculate_global_E0 implementation for more information.
Info
The validity of this approach is still under consideration for non-normal incidence.
BeamletOptics.AbstractKinematicFrame Type
Reference frame of a Movable value, either Oriented or Directed.
BeamletOptics.AbstractKinematicTrait Type
The kinematic trait defines whether an entity can be moved by the kinematic API (translate3d!, rotate3d!, ...). It is returned by kinematic_trait_of and follows the same dispatch pattern as AbstractShapeTrait: every public function e.g. translate3d!(x, args...) forwards to translate3d!(kinematic_trait_of(x), x, args...).
Two traits are defined:
Static:xcannot be moved, every kin. function throws anArgumentErrorMovable:xcan be moved; its frame (OrientedorDirected) selects orientation- or direction-based behaviour
The trait is opt-in: shapes, objects, rays, beams, beam groups and object groups declare it on their abstract type, any other type with its own kinematic_trait_of method. For a type without a method, kinematic_trait_of and every kinematic function throw an ErrorException.
A subtype of a movable abstract type can opt out of the kinematic API by declaring its own kinematic_trait_of method, e.g.
struct FixedMirror{T, S <: AbstractShape{T}} <: AbstractObject{T}
shape::S
end
kinematic_trait_of(::FixedMirror) = Static()Every kinematic function on a FixedMirror now throws an ArgumentError; its getters (position, orientation, ...) stay available.
Containers
All members of a container (ObjectGroup, UnionSDF/DifferenceSDF, AbstractBeamGroup) must be either all Static or all Movable. Frames can still be mixed. This must be checked in the respective constructors; nesting is then covered because a nested container already has a uniform class from its own constructor. The container then takes that class: Static if all members are Static, else Movable(Oriented()). All shapes returned by shape(object) of a MultiShape object must be movable, since MultiShape objects (e.g. a CubeBeamsplitter) have no shared constructor to enforce this.
A container moves each of its members once per motion, compared by identity (===). Two members that reach the same shape, or a static value at any level, throw an ArgumentError before anything moves, see shape.
BeamletOptics.AbstractLensSDF Type
AbstractLensSDFA class of AbstractSDFs that can be used to represent rotationally symmetric lens surfaces. It is implicity assumed that all surfaces are represented by closed volumes for ray-tracing correctness.
Implementation reqs.
Subtypes of AbstractLensSDF must implement the following:
Functions:
thickness: this function returns the material thickness of the element along its symmetry axisdiameter: this function returns the outer diameter of the element
Shape orientation
For easy compatibility between subtypes, the follwing requirements should be fulfilled:
Symmetry axis aligned onto the y-axis
Surface contour aligned towards negative y-values
Surface point with
min(y)should satisfymin(y) = 0on the symmetry axis
BeamletOptics.AbstractMesh Type
AbstractMesh <: AbstractShapeA generic type for a shape whose volume can be described by a mesh. See also Mesh{T}.
Implementation reqs.
Subtypes of AbstractMesh should implement all reqs. of AbstractShape as well as the following:
Fields
vertices: (m x 3)-matrix that stores the points of all trianglesfaces: (n x 3)-matrix of row indices intovertices, one row per trianglescale: scalar value that represents the current scale of the mesh
BeamletOptics.AbstractObject Type
AbstractObjectA generic type for 2D/3D objects that can be used to model optical elements. The geometry of the object is represented via an AbstractShape. The optical effect that occurs between the object and an incoming ray/beam of light is modeled via its interact3d method.
Implementation reqs.
Subtypes of AbstractObject must implement the following:
Shape trait
An AbstractObject can consist of a single AbstractShape, e.g. a lens element, or a collection of functionally dependant shapes, e.g. a cube beamsplitter. In order to model this, the API implementation of an AbstractObject requires the definition of the shape trait. This trait allows the dispatch onto specialized methods to handle the kinematic interface and tracing methods for objects consisting of one or more shapes.
shape_trait_of: defines the shape type of theAbstractObject, refer toAbstractShapeTraitfor more information
Default shape trait
Unless specified otherwise, the shape_trait_of an AbstractObject is defined as SingleShape. This requires object.shape as a dedicated field. For MultiShapes the getter function shape(object) must return a tuple of all shapes that make up the object.
Getters/setters
All kinematic functions defined for the AbstractShape can also be called for a AbstractObject. In this case, the shape trait will define how the specific movement function is dispatched.
Kinematic
AbstractObjects are BeamletOptics.Movable with an BeamletOptics.Oriented frame, see BeamletOptics.AbstractKinematicTrait. The primitives translate3d!(::Movable, object, offset) and rotate3d!(::Movable, object, R::AbstractMatrix) forward to the shape trait. A subtype can opt out of the kinematic API via BeamletOptics.kinematic_trait_of(::Foo) = BeamletOptics.Static().
Functions:
interact3d: defines the optical interaction, the return type must beNothingor anAbstractInteractioninitialize!(optional): resets the data that the object stores during a solve, e.g. the hits of a detector. By default nothing is reset.intersect3d(object, ray)(optional): replaces the default intersection of the object, which tests its shapes via the shape trait, e.g. theRectangularPlateBeamsplitterdoes so. The solver still skips the object if the ray misses its bounding sphere or enters it only beyond a hit found already, hence every hit of the method must lie within the sphere of the object:bounding_sphere_of(object)for aSingleShapeobject, the sphere around the parts for aMultiShapeobjectbounding_sphere_of(object)(optional): the sphere around aSingleShapeobject, if it differs from the sphere of its shape. The default is the sphere ofshape(object), seebounding_sphere_of. An object whose ownintersect3dhits points outside of its shape returnsNoBoundingSphere()
BeamletOptics.AbstractObjectGroup Type
AbstractObjectGroupContainer type for groups of optical elements, based on a tree-like data structure. Intended for easier kinematic handling of connected elements. See also ObjectGroup for a concrete implementation.
A ray or beam interacts with the object of the group that it hits. A component whose parts interact as one, e.g. a cemented doublet, is an AbstractObject with the MultiShape trait.
Own assembly types
An assembly of separate parts, e.g. a telescope from its mirrors, can be a subtype of AbstractObjectGroup with named parts and its own constructor: it needs the fields below and no interact3d method, and the kinematic API, set_pivot3d!, systems and rendering work as for an ObjectGroup. See templates/08_custom_group.jl of the agent skill.
Implementation reqs.
Subtypes of AbstractObjectGroup must implement the following:
Fields
objects: a tuple or a vector ofAbstractObjects or additional subgroups, allows for hierarchical structures. OnlyObjectGroupcan be changed after its construction, viapush!,delete!,pop!andpopat!.center: aPoint3{T}which is regarded as the reference origin (pivot) of the groupdir: aSMatrix{3,3,T,9}that describes the local coordinate system of the group
Since the kinematic API modifies center and dir, the subtype must be a mutable struct.
Getters/setters
If the fields above do not exist, the following getters/setters must be dispatched:
objects: getter for theobjectsfield or equivalent return typeposition/position!: gets or sets the reference origin (pivot)orientation/orientation!: gets or sets the orientation matrix
Functions
None required: no interact3d method; the kinematic primitives below are generic.
Kinematic
An AbstractObjectGroup is a container: it takes the kinematic class of its objects, i.e. BeamletOptics.Movable with an BeamletOptics.Oriented frame for movable objects, see BeamletOptics.AbstractKinematicTrait. The constructors must check that the objects are either all static or all movable, i.e. that kinematic_trait_of returns BeamletOptics.Static for every object or a Movable for every object: call BeamletOptics.check_kinematic_members(objects). The primitives translate3d!(::Movable, group, offset) and rotate3d!(::Movable, group, R::AbstractMatrix) move all objects and the pose of the group. A group that is nested in another group moves as a frame (position!/orientation!), its own primitives are not called then.
BeamletOptics.AbstractObjectRenderHandle Type
Handle of one movable thing, returned by live_render!(ax, obj) for an AbstractObject or an object group and by live_render!(draw, ax, x) for anything with a pose. The plots are drawn once; update_render! applies the current pose of rendered(h) as their model matrix (and draws them again if the parts of a MultiShape object moved relative to each other). After a change of the shape, rerender! draws the object again, in place of the old plots. pick_object returns rendered(h) for the plots of pickable_plots.
BeamletOptics.AbstractPlateBeamsplitter Type
A generic type to represent an AbstractBeamsplitter that consists of a substrate with a single coated face at which a beam splitting interaction occurs.
Implementation reqs.
Subtypes of AbstractPlateBeamsplitter should implement all supertype reqs. as well as:
Fields
coating: aThinBeamsplitterthat represents the splitter coatingsubstrate: aPrismthat represents the substrate
Getters/setters
If the concrete implementation does not define the above fields, the following getters must be defined:
coating: returns aThinBeamsplittersubstrate: returns aPrism
Additional information
Object orientation
This interact3d method of this type strongly assumes that the coating is positioned directly upon a single face of the substrate with a 100% fill factor.
Interaction logic
This type uses the Hint-API in order to ensure that the splitting interaction is correctly triggered at the coating.
BeamletOptics.AbstractRay Type
AbstractRay{T<:Real}An implementation for a geometrical optics ray in R³. In general, a AbstractRay is described by AbstractRays are intended to model the propagation of light between optical interactions according to the laws of geometrical optics. To store the result of a ray tracing solution, refer to AbstractBeam.
Intersections:
Since the length of a ray can not be known before solving an optical system, the Intersection-type is used. This Nullable type can represent the intersection with an optical element, or lack thereof.
Implementation reqs.
Subtypes of AbstractRay must implement the following:
Fields:
pos: a R³-vector that stores the current positiondir: a R³-vector that stores the current directionintersection: aNullablefield that stores the current [Intersection] ornothingλ: wavelength in [m]n: refractive index along the ray path
Functions:
empty!: resets the ray to its initial, unsolved stateintersect3d: calculates theIntersectionbetween a ray and a shaperotate3d!(::Movable, ray, R::AbstractMatrix): only required for subtypes carrying direction-dependent data (e.g. field vectors); must rotate this data together with the ray direction and clear the intersection
Kinematic
AbstractRays are BeamletOptics.Movable with a BeamletOptics.Directed frame, see BeamletOptics.AbstractKinematicTrait. Every verb clears the ray Intersection, i.e. resets the ray to its unsolved state. Rotations are applied about the ray start position. reset_rotation3d! throws an ArgumentError, since a ray has no orientation.
Additional information
Ray length
Base.length: this function is used to return the length of the AbstractRay (if no intersection exists, the ray length is Inf). Use optical_path_length to obtain the optical path length instead.
Ray direction
Many functions assume that the direction vector has unit length (i.e.
BeamletOptics.AbstractRayHit Type
AbstractRayHit{T} <: AbstractDetectorHitAbstract supertype for detector hits produced by AbstractRays. Currently the following concrete types are implemented:
A hit stores the values of the ray at the moment it hit the detector, not the ray itself: a new solve of the beam or a move of any object does not change it.
Implementation reqs.
Fields
The default getters read these fields:
p: the R³ point of intersectiondir: the direction of the rayopl: the optical path length of the beam up to the hit point (incl. its parents)λ: the vacuum wavelength of the rayn: the refractive index in front of the detectorproj: the projection factor, see below
Functions
Subtypes of AbstractRayHit must implement the following functions:
hit_point: the R³ point of intersectiondirection: the direction of the rayoptical_path_length: the optical path length of the beam up to the hit point (incl. its parents)wavelength: the vacuum wavelength of the raywavenumber: the vacuum wavenumber2π / λrefractive_index: the refractive index in front of the detectorprojection_factor:|d · n|of the ray directiondand the surface normaln;1if the ray ended without an intersection
BeamletOptics.AbstractReflectiveOptic Type
A generic type to represent an AbstractObject which reflects incoming rays.
Implementation reqs.
Subtypes of AbstractReflectiveOptic should implement all supertype reqs. as well as:
Fields
- no specific fields required
Getters/setters
- none required
Functions
interact3d: the interaction logic should be akin toreflection3dfor each surface crossing
Additional information
The information provided below applies to the standard functional implementation of this type and may be overwritten by specialized subtypes.
Polarization ray tracing
Fresnel coefficients during reflection are set such that no reflection losses occur (i.e. |rₚ| = |rₛ| = 1).
BeamletOptics.AbstractRefractiveIndex Type
A generic representation of the refractive index n(λ) of a material, passed as n to e.g. Lens, Prism and the beamsplitters. See ConstantRefractiveIndex, DiscreteRefractiveIndex and SellmeierEquation.
Implementation reqs.
Subtypes of AbstractRefractiveIndex must implement the following:
Functions
(n::AbstractRefractiveIndex)(λ): returns the refractive index as aRealfor the wavelengthλin [m], for anyRealtype ofλwithin the domain of the model
Additional information
Domain
A model may be defined for some wavelengths only, e.g. a DiscreteRefractiveIndex only at its stored wavelengths.
BeamletOptics.AbstractRefractiveOptic Type
A generic type to represent an AbstractObject that refracts incoming rays.
Implementation reqs.
Subtypes of AbstractRefractiveOptic should implement all supertype reqs. as well as:
Fields
n: theAbstractRefractiveIndexof the material, called asn(λ)
Getters/setters
refractive_index: gets the ref. index data of the optic
Functions
interact3d: the interaction logic should be akin torefraction3dfor each surface crossing
Additional information
The information provided below applies to the standard functional implementation of this type and may be overwritten by specialized subtypes.
Uniform ref. index
It is assumed that the optic consists of a single transparent material with a homogeneous refractive index n. It does not consider coated surfaces.
Polarization ray tracing
Fresnel coefficients at the point of refraction are calculated via the fresnel_coefficients function with the refractive index data of the substrate and the previous medium.
BeamletOptics.AbstractRenderHandle Type
AbstractRenderHandleSupertype of all handles returned by live_render!. A handle references the rendered object, system or beam and its plots, which can be re-synchronized via update_render!, drawn again via rerender! and deleted via remove_render!. Concrete handles are implemented by the Makie extension.
Render handle protocol
Every handle implements rendered and render_plots. The subtypes add:
AbstractObjectRenderHandle: one movable thing, e.g. an object or a marker drawn vialive_render!(draw, ax, x)AbstractSystemRenderHandle: the object handles of a system, with its hierarchy of groupsAbstractBeamRenderHandle: a ray, beam or beam group, withrender_settingsandrender_settings!
Code that uses handles, e.g. a GUI, relies on this protocol only, and may add own subtypes, e.g. a system handle that combines the handles of several systems.
sourceBeamletOptics.AbstractRotationallySymmetricSurface Type
AbstractRotationallySymmetricSurface{T} <: AbstractSurface{T}A surface type which is rotationally symmetric around one axis.
Implementation reqs.
Subtypes of AbstractShape should implement the following:
Getters/setters
radius: Returns the radius of curvature of theAbstractRotationallySymmetricSurfacediameter: Returns the clear optical diameter of theAbstractRotationallySymmetricSurfacemechanical_diameter: Returns the mechanical diameter of theAbstractRotationallySymmetricSurfaceedge_sag: Returns the edge sagitta of theAbstractRotationallySymmetricSurface
Functions:
sdf(::AbstractRotationallySymmetricSurface, ::Union{Nothing, AbstractOrientationType}): Converts the surface specification ofAbstractRotationallySymmetricSurfaceinto anAbstractSDF
BeamletOptics.AbstractSDF Type
AbstractSDF <: AbstractShapeProvides a shape function based on signed distance functions. See https://iquilezles.org/articles/distfunctions/ for more information.
Implementation reqs.
Subtypes of AbstractSDF should implement all reqs. of AbstractShape as well as the following:
Fields
transposed_dir: the transpose ofdir, whichorientation!keeps in sync and which_world_to_sdfreads
Functions
sdf(::AbstractSDF, point): a function that returns the signed distance for a point in 3D space, usually evaluated at_world_to_sdf(sdf, point)thickness(::AbstractSDF)(optional): the material of the shape on its optical axis (local y) in [m]
_world_to_sdf(sdf, point) is provided: it transforms a world point into the local frame of the sdf via position and transposed_dir, such that sdf only has to describe the shape at the origin.
BeamletOptics.AbstractShape Type
AbstractShape{T<:Real}A generic type for a shape that exists in 3D-space. Must have a position and orientation. Types used to describe the geometry of a shape should be subtypes of Real.
Implementation reqs.
Subtypes of AbstractShape should implement the following:
Fields:
pos: a 3D-vector that stores the currentpositionof the object-specific coordinate systemdir: a 3x3-matrix that represents the orthonormal basis of the object and therefore, theorientation
Getters/setters
position/position!: gets or sets theposition vector of theAbstractShapeorientation/orientation!: gets or sets the orientation matrix of theAbstractShape
Kinematic
AbstractShapes are BeamletOptics.Movable with an BeamletOptics.Oriented frame, see BeamletOptics.AbstractKinematicTrait. The default primitives translate3d!(::Movable, shape, offset) and rotate3d!(::Movable, shape, R::AbstractMatrix) act on position/orientation; subtypes with additional geometry data (e.g. mesh vertices) dispatch their own.
Ray Tracing:
intersect3d: returns the intersection between anAbstractShapeandAbstractRay, or lack thereof. See alsoIntersectionbounding_sphere_of(optional): computes a sphere that encloses the shape. A solve then skips the shape for every ray that misses the sphere, without a call ofintersect3d
Rendering (with Makie):
Refer to the render! documentation.
BeamletOptics.AbstractShapeTrait Type
AbstractShapeTraitThe shape trait defines how many shapes an AbstractObject consists of. Two different traits are defined:
SingleShape: theAbstractObjectconsists of a singleAbstractShapeMultiShape: theAbstractObjectconsists of two or more parts, i.e.AbstractShapes or objects
Refer to the respective documentation for more information
sourceBeamletOptics.AbstractSourceSampling Type
How the rays of a CollimatedSource or PointSource are sampled. The source stores its sampling in the field sampling, such that num_rays! can regenerate its rays with another number of rays. A source built from given beams stores BeamletOptics.NoSampling. The generic constructors CollimatedSource(pos, dir, diameter, sampling, λ; num_rays) and PointSource(pos, dir, sampling, λ; num_rays) build a source from any sampling; the catalog constructors call them.
Implementation reqs.
Parameters of the sampling other than the number of rays (e.g. the number of rings or the half spread angle) are fields of the subtype.
Functions
A subtype S <: AbstractSourceSampling implements:
source_beams(s::S, pos, dir, b1, args..., λ, num_rays::Int, T) -> Vector{<:Beam}: the beams of the source, seeBeamletOptics.source_beams.argsare the arguments of the source type, i.e. thediameter[m] for aCollimatedSourceand none for aPointSource. The sampling pattern must depend on the pose only viapos,dirandb1, i.e. it must move rigidly with the source. The first beam must be the center ray, which starts atposalongdir. Throws anArgumentErrorifnum_raysis belowmin_num_rays(s).min_num_rays(s::S) -> Union{Nothing, Int}(optional): the fewest rays of the sampling, default1, seeBeamletOptics.min_num_rays.numerical_aperture(s::S): the numerical aperture of the half spread angle, required for a sampling of aPointSource. The fallback throws anErrorException.
Implementations
BeamletOptics.NoSampling: given beams, can not be regeneratedBeamletOptics.DiscRings,BeamletOptics.DiscSunflower,BeamletOptics.DiscLine:CollimatedSourceBeamletOptics.ConeRings,BeamletOptics.ConeSunflower,BeamletOptics.ConeFan:PointSource
BeamletOptics.AbstractSphericalSurfaceSDF Type
AbstractSphericalSurfaceSDF{T} <: AbstractSDF{T}An abstract type for SDF-based volumes which represent spherical lens surfaces, i.e. ConvexSphericalSurfaceSDF or ConcaveSphericalSurfaceSDF.
Implementation reqs.
Subtypes of AbstractSphericalSurfaceSDF should implement all supertype reqs. as well as the following:
Fields:
radius: the radius of curvaturediameter: the lens outer diametersag: the lens sagitta
Lens construction
It is intended that practical lens shapes are constructed from AbstractSphericalSurfaceSDFs using the UnionSDF type.
BeamletOptics.AbstractSurface Type
AbstractSurface{T}A generic type for a surface which is basically an information storage type in order to build shapes (volumes) from a combination of surfaces.
sourceBeamletOptics.AbstractSystem Type
AbstractSystemA generic representation of a system of optical elements.
Implementation reqs.
Subtypes of AbstractSystem must implement the following:
Fields:
objects: a vector or tuple ofAbstractObjects and object groups (AbstractObjectGroup) that make up the system. The solver does not read this field itself but calls the functionobjects, see below
Functions:
objects(system): returns the objects of the system with object groups flattened into their objects. There is no fallbackAbstractTrees.children(system)(optional): returns the top-level objects and groups of the system, which the solver tests. The default isobjects(system)refractive_index(system, λ::Real)(optional): returns the refractive index of the surrounding medium at the wavelengthλ. The default is1.0; a system does not store a refractive index
The solver tests a ray against children(system). The built-in System returns its groups unflattened: the solver tests the bounding sphere of a group first and then its objects one by one. A StaticSystem flattens its groups when it is built.
BeamletOptics.AbstractSystemRenderHandle Type
Handle of a system, returned by live_render!(ax, sys): one AbstractObjectRenderHandle per object, object groups rendered per object, such that each object of a group can be moved on its own. A subtype implements
rendered(h): the systemAbstractTrees.children(h): the object handlesrender_parent(h, obj): the group that holdsobj, ornothingat the top levelpush!(h, oh::AbstractObjectRenderHandle): adds the object handleohat the top level, e.g. of an object added to the scene, and returnshdelete!(h, oh::AbstractObjectRenderHandle): removesohfromhand returnsh; its plots stay, seeremove_render!
render_plots, update_render!, rerender!, remove_render! and pick_object of a system handle are defined in terms of these.
A handle that knows its axis, like the one returned by live_render!(ax, sys), also implements live_render!(h, obj; kwargs...), which renders an object (or object group) into h at runtime, and extends remove_render!(h, obj) by the hierarchy of the groups.
BeamletOptics.AconcaveCylinderSDF Type
AconcaveCylinderSDF{T} <: AbstractAcylindricalSurfaceSDF{T}Implements the SDF of a concave cylinder with radius r, diameter d and height h.
BeamletOptics.AconcaveCylinderSDF Method
AconcaveCylinderSDF(radius, diameter, height)Constructs an aconcave cylinder cutout with radius r, diameter d and height h in [m]. The acylindric shape is defined by its conic_constant and the coefficients for the even aspheric polynomial, starting with A2 (r²).
BeamletOptics.AconvexCylinderSDF Type
AconvexCylinderSDF{T} <: AbstractAcylindricalSurfaceSDF{T}Implements the SDF of a cut cylinder with radius r, diameter d and height h.
BeamletOptics.AconvexCylinderSDF Method
AconvexCylinderSDF(radius, diameter, height)Constructs an aconvex cylinder with radius r, diameter d and height h in [m]. The acylindric shape is defined by its conic_constant and the coefficients for the even aspheric polynomial, starting with A2 (r²).
BeamletOptics.AcylindricalSurface Type
AcylindricalSurface{T} <: AbstractAcylindricalSurface{T}A type representing an acylindric optical surface defined by its radius of curvature, diameter, height, mechanical diameter, conic constant and even aspheric coefficients. It is therefore a cylindric surface with a deviation from the perfect cylindric shape.
Fields
radius::T: The radius of curvature of the curved surface.diameter::T: The clear (optical) aperture of the surface.height::T: The height/length of the uncurved surface directionconic_constant::T: The conic_constant of the curved surfacecoefficients::Vector{T}: The coefficients of the even aspherical equation for the curved surface, starting with A2 (r²).mechanical_diameter::T: The overall mechanical diameter of the surface. In many cases, this is equal to the optical diameter, but it can be set independently if the mechanical mount requires a larger dimension.
BeamletOptics.AcylindricalSurface Method
AcylindricalSurface(radius, diameter, height, conic_constant, coefficients)Construct a CylindricalSurface given the radius of curvature, optical diameter and height. This constructor automatically sets the mechanical diameter equal to the optical diameter.
Arguments
radius: The radius of curvature of the curved surface.diameter: The clear (optical) diameter of the surface.height: The height/length of the uncurved surface direction.conic_constant::T: The conic_constant of the curved surfacecoefficients::Vector{T}: The coefficients of the even aspherical equation for the curved surface, starting with A2 (r²).
BeamletOptics.AstigmaticBeamGroup Type
AstigmaticBeamGroup{T, R} <: AbstractBeamGroup{T, R}A generic container for groups of AstigmaticGaussianBeamlets.
Fields
beams: vector of all beamletscenter: source position, pivot for rotationsdir: theorientationof the group, a right-handed orthonormal matrix whose columns are the sampling reference vector, the central source direction and their cross product, seeAbstractBeamGroup
BeamletOptics.AstigmaticBeamGroup Method
AstigmaticBeamGroup(beams, pos, dir::AbstractVector)
AstigmaticBeamGroup(beams, pos, orientation::AbstractMatrix)Wraps existing beams into an AstigmaticBeamGroup with the source position pos. The group orientation is either derived from the central direction dir (the sampling reference vector is then picked deterministically via normal3d), or passed explicitly as a right-handed orthonormal 3x3 orientation matrix whose second column is the central direction. An invalid orientation throws an ArgumentError.
BeamletOptics.AstigmaticGaussianBeamlet Type
AstigmaticGaussianBeamlet(position, direction, λ, w0; kwargs...)Constructs an astigmatic Gaussian beamlet at position 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 beamletdirection: 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 1P0: beam total power in [W]. Default is 1 mW.E0: electric field vector in [V/m] atposition, it replacesP0. Default isnothing(aligned with support axes, scaled byP0, zero Gouy phase at the waist).support: optional support vector for basis construction, i.e. the X axis of the beamlet. Must be orthogonal todirection, otherwise anArgumentErroris thrown; has any non-zero length and is normalized internally. Default isnothing, i.e. a vector orthogonal todirectionis chosen.z0: beam waist offset in [m]. Default is 0 m
Additional information
Waist offset
As for a GaussianBeamlet, the z0 keyword arg. spawns a beam at the specified position with its waist at an offset z0 in [m] along the chief ray axis.
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.
BeamletOptics.AstigmaticGaussianBeamlet Type
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 and 8 auxiliary Rays 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: chiefBeamofPolarizedRaysparent: reference to the parent beam (ornothing)children: vector of child beams (e.g. after beam-splitting)
Additional information
Waist and field calculation
For a given beamlet the Gaussian beam parameters can be obtained via the gauss_parameters function.
BeamletOptics.AstigmaticGaussianBeamlet Method
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: Origin 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: Offset of the X waist frompositionalong the propagation axis in [m]. Defaults toz0.z0_y: Offset of the Y waist frompositionalong the propagation axis in [m]. Defaults toz0.z0: Default forz0_xandz0_y. Default is 0 m.M2_x,M2_y: Beam quality factors. Default is 1.P0: Total power in [W].E0: Optional electric field vector in [V/m] atposition, it replacesP0.support: Optional vector orthogonal todirectionto define the X axis. Has any non-zero length and is normalized internally. Asupportthat is not orthogonal to thedirection(the dot product of the unit vectors exceedsget_orthogonality_threshold(), default1e-10) throws anArgumentError. Default isnothing, i.e. a vector orthogonal todirectionis chosen.
Additional information
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.
BeamletOptics.AstigmaticGaussianBeamletHit Type
AstigmaticGaussianBeamletHit{T} <: AbstractBeamletHit{T}Stores the segment of an AstigmaticGaussianBeamlet that hit the detector as values, without a reference to the beamlet: p0 and dir are start and direction of the segment, l_seg its length, l0 the length of the beam (including its parents) up to p0, Δl0 the optical minus the geometric path up to there, n the refractive index of the segment, λ the wavelength, k0 the vacuum wavenumber and E0 the polarization of the chief ray of the segment. h1, u1, h2 and u2 are the parabasal ray parameters at p0. The amplitude and Gouy factor of the complex beam area a at the local distance l behind p0 is gouy0 / (√(1 − ρ1 l) √(1 − ρ2 l)): gouy0 is the change of the amplitude with the beam area and the Gouy phase up to p0, followed from the start of the root beam (see _area_from_root), and ρ1 and ρ2 are the inverse roots of a(l) (see area_inverse_roots).
BeamletOptics.AstigmaticGaussianBeamletHit Method
AstigmaticGaussianBeamletHit(agb::AstigmaticGaussianBeamlet, id)Hit record of the traced segment id of agb: the data that electric_field(hit, p) needs to evaluate the field of that segment at any point near it, including the optical path from the source (parents included), the Gouy factor and the amplitude. The amplitude is that of the polarization of the chief ray of the segment, times the change with the beam area within the segments since the start of the root beam; the Gouy phase is followed from there as well, i.e. a child beamlet continues its parent. Detectors store one per beamlet that hits them; it can also be built for any traced segment, e.g. to sample a beamlet on a plane of one's own. The hit keeps no reference to agb: a new solve of agb does not change it.
BeamletOptics.AstigmaticGaussianBeamletInteraction Type
Stores the interaction result for all 9 component beams of an AstigmaticGaussianBeamlet. Uses the hint from the chief beam interaction.
Fields
chief:BeamInteractionfor the chief raywxp,wxm,wyp,wym: waist beam interactionsdxp,dxm,dyp,dym: divergence beam interactions
BeamletOptics.Beam Type
Beam{T, R <: AbstractRay{T}} <: AbstractBeam{T, R}Stores the rays that are calculated from geometric optics when propagating through an optical system. The Beam type is parametrically defined by the AbstractRay subtype that it stores.
Fields
rays: vector ofAbstractRayobjects, representing the rays that make up the beamparent: reference to the parent beam, if any (Nullableto account for the root beam which has no parent)children: vector of child beams, each child beam represents a branching or bifurcation of the original beam, i.e. beam-splitting
BeamletOptics.Beam Method
Beam(pos, dir, λ, E0)Spawns a Beam of PolarizedRays at the start position in the specified direction with the wavelength λ and the electric field vector E0, which may be complex, e.g. [1, 0, im] / √2 for circular polarization. The number type of the beam is that of the PolarizedRay, i.e. real also for a complex E0.
BeamletOptics.Beam Method
Beam(pos, dir, λ=1e-6)Spawns a Beam at the start position in the specified direction with the wavelength λ = 1000 nm.
BeamletOptics.BeamInteraction Type
BeamInteraction <: AbstractInteractionThis type is used to store the new AbstractRay resulting from on optical interaction between a Beam and some AbstractObject.
Fields
hint: optionalHintfor the solverray: newAbstractRayresulting from the interaction
BeamletOptics.BoundingSphereTable Type
The table of the bounding spheres of a solve, keyed by shape, object or group (by identity). The values have concrete types, such that the lookup per ray needs no dynamic dispatch.
sourceBeamletOptics.BoxSDF Type
BoxSDF <: AbstractSDFImplements the box SDF with edge lengths x, y, and z. Note that these values are stored in the dimensions field as:
dimensions::Point3 = ( len_in_x/2, len_in_y/2, len_in_z/2,
)
sourceBeamletOptics.BoxSDF Method
BoxSDF(x, y, z)Creates a BoxSDF with:
x: x-dir. edge length in [m]y: y-dir. edge length in [m]z: z-dir. edge length in [m]
BeamletOptics.CircularFlatSurface Type
CircularFlatSurface{T} <: AbstractRotationallySurface{T}A type representing a planar circular surface, which is only parametrized by its diameter.
Fields
diameter::T: The diameter of the planar surface
BeamletOptics.CollimatedSource Type
CollimatedSource <: AbstractBeamGroupRepresents a parallel bundle of Beams being emitted from a disk in space.
Fields
beams: a vector of allBeams originating from the source. The first one is the center beam, which starts at the source position along the central source direction, unless the source wraps given beams.diameter: the diameter of the outermost beam ringcenter: source position, pivot for rotationsdir: theorientationof the group, a right-handed orthonormal matrix whose columns are the sampling reference vector, the central source direction and their cross product, seeAbstractBeamGroupsampling: how the rays were sampled (rings, sunflower or line) (orNoSampling()for given beams), seenum_rays!
Functions
BeamletOptics.diameter(source): returns the diameter of the sourcenum_rays!: regenerates the rays with another number of rays
BeamletOptics.CollimatedSource Method
CollimatedSource(pos, dir, diameter, λ; num_rings, num_rays, basis)Spawns a bundle of collimated Beams at the specified position and direction. The source is modelled as a ring of concentric beam rings around the center beam. The amount of beam rings between the center ray and outer diameter can be specified via num_rings.
Warning
For correct sampling, num_rays must be at least 20 times num_rings, otherwise an ArgumentError is thrown.
Arguments
The following inputs and arguments can be used to configure the CollimatedSource:
Inputs
pos: center beam starting positiondir: center beam starting directiondiameter: outer beam bundle diameter in [m]λ = 1e-6: wavelength in [m], default val. is 1000 nm
Keyword Arguments
num_rings: number of concentric beam rings, default is 10; the number of rings counts the center as the innermost one, i.e.num_rings - 1rings lie around itnum_rays: total number of rays in the source, default is 100x num_ringsbasis: Optional reference vector (e.g.[1,0,0]) to define the starting azimuthal angle for the beam rings.
Reproducible sampling
If no basis is passed, the orthogonal basis vectors spanning the pupil plane are derived from dir deterministically, so two sources sharing the same dir, diameter, num_rings and num_rays sample exactly the same ray positions. Pass a basis to rotate the azimuthal sampling of a source about its own axis, e.g. to interleave several otherwise identical sources.
BeamletOptics.CollimatedSource Method
CollimatedSource(pos, dir, diameter, sampling::AbstractSourceSampling, λ = 1e-6; num_rays, basis = nothing)Spawns a CollimatedSource of parallel Beams along dir from a disc with the diameter [m] centered at pos [m], with the wavelength λ [m], sampled by sampling with num_rays rays, e.g. BeamletOptics.DiscRings. The catalog constructors CollimatedSource, UniformDiscSource and UniformLineSource call this method; a custom BeamletOptics.AbstractSourceSampling implements source_beams for it. The number type is promote_type of pos, dir, diameter and λ.
The optional basis vector sets the azimuth of the sampling pattern about dir, see BeamletOptics.sampling_basis. A num_rays below BeamletOptics.min_num_rays of the sampling and a basis that is zero or parallel to dir throw an ArgumentError.
BeamletOptics.CollimatedSource Method
CollimatedSource(beams, diameter, pos, dir::AbstractVector)
CollimatedSource(beams, diameter, pos, orientation::AbstractMatrix)Wraps existing beams into a CollimatedSource with the given diameter and the source position pos. The group orientation is either derived from the central direction dir (the sampling reference vector is then picked deterministically via normal3d), or passed explicitly as a right-handed orthonormal 3x3 orientation matrix whose second column is the central direction. An invalid orientation throws an ArgumentError. The rays of such a source can not be regenerated with num_rays!: its sampling is NoSampling().
BeamletOptics.ConcaveAsphericalSurfaceSDF Type
Constructs an aspheric lens with a concave-like surface according to ISO10110.
Note
Currently, it is assumed that the aspheric surface is concave if the radius is negative. There might be unexpected effects for complex shapes which do not show a generally concave behavior.
coefficients: (even) coefficients of the asphere, starting with A2 (r²).radius: radius of the lens (negative!)conic_constant: conic constant of the lens surfacediameter: lens diametermechanical_diameter: mechanical lens diameter, defaults to be identical to the lens diameter, Otherwise an outer ring section will be added to the lens, ifmechanical_diameter>diameter.
BeamletOptics.ConcaveCylinderSDF Type
ConcaveCylinderSDF <: AbstractSDFImplements the SDF of a concave cylinder with radius r, diameter d and height h.
BeamletOptics.ConcaveCylinderSDF Method
ConcaveCylinderSDF(radius, diameter, height)Constructs a concave cylinder with radius r, diameter d and height h in [m].
BeamletOptics.ConcaveSphericalSurfaceSDF Type
AbstractSDF-based representation of a concave spherical lens surface. When constructed, it is assumed that the plano-surface lies at the origin and the optical axis is aligned with the y-axis. The concave surface is orientated towards negative y-values for R > 0 and vice versa.
Fields:
radius: the radius of curvature of the convex spherical surface.diameter: the outer diameter of the lens surfacesag: the sagitta of the opposing convex shape
BeamletOptics.ConcaveSphericalSurfaceSDF Method
Constructs a ConcaveSphericalSurfaceSDF with a specific radius of curvature and lens outer diameter.
BeamletOptics.ConeFan Type
ConeFan(θ::Real)Rays with equidistant angles in the plane fan of a UniformFanSource, i.e. in the plane spanned by the source direction and the sampling reference vector, between -θ and θ [rad] to the source direction. The center ray comes first, followed by the other rays from one edge of the fan to the other, both edges included. An even number of rays has a second ray at the center, see UniformFanSource. Needs at least one ray. θ ≥ π throws an ArgumentError.
BeamletOptics.ConeRings Type
ConeRings(num_rings::Int, θ::Real)Concentric cones of rays around a center ray of a PointSource, the center counted as the innermost of the num_rings cones, the outermost with the half spread angle θ [rad]. The rays are distributed over the cones in proportion to the solid angle each cone represents, i.e. to its circumference, but half of it for the outermost cone, 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. θ ≥ π throws an ArgumentError.
BeamletOptics.ConeSunflower Type
ConeSunflower(θ::Real)Sunflower (Fibonacci) sampling of the spherical cap with the half spread angle θ [rad] of a UniformPointSource: every ray represents the same solid angle. The spiral starts with the center ray. Needs at least one ray. θ ≥ π throws an ArgumentError.
BeamletOptics.ConicSDF Type
ConicSDF{T} <: AbstractSDF{T}Signed distance function representation of a segment of a conic of revolution (sphere, paraboloid, prolate/oblate ellipsoid or hyperboloid), used as the substrate of ParabolicMirror, ConicMirror, EllipsoidalMirror, HyperbolicMirror and their OffAxis* twins.
Frame convention
The origin is the segment centre, lying on the reflecting surface.
The parent optical axis is parallel to the local y-axis, offset by
x_offalong the negative x-axis; there is no tilt between the segment and its parent axis.A concave surface (
R > 0) opens towards the negative y-axis; a convex surface (R < 0) opens towards the positive y-axis.The parent vertex lies at
(-x_off, +Z(x_off), 0), whereZis the sag function of the parent conic.For
x_off = 0andk = -1,R = 2f: the vertex lies at the origin and the (real) focus lies at(0, -f, 0). This on-axis case needs no separate type:x_off = 0is an ordinary argument value, not a differentConicSDFvariant.
Fields
f: paraxial focal length of the parent conic,R/2[m]k: conic constant (k = -1paraboloid,k = 0sphere,-1 < k < 0prolate ellipsoid,k > 0oblate ellipsoid,k < -1hyperboloid)x_off: off-axis distance from the parent vertex to the segment centre [m]diameter: segment aperture diameter [m]thickness: substrate thickness in y-direction [m]pos: position point in world coordinates [m]dir: rotation matrix in world coordinatestransposed_dir: transposed rotation matrix
Surface equation
With r_p = sqrt((x + x_off)^2 + z^2) the parent radius and
the reflecting surface is y_surf(x, z) = -(Z(r_p) - Z(x_off)). The substrate is the solid {y_surf <= y <= thickness, sqrt(x^2 + z^2) <= diameter/2}.
BeamletOptics.ConicSDF Method
Constructs a ConicSDF representing a segment of a conic of revolution.
Arguments
R: radius of curvature at the parent vertex [m];R > 0is concave (opens towards-y),R < 0is convex (opens towards+y). Must be non-zero.k: conic constant.k = -1is a paraboloid,k = 0a sphere,-1 < k <= 0a prolate ellipsoid,k > 0an oblate ellipsoid,k < -1a hyperboloid.x_off: off-axis distance from the parent vertex to the segment centre [m]diameter: segment aperture diameter [m]. Must be positive.thickness: substrate thickness in y-direction [m]
For k > -1 the parent conic is only defined for r < abs(R)/sqrt(1+k); the constructor throws an ArgumentError if the aperture (abs(x_off) + diameter/2) reaches or exceeds this limit. For k <= -1 the surface is defined for all r, so no such limit applies.
BeamletOptics.ConstantRefractiveIndex Type
ConstantRefractiveIndex{T}Represents a refractive index n that is the same for all wavelengths, i.e. without dispersion. Can be called like a function n = n(λ).
BeamletOptics.ConvexAsphericalSurfaceSDF Type
Constructs an aspheric lens with a convex-like surface according to ISO10110.
Note
Currently, it is assumed that the aspheric surface is convex if the radius is positive. There might be unexpected effects for complex shapes which do not show a generally convex behavior.
coefficients: (even) coefficients of the asphere, starting with A2 (r²).radius: radius of the lensconic_constant: conic constant of the lens surfacediameter: lens diameter
BeamletOptics.ConvexCylinderSDF Type
ConvexCylinderSDF <: AbstractSDFImplements the SDF of a cut cylinder with radius r, diameter d and height h.
BeamletOptics.ConvexCylinderSDF Method
ConvexCylinderSDF(radius, diameter, height)Constructs a cut cylinder with radius r, diameter d and height h in [m].
BeamletOptics.ConvexSphericalSurfaceSDF Type
AbstractSDF-based representation of a convex spherical lens surface. When constructed, it is assumed that the plano-surface lies at the origin and the optical axis is aligned with the y-axis. The convex surface is orientated towards negative y-values for R > 0 and vice versa.
Fields:
radius: the radius of curvature of the concave spherical surface.diameter: the outer diameter of the lens surfacesag: the sagitta of the convex shapeheight: the sphere cutoff height, see alsoCutSphereSDF
BeamletOptics.ConvexSphericalSurfaceSDF Method
Constructs a ConvexSphericalSurfaceSDF with a specific radius of curvature and lens outer diameter.
BeamletOptics.CubeBeamsplitter Type
CubeBeamsplitter <: AbstractBeamsplitterA cuboid beamsplitter where the splitting interaction occurs between two RightAnglePrisms. For more information refer to the AbstractPlateBeamsplitter docs.
Fields
front: the forward facing substrate, represented by aRightAnglePrismback: the backward facing substrate, represented by aRightAnglePrismcoating: a rectangularThinBeamsplitterthat represents the splitting interface
Additional information
Hints and interaction logic
In order to model gap-free beam propagation, the interact3d model relies heavily on the Hint-API. If the front or back substrate is hit, the Hint will ensure that the beam intersects the coating.
BeamletOptics.CubeBeamsplitter Method
CubeBeamsplitter(leg_length, n; reflectance=0.5)Creates a CubeBeamsplitter. The cuboid is centered at the origin. The splitter coating is orientated at a 45° angle with respect to the y-axis.
Inputs
leg_length: the x-, y- and z-edge length in [m]n: theAbstractRefractiveIndexof the front and back prism
Keywords
reflectance: defines the power reflectance R (dimensionless) of the coating, in the open interval (0, 1)
BeamletOptics.CutSphereSDF Type
CutSphereSDF <: AbstractSDFImplements SDF of a sphere which is cut off in the x-z-plane at some point along the y-axis.
sourceBeamletOptics.CutSphereSDF Method
CutSphereSDF(pos, radius, height)Constructs a sphere with radius which is cut off along the y-axis at height.
BeamletOptics.CylinderSDF Type
CylinderSDF <: AbstractSDFImplements cylinder SDF. Cylinder is initially orientated along the y-axis and symmetrical in x-z.
sourceBeamletOptics.CylindricalSurface Type
CylindricalSurface{T} <: AbstractCylindricalSurface{T}A type representing a cylindric optical surface defined by its radius of curvature, diameter, height and mechanical diameter
Fields
radius::T: The radius of curvature of the curved surface.diameter::T: The clear (optical) aperture of the surface.height::T: The height/length of the uncurved surface directionmechanical_diameter::T: The overall mechanical diameter of the surface. In many cases, this is equal to the optical diameter, but it can be set independently if the mechanical mount requires a larger dimension.
BeamletOptics.CylindricalSurface Method
CylindricalSurface(radius::T, diameter::T, height::T) where TConstruct a CylindricalSurface given the radius of curvature, optical diameter and height. This constructor automatically sets the mechanical diameter equal to the optical diameter.
Arguments
radius::T: The radius of curvature of the curved surface.diameter::T: The clear (optical) diameter of the surface.height::T: The height/length of the uncurved surface direction.
BeamletOptics.Detector Type
Spawns a quadratic Detector surface that is aligned with the neg. y-axis. The detector edge length can be configured via edge_length. Additionally, continued tracing can be configured via the stop flag where
falseindicates continued tracing: rays and beamlets pass the detector unchangedtruestops the incoming beams as with any hard target
Partly clipped beamlets
A beamlet whose rays hit the detector only partly ends there, as at any other object, also with stop = false. To sample a beamlet on an intermediate plane, make the detector larger than the beamlet.
BeamletOptics.Detector Type
Detector <: AbstractDetectorRepresents a flat rectangular or quadratic, infinitesimally thin surface in R³. The detector surface is a detection screen that captures incoming ray or beamlet data. The active surface is discretized in the local R² (x, z) coordinate system, see below. If configured, beams or beamlets can continue tracing after hitting the detector.
Hits
Hits are represented via the AbstractDetectorHit 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.
Functions
The following functions allow a posteriori evaluation of hit contributions via e.g. f(detector). Refer to the respective function documentation.
Additional information
In general, the detection surface is represented by a flat Mesh 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.
Reset behavior
A Detector accumulates hits across calls of solve_system!, on purpose: all beams of a beam group and several sources solved one after another superpose on it. To discard the results of previous solves, e.g. after changing a component in a loop, call initialize!(system) for all detectors of a system (nested groups included), empty!(detector) for a single one, or solve with initialize = true. Otherwise, the current result is added onto the previous result.
Thread safety
Beam groups are solved multithreaded. Pushing hits is guarded by the lock of the detector, so all beams can hit the same detector concurrently. Each task of the solve of a beam group collects its hits and stores them at its end, see with_hit_buffers. The order of the stored hits is not deterministic.
Reading hits
A hit stores the values of the ray or beamlet at the moment of the solve, in world coordinates. Solving again or moving a source or another object does not change the stored hits. Moving the detector itself empties it, since its hits would no longer lie on its surface. The hits of consecutive solves are kept side by side, and it is up to the user when to evaluate them: spot_diagram shows all of them, whereas electric_field, intensity and optical_power superpose all of them coherently, as for beams that exist at the same time.
Fields
shape: geometry of the active surface, must represent a 2D field in the localxandzdimensions, normal vector direction must adhere to definition abovehits: a union ofNothingand all implementedAbstractDetectorHits, resettable viaempty!(note that only one type is allowed at any time)stop: a boolean value that allows for continued tracing after "passing through" the detectorlock: locks theDetectorfor multithreading-safepush!ing to the hits vector
BeamletOptics.DetectorSamples Type
DetectorSamples(coordinates, points, weights)The points at which the readouts of a Detector are evaluated, as returned by sample_points:
points: an array of local detector coordinates(x, z)in [m], each a vector (e.g. aPoint2). The readouts return their values in the shape ofpoints.weights: the detector area in [m²] each point stands for, in the shape ofpoints, as an array or a lazy broadcast (Broadcast.broadcasted), which is only evaluated byoptical_power. It isΣ wᵢ Iᵢwith the irradianceIᵢ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(pd, sampling).
BeamletOptics.DifferenceSDF Type
DifferenceSDF{T, S, TT <: Tuple} <: AbstractCompositeSDF{T}Represents the boolean subtraction of one or more tools from a base AbstractSDF, i.e. base \ (tool_1 ∪ tool_2 ∪ …). Unlike UnionSDF, the constituent SDFs are required to overlap: the tools must intersect the base for anything to be removed.
The intended way to construct these is not explicitly but by subtracting AbstractSDFs using the regular - operator:
s1 = SphereSDF(1.0)
s2 = SphereSDF(0.5)
translate3d!(s2, Point3(0.5, 0.0, 0.0))
# will result in a sphere with a smaller, off-center sphere carved out of it
s_diff = s1 - s2Non-commutativity and evaluation order
Subtraction is neither commutative nor associative, so a - b and b - a differ, and a chain like a + b - c + d must keep track of when each operand was combined. Repeated subtraction is flattened along its own chain via the identity
so a - b - c produces a single DifferenceSDF with one base and a flat tools tuple, rather than deepening the type on every chained -. Mixed +/- chains still nest (e.g. a + b - c is (a + b) - c, and ... + d afterwards wraps the whole difference in a UnionSDF) — this is what keeps their meaning, since material added after a subtraction must not be carved away by it.
Note
The SDF is a lower bound of the distance, not exact; normals are exact through operand selection.
BeamletOptics.Directed Type
Directed <: AbstractKinematicFrameReference frame of a movable value that only has a direction but no orientation, e.g. rays and beams.
Implementation reqs.
positiondirection: the direction getter of the type
reset_rotation3d! throws an ArgumentError, use align3d! instead.
BeamletOptics.DiscLine Type
DiscLine()Equidistant rays on the line of a UniformLineSource, i.e. on the diameter of the disc along the sampling reference vector. The center ray comes first, followed by the other rays from 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. Needs at least one ray.
BeamletOptics.DiscRings Type
DiscRings(num_rings::Int)Concentric rings of rays around a center ray on the disc of a CollimatedSource, the center counted as the innermost of the num_rings rings. The outermost ring lies on the edge of the disc; the rays are distributed over the rings in proportion to the area of the disc each ring represents, i.e. to its circumference, but half of it for the outermost ring, which represents only the inner half of its annulus. Every ray then 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.
BeamletOptics.DiscSunflower Type
DiscSunflower()Sunflower (Fibonacci) sampling of the disc of a UniformDiscSource: every ray represents the same area of the disc. The spiral starts with the center ray. Needs at least one ray.
BeamletOptics.DiscreteRefractiveIndex Type
DiscreteRefractiveIndex{T}Represents a incomplete set of dispersion data where for each exact wavelength one refractive index value is stored in the data field. Can be called like a function n = n(λ). Does not interpolate between data points. Refer to AbstractRefractiveIndex for more information.
BeamletOptics.DiscreteRefractiveIndex Method
DiscreteRefractiveIndex(λs, n)Creates a DiscreteRefractiveIndex dictionary where each wavelength in λs is mapped onto an exact exact refractive index in ns.
Inputs
λs: array of wavelengthsns: array of refractive indices
BeamletOptics.DoubletLens Type
DoubletLensRepresents a two-component cemented doublet lens with two respective refractive indices n = n(λ). See also SphericalDoubletLens and the surface-based constructor DoubletLens(s1, s2, s3, l1, l2, n1, n2).
Fields
Additional information
Air gap
This component type strongly assumes that both lenses are mounted fully flush with respect to each other. Gaps between the components might lead to incorrect results.
BeamletOptics.DoubletLens Method
DoubletLens(s1, s2, s3, l1, l2, n1, n2)Generates a two-component "cemented" DoubletLens from three surface specifications, e.g. SphericalSurface, EvenAsphericalSurface or CircularFlatSurface. The front element is Lens(s1, s2, l1, n1) and the back element is Lens(s2, s3, l2, n2), refer to the surface-based Lens constructor for the construction of the elements. The front vertex lies at the origin and the back element is translated along +y by l1, so that both elements share the cemented surface s2.
Arguments
s1: first surfaces2: second (cemented) surfaces3: third surfacel1: first lens center thickness in ml2: second lens center thickness in mn1: first lensAbstractRefractiveIndexn2: second lensAbstractRefractiveIndex
Additional information
Radius of curvature (ROC) sign definition
The ROC is defined to be positive if the center is to the right of the surface, i.e. at +y. Otherwise it is negative.
Clear apertures
Each surface has its own clear aperture and mechanical diameter, which are leveled per element as for a single Lens.
Supported surfaces
Only rotationally symmetric surfaces are supported, cylindrical surfaces are not. The limitations of the surface-based Lens constructor apply to each element: a meniscus element, whose center thickness does not exceed the sagitta of its convex surface, must consist of spherical surfaces.
Total internal reflection
Total internal reflection at the cemented interface between the two elements is not modeled correctly.
BeamletOptics.EvenAsphericalSurface Type
EvenAsphericalSurface{T} <: AbstractRotationallySymmetricSurface{T}A type representing an aspherical optical surface defined by its radius of curvature, clear (optical) diameter, conic constant, aspheric coefficients and mechanical diameter. This surface is rotationally symmetric about its optical axis.
Fields
spherical::SphericalSurface{T}: The base spherical surface portion of the asphere.conic_constant::T: The conic constant defining the deviation from a spherical shape.coefficients::AbstractVector{T}: A vector of even aspheric coefficients for higher-order corrections, starting with A2 (r²).
BeamletOptics.EvenAsphericalSurface Method
EvenAsphericalSurface(radius, diameter, conic_constant, coefficients::AbstractVector, mechanical_diameter = diameter)Construct a EvenAsphericalSurface given the radius of curvature, the optical diameter, conic constant, the aspheric coefficients and optionally the mechanical diameter. This constructor automatically sets the mechanical diameter equal to the optical diameter.
Arguments
radius: The radius of curvature of the base spherical surface.diameter: The clear (optical) diameter of the surface.conic_constant: The conic constant defining the deviation from a spherical shape.coefficients::AbstractVector: The even aspheric coefficients of the termsΣᵢ αᵢ r²ⁱin SI units, starting with A2 (r²), e.g.[0, A4 * 1e3^3, A6 * 1e3^5]for mm-based catalog values without an r² term.mechanical_diameter: The mechanical diameter of the surface; if not provided, it defaults todiameter.
BeamletOptics.GaussianBeamlet Type
GaussianBeamlet{T} <: AbstractBeam{T, Ray{T}}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)
and
Donald DeJager and Mark Noethen, "Gaussian beam parameters that use Coddington-based Y-NU paraprincipal ray tracing," Appl. Opt. 31, 2199-2205 (1992)
Fields
λ: beam wavelength in [m]w0: local beam waist radius in [m]E0: complex reference amplitude in [V/m] of the field, normalized to the power of the beamlet:P = |E0|² π w0² / (4 Z₀)for any medium. The physical field of a segment in a medium of refractive indexnisE0 / √n(times the profile), so that the irradiancen |E|² / (2 Z₀)of a beam of fixed power does not depend on the medium, seeelectric_fieldparent: reference to the parent beam, if any (Nullableto account for the root beam which has no parent)children: vector of child beams, each child beam represents a branching or bifurcation of the original beam, i.e. beam-splitting
Additional information
Beam parameters
Parameters of the beam, e.g. gauss_parameters function.
Astigmatism and abberations
It is assumed, but not forbidden, that the optical system contains non-flat or non-parabolic beam-surface-interactions that cause the beam to obtain astigmatism or higher-order abberations. These can not be represented by the GaussianBeamlet.
Optical invariant check
When using the solve_system! function, the Lagrange invariant is checked for each interaction. If it deviates by more than get_lagrange_tolerance() from its start value, the beamlet has left the range of its model and tracing is stopped with a warning, as for an AstigmaticGaussianBeamlet.
BeamletOptics.GaussianBeamlet Method
GaussianBeamlet(position, direction, λ, w0; kwargs...)Constructs a Gaussian beamlet at its waist with the specified beam parameters.
Arguments
The following inputs and arguments can be used to configure the beamlet:
Inputs
position: origin of the beamletdirection: 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.
Keyword Arguments
M2: beam quality factor. Default is 1P0: beam total power in [W]. Default is 1 mWz0: beam waist offset in [m]. Default is 0 msupport:Nullablesupport vector for the construction of the waist and div rays. Must be orthogonal todirection, has any non-zero length and is normalized internally. Default isnothing, i.e. a vector orthogonal todirectionis chosen.
Additional information
Waist offset
The z0 keyword arg. can be used in order to spawn a beam where the waist is not located at the specified position, but rather at an offset z0 in [m] along the chief ray axis.
Support vector
In order to calculate the basis vectors required for the beamlet construction, an orthogonal vector is chosen deterministically from direction via normal3d. Specify a support vector to choose it yourself. The waist and divergence rays start from the chief ray along this vector. A support that is not orthogonal to the direction (the dot product of the unit vectors exceeds get_orthogonality_threshold(), default 1e-10) throws an ArgumentError, since it would give a beamlet with a smaller waist radius and a shifted waist.
BeamletOptics.GaussianBeamletHit Type
GaussianBeamletHit{T} <: AbstractBeamletHit{T}Stores the segment of a GaussianBeamlet that hit the detector as values, without a reference to the beamlet: p0 and dir are start and direction of the segment, l_seg its length, l0 the length of the beam (including its parents) up to p0, Δl0 the optical minus the geometric path and ψ0 the Gouy phase that the beam has collected up to there. segment holds the waist and divergence rays of the segment (see BeamletOptics.GaussianSegment), from which the field follows as from the beamlet itself, see gauss_parameters. E_amp is the reference amplitude times the beam radius, E0 w0 of the source, which is normalized to the power of the beamlet: the physical field in a medium of index n is smaller by √n, see electric_field(::BeamletOptics.AbstractDetectorHit, ::AbstractVector).
BeamletOptics.GaussianBeamletHit Method
GaussianBeamletHit(g::GaussianBeamlet, id)Hit record of the traced segment id of g: the data that electric_field(hit, p) needs to evaluate the field of that segment at any point near it. Detectors store one per beamlet that hits them; it can also be built for any traced segment, e.g. to sample a beamlet on a plane of one's own. l0 is the length of the beam (including its parents) up to the start of the segment.
BeamletOptics.GaussianBeamletInteraction Type
This type is used to store the new beamlet section resulting from on optical interaction between a GaussianBeamlet and some AbstractObject. Uses the hint of the chief beam.
Fields
sourceBeamletOptics.GaussianSegment Type
GaussianSegment{T}The waist and divergence rays of one segment of a GaussianBeamlet, as two RayCrossings relative to its chief ray. Both rays are straight within the segment, hence the crossings hold exactly. n is the refractive index of the segment and λ the vacuum wavelength. gauss_parameters(segment, l) evaluates it, a GaussianBeamletHit stores it.
BeamletOptics.GlobalJonesBasis Type
GlobalJonesBasis <: AbstractJonesMatrixStores the Jones matrix entries for a polarizing optical element that is aligned with the global y-axis as the optical axis.
sourceBeamletOptics.Hint Type
HintA Hint can be passed as part of an AbstractInteraction and will inform the tracing algorithm about which AbstractObject in the AbstractSystem will be hit next.
Info
The Hint does not need to result in a guaranteed Intersection, and it does not change which surface is hit: the hinted object is tested first, the objects beyond its hit are skipped, and a closer hit of another object wins. Among the surfaces hit at the same point, e.g. the touching faces of a cemented doublet, the hinted shape comes first.
Fields
object: the object that might or will be intersected next. The solver callsinteract3dfor this object, hence for a part of aMultiShapeobject it is the composite itself, not the partshape: the underlying shape that will be intersected next, i.e.shape(object), relevant for multi-shape objects
Hint(object) uses shape(object), which is a tuple for a MultiShape object and fails. Pass the hit part explicitly there, Hint(object, part), with the composite as object and the shape that will be hit as part.
BeamletOptics.HitBuffers Type
The hits of the current task per Detector, see with_hit_buffers. Pushing detector => hit collects the hit in the buffer of the detector. The buffer of the last detector is kept at hand, since consecutive hits mostly go to the same detector.
BeamletOptics.IntersectableObject Type
IntersectableObjectA passive AbstractObject which can be hit by a beam. In this case, the object acts like a hard target and blocks the beam path.
Fields
shape: anAbstractShape
BeamletOptics.Intersection Type
Intersection{T}Stores data calculated by the intersect3d method.
Fields:
object: aNullablereference to theAbstractObjectthat has been hit. Theintersect3dmethods of shapes leave itnothing, the solver sets itshape: aNullablereference to theAbstractShapeof theobjectthat has been hit. Provide it: composite objects and the check whether the rays of a beamlet hit the same shape identify the hit part by this referencet: length of the ray parametrization in [m]n: normal vector at the point of intersectionnext: the next hit of the ray at the same point, ornothing, seecoincident_hits
Coincident hits
Where surfaces touch, e.g. the faces of a cemented doublet or a coating on its substrate, the ray hits several of them within the tolerance get_coincidence_tolerance() of the closest hit. The intersection of the ray then is a chain of all of them, linked by next. A shape or object type returns a single hit from intersect3d; the chain is built by intersect3d(parts, ray) and the solver.
BeamletOptics.Lens Type
Lens{T, S <: AbstractShape{T}, N <: AbstractRefractiveIndex} <: AbstractRefractiveOptic{T, N}Represents an uncoated Lens with a homogeneous AbstractRefractiveIndex n = n(λ). Refer to the Lens and SphericalLens constructors for more information on how to generate lenses.
Fields
shape: geometry of the lens, refer toAbstractShapefor more informationn:AbstractRefractiveIndexof the lens material
Additional information
Refractive index
The chromatic dispersion of the lens is represented by the AbstractRefractiveIndex n, e.g. a SellmeierEquation. A ConstantRefractiveIndex gives the lens the same refractive index for all wavelengths.
BeamletOptics.Lens Method
Lens(front_surface::AbstractCylindricalSurface, back_surface::AbstractCylindricalSurface, center_thickness::Real, n::AbstractRefractiveIndex)Constructs a new Lens object using the cylindric surface specifications front_surface and back_surface and the center_thickness. These inputs are used to construct a UnionSDF that consists of the appropriate sub-SDFs to represent the shape of the lens.
This method of Lens is specific for cylindric lenses and has some limitations: - The cylinder height of both surfaces has to be identical - No mixture with non-cylindric surfaces is supported at the moment
The material is supplied via the AbstractRefractiveIndex n.
Additional information
Radius of curvature (ROC) sign definition
The ROC is defined to be positive if the center is to the right of the surface. Otherwise it is negative.
BeamletOptics.Lens Method
Lens(front_surface::AbstractCylindricalSurface, center_thickness::Real, n::AbstractRefractiveIndex)Constructs a plano-cylindrical Lens: the back surface is a RectangularFlatSurface with the diameter of the front_surface. See the two-surface cylindrical method for the other arguments.
BeamletOptics.Lens Method
Lens(front_surface::AbstractRotationallySymmetricSurface, back_surface::AbstractRotationallySymmetricSurface, center_thickness::Real, n::AbstractRefractiveIndex)Constructs a new Lens object using the surface specifications front_surface and back_surface and the center_thickness. These inputs are used to construct a UnionSDF that consists of the appropriate sub-SDFs to represent the shape of the lens.
The material is supplied via the AbstractRefractiveIndex n.
Additional information
Radius of curvature (ROC) sign definition
The ROC is defined to be positive if the center is to the right of the surface. Otherwise it is negative.
Meniscus
A meniscus lens, whose center thickness does not exceed the sagitta of its convex surface, must consist of spherical surfaces. An aspherical surface throws an ArgumentError in this case.
BeamletOptics.Lens Method
Lens(front_surface::AbstractRotationallySymmetricSurface, center_thickness::Real, n::AbstractRefractiveIndex)Constructs a plano-convex or plano-concave Lens: the back surface is a CircularFlatSurface with the diameter of the front_surface. See the two-surface method for the other arguments.
BeamletOptics.LinearPolarizer Type
LinearPolarizer{T, N <: AbstractRefractiveIndex} <: AbstractObject{T}Represents a real, round linear polarizing film laminated between two uncoated glass plates (e.g. Thorlabs LPNIRE100-B), modeled as a thin PolarizationFilter cemented between two Prism substrates that sit flush against the film. Refer to RoundLinearPolarizer for the constructor.
Fields
filter: the thinPolarizationFilterthat models the polarizing filmfront: front glass substratePrismback: back glass substratePrism
Additional information
Kinematic center
The center of kinematics of this component lies at the center of the film.
Uncoated surfaces
Since the glass substrates are uncoated, a PolarizedRay loses approx. 4 % of its intensity per outer surface at n ≈ 1.5 due to Fresnel reflection, unlike the anti-reflection coated real-world part.
Crossed orientation
When the film orientation is crossed (transmission axis perpendicular to the incident polarization), the beam is terminated at the cemented film interface once the norm of the transmitted electric field falls to or below the cutoff_strength of the underlying PolarizationFilter.
BeamletOptics.LocalJonesBasis Type
LocalJonesBasisStores the s-p-basis Jones matrix coefficients. Must be defined for x-y-aligned elements where z is the optical axis.
sourceBeamletOptics.LockedHits Type
Stores each pushed detector => hit directly in its detector, guarded by the lock of the detector.
BeamletOptics.MeniscusLensSDF Type
MeniscusLensSDFAbstractSDF-based representation of a positive or negative meniscus lens. When constructed, it is assumed that the lens lies at the origin and the optical axis is aligned with the y-axis. Parameters that lead to a sharp lens edge will cause an error.
Notes
Radius of curvature sign convention
The ROC is defined to be positive if the center is to the right of the surface. Otherwise it is negative.
Fields:
convex: the convex part of the lens composite SDFcylinder: the cylindrical part of the lens composite SDFconcave: the concave part of the lens composite SDFthickness: lens thickness on the optical axis
BeamletOptics.MeniscusLensSDF Method
MeniscusLensSDF(r1::R1, r2::R2, l::L, d::D, md::MD)Constructs a positive or negative MeniscusLensSDF with:
r1: front surface radis or curvaturer2: back surface radis or curvaturel: lens thicknessd: lens diameter, default value is one inchmd: mechanical lens diameter, must be > d
BeamletOptics.Mesh Type
Mesh <: AbstractMeshContains the STL mesh information for an arbitrary shape, that is the vertices that make up the mesh and a matrix of faces, i.e. the connectivity matrix of the mesh. The data is read in using the FileIO.jl and MeshIO.jl packages. Translations and rotations of the mesh are directly saved in absolute coordinates in the vertex matrix. For orientation and translation tracking, a positional and directional matrix are stored.
Fields
vertices: (m x 3)-matrix that stores the edge points of all trianglesfaces: (n x 3)-matrix that stores the connectivity data for all facesdir: (3 x 3)-matrix that represents the current orientation of the meshpos: 3-element vector that is used as the mesh location referencescale: scalar value that represents the current scale of the original mesh
BeamletOptics.Mesh Method
Mesh(mesh)Parametric type constructor for struct Mesh. Takes data of type GeometryBasics.Mesh and extracts the vertices and faces. The mesh is initialized at the global origin. Data type of Mesh is variably selected based on type of vertex data (i.e Float32).
Tip
Mesh vertex data is scaled by the factor 1e-3, i.e. the STL file is assumed to be in mm and the mesh is in [m]. Ensure that the export program is adjusted accordingly when scaling issues occur.
BeamletOptics.Mirror Type
Mirror{S <: AbstractShape} <: AbstractReflectiveOpticConcrete implementation of a perfect mirror (R = 1) with arbitrary shape.
Reflecting surfaces
It is important to consider that all surfaces of this mirror type are reflecting!
BeamletOptics.MissingBackendError Type
MissingBackendErrorCustom Exception type that indicates that the Makie extension of BeamletOptics has not been loaded correctly.
BeamletOptics.Movable Type
Movable{F <: AbstractKinematicFrame} <: AbstractKinematicTraitRepresents a value that can be moved by the kinematic API. The frame field (Oriented or Directed) selects orientation- or direction-based behaviour of the derived functions.
Rotations are applied about the own position of the value unless a pivot is passed explicitly. A rotation axis can have any non-zero length (it is normalized internally).
Kinematic functions
translate3d!: movesxby anoffsetvector (primitive, implemented per type)rotate3d!: rotatesxby a rotation matrixRaboutposition(x), or about a givenpivotif one is passed (theR-only form is the primitive, implemented per type; the axis/angle and pivot forms are derived from it)translate_to3d!: movesxso thatposition(x)coincides with a target pointxrotate3d!/yrotate3d!/zrotate3d!: rotatexby an angleθ[rad] about the global x-, y- or z-axis throughposition(x)align3d!: rotatesxaboutposition(x)so thatdirection(x)is aligned with a target vectorreset_translation3d!: movesxso thatposition(x)is the global origin; available for everyMovable, including rays, beams and beam groupsreset_rotation3d!: only available forOrientedvalues, where it rotatesxback to identityorientation; forDirectedvalues (rays, beams) it throws anArgumentError, usealign3d!insteaddirection: forOrientedvalues this is the local y-axis,orientation(x)[:, 2];Directedvalues provide their own getter
Sources (rays, beams and beam groups) are additionally reset to their untraced start state by every one of the functions above that moves them, i.e. all but the getter direction: a moved but already-traced source would otherwise keep rays or child beams belonging to the old, now geometrically wrong, light path. Moving a beam that is not the root of its beam tree (e.g. one created by a beamsplitter interaction) throws an ArgumentError; move its root beam instead.
Implementation reqs.
If kinematic_trait_of(::Foo) = Movable(...) is declared, Foo must implement the following:
positiontranslate3d!(::Movable, x::Foo, offset): movesxbyoffsetrotate3d!(::Movable, x::Foo, R::AbstractMatrix): rotatesxbyRaboutposition(x)
All other kin. functions listed above are derived from these two primitives.
sourceBeamletOptics.MultiBoundingSphere Type
MultiBoundingSphere{T} <: AbstractBoundingSphereA sphere that encloses several bounding spheres, i.e. all parts of a MultiShape object or all objects of an object group, see bounding_sphere_of. A ray that misses it hits none of the parts, hence a solve tests it before the parts. It is tested against a ray like a SingleBoundingSphere and differs only in what it states: the sphere of several things.
Fields
pos: the center in world coordinates [m]radius: the radius [m]
BeamletOptics.MultiBoundingSphere Method
MultiBoundingSphere(a::AbstractBoundingSphere, b::AbstractBoundingSphere)
MultiBoundingSphere(spheres::Tuple)
MultiBoundingSphere(spheres::AbstractVector)Returns the smallest sphere that encloses the bounding spheres a and b, or all spheres, e.g. those of the parts of an object or of the objects of a group. The result is NoBoundingSphere() if one of them is none, since then no sphere encloses all parts, and for no spheres at all.
BeamletOptics.MultiShape Type
MultiShape <: AbstractShapeTraitRepresents that the AbstractObject consists of two or more parts, i.e. AbstractShapes or subsidiary AbstractObjects. The built-in composites, e.g. the CubeBeamsplitter, list objects, such that every part has its own bounding sphere.
AbstractObject implementation reqs.
If shape_trait_of(::Foo) = MultiShape() is defined, Foo must implement the following:
Functions
shape(::Foo): a getter function that returns aTupleof all parts (shapes or objects), e.g.(foo.front, foo.middle, foo.back)
All parts returned by shape(::Foo) must be movable, see BeamletOptics.AbstractKinematicTrait.
Additional information
Kinematic center
Unless specified otherwise by dispatching position / position! and orientation / orientation! onto custom pos and dir data fields, the position and orientation of the first element returned by shape(object) will be used as the kinematic center for e.g. translate3d!.
BeamletOptics.NoBoundingSphere Type
States that a shape or object has no bounding sphere. It is then tested against every ray via intersect3d, see bounding_sphere_of.
It has no center and no radius: position and radius throw an ArgumentError. Code that needs them handles NoBoundingSphere by a method of its own, or tests for it first.
BeamletOptics.NoSampling Type
NoSampling()The beams of the source were given to its constructor, e.g. CollimatedSource(beams, diameter, pos, dir). They can not be regenerated: num_rays! throws an ArgumentError and min_num_rays returns nothing.
BeamletOptics.NonInteractableObject Type
A passive AbstractObject which does not interact with the ray tracing simulation but can be moved via the kinematic API.
Fields
shape: anAbstractShape
Usage
This type is intended mainly for visualization purposes, e.g. kinematic mount Meshs, or similar applications. In essence, this object behaves fully transparent. The intersect3d and interact3d methods default to nothing.
BeamletOptics.NonInteractableObject Method
NonInteractableObject(loadpath::String)Creates a NonInteractableObject with a Mesh loaded from the specified file path. Useful for rendering background objects or geometry that does not interact with rays.
BeamletOptics.ObjectGroup Type
ObjectGroup(objects, T = Float64)A tree-like storage container for groups of objects. Can store individual objects and subgroups. Main purpose is handling of, i.e., groups of lenses.
objects is a vector or tuple of AbstractObjects and subgroups. A new group has its center at the global origin and the identity orientation, independent of the poses of its objects, so rotate3d! rotates about the global origin until set_pivot3d! moves the pivot.
Fields
center: a point in 3D space which is regarded as the reference origin of the groupdir: a 3x3 matrix that describes the commonorientationof the groupobjects: storesAbstractObject, can also store subgroups of typeAbstractObjectGroup
Each of its objects is traced and interacts on its own, read them via objects(group).
Kinematic
An ObjectGroup implements the kinematic API, see BeamletOptics.AbstractKinematicTrait. The following logic is applied to
translate3d!: all objects in the group are translated by the offset vectortranslate_to3d!: all objects are moved in parallel such that the groupcenteris equal to the target positionrotate3d!: all objects are rotated around thecenterpoint with respect to their relative positionset_pivot3d!: moves the groupcenter(the pivot used above) without moving any of itsobjects
The objects must be either all static or all movable, otherwise the constructor throws an ArgumentError. The group takes that kinematic class, see BeamletOptics.AbstractKinematicTrait.
Changing the objects
Objects and subgroups are added to and removed from the top level of the group via push!, delete!, pop! and popat!, like those of a System. The constructor copies the vector or tuple it is given, such that these do not change it.
BeamletOptics.Oriented Type
Oriented <: AbstractKinematicFrameReference frame of a movable value with a full local coordinate system, e.g. shapes, objects and beam groups.
Implementation reqs.
position/position!orientation/orientation!: a right-handed orthonormal 3x3 matrix
direction returns the local y-axis, i.e. orientation(x)[:, 2]. reset_rotation3d! rotates x by transpose(orientation(x)) about its position and then sets the orientation to the identity.
BeamletOptics.PathSegment Type
PathSegment{T}Element type of the vector returned by path_segments, a straight segment of a beam with the fields
start,stop: start and end point of the segment,Point3{T}in [m]s_start,s_stop: geometric path length from the source to the start and the end of the segment [m]opl_start,opl_stop: optical path length from the source to the start and the end of the segment [m]λ: wavelength of the segment in [m]depth: depth of the beam in the beam tree,1for a root beam,2for its children, ...parent: index of the preceding segment in the vector (the previous segment of the same beam or, for the first segment of a child beam, the last segment of its parent beam),0for the first segment of a root beambeam_index: index of the root beam in a beam group,1for a single beamray_index: index of the ray of the segment in theraysof its beam (of the chief beam of a beamlet), as returned bypoint_on_beam; starts at1for every beam of the treefinal:trueif the segment is a final ray without intersection, drawn with the lengthflenleaf:trueif the segment ends its branch, i.e. no other segment names it asparent: a final ray, or a ray that ends on an object without leaving it (e.g. on a detector)object: theAbstractObjecthit at the end of the segment (the object itself, not itsObjectGroup),nothingfor a final segment or if the intersection does not name its object
BeamletOptics.PlanoSurfaceSDF Type
PlanoSurfaceSDFAbstractSDF-based representation of two flat optical surfaces, i.e. equivalent to the CylinderSDF. When constructed, it is assumed that the first flat surface lies at the origin and the optical axis is aligned with the positive y-axis.
Fields:
diameter: the outer diameter of the circular flat lens surfacethickness: the distance between the flat surfaces
BeamletOptics.PointSource Type
PointSource <: AbstractBeamGroupRepresents a cone of Beams being emitted from a single point in space.
Fields
beams: a vector of allBeams originating from the source. The first one is the center beam, which starts at the source position along the central source direction, unless the source wraps given beams.NA: thenumerical_apertureof the point source spread anglecenter: source position, pivot for rotationsdir: theorientationof the group, a right-handed orthonormal matrix whose columns are the sampling reference vector, the central source direction and their cross product, seeAbstractBeamGroupsampling: how the rays were sampled (rings, sunflower or fan) (orNoSampling()for given beams), seenum_rays!
Functions
numerical_aperture: returns the NA of the sourcenum_rays!: regenerates the rays with another number of rays
BeamletOptics.PointSource Method
PointSource(pos, dir, sampling::AbstractSourceSampling, λ = 1e-6; num_rays, basis = nothing)Spawns a PointSource of Beams emitted from pos [m] around the central direction dir with the wavelength λ [m], sampled by sampling with num_rays rays, e.g. BeamletOptics.ConeRings. The catalog constructors PointSource, UniformPointSource and UniformFanSource call this method; a custom BeamletOptics.AbstractSourceSampling implements source_beams and numerical_aperture for it. The number type is promote_type of pos, dir and λ.
The optional basis vector sets the azimuth of the sampling pattern about dir, see BeamletOptics.sampling_basis. A num_rays below BeamletOptics.min_num_rays of the sampling and a basis that is zero or parallel to dir throw an ArgumentError.
BeamletOptics.PointSource Method
PointSource(pos, dir, θ, λ; num_rings, num_rays, basis)Spawns a point source of Beams at the specified position and direction. The point source is modelled as a collection of concentric beam fans centered around the center beam. The amount of beam rings between the center ray and half-spread-angle θ can be specified via num_rings.
Warning
For correct sampling, num_rays must be at least 20 times num_rings, otherwise an ArgumentError is thrown.
Arguments
The following inputs and arguments can be used to configure the PointSource:
Inputs
pos: center beam starting positiondir: center beam starting directionθ: half spread angle in rad, must be< πλ = 1e-6: wavelength in [m], default val. is 1000 nm
Keyword Arguments
num_rings: number of concentric beam rings, default is 10; the number of rings counts the center as the innermost one, i.e.num_rings - 1rings lie around itnum_rays: total number of rays in the source, default is 100x num_ringsbasis: Optional reference vector (e.g.[1,0,0]) to define the starting azimuthal angle for the source rings.
Reproducible sampling
If no basis is passed, the orthogonal basis vectors are derived from dir deterministically, so two sources sharing the same dir, θ, num_rings and num_rays sample exactly the same ray directions. Pass a basis to rotate the azimuthal sampling of a source about its own axis, e.g. to interleave several otherwise identical sources.
BeamletOptics.PointSource Method
PointSource(beams, NA, pos, dir::AbstractVector)
PointSource(beams, NA, pos, orientation::AbstractMatrix)Wraps existing beams into a PointSource with the numerical aperture NA and the source position pos. The group orientation is either derived from the central direction dir (the sampling reference vector is then picked deterministically via normal3d), or passed explicitly as a right-handed orthonormal 3x3 orientation matrix whose second column is the central direction. An invalid orientation throws an ArgumentError. The rays of such a source can not be regenerated with num_rays!: its sampling is NoSampling().
BeamletOptics.PolarizationFilter Method
PolarizationFilter(edge_length; cutoff_strength)Spawns a thin, rectangular PolarizationFilter. The edge_length has to be specified in [m]. The filter is aligned with the global y-axis and transmits along the x-axis, while blocking polarization components along the global z-axis.
A PolarizedRay whose polarization vector has a norm of at most cutoff_strength behind the filter is blocked, i.e. its beam ends here. Rays without polarization pass unchanged.
BeamletOptics.PolarizedRay Type
PolarizedRay{T} <: AbstractRay{T}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.
The geometrical ray description is identical to the standard Ray. 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.
Fields
pos: a point in R³ that describes theRayorigindir: a normalized vector in R³ that describes theRaydirectionintersection: refer toIntersectionλ: wavelength in [m]n: refractive index along the beam pathE0: complex-valued 3-tuple to represent the electric field in global coordinates
Jones matrices
In local coordinates the Jones matrices in the case of reflection/refraction are defined as
reflection: [-rₛ 0; 0 rₚ]
transmission: [tₛ 0; 0 tₚ]
where r and t are the complex-valued Fresnel coefficients (see also fresnel_coefficients).
Additional information
Field vector
It is assumed that the electric field vector ErrorException if the component of E0 along dir exceeds get_orthogonality_threshold() (default 1e-10) times |E0|.
Intensity
E0 can not be converted into an intensity value, since a single PolarizedRay can not directly model the change in intensity during imaging by an optical system.
BeamletOptics.PolarizedRay Method
PolarizedRay(pos, dir, λ = 1000e-9, E0 = [electric_field(1), 0, 0])Constructs a PolarizedRay at pos [m] along dir with the wavelength λ [m] in a medium of refractive index 1.
The default E0 is the field phasor of an intensity of 1 W/m², i.e. electric_field(1) ≈ 27.4 V/m, polarized along x. E0 is the complex electric field vector in [V/m] and must be orthogonal to dir, otherwise the constructor throws an ErrorException: the default fails for a dir along x, pass an E0 explicitly in that case.
BeamletOptics.PolarizedRayHit Type
PolarizedRayHit(ray::PolarizedRay, opl)Stores the hit of a PolarizedRay as values: those of a RayHit and the field vector E0 of the ray in global coordinates.
BeamletOptics.PolygonPrismSDF Type
PolygonPrismSDF <: AbstractSDFImplements the exact SDF of a right prism, i.e. the extrusion of a convex polygon along the local z-axis. The local origin is the origin of the coordinates given to the constructor, it is not shifted.
Fields
vertices: corners of the cross-section in the local x-y-plane in [m], in counter-clockwise ordernormals: outward unit normals of the edges, where edgeiruns from vertexito vertexi + 1height: extent along the local z-axis in [m], the prism spansz ∈ [-height/2, height/2]
BeamletOptics.PolygonPrismSDF Method
PolygonPrismSDF(vertices, height)Constructs the prism over the convex polygon given by vertices, a vector of 2D points (x, y) in [m], extruded symmetrically by height in [m] along the local z-axis. Both vertex orders are accepted and normalized to counter-clockwise. Throws an ArgumentError for fewer than three vertices, for points that are not 2D, for degenerate (zero area or collinear) corners and for non-convex or self-intersecting polygons.
BeamletOptics.Prism Type
Prism{T, S <: AbstractShape{T}, N <: AbstractRefractiveIndex} <: AbstractRefractiveOptic{T, N}Essentially represents the same functionality as Lens. Refer to its documentation.
BeamletOptics.Prism Method
Creates a Prism with a convex polygonal cross-section, extruded along the local z-axis. The local origin is the origin of the given coordinates, i.e. the prism is placed where the vertices are, and rotations act around it. Like the RightAnglePrism the prism is not aligned with the y-axis, orient it with the kinematic functions. See PolygonPrismSDF for the geometry. See also EquilateralPrism and DovePrism.
Arguments
vertices: corners(x, y)of the cross-section in the local x-y-plane in [m], as a vector of 2D points or tuples. Both vertex orders are accepted. The polygon must be strictly convex.height: extent along the local z-axis in [m], the prism is centered atz = 0n:AbstractRefractiveIndexof the prism
BeamletOptics.ProgressSink Type
ProgressSink()Receiver of the progress of all progress loops of BeamletOptics (e.g. of solve_system! with progress = true, see _with_progress) that run inside with(PROGRESS_SINK => sink) do … end, including the tasks of Threads.@threads started there. Such loops draw no terminal bar. Part of the developer API, e.g. for a GUI that shows the progress of a solve in the background and cancels it. Another task reads the running loop with progress_state(sink), and cancels the loops by setting sink.cancel[] = true: the next _tick! then throws _ProgressCancelled, i.e. a loop stops after its current item.
Fields
current: the innermost running loop,nothingbetween loops (atomic)cancel: cancel request, checked by every tick
BeamletOptics.Ray Type
Ray{T} <: AbstractRay{T}Mutable struct to store ray information.
Fields
pos: a point in R³ that describes theRayorigindir: a normalized vector in R³ that describes theRaydirectionintersection: refer toIntersectionλ: wavelength in [m]n: refractive index along the beam path
BeamletOptics.Ray Method
Ray(pos, dir, λ=1000e-9)Constructs a Ray where:
pos: is theRayorigindir: is theRaydirection of propagation, normalized to unit length
Optionally, a wavelength λ can be specified. The start refractive index is assumed to be in vacuum (n = 1).
BeamletOptics.RayCrossing Type
RayCrossing{T}Offset y0 + l * v of an auxiliary ray from the chief ray at distance l, with the slope v.
BeamletOptics.RayHit Type
Stores the hit of a Ray as values: hit point p, direction dir, optical path length opl of the beam up to the hit point, wavelength λ, refractive index n and projection factor proj.
BeamletOptics.RectangularFlatSurface Type
RectangularFlatSurface{T} <: AbstracCylindricalSurface{T}A type representing a planar rectangular surface, which is only parametrized by its size.
Fields
size::T: The size of the planar surface
BeamletOptics.RectangularPlateBeamsplitter Type
A plate beamsplitter with rectangular substrate and a single coated face. For more information refer to the AbstractPlateBeamsplitter docs.
Fields
substrate: a rectangularPrismthat acts as the substratecoating: aThinBeamsplitterthat acts as the coating
Additional information
Kinematic center
The center of kinematics of this splitter lies at the center of the coating.
BeamletOptics.RectangularPlateBeamsplitter Method
RectangularPlateBeamsplitter(width, height, thickness, n; reflectance=0.5)Creates a RectangularPlateBeamsplitter. The splitter coating is centered at the origin and the substrate lies on the positive y-side of it, from y = 0 to thickness. See also RoundPlateBeamsplitter.
Arguments
width: substrate width along the x-axis in [m]height: substrate height along the z-axis in [m]thickness: substrate thickness along the y-axis in [m]n: theAbstractRefractiveIndexof the substrate
Keywords
reflectance: defines the power reflectance R (dimensionless) of the coating, in the open interval (0, 1)
BeamletOptics.RectilinearGrid Type
RectilinearGrid(xs::AbstractVector, zs::AbstractVector)A Detector 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 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.
BeamletOptics.RegularGrid Type
RegularGrid(; num_points = 100, center = Centroid(), crop_factor, x_min, x_max, z_min,
z_max, x0_shift = 0, z0_shift = 0)The default sampling of a Detector: num_points×num_points 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 integrates with the trapezoidal rule. The window follows from the hits when the readout is evaluated, see calc_local_lims. A detector that no beam hit has the window of its active surface.
Keyword arguments
num_points::Int = 100: number of points per axis.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.crop_factor::Real: scales the width of the window around the hits; values >1 expand, <1 shrink. The default is1for ray hits (the box around the hit points) and3for beamlet hits (three beam radii around each hit, which holds the power of a Gaussian beam except for a part of10⁻⁸).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 anArgumentError.x0_shift = 0, z0_shift = 0: shift the whole window alongxorzin [m].
BeamletOptics.Retroreflector Type
RetroreflectorA Retroreflector reflects incoming rays back toward their source, independent of the incident angle. The shape is represented by a tetrahedral Mesh.
Fields
mesh: shape of theRetroreflector
BeamletOptics.Retroreflector Method
Retroreflector(scale)Spawns a Retroreflector.
Inputs
scale: a scaling factor for the size of the retroreflector, e.g.1e-3for 1 mm
BeamletOptics.RightAnglePrismSDF Type
RightAnglePrismSDF <: AbstractSDFImplements the SDF of a right angle prism with symmetric leg length l and height h. Note that these values are stored in the dimensions field as:
dimensions::Point3 = ( leg_length, # dim in x leg_length, # dim in y height, # dim in z )
The prism is the half of the box |x|, |y| ≤ l / 2, |z| ≤ h / 2 with x + y ≤ 0. The local origin is the center of the hypotenuse face, the right angle edge lies at (-l / 2, -l / 2).
Alignment
Note that the prism is not aligned with the positive y-axis! The legs have the normals -x and -y, the hypotenuse has the normal (1, 1, 0) / √2.
BeamletOptics.RightAnglePrismSDF Method
RightAnglePrismSDF(leg_length, height)Constructs a symmetric right angle prism with leg_length in x and y and height z in [m].
BeamletOptics.RingSDF Type
RingSDF <: AbstractSDFImplements the SDF of a ring in the x-z-plane for some distance in the y axis. This allows to add planar outer sections to any SDF which fits inside of the ring.
sourceBeamletOptics.RingSDF Method
Constructs a ring with inner_radius with a width and some thickness.
BeamletOptics.RoundPlateBeamsplitter Type
A plate beamsplitter with cylindrical substrate and a single coated face. For more information refer to the AbstractPlateBeamsplitter docs.
Fields
substrate: a cylindricalPrismthat acts as the substratecoating: aRoundThinBeamsplitterthat acts as the coating
Additional information
Kinematic center
The center of kinematics of this splitter lies at the center of the coating.
BeamletOptics.RoundPlateBeamsplitter Method
RoundPlateBeamsplitter(diameter, thickness, n; reflectance=0.5)Creates a RoundPlateBeamsplitter. The coating is centered at the origin and the substrate lies on the positive y-side of it, from y = 0 to thickness. See also RectangularPlateBeamsplitter.
Arguments
diameter: x-z-plane substrate diameter in [m]thickness: substrate thickness along the y-axis in [m]n: theAbstractRefractiveIndexof the substrate
Keywords
reflectance: defines the power reflectance R (dimensionless) of the coating, in the open interval (0, 1)
BeamletOptics.SellmeierEquation Type
SellmeierEquationA parametric type representing the six-coefficient Sellmeier equation for a transparent dielectric material. The Sellmeier equation models the wavelength dependence of the refractive index n(λ) in the material's transparency window. This type can provide n(λ) via a functor call, e.g.:
NBK7 = SellmeierEquation(...)
n_532 = NBK7(532e-9)Info
When initializing this type, the data should be provided with the classic μm-based coefficients. However, when calling the function, use SI-units, e.g. 532e-9 for 532 nm.
Fields
B1,B2,B3: dimensionless Sellmeier coefficients.C1,C2,C3: squared resonance wavelengths in μm².
BeamletOptics.SellmeierEquation Method
Returns the ref. index n(λ) for the six coefficient Sellmeier equation.
BeamletOptics.SingleBoundingSphere Type
SingleBoundingSphere{T} <: AbstractBoundingSphereA sphere that encloses one shape, see bounding_sphere_of.
Fields
pos: the center in world coordinates [m]radius: the radius [m]
BeamletOptics.SingleBoundingSphere Method
SingleBoundingSphere(sphere::AbstractBoundingSphere)
MultiBoundingSphere(sphere::AbstractBoundingSphere)The sphere with the same center and radius as a sphere of the other kind, e.g. the sphere around the parts of a composite shape as the sphere of this one shape. NoBoundingSphere() is passed on.
BeamletOptics.SingleBoundingSphere Method
SingleBoundingSphere(shape::AbstractShape, center, radius)The bounding sphere of the shape from a center given in the local frame of the shape, i.e. relative to its position and along the axes of its orientation, and the radius in [m]. The center is converted to world coordinates for the current pose of the shape. This is the constructor for a method of bounding_sphere_of.
BeamletOptics.SingleBoundingSphere Method
SingleBoundingSphere(shape::AbstractShape, sphere::AbstractBoundingSphere)The sphere, whose center is given in the local frame of the shape, in world coordinates, e.g. the sphere around the parts of a shape that are positioned in its local frame. NoBoundingSphere() is passed on.
BeamletOptics.SingleShape Type
SingleShape <: AbstractShapeTraitRepresents that the AbstractObject consists of a single underlying shape.
AbstractObject implementation reqs.
If shape_trait_of(::Foo) = SingleShape() is defined, Foo must implement the following:
Fields
shape: a single concreteAbstractShape, e.g. aCylinderSDF
BeamletOptics.SphereSDF Type
SphereSDFImplements the SDF of a perfect sphere. Orientation is fixed to unity matrix.
sourceBeamletOptics.SphericalSurface Type
SphericalSurface{T} <: AbstractRotationallySymmetricSurface{T}A type representing a spherical optical surface defined by its radius of curvature, clear (optical) diameter, and mechanical diameter. This surface is rotationally symmetric about its optical axis.
Fields
radius::T: The radius of curvature of the spherical surface. A positive value indicates that the center of curvature lies to the right of the vertex (following ISO 10110).diameter::T: The clear (optical) aperture of the surface.mechanical_diameter::T: The overall mechanical diameter of the surface. In many cases, this is equal to the optical diameter, but it can be set independently if the mechanical mount requires a larger dimension.
BeamletOptics.SphericalSurface Method
SphericalSurface(radius, diameter)Construct a SphericalSurface given the radius of curvature and the optical diameter. This constructor automatically sets the mechanical diameter equal to the optical diameter.
Arguments
radius: The radius of curvature of the surface.diameter: The clear (optical) diameter of the surface.
BeamletOptics.Static Type
Static <: AbstractKinematicTraitRepresents a value that cannot be moved. Every kinematic function throws an ArgumentError; the getters (e.g. position, orientation) stay available.
BeamletOptics.StaticSystem Type
StaticSystem <: AbstractSystemA static container storing the optical elements of, i.e. a camera lens or lab setup. Compared to System this way defining the system is less flexible, i.e. no elements can be added or removed after construction but it allows for more performant ray-tracing. The objects of its groups are stored when it is built: objects that are added to or removed from a group later, e.g. via push!(group, object), are not seen.
Warning
This type uses long tuples for storing the elements. This container should not be used for very large optical systems as it puts a lot of stress onto the compiler.
Fields
objects: vector containing the different objects that are part of the system (subtypes ofAbstractObject)
BeamletOptics.System Type
System <: AbstractSystemA container storing the optical elements of, i.e. a camera lens or lab setup.
Fields
objects: vector containing the different objects (subtypes ofAbstractObject) and object groups (subtypes ofAbstractObjectGroup) that are part of the system. The constructor copies the vector it is given, such thatpush!anddelete!of the system do not change it.
BeamletOptics.System Method
System()Creates an empty system, to which objects are added via push!.
BeamletOptics.ThinBeamsplitter Type
ThinBeamsplitter <: AbstractBeamsplitterRepresents a 2D beam-splitting device.
Fields
shape: 2DAbstractShapeat which the splitting process occurs (e.g. a 2D-Mesh)reflectance: scalar reflection factor, the amplitudefor the power reflectance transmittance: scalar transmission factor, the amplitude
Warning
The stored reflectance and transmittance are amplitudes. They should be calculated from the power reflectance reflectance^2 + transmittance^2 = 1, as checked by isvalid.
BeamletOptics.ThinBeamsplitter Method
ThinBeamsplitter(width, height; reflectance=0.5)Creates a zero-thickness, lossless, non-polarizing 2D rectangular ThinBeamsplitter where
width: is the x-dir. edge length in [m]height: is the z-dir. edge length in [m]reflectance: kw-arg in the open interval (0, 1) that determines how much light is reflected, i.e. 0.7 for a 70:30 splitter
Additional information
Reflectance
The input reflectance is the power reflectance reflectance and transmittance, such that their squares sum to one.
Reflection phase jump
Note that the reflection phase jump θᵣ is implemented by the individual interact3d-methods. Refer to them for more information.
BeamletOptics.TripletLens Type
TripletLensRepresents a three-component cemented triplet lens with three respective refractive indices n = n(λ). See also SphericalTripletLens and the surface-based constructor TripletLens(s1, s2, s3, s4, l1, l2, l3, n1, n2, n3).
Fields
Additional information
Clear apertures
If the surfaces need different clear apertures (e.g. a steep last surface), use the surface-based constructor TripletLens(s1, s2, s3, s4, l1, l2, l3, n1, n2, n3) with e.g. SphericalSurface(r, d) for each surface. SphericalTripletLens uses one diameter for all surfaces.
Air gap
This component type strongly assumes that all three lenses are mounted fully flush with respect to each other. Gaps between the components might lead to incorrect results.
Total internal reflection
Total internal reflection at a cemented interface between two elements is not modeled correctly.
BeamletOptics.TripletLens Method
TripletLens(s1, s2, s3, s4, l1, l2, l3, n1, n2, n3)Generates a three-component "cemented" TripletLens from four surface specifications, e.g. SphericalSurface, EvenAsphericalSurface or CircularFlatSurface. The front, middle and back elements are Lens(s1, s2, l1, n1), Lens(s2, s3, l2, n2) and Lens(s3, s4, l3, n3), refer to the surface-based Lens constructor for the construction of the elements. The front vertex lies at the origin and the middle and back elements are translated along +y by l1 and l1 + l2, so that neighbouring elements share the cemented surfaces s2 and s3.
Arguments
s1: first surfaces2: second (first cemented) surfaces3: third (second cemented) surfaces4: fourth surfacel1: first lens center thickness in ml2: second lens center thickness in ml3: third lens center thickness in mn1: first lensAbstractRefractiveIndexn2: second lensAbstractRefractiveIndexn3: third lensAbstractRefractiveIndex
Additional information
Radius of curvature (ROC) sign definition
The ROC is defined to be positive if the center is to the right of the surface, i.e. at +y. Otherwise it is negative.
Clear apertures
Each surface has its own clear aperture and mechanical diameter, which are leveled per element as for a single Lens.
Supported surfaces
Only rotationally symmetric surfaces are supported, cylindrical surfaces are not. The limitations of the surface-based Lens constructor apply to each element: a meniscus element, whose center thickness does not exceed the sagitta of its convex surface, must consist of spherical surfaces.
Total internal reflection
Total internal reflection at a cemented interface between two elements is not modeled correctly.
BeamletOptics.UnionSDF Type
UnionSDF{T, TT <: Tuple} <: AbstractCompositeSDF{T}This SDF represents the merging of two or more SDFs. If the constituent SDFs do not overlap (they can and should touch) the resulting SDF should be still exact if the constituent SDFs are exact.
The intended way to construct these is not explicitely but by just adding two AbstractSDFs using the regular + operator.
s1 = SphereSDF(1.0)
translate3d!(s1, Point3(0, 1.0, 0.0))
s2 = SphereSDF(1.0)
# will result in a SDF with two spheres touching each other.
s_merged = s1 + s2Warning
Where operands touch tangentially, the normal is taken from the operand that is closest at probes ρ = 1 µm beside the surface, which is valid for features much larger than ρ. The traced values are unaffected, but on the µm scale the derivatives in automatic differentiation may come from the inner operand.
BeamletOptics._LazyProgress Type
_LazyProgress{O}Thread-safe progress counter for long loops. Where the progress goes depends on the output type O, see _report!:
an
IO: aProgressMeter.Progressbar is drawn only once the loop has run forthresholdseconds, seeget_progress_threshold,a
ProgressSink: nothing is drawn, the sink exposes the running loop to another task (e.g. the live view) and can cancel it.
_tick! costs one atomic increment plus the report of the output: one time() call for an IO, one atomic load of the cancel flag for a sink. The terminal bar is created lazily and redrawn at most every dt seconds by one thread at a time (trylock), so an invisible bar never contends for a lock. Use it through _with_progress, which finishes the bar, or cancels it if the loop throws.
Fields
n: total number of itemsdesc: description printed in front of the barenabled: iffalse,_tick!returns after a single branchoutput: stream the bar is drawn to, or theProgressSinkthe loop reports tocount: number of finished itemstnext: earliesttime()at which the bar is created or redrawn,Infstops drawingdt: minimum interval in s between redrawst0:time()at which the counter was created, i.e. the loop startedlock: serializes creating, redrawing and stopping the barbar: the ProgressMeter bar,nothinguntil it is first drawn
BeamletOptics._LazyProgress Method
_LazyProgress(progress::Bool, n, desc)Progress counter for the progress keyword of a public function. It reports to the scoped PROGRESS_SINK if one is set, otherwise to stderr. It is enabled only if progress is true and the output can show it: a sink always, stderr only if it is a terminal (Base.TTY), so documentation builds, CI logs and piped output stay clean.
BeamletOptics._LazyProgress Method
_LazyProgress(n, desc; enabled = true, output = stderr, threshold = get_progress_threshold(), dt = 0.2)Progress counter for n items that reports to output, an IO or a ProgressSink. An IO is drawn to once threshold seconds have passed; a sink ignores threshold and dt.
BeamletOptics._ProgressCancelled Type
_ProgressCancelled()Thrown by _tick! inside a loop whose ProgressSink was cancelled. Check caught exceptions with is_cancelled, which also sees through the wrappers of Threads.@threads.
AbstractTrees.children Method
AbstractTrees.children(h::AbstractSystemRenderHandle) -> AbstractVector{<:AbstractObjectRenderHandle}The object handles of the system handle h, one per rendered object (the objects of groups, not the groups). Change them via push! and delete! of h, not via the returned vector.
AbstractTrees.children Method
AbstractTrees.children(system::System)Returns the objects and object groups of the system as they were added, groups not flattened. See also objects(system), which flattens the groups.
Base.append! Method
append!(d::Detector, new::Vector{<:AbstractDetectorHit})Stores all hits of new in the detector d at once, guarded by the lock of d. The vector new may become the vector of hits of d, i.e. it must not be used afterwards.
Base.delete! Method
delete!(h::AbstractSystemRenderHandle, oh::AbstractObjectRenderHandle) -> hRemoves the object handle oh from the system handle h. Its plots stay in the axis, delete them via remove_render!(oh).
Base.delete! Method
delete!(group::ObjectGroup, object::ObjectOrGroup) -> groupRemoves the top-level object (or subgroup) from the group, compared by identity. The pose of the group and the pose of the object stay as they are. Nothing happens for an object that is not part of the group. An object within a subgroup throws an ArgumentError: remove it from its subgroup instead. A group without objects remains a valid, empty group.
Beams that were solved before must be solved again, see delete!(system, object). A StaticSystem keeps the objects that its groups had when it was built and still traces the removed object: trace the group in a System, or build a new StaticSystem. The group must not be changed while a system that holds it is being solved.
Base.delete! Method
delete!(system::System, object::ObjectOrGroup) -> systemRemoves the top-level object (or object group) from the system, compared by identity. Nothing happens for an object that is not part of the system. An object within a group can not be removed on its own and throws an ArgumentError: remove the group instead.
Beams and beam groups that were solved before still end on the removed object: solve them again with solve_system!(system, beam). The system must not be changed while it is being solved.
Base.empty! Method
empty!(bg::AbstractBeamGroup)Resets every beam of the group to its untraced start state, e.g. to solve the group again after the objects of a System were changed. The pose of the group is unchanged.
Base.empty! Method
empty!(beam::AbstractBeam)Resets the beam to its untraced start state: resets every component beam (e.g. the chief, waist and divergence beams of a GaussianBeamlet) and drops all child beams.
Base.empty! Method
Resets the beam to its untraced start state: all rays but the first are removed, the intersection of the start ray is cleared and all child beams are dropped.
Base.empty! Method
empty!(detector)Resets the field data of the detector. Must be implemented for each concrete subtype of AbstractDetector.
Base.length Method
The number of hits stored in the detector d, 0 before the first solve and after empty!(d).
Base.length Method
Base.length(beam::AbstractBeam)Calculate the length of a beam up to the point of the last intersection.
Tip
Use optical_path_length to get the optical path length instead.
Base.length Method
Base.length(ray::AbstractRay)Returns the geometric length of a ray between its start and intersection point. If no intersection exists, Inf is returned.
Tip
Use optical_path_length to get the optical path length instead.
Base.pop! Method
pop!(group::ObjectGroup) -> ObjectOrGroupRemoves the last top-level object (or subgroup) of the group and returns it. The pose of the group and the pose of the object stay as they are, see delete!(group, object). An empty group throws an ArgumentError.
Base.pop! Method
pop!(system::System) -> ObjectOrGroupRemoves the last top-level object (or object group) of the system and returns it. Beams that were solved before must be solved again, see delete!(system, object).
Base.popat! Method
popat!(group::ObjectGroup, i::Integer) -> ObjectOrGroupRemoves the i-th top-level object (or subgroup) of the group and returns it. The index counts the objects and subgroups as they were added, a subgroup counts as one. An index out of bounds throws a BoundsError. The pose of the group and the pose of the object stay as they are, see delete!(group, object).
Base.popat! Method
popat!(system::System, i::Integer) -> ObjectOrGroupRemoves the i-th top-level object (or object group) of the system and returns it. The index counts the objects and groups as they were added, a group counts as one. An index out of bounds throws a BoundsError. Beams that were solved before must be solved again, see delete!(system, object).
Base.position Method
position(object) -> Point3Returns the current position of the object in R³ as a Point3 where (x, y, z) in a right-hand coordinate system.
In general, position(object) returns position(shape(object)) unless specified otherwise.
Base.push! Method
push!(h::AbstractSystemRenderHandle, oh::AbstractObjectRenderHandle) -> hAdds the object handle oh at the top level of the system handle h, e.g. of an object added to the scene after live_render!, such that update_render! and pick_object of h include it.
Base.push! Method
push!(d::Detector, hit::AbstractDetectorHit)Stores the hit in the detector d, guarded by the lock of d, and returns d. Within with_hit_buffers, e.g. in the solve of a beam group, the hit is collected in the buffer of the current task instead and reaches d when the buffer is flushed.
Base.push! Method
push!(group::ObjectGroup, objects::ObjectOrGroup...) -> groupAdds the objects (or object groups) at the top level of the group. The pose of the group (its pivot and orientation) and the poses of the objects stay as they are, i.e. the objects are added where they are.
The objects join the current frame of the group, like parts put onto a mount that was moved before: reset_rotation3d! and reset_translation3d! of the group undo its rotation and translation so far and move the added objects by the same amount, although these did not take part in that motion.
Throws an ArgumentError and adds nothing if an object is already part of the group, directly or within a subgroup, or if the objects and those of the group would not be all static or all movable, see BeamletOptics.AbstractKinematicTrait. Objects are compared by identity.
The group does not know the systems that hold it: an object that is also part of such a system is then traced twice, so remove it from the system first, e.g. via delete!(system, object). Beams that were solved before must be solved again, see push!(system, objects...). A StaticSystem keeps the objects that its groups had when it was built and does not trace the new objects: trace the group in a System, or build a new StaticSystem. The group must not be changed while a system that holds it is being solved.
Base.push! Method
push!(system::System, objects::ObjectOrGroup...) -> systemAdds the objects (or object groups) at the top level of the system, such that they are traced by the following calls of solve_system!. An object that is already part of the system, directly or within a group, throws an ArgumentError; in this case nothing is added.
Beams and beam groups that were solved before do not know the new object: solve them again with solve_system!(system, beam). The system must not be changed while it is being solved.
BeamletOptics.BiConcaveLensSDF Method
BiConcaveLensSDF(r1, r2, l, d=1inch)Constructs a bi-concave lens SDF with:
r1> 0: radius of concave frontr2> 0: radius of convex backl: lens thicknessd: lens diameter, default value is one inchmd: mechanical lens diameter, adds an outer ring section to the lens, ifmd>d.
The spherical surfaces are constructed flush with the cylinder surface.
sourceBeamletOptics.BiConvexLensSDF Method
BiConvexLensSDF(r1, r2, l, d=1inch)Constructs a cylindrical bi-convex lens SDF with:
r1> 0: radius of convex frontr2> 0: radius of convex backl: lens thicknessd: lens diameter, default value is one inch
The spherical surfaces are constructed flush with the cylinder surface.
sourceBeamletOptics.CircularFlatMesh Method
CircularFlatMesh(radius, n)Creates a 2D rectangular Mesh that is centered around the origin and aligned with respect to the negative y-axis.
Inputs
radius: of the mesh in [m]n: slice discretization factor (higher equals better resolution)
BeamletOptics.CollimatedGaussianBeamletSource Method
CollimatedGaussianBeamletSource(pos, dir, D, λ, w0s; n_grid=20, P0)Generates an n_grid × n_grid square array of AstigmaticGaussianBeamlets, all pointing in the same direction 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 (default20yields400total beamlets).basis: Optional tuple(ex, ey)of the macroscopic sampling grid axes, i.e. the 3D directions corresponding to thexandygrid axes.exmust not be zero or parallel todir; its component normal todirbecomes the local x-axis of the grouporientation.randomize_axes: Iftrue, 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 forrandomize_axes.P0: Total power of the source in [W]. The beamlets overlap and add coherently; their fields are scaled such that the superposition carriesP0.
BeamletOptics.ConicMirror Method
ConicMirror(R, k, diameter; thickness=nothing, hole_diameter=nothing)Constructs an on-axis segment of a general conic-of-revolution Mirror (sphere, paraboloid, ellipsoid or hyperboloid). The vertex lies at the origin and the mirror opens towards the negative y-axis for R > 0. See OffAxisConicMirror for the off-axis case and the full sign/domain conventions.
If hole_diameter is given, a cylindrical bore centred on the optical axis (the local +y-axis) is subtracted from the substrate, piercing it completely (e.g. Cassegrain, Ritchey-Chrétien, or Dall-Kirkham primary).
Arguments
R: Radius of curvature at the vertex [m];R > 0concave,R < 0convexk: Conic constant;k = -1is a paraboloid (seeParabolicMirror),k = 0a sphere (seeSphericalMirror)diameter: Mirror aperture diameter [m]thickness: Substrate thickness [m], calculated automatically to ensure solid backing ifnothing(default)hole_diameter: Diameter of the central through-hole [m], no hole ifnothing(default). Must satisfy0 < hole_diameter < diameter.
BeamletOptics.CuboidMesh Method
CuboidMesh(x, y, z, θ=π/2)Constructs the Mesh of a rectangular cuboid as per the dimensions specified by x, y and z. In addition, one side of the mesh can be tilted by an angle θ in order to generate the mesh of a rhomb. The mesh is initialized such that one corner of the cuboid lies at the origin.
Arguments
x, y, z: dimensions for the cube in [m]θ: parallel tilt angle
BeamletOptics.DovePrism Method
Creates a Prism with an isosceles trapezoid cross-section and 45° end faces, e.g. a Dove prism that inverts an image without deviating a beam along its axis. The long axis is the local y-axis, so that a beam travelling along +y enters the 45° end face. The base face with the normal -x is the one that totally internally reflects. The local origin is the center of the cross-section's bounding box. A beam along +y leaves the prism parallel to the y-axis, but in general laterally shifted.
Arguments
length: length of the long base face in [m], must be larger than2 * apertureaperture: distance between the base face and the parallel short face in [m], must be positiveheight: extent along the local z-axis in [m]n:AbstractRefractiveIndexof the prism
BeamletOptics.EllipsoidalMirror Method
EllipsoidalMirror(s, s′, diameter; thickness=nothing, hole_diameter=nothing)Constructs an on-axis segment of an ellipsoidal Mirror whose two real conjugate foci lie at (0, -s, 0) and (0, -s′, 0); the vertex lies at the origin. See OffAxisEllipsoidalMirror for the off-axis case and the sign convention for s, s′.
If hole_diameter is given, a cylindrical bore centred on the optical axis (the local +y-axis) is subtracted from the substrate, piercing it completely (e.g. Dall-Kirkham primary).
Arguments
s,s′: Conjugate object/image distances from the vertex [m], same signdiameter: Mirror aperture diameter [m]thickness: Substrate thickness [m], calculated automatically to ensure solid backing ifnothing(default)hole_diameter: Diameter of the central through-hole [m], no hole ifnothing(default). Must satisfy0 < hole_diameter < diameter.
BeamletOptics.EllipticalGaussianBeamletSource Method
EllipticalGaussianBeamletSource(pos, dir, θ_x, θ_y, λ; num_rings=10, num_rays=100*num_rings, ...)Spawns a coherent array of AstigmaticGaussianBeamlets 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; the number of rings counts the center as the innermost one, i.e.num_rings - 1rings lie around it.num_rays: Total number of beamlets to generate.overlap: Scaling factor for the sub-waist divergence (default1.2ensures smooth overlap).basis: Optional reference vector (e.g.[1,0,0]) to define the starting azimuthal angle for the source rings.randomize_axes: Iftrue, the internal principal axes of each individual beamlet are randomly rotated.rng: Random number generator to use forrandomize_axes.P0: Total power of the source in [W]. The beamlets overlap and add coherently in the far field; their fields are scaled such that the superposition carriesP0.E0: Optional Jones vector defining the polarization and phase of the wave; its component transverse to each beamlet is used, its magnitude does not matter, the power isP0.
Reproducible sampling
If no basis is passed, the orthogonal basis vectors are derived from dir deterministically, so two sources sharing the same arguments sample exactly the same beamlet directions. Pass a basis to rotate the azimuthal sampling of a source about its own axis. A basis that is zero or parallel to dir throws.
BeamletOptics.EquilateralPrism Method
EquilateralPrism(side, height, n)Creates an equilateral triangular Prism, e.g. for dispersion. The local origin is the centroid of the triangle. The apex points along the local +y-axis and the base face has the normal -y. A beam travelling along +x or -x through the faces next to the apex at (approximately) minimum deviation is deflected towards the base. For a beam along +y, zrotate3d!(prism, π / 2 - θ) with θ = asin(n sin 30°) - 30° sets minimum deviation, the beam is deflected towards +x.
Arguments
side: edge length of the triangular cross-section in [m], must be positiveheight: extent along the local z-axis in [m]n:AbstractRefractiveIndexof the prism
BeamletOptics.GaussianBeamletDecomposition Method
GaussianBeamletDecomposition(pos, dir, λ, w0; n_grid=20)Decomposes a macroscopic Gaussian beam of waist w0 into an n_grid × n_grid array of microscopic AstigmaticGaussianBeamlets. 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 (default20yields400total beamlets). The grid spans4 w0; the sub-waistoverlap ⋅ 4 w0 / n_gridof the beamlets must be smaller thanw0, i.e.n_grid > 4 overlap, else anArgumentErroris thrown. The superposition of the beamlets is the Gaussian beam of the waistw0and the powerP0: the sampled envelope is deconvolved with the profile of a beamlet.overlap: Scaling factor for the sub-waist relative to grid spacing (default1.2ensures smooth overlap).basis: Optional tuple(ex, ey)of the macroscopic sampling grid axes, i.e. the 3D directions corresponding to thexandygrid axes.exmust not be zero or parallel todir; its component normal todirbecomes the local x-axis of the grouporientation.randomize_axes: Iftrue, 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 forrandomize_axes.P0: Total power of the macroscopic Gaussian beam in [W].E0: Optional Jones vector defining the polarization and initial phase of the beam; its component transverse todiris used, its magnitude does not matter, the power isP0. Ifnothing, defaults to linear polarization along the first grid axis.threshold: Relative amplitude below which beamlets are not spawned (default1e-4).
BeamletOptics.GaussianModeDecomposition Method
GaussianModeDecomposition(x, y, Eu, Ev, pos, dir, λ; basis = nothing, R = Inf)Fits a single AstigmaticGaussianBeamlet to a transverse complex vector field, given by its components Eu, Ev along the sampling axes e1, e2 of a plane normal to dir. This is the lowest-order Gaussian mode decomposition: the counterpart of WavefrontBeamletDecomposition for fields that are close to one Gaussian mode and too small to be tiled into many beamlets, e.g. the output of a single-mode fiber (beamlets must be much larger than λ).
Arguments
x,y: 1D sample coordinates alonge1,e2in [m], relative topos.Eu,Ev:length(x) × length(y)complex field components alonge1,e2in [V/m] (peak amplitude), with the full spatial phase and travelling alongdir.pos: global position of the samplex = y = 0in [m].dir: propagation direction, the normal of the sampling plane.λ: vacuum wavelength in [m]. The plane must lie in vacuum or air (n = 1), where BMO starts beams.basis: optional tuple(ex, ey)of the sampling axese1,e2, as inWavefrontBeamletDecomposition. Default:e1 = normal3d(dir),e2 = dir × e1.R: radius in [m] of a reference sphere that has been removed fromEu,Ev, as inWavefrontBeamletDecomposition(x, y, Eu, Ev, pos, dir, λ). DefaultInf:Eu,Evare the physical field. The sphere enters the fit analytically (tilt at the centroid, curvature1/R), so the grid only has to resolve the phase ofEu,Ev.
The beamlet starts at the centroid on the plane, with waist radii and waist positions along its principal axes that reproduce the fitted radii and curvatures there.
The beamlet carries only the projected part of the field: optical_power(beamlet) divided by the power of the input is the fraction of the power in the fitted Gaussian mode, i.e. the quality of the approximation.
Limits
The widths are measured in the plane, so the tilt of the fitted direction against dir must be small. A twist between the axes of curvature and intensity (general astigmatism) is not represented.
BeamletOptics.HyperbolicMirror Method
HyperbolicMirror(s, s′, diameter; thickness=nothing, hole_diameter=nothing)Constructs an on-axis segment of a hyperboloidal Mirror (e.g. a Cassegrain/Gregory secondary, or a Ritchey-Chrétien primary) whose conjugate foci lie at (0, -s, 0) and (0, -s′, 0); the vertex lies at the origin. See OffAxisHyperbolicMirror for the off-axis case and the sign convention.
If hole_diameter is given, a cylindrical bore centred on the optical axis (the local +y-axis) is subtracted from the substrate, piercing it completely (e.g. Ritchey-Chrétien primary).
Cassegrain secondary
The secondary of a Cassegrain/Gregory telescope sees the prime focus behind itself, so pass it as a negative s.
Arguments
s,s′: Conjugate object/image distances from the vertex [m], opposite signsdiameter: Mirror aperture diameter [m]thickness: Substrate thickness [m], calculated automatically to ensure solid backing ifnothing(default)hole_diameter: Diameter of the central through-hole [m], no hole ifnothing(default). Must satisfy0 < hole_diameter < diameter.
BeamletOptics.KM100CPMount Method
KM100CPMount()Returns a NonInteractableObject of a Thorlabs KM100CP/M kinematic mount for Ø1" optics on a post. The origin lies at the center of a mounted Ø1" mirror, i.e. a RoundPlanoMirror spawned at the origin sits in the mount, and the post base is 81.8 mm below it.
The mesh is loaded from the documentation assets that ship with the package. Combine it with a mirror via ObjectGroup to move both together.
BeamletOptics.MoellerTrumboreAlgorithm Method
MoellerTrumboreAlgorithm(face::Matrix, ray::AbstractRay; kϵ = 1e-9, lϵ = 1e-9)An implementation of the Möller-Trumbore algorithm for ray-triangle-intersection, which hits the face from both sides. This algorithm evaluates the possible intersection between a ray and a face that is defined by three vertices. If no intersection occurs, Inf is returned.
kϵ: dimensionless tolerance. A ray misses the face ifsin α |cos θ| ≤ kϵ, with the corner angleαbetween the first two edges and the angleθbetween the ray and the face normal, i.e. if it runs (almost) parallel to the face or the face is degenerate. The barycentric coordinates of a hit may exceed the face bykϵ. Both are independent of the size of the face.lϵ: the shortest distance in [m] from the start of the ray at which a hit counts, such that a ray that starts on the face does not hit it again.
This algorithm is fast due to multiple breakout conditions.
sourceBeamletOptics.OffAxisConicMirror Method
OffAxisConicMirror(R, k, x_off, diameter; thickness=nothing, hole_diameter=nothing)Constructs an off-axis segment of a general conic-of-revolution Mirror (sphere, paraboloid, ellipsoid or hyperboloid), offset by x_off from the parent vertex. See ConicSDF for the frame convention (origin, parent axis, opening direction, vertex location).
Arguments
R: Radius of curvature at the parent vertex [m];R > 0is concave (opens towards-y),R < 0is convex (opens towards+y). Must be non-zero.k: Conic constant.k = -1is a paraboloid,k = 0a sphere,-1 < k <= 0a prolate ellipsoid,k > 0an oblate ellipsoid,k < -1a hyperboloid.x_off: Off-axis distance from the parent vertex to the aperture center [m]diameter: Mirror aperture diameter [m]thickness: Substrate thickness [m], calculated automatically to ensure solid backing ifnothing(default)hole_diameter: Diameter of the central through-hole [m], no hole ifnothing(default). Must satisfy0 < hole_diameter < diameter. The bore is parallel to the local +y axis through the aperture centre.
For k > -1 the aperture must stay within the domain of the parent conic (abs(x_off) + diameter/2 < abs(R)/sqrt(1+k)), otherwise an ArgumentError is thrown; for k <= -1 there is no such limit. See also ConicMirror for the on-axis case.
Note that hole_axis (collimated/focused bore) exists only for OffAxisParabolicMirror.
BeamletOptics.OffAxisEllipsoidalMirror Method
OffAxisEllipsoidalMirror(s, s′, x_off, diameter; thickness=nothing, hole_diameter=nothing)Constructs an off-axis segment of an ellipsoidal Mirror whose two real conjugate foci lie at object/image distances s, s′ from the parent vertex, offset by x_off. Both foci lie on the same side (the -y, i.e. reflecting, side) of the parent vertex for positive s, s′.
Arguments
s,s′: Conjugate object/image distances from the parent vertex [m], measured positive towards-y(in front of the mirror). Must have the same sign.x_off: Off-axis distance from the parent vertex to the aperture center [m]diameter: Mirror aperture diameter [m]thickness: Substrate thickness [m], calculated automatically to ensure solid backing ifnothing(default)hole_diameter: Diameter of the central through-hole [m], no hole ifnothing(default). Must satisfy0 < hole_diameter < diameter. The bore is parallel to the local +y axis through the aperture centre.
The vertex radius of curvature and conic constant are derived via R = 2ss′/(s+s′), k = -((s′-s)/(s′+s))^2. See also EllipsoidalMirror for the on-axis case.
Note that hole_axis (collimated/focused bore) exists only for OffAxisParabolicMirror.
BeamletOptics.OffAxisHyperbolicMirror Method
OffAxisHyperbolicMirror(s, s′, x_off, diameter; thickness=nothing, hole_diameter=nothing)Constructs an off-axis segment of a hyperboloidal Mirror whose conjugate foci lie at object/image distances s, s′ from the parent vertex, offset by x_off. Exactly one focus is virtual, i.e. s and s′ have opposite signs.
Arguments
s,s′: Conjugate object/image distances from the parent vertex [m], measured positive towards-y(real focus, in front of the mirror) and negative towards+y(virtual focus, behind the mirror). Must have opposite signs.x_off: Off-axis distance from the parent vertex to the aperture center [m]diameter: Mirror aperture diameter [m]thickness: Substrate thickness [m], calculated automatically to ensure solid backing ifnothing(default)hole_diameter: Diameter of the central through-hole [m], no hole ifnothing(default). Must satisfy0 < hole_diameter < diameter. The bore is parallel to the local +y axis through the aperture centre.
Cassegrain secondary
The secondary of a Cassegrain/Gregory telescope sees the prime focus behind itself, so pass it as a negative s.
The vertex radius of curvature and conic constant are derived via R = 2ss′/(s+s′), k = -((s′-s)/(s′+s))^2. See also HyperbolicMirror for the on-axis case.
Note that hole_axis (collimated/focused bore) exists only for OffAxisParabolicMirror.
BeamletOptics.OffAxisParabolicMirror Method
OffAxisParabolicMirror(rfl, diameter; angle=90, thickness=nothing, hole_diameter=nothing, hole_axis=:collimated)Constructs an Off-Axis Parabolic (OAP) Mirror from:
Arguments
rfl: Reflected Focal Length (distance from aperture center to focus) [m]diameter: Mirror aperture diameter [m]angle: Deflection angle in degrees (default: 90°)thickness: Substrate thickness [m], calculated automatically to ensure solid backing ifnothing(default)hole_diameter: Diameter of the through-hole [m], no hole ifnothing(default). Must satisfy0 < hole_diameter < diameter.hole_axis: Orientation of the through-hole. Options: -:collimated(default): parallel to the collimated beam (local y-axis / substrate normal), centered at the aperture center(0, 0, 0). -:focused: angled towards the parent paraboloid focus(-x_off, x_off^2/(4f) - f, 0)in the segment frame, equivalently(-rfl*sind(angle), -rfl*cosd(angle), 0)withanglein degrees, passing through the aperture center(0, 0, 0)(e.g. for collinear pump-probe beams).
BeamletOptics.OffAxisParaboloidSDF Method
OffAxisParaboloidSDF(f, x_off, diameter, thickness)Constructs a ConicSDF with R = 2f and k = -1, i.e. a segment of a paraboloid of revolution. Kept for backwards compatibility; prefer ConicSDF.
BeamletOptics.ParabolicMirror Method
ParabolicMirror(f, diameter; thickness=nothing, hole_diameter=nothing)Constructs an on-axis parabolic Mirror with focal length f, i.e. a ConicMirror with R = 2f and k = -1. The vertex of the reflecting surface lies at the origin and the focus at (0, -f, 0). For f > 0 the mirror is concave and opens towards the negative y-axis; for f < 0 it is convex and its focus is virtual, behind the mirror. The shape is an OffAxisParaboloidSDF without off-axis offset.
If hole_diameter is given, a cylindrical bore centred on the optical axis (the local +y-axis) is subtracted from the substrate, piercing it completely (a Cassegrain primary).
Reflective bore wall
Rays that graze into the hole will reflect off its wall rather than being absorbed.
Arguments
f: Focal length [m];f > 0concave,f < 0convexdiameter: Mirror aperture diameter [m]thickness: Substrate thickness [m],|rim sag| + 10 mmifnothing(default)hole_diameter: Diameter of the central through-hole [m], no hole ifnothing(default). Must satisfy0 < hole_diameter < diameter.
BeamletOptics.PlanoConcaveAsphericalLensSDF Method
PlanoConcaveAsphericalLensSDF(r, l, d=1inch)Constructs a plano-concave aspheric lens SDF with:
r> 0: front radiusl: lens thicknessd: lens diametercz: aspheric surface chip zonek: The conic constant of the surfaceα_coeffs: The (even) aspheric coefficients, starting with A2 (r²).md: lens mechanical diameter (default: md = d)
The spherical surface is constructed flush with the cylinder surface.
sourceBeamletOptics.PlanoConcaveLensSDF Method
PlanoConcaveLensSDF(r, l, d=1inch)Constructs a plano-concave lens SDF with:
r> 0: front radiusl: lens thicknessd: lens diameter, default value is one inchmd: mechanical lens diameter, must be > d
The spherical surface is constructed flush with the cylinder surface.
sourceBeamletOptics.PlanoConvexAsphericalLensSDF Method
PlanoConvexAsphericalLensSDF(r, l, d=1inch)Constructs a plano-convex aspheric lens SDF with:
r> 0: front radiusl: lens thicknessd: lens diameterk: The conic constant of the surfaceα_coeffs: The (even) aspheric coefficients, starting with A2 (r²).
The spherical surface is constructed flush with the cylinder surface.
sourceBeamletOptics.PlanoConvexLensSDF Method
PlanoConvexLensSDF(r, l, d=1inch)Constructs a plano-convex lens SDF with:
r> 0: front radiusl: lens thicknessd: lens diameter, default value is one inch
The spherical surface is constructed flush with the cylinder surface.
sourceBeamletOptics.QuadraticFlatMesh Method
QuadraticFlatMesh(width)Creates a 2D quadratic Mesh. Refer to RectangularFlatMesh for more information.
BeamletOptics.RectangularCompensatorPlate Method
RectangularCompensatorPlate(width, height, thickness, n)Creates a compensator plate (modeled as a Prism) that can be used to remove parallel beam offsets created by e.g. the RectangularPlateBeamsplitter. The compensator is aligned with the positive y-axis. The first surface lies at the origin.
Inputs
width: compensator width along the x-axis in [m]height: compensator height along the z-axis in [m]thickness: compensator thickness along the y-axis in [m]n: theAbstractRefractiveIndexof the substrate
BeamletOptics.RectangularFlatMesh Method
RectangularFlatMesh(width, height)Creates a 2D rectangular Mesh that is centered around the origin and aligned with respect to the y-axis. Vertex normals are parallel to the positive y-axis.
Inputs
width: width along the x-axis in [m]height: height along the z-axis in [m]
BeamletOptics.RectangularPlanoMirror Method
RectangularPlanoMirror(width, height, thickness)Constructs a rectangular plano Mirror based on the input dimensions. The front reflecting surface is normal to the y-axis and lies at the origin.
Arguments
width: of the mirror in x-direction [m]height: of the mirror in z-direction [m]thickness: of the mirror in y-direction [m]
BeamletOptics.RetroMesh Method
RetroMesh(scale::Real; T = Float64)Creates an open tetrahedral Mesh with edges derived from the vertices of a unit cube. Can be scaled with a scale factor. The data type for the vertices and internal computations can be adjusted using T (default: Float64).
BeamletOptics.RightAnglePrism Method
RightAnglePrism(leg_length, height, n)Creates a right angle symmetric Prism, see RightAnglePrismSDF. The legs are the faces with the normals -x and -y, the hypotenuse has the normal (1, 1, 0) / √2. The local origin is the center of the hypotenuse face, the right angle edge lies at (-leg_length / 2, -leg_length / 2).
As constructed, a beam along +y enters the leg with the normal -y, is totally internally reflected at the hypotenuse (for n > √2) and leaves along -x; after yrotate3d!(prism, π) it leaves along +x. zrotate3d!(prism, 5π / 4) turns the hypotenuse normal to -y, so that the hypotenuse faces a beam along +y and returns it antiparallel.
Arguments
leg_length: dimension in x- and y-direction in [m]height: extent along the local z-axis in [m]n:AbstractRefractiveIndexof the prism
BeamletOptics.RightAnglePrismMirror Method
RightAnglePrismMirror(leg_length, height)Constructs a right-angle prism Mirror with perfect reflectivity (R = 1). The reflecting surface is modeled using a BeamletOptics.RightAnglePrismSDF, which is rotated by 225° about z: the hypotenuse passes through the local origin with the normal -y and reflects a beam along +y back onto itself. The right angle edge lies on the +y-axis. Rotate the mirror by 45° about z or x to fold a beam by 90°.
Arguments
leg_length: edge length in x and y [m]height: height in z-axis [m]
BeamletOptics.RoundLinearPolarizer Method
RoundLinearPolarizer(diameter, front_thickness, back_thickness, n; cutoff_strength=eps())Creates a LinearPolarizer: a round polarizing film cemented between two round glass plates of the given diameter, flush against the film on both sides.
Inputs
diameter: outer diameter of the film and substrates in [m]front_thickness: thickness of the front glass substrate in [m]back_thickness: thickness of the back glass substrate in [m]n:AbstractRefractiveIndexof both glass substrates
Keywords
cutoff_strength: passed toRoundPolarizationFilter
Additional information
The component is centered on the film (local origin); the front substrate extends from y = -front_thickness to y = 0, the back substrate from y = 0 to y = back_thickness, along local +y. The film transmits along local x and blocks local z.
BeamletOptics.RoundPlanoMirror Method
RoundPlanoMirror(diameter, thickness; hole_diameter=nothing)Constructs a round plano Mirror with a flat reflecting surface and perfect reflectivity (R = 1). The reflecting surface is modeled using a BeamletOptics.PlanoSurfaceSDF.
Arguments
diameter: mirror diameter [m]thickness: mirror substrate thickness [m]hole_diameter: diameter of the central through-hole [m], no hole ifnothing(default)
BeamletOptics.RoundPolarizationFilter Method
RoundPolarizationFilter(diameter; cutoff_strength)Spawns a thin, round PolarizationFilter with the given diameter in [m]. The filter is centered at the origin, aligned with the global y-axis and transmits along the x-axis, while blocking polarization components along the global z-axis.
BeamletOptics.RoundThinBeamsplitter Method
RoundThinBeamsplitter(diameter; reflectance=0.5)Creates a zero-thickness, 2D round ThinBeamsplitter with the specified diameter in [m]. For more information, refer to the ThinBeamsplitter constructor.
BeamletOptics.SphericalDoubletLens Method
SphericalDoubletLens(r1, r2, r3, l1, l2, d, n1, n2)Generates a two-component "cemented" doublet lens consisting of two spherical lenses. For radii sign definition, refer to the SphericalLens constructor.
Arguments
r1: radius of curvature for first surfacer2: radius of curvature for second (cemented) surfacer3: radius of curvature for third surfacel1: first lens thicknessl2: second lens thicknessd: lens diametern1: first lensAbstractRefractiveIndexn2: second lensAbstractRefractiveIndex
BeamletOptics.SphericalGaussianBeamletSource Method
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 AstigmaticGaussianBeamlets 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; the number of rings counts the center as the innermost one, i.e.num_rings - 1rings lie around it.num_rays: Total number of beamlets to generate.overlap: Scaling factor for the sub-waist divergence (default1.2ensures smooth overlap).basis: Optional reference vector (e.g.[1,0,0]) to define the starting azimuthal angle for the source rings.randomize_axes: Iftrue, 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 forrandomize_axes.P0: Total power of the spherical source in [W]. The beamlets overlap and add coherently in the far field; their fields are scaled such that the superposition carriesP0.E0: Optional Jones vector defining the polarization and phase of the spherical wave; its component transverse to each beamlet is used, its magnitude does not matter, the power isP0.
Reproducible sampling
If no basis is passed, the orthogonal basis vectors are derived from dir deterministically, so two sources sharing the same arguments sample exactly the same beamlet directions. Pass a basis to rotate the azimuthal sampling of a source about its own axis. A basis that is zero or parallel to dir throws.
BeamletOptics.SphericalLens Function
SphericalLens(r1, r2, l, d=1inch, n=ConstantRefractiveIndex(1.5))Creates a spherical Lens based on:
r1: front radiusr2: back radiusl: lens thicknessd: lens diameter, default is one inchn:AbstractRefractiveIndexof the lens material
Notes
Radius of curvature (ROC) sign
The ROC is defined to be positive if the center is to the right of the surface. Otherwise it is negative.
Thin lenses
If l is set to zero, a ThinLens will be created. However, note that the actual lens thickness will be different from zero.
BeamletOptics.SphericalMirror Method
SphericalMirror(radius, thickness, diameter; hole_diameter=nothing)Constructs a concave spherical Mirror with perfect reflectivity (R = 1). The reflecting surface is modeled as a BeamletOptics.UnionSDF of a concave spherical surface and a plano substrate, combining BeamletOptics.ConcaveSphericalSurfaceSDF and BeamletOptics.PlanoSurfaceSDF.
Arguments
radius: spherical surface radius of curvature [m]thickness: substrate thickness [m]diameter: mirror outer diameter [m]hole_diameter: diameter of the central through-hole [m], no hole ifnothing(default)
BeamletOptics.SphericalTripletLens Method
SphericalTripletLens(r1, r2, r3, r4, l1, l2, l3, d, n1, n2, n3)Generates a three-component "cemented" triplet lens consisting of three spherical lenses. The middle and back lens are translated along +y so that they sit flush. For radii sign definition, refer to the SphericalLens constructor.
Arguments
r1: radius of curvature for first surfacer2: radius of curvature for second (first cemented) surfacer3: radius of curvature for third (second cemented) surfacer4: radius of curvature for fourth surfacel1: first lens thicknessl2: second lens thicknessl3: third lens thicknessd: lens diametern1: first lensAbstractRefractiveIndexn2: second lensAbstractRefractiveIndexn3: third lensAbstractRefractiveIndex
Additional information
Inf gives a plano surface.
BeamletOptics.SquarePlanoMirror Method
SquarePlanoMirror(width, thickness)Constructs a square plano Mirror with equal width and height. The front reflecting surface is normal to the y-axis and lies at the origin. See also RectangularPlanoMirror.
Arguments
width: the side length of the square mirror in x- and y-direction [m]thickness: of the mirror in [m]
BeamletOptics.SquarePlanoMirror2D Method
SquarePlanoMirror2D(edge_length)Constructs a 2D square plano Mirror with a given edge_length. The reflecting surface is normal to the y-axis.
Arguments
edge_length: the edge length of the square mirror in [m]
BeamletOptics.ThinLens Method
ThinLens(R1::Real, R2::Real, d::Real, n::AbstractRefractiveIndex)Directly creates a bi-convex spherical thin Lens with the radii of curvature R1 and R2 of its convex front and back (both positive), the diameter d and the AbstractRefractiveIndex n. The two spherical caps are flush, i.e. the lens has no cylindrical section between them.
BeamletOptics.ThinLensSDF Method
ThinLensSDF(r1, r2, d=1inch)Constructs a bi-convex thin lens SDF-based shape with:
r1 > 0: radius of convex frontr2 > 0: radius of convex backd: lens diameter, default value is one inch
The spherical surfaces are constructed flush.
sourceBeamletOptics.UniformDiscSource Method
UniformDiscSource(pos, dir, diameter, λ; num_rays=1_000, basis)Generates a ray fan with equal area per ray across a circular pupil using the deterministic sunflower (Fibonacci) pattern.
The spiral starts with the center ray at pos (k = 0). The radius of the k-th ray (k = 1 … N-1) is ρₖ = diameter/2 ⋅ √((k + ½)/N), its azimuth is k times the golden angle π(3 - √5).
Note
This is merely a CollimatedSource constructor which uses Fibonacci sampling instead of concentric rings. All rays are equally weighted samples of the pupil: ray k represents the part of the disc between the radii diameter/2 ⋅ √(k/N) and diameter/2 ⋅ √((k + 1)/N). The center ray represents the innermost of these parts, a disc, by its center.
Arguments
The following inputs and arguments can be used to configure the underlying CollimatedSource:
Inputs
pos: center of the pupil disc, i.e. the source positiondir: starting direction of all beamsdiameter: outer beam bundle diameter in [m]λ = 1e-6: wavelength in [m]
Keyword Arguments
num_rays=1000: total number of rays in the source, must be≥ 1basis: Optional reference vector (e.g.[1,0,0]) to define the starting azimuthal angle of the sunflower pattern.
Reproducible sampling
If no basis is passed, the orthogonal basis vectors spanning the pupil plane are derived from dir deterministically, so two sources sharing the same dir, diameter and num_rays sample exactly the same ray positions. Pass a basis to rotate the sunflower pattern about its own axis, e.g. to interleave several otherwise identical sources.
BeamletOptics.UniformFanSource Method
UniformFanSource(pos, dir, θ, λ; num_rays=101, basis)Generates a plane fan of Beams emitted from pos, i.e. a two-dimensional point source: the rays lie in the plane spanned by dir and basis, with equidistant angles between -θ and θ to dir. This is useful for layout sketches and for tracing a single (e.g. meridional or sagittal) section of a system.
The first ray is the center ray along dir. It is followed by h = (N - 1) ÷ 2 rays on each side of it, which enclose the angles φⱼ = j/h ⋅ θ with dir for j = -h … h without j = 0 and point along cos φⱼ ⋅ dir + sin φⱼ ⋅ basis, i.e. from one marginal ray at the edge of the fan to the other. A single ray points along dir.
Use an odd number of rays
A pattern that is symmetric to its center ray has an odd number of rays. An even num_rays yields the pattern of num_rays - 1 rays and a second ray along dir.
Note
This is merely a PointSource constructor which samples one section of the cone instead of concentric rings.
Warning
The rays sample a plane angle, not a solid angle: they are not equal solid angle samples of a cone. For a point spread function or an intensity use UniformPointSource.
Arguments
The following inputs and arguments can be used to configure the underlying PointSource:
Inputs
pos: starting position of all beamsdir: central source direction, i.e. the axis of the fanθ: half spread angle in rad, must be< πλ = 1e-6: wavelength in [m], default val. is 1000 nm
Keyword Arguments
num_rays=101: total number of rays in the source, must be≥ 1basis: direction (e.g.[1,0,0]) that spans the plane of the fan together withdir, projected into the plane normal todir. Rays with a positive angle are tilted towards it. Must not be zero or parallel todir.
Orientation of the fan
If no basis is passed, the plane of the fan is derived from dir deterministically via normal3d, which is rarely the section of interest: pass a basis to choose the plane of the rays. The fan can also be turned about dir afterwards with rotate3d!.
BeamletOptics.UniformLineSource Method
UniformLineSource(pos, dir, width, λ; num_rays=101, basis)Generates a plane sheet of parallel Beams, i.e. a two-dimensional collimated source: the rays start equidistantly on a line of the length width centered at pos and travel along dir. The line lies along basis, such that all rays lie in the plane spanned by dir and basis. This is useful for layout sketches and for tracing a single (e.g. meridional or sagittal) section of a system.
The first ray is the center ray at pos. It is followed by h = (N - 1) ÷ 2 rays on each side of it, at pos + j/h ⋅ width/2 ⋅ basis for j = -h … h without j = 0, i.e. from one marginal ray at the end of the line to the other. A single ray starts at pos.
Use an odd number of rays
A pattern that is symmetric to its center ray has an odd number of rays. An even num_rays yields the pattern of num_rays - 1 rays and a second ray at pos.
Note
This is merely a CollimatedSource constructor which samples one diameter of the disc instead of concentric rings. width is stored as the diameter of the source.
Warning
The rays sample a line, not an area: they are not equal-area samples of a circular pupil. For a point spread function or an intensity use UniformDiscSource.
Arguments
The following inputs and arguments can be used to configure the underlying CollimatedSource:
Inputs
pos: center of the line, i.e. the source positiondir: starting direction of all beamswidth: length of the line in [m], i.e. the distance between the marginal raysλ = 1e-6: wavelength in [m]
Keyword Arguments
num_rays=101: total number of rays in the source, must be≥ 1basis: direction of the line (e.g.[1,0,0]), projected into the plane normal todir. Must not be zero or parallel todir.
Orientation of the line
If no basis is passed, the direction of the line is derived from dir deterministically via normal3d, which is rarely the section of interest: pass a basis to choose the plane of the rays. The line can also be turned about dir afterwards with rotate3d!.
BeamletOptics.UniformPointSource Method
UniformPointSource(pos, dir, θ, λ; num_rays=1_000, basis)Generates a cone of Beams emitted from pos with equal solid angle per ray across the spherical cap 0 ≤ ϑ ≤ θ around dir, using the deterministic sunflower (Fibonacci) pattern. The spiral starts with the center ray along dir (k = 0). The polar angle ϑₖ of the k-th ray (k = 1 … N-1) follows from cos ϑₖ = 1 - (k + ½)/N ⋅ (1 - cos θ), its azimuth is k times the golden angle π(3 - √5).
Note
This is merely a PointSource constructor which uses Fibonacci sampling instead of concentric rings. All rays are equally weighted samples of the cap: ray k represents the part of the cap with 1 - (k + 1)/N ⋅ (1 - cos θ) ≤ cos ϑ ≤ 1 - k/N ⋅ (1 - cos θ). The center ray represents the innermost of these parts, a cap, by its center.
Arguments
The following inputs and arguments can be used to configure the underlying PointSource:
Inputs
pos: starting position of all beamsdir: central source direction, i.e. the cone axisθ: half spread angle in rad, must be< πλ = 1e-6: wavelength in [m], default val. is 1000 nm
Keyword Arguments
num_rays=1000: total number of rays in the source, must be≥ 1basis: Optional reference vector (e.g.[1,0,0]) to define the starting azimuthal angle of the sunflower pattern. Must not be zero or parallel todir.
Reproducible sampling
If no basis is passed, the orthogonal basis vectors are derived from dir deterministically, so two sources sharing the same dir, θ and num_rays sample exactly the same ray directions. Pass a basis to rotate the sunflower pattern about its own axis, e.g. to interleave several otherwise identical sources.
BeamletOptics.WavefrontBeamletDecomposition Method
WavefrontBeamletDecomposition(x, y, Eu, Ev, pos, dir, λ; threshold=1e-4)Vector-field counterpart of WavefrontBeamletDecomposition(x, y, amplitude, phase, pos, dir, λ): decomposes a transverse complex vector field, given as its two components Eu, Ev along the sampling axes e1, e2 (basis, default e1 = normal3d(dir), e2 = dir × e1), into a collection of AstigmaticGaussianBeamlets.
Unlike the scalar method (one amplitude/phase pair plus a single macroscopic polarization E0), this method carries an independent complex amplitude per polarization component and grid point, i.e. an arbitrary, spatially varying polarization state (including elliptical and depolarizing-looking patterns coming from separate Eu, Ev measurements).
Arguments
x,y: 1D spatial coordinates of the field grid, alonge1,e2, relative topos, in [m].Eu,Ev:length(x) × length(y)complex matrices, the field components alonge1,e2in [V/m] (peak amplitude). Both must have the full spatial phase.pos: global position of the samplex = y = 0in [m], the center of the group.dir: macroscopic reference propagation direction (e.g.[0, 1, 0]).λ: wavelength in [m].threshold: relative amplitude (ofhypot.(abs.(Eu), abs.(Ev))) below which no beamlet is spawned.overlap,basis,randomize_axes,rng: as in the scalar method.R: radius in [m] of a reference sphere that has been removed fromEu,Ev: the physical field isE .* cis(sign(R) k (√(x² + y² + R²) − |R|))withk = 2π/λ(R > 0: diverging from the point at the distanceRbehindx = y = 0,R < 0: converging to the point|R|in front of it). DefaultInf:Eu,Evare the physical field. The sphere enters analytically, so the grid only has to resolve the phase ofEu,Ev, not that of the sphere: every beamlet travels along the ray of the sphere through its sample (plus the gradient of the sampled phase) and starts with the wavefront curvature of the sphere.
Throws an ArgumentError for a field that is zero everywhere and for R = 0.
Sampling
The phase step between neighboring samples must stay below π: a field tilted by θ against dir needs dx < λ / (2 sin θ), while the beamlets (waist overlap * dx) must stay much larger than λ. Keep the sampling plane close to normal to the beam. Both components must share one local wavevector at each sample.
BeamletOptics.WavefrontBeamletDecomposition Method
WavefrontBeamletDecomposition(x, y, amplitude, phase, pos, 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 AstigmaticGaussianBeamlets.
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.
The grid lies in the plane normal to dir through pos, the position of the sample x = y = 0 and the center of the group.
Arguments
x,y: Vectors defining the 1D spatial coordinates of the 2D field grid, relative topos.amplitude: 2D array of field amplitudes(length(x) × length(y)).phase: 2D array of phase values in radians.pos: global position of the samplex = y = 0in [m].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 (default1.2ensures smooth overlap).basis: Optional tuple(ex, ey)of the macroscopic sampling grid axes, i.e. the 3D directions corresponding to thexandyinput axes.exmust not be zero or parallel todir; its component normal todirbecomes the local x-axis of the grouporientation.randomize_axes: Iftrue, 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 forrandomize_axes.E0: Optional reference polarization vector or Jones vector. Ifnothing, defaults to linear polarization along the first grid axis.
Sampling
The phase step between neighboring samples must stay below π: a field tilted by θ against dir needs dx < λ / (2 sin θ), while the beamlets (waist overlap * dx) must stay much larger than λ. Keep the sampling plane close to normal to the beam.
BeamletOptics._beams_hits_same_shape Method
_beams_hits_same_shape(agb, id)Tests if all 9 component rays at section id hit the same object shape.
BeamletOptics._beams_hits_same_shape Method
_beams_hits_same_shape(gauss, id)Tests if all rays at section id of gauss hit the same object shape. Returns true or false.
BeamletOptics._calculate_global_E0 Method
_calculate_global_E0(in_dir, out_dir, normal, J)Calculates the resulting polarization matrix as per the publication by Yun et al. for each surface interaction. If the normal- vector and the in- and out-directions of propagation are in parallel, an arbitrary basis is chosen for the s- and p-components.
Arguments
in_dir: propagation direction before surface interactionout_dir: propagation direction after surface interactionnormal: surface normal at the point of intersectionJ: Jones matrix extended to 3x3, e.g. [-rₛ 0 0; 0 rₚ 0; 0 0 1] for reflection
BeamletOptics._claim_shapes! Method
_claim_shapes!(owner::IdDict, x, part)Records part as the owner of every shape below x and throws an ArgumentError if a shape already belongs to another part, or if x or a value below it is static.
BeamletOptics._component_beams Method
Return a tuple of all 9 component beams of the AstigmaticGaussianBeamlet.
BeamletOptics._component_beams Method
_component_beams(beam::AbstractBeam)Returns a tuple of the beams that store the rays of beam, chief beam first: (beam,) for a beam that stores its rays itself (e.g. Beam), the component beams of a composite beam (e.g. a GaussianBeamlet). The generic beam methods, including the kinematic API, are built on it.
BeamletOptics._component_beams Method
Return a tuple of the chief, waist and divergence beams of the GaussianBeamlet.
BeamletOptics._container_trait Method
_container_trait(members)
_container_trait(trait::AbstractKinematicTrait)Returns the kinematic trait of a container with homogeneous members (see check_kinematic_members), or of a container whose members have the trait trait: Static() for static members, else Movable(Oriented()). An empty container is movable.
BeamletOptics._film_interface Method
_film_interface(system, lp::LinearPolarizer, from, to, beam, ray::PolarizedRay)Handles the cemented from → to glass interface for a PolarizedRay. The polarizing film acts on the incident field (still expressed in from) before the ray crosses into to. In case of total internal reflection at the cemented interface, the ray is reflected back into from and the film is not applied.
BeamletOptics._film_interface Method
_film_interface(system, lp::LinearPolarizer, from, to, beam, ray::Ray)Handles the cemented from → to glass interface for an unpolarized Ray: the film has no effect, only glass-to-glass refraction (with total internal reflection handling) occurs.
BeamletOptics._flat_size Method
_flat_size(s::AbstractShape) -> Vector{Pair{String, Any}}Returns "Size [m]", the extent of the flat mesh s along its local x and z axes, i.e. the width and height of e.g. a Detector, or nothing for other shapes. Linear in the number of vertices, hence only used for flat components.
BeamletOptics._gouy_before Method
_gouy_before(gauss::GaussianBeamlet, index)Gouy phase collected in front of segment index, parents included.
BeamletOptics._group_orientation Method
_group_orientation(dir, e1, T) -> SMatrix{3,3,T,9}Returns the orientation matrix of a beam group with the columns (e1, dir, e1 × dir), i.e. local x = sampling reference vector e1, local y = optical axis dir. Both inputs are normalized, e1 must be normal to dir.
BeamletOptics._index_properties Method
Returns the refractive index model n (see AbstractRefractiveIndex) and its value at the default wavelength λ₀, see get_default_wavelength.
BeamletOptics._is_film_interface Method
_is_film_interface(lp::LinearPolarizer, from, ray::AbstractRay)::BoolTests whether ray, having just crossed a prism (from is lp.front or lp.back), is exiting through the flat inner face that is cemented to the polarizing film (as opposed to exiting the outer face or the cylindrical edge close to the film).
BeamletOptics._is_leaf_of Method
Returns true if object is one of the leaves, compared by identity.
BeamletOptics._leaf_objects Method
_leaf_objects(tree)Iterates the objects at all depths of tree, an object, an object group or a collection of them. Leaves(tree) without the nodes that have no children but are no objects, i.e. empty groups and an empty collection.
BeamletOptics._movable_parts Method
_movable_parts(parts) -> VectorReturns the parts of one rigid motion in their order, each once, compared by identity (===). Throws an ArgumentError before anything moves if a part, or an object or shape below it, is static, or if two different parts reach the same shape, which would then move twice. The shapes are collected recursively via shape(object), down to the operands of composite SDFs.
BeamletOptics._move_rigidly! Method
_move_rigidly!(frames, parts, offset)
_move_rigidly!(frames, parts, R::AbstractMatrix, pivot::AbstractVector)Moves a container by offset, or rotates it by R about pivot: first the pose of every frame, then every part with the public translate3d! or rotate3d!. The caller passes each part once.
BeamletOptics._path_segments! Method
_path_segments!(segments, beam, beam_index, flen, parent = 0, depth = 1, s = 0, opl = 0)Appends the segments of beam and, recursively, of its children to segments, see path_segments. parent is the index of the segment the beam continues from, and s, opl are the geometric and optical path length accumulated there.
BeamletOptics._pseudo_cross2d Method
_pseudo_cross2d(a, b, c)Calculates the triple product (a × b) ⋅ c using a non-conjugating dot product.
BeamletOptics._pseudo_dot Method
_pseudo_dot(a, b)Calculates the non-conjugating dot product a ⋅ b = Σ aᵢbᵢ.
BeamletOptics._ray_to_plane_projection Method
_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.
BeamletOptics._report! Method
_report!(output::IO, p::_LazyProgress)
_report!(s::ProgressSink, p::_LazyProgress)Report a tick of p. To an IO, the bar is drawn lazily (threshold and redraw interval of p). To a sink nothing is drawn; if the sink is cancelled, _ProgressCancelled is thrown.
BeamletOptics._signed_edge_sag Method
_signed_edge_sag(surface, sd)Returns the edge sagitta of the surface with sign, such that the edge of a front surface lies at y = s and the edge of a back surface at y = center_thickness + s. edge_sag returns the unsigned sagitta for spherical and cylindrical surfaces, hence the sign of the radius is applied; the sagitta of aspherical and acylindrical surfaces is already signed.
BeamletOptics._sphere_exit Function
_sphere_exit(sphere::AbstractBoundingSphere, ray, margin = 0)Returns the path length in [m] at which the ray leaves the sphere, or nothing if the ray does not pass through it, i.e. if its line misses the sphere or the sphere lies behind its start. The radius is enlarged by the margin in [m] and by the rounding error of the test, such that a ray towards a point on the sphere still passes through it.
BeamletOptics._splitting_ratio Method
Returns the power "Reflectance" R and "Transmittance" T of the coating, which stores the amplitude factors √R and √T, i.e. R as passed to the constructors of the beamsplitters.
BeamletOptics._tick! Method
_tick!(p::_LazyProgress)Count one finished item and report it to the output of p, see _report!. Safe to call from any thread. Throws _ProgressCancelled if p reports to a cancelled ProgressSink.
BeamletOptics._transverse Method
_transverse(E0, dir)Removes the component of the field E0 along dir.
BeamletOptics._with_progress Method
_with_progress(f, p::_LazyProgress)
_with_progress(f, progress::Bool, n, desc)Run f(p), which calls _tick!(p) once per finished item, and return its result. Afterwards the bar is completed. If f throws, e.g. an InterruptException from Ctrl-C, the bar is cancelled before the exception is rethrown, so no half-drawn bar is left behind. In both cases later ticks draw nothing.
If p reports to a ProgressSink, p is the sink's current loop while f runs; the previous loop is restored afterwards, also if f throws, so nested loops show the inner loop while it runs.
BeamletOptics._world_to_sdf Method
_world_to_sdf(sdf, point)Transforms the coordinates of point into a reference frame where the sdf lies at the origin. Useful to represent translation and rotation. If rotations are applied, the rotation is applied around the local sdf coordinate system.
BeamletOptics.align3d! Method
align3d!(x, target)Rotates x about its position such that its direction is aligned with target. The rotation is the shortest one, so for BeamletOptics.Oriented values the twist about the new direction depends on the previous orientation. See BeamletOptics.Movable.
BeamletOptics.align3d Method
align3d(start::AbstractVector, target::AbstractVector)Returns the rotation matrix R that will align the start vector to be parallel to the target vector. Based on 'Avoiding Trigonometry' by Íñigo Quílez. The resulting matrix was transposed due to column/row major issues. Vector length is maintained. This function is very fast.
R is the rotation about the axis normal to both vectors (the smallest rotation). It is exact and orthonormal for all angles, including angles of a few nrad (alignment of optics) and angles close to π. For antiparallel vectors, R is a rotation by π about an axis normal to start.
For an obtuse angle, the closed form loses orthonormality close to π (error ~eps/(π - A)), so R is composed of a rotation by π and one by the remaining acute angle, both about the same normal axis. The closed form is the Rodrigues form, whose diagonal avoids rᵢ² k + cosA, because the rounding of cosA would scale R by 1 ± eps, also for parallel vectors, where R must be the identity.
BeamletOptics.angle3d Function
angle3d(ray::AbstractRay, intersect::Intersection=intersection(ray))Calculates the angle between a ray and its or some other intersection.
BeamletOptics.angle3d Method
angle3d(target::AbstractArray, start::AbstractArray, reference::AbstractArray)Returns the angle between the target and start vector in rad. In addition, a reference axis must be specified. This axis is used in order to determine the angle sign of rotation according to the right hand rule.
BeamletOptics.angle3d Method
angle3d(target::AbstractVector, start::AbstractVector)Returns the angle between the target and start vector in rad.
BeamletOptics.append_hits! Method
append_hits!(head::Intersection, other::Intersection, tol)Appends the hits of the chain other that lie within tol of the first hit of head to the chain of head, which stays the first hit. A hit of a shape that the chain holds already is dropped. A hit without a shape (the shape of an Intersection is optional) is always kept.
BeamletOptics.area_arg Method
Continuous argument of the complex beam area at local distance l on segment i, from the root start.
BeamletOptics.arrow! Method
arrow!(ax, pos, dir; scale=1, kwargs...)Draws a single 3D arrow from pos pointing along dir into ax, if a suitable backend is loaded. The arrow spans 5e-3 * scale * dir in world units [m], so a unit dir gives a 5 mm arrow that is legible next to CAD geometry. ax must be an LScene, any other Makie axis throws an InvalidAxisError. If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.aspheric_edge Method
aspheric_edge(c, k, α_coeffs, d)Returns the sag of the asphere at its edge r = d/2 and the norm of the gradient of its 2D distance field there, as a Point2. Both are constant for a surface, hence the SDFs store them instead of evaluating the asphere at the edge for every distance.
BeamletOptics.aspheric_equation Method
aspheric_equation(r, c, k, α_coeffs)
The aspheric surface equation. The asphere is defined by:
c: The curvature (1/radius) of the surfacek: The conic constant of the surfaceα_coeffs: The (even) aspheric coefficients of the termsΣᵢ αᵢ r²ⁱ, starting with A2 (r²).
This function returns NaN if the square root argument becomes negative.
Note
Only even aspheres are implemented at the moment. This will change soon.
sourceBeamletOptics.axial_extent Method
axial_extent(s::Union{AbstractAsphericalSurfaceSDF, AbstractAcylindricalSurfaceSDF})Returns (lo, hi), the smallest and largest local y-coordinate of the surface of s over its aperture. The candidates are the vertex, the edge and the stationary point of the sag (max_sag), which is exact for profiles with at most one stationary point within the aperture.
BeamletOptics.axial_extent Method
axial_extent(s::ConicSDF)Returns (lo, hi), the smallest and largest local y-coordinate of the surface of s over its aperture. The back side at thickness is not included. The range contains 0, since the origin lies on the surface.
BeamletOptics.base_transform Function
base_transform(base, base2=I(3))Return the base transformation matrix for transforming from vectors given relative to base2 into base.
BeamletOptics.bounding_box Method
bounding_box(sphere::AbstractBoundingSphere)Returns the limits (xmin, xmax, ymin, ymax, zmin, zmax) of the axis-aligned box around the sphere.
BeamletOptics.bounding_box Method
bounding_box(s::AbstractSDF)Returns the limits (xmin, xmax, ymin, ymax, zmin, zmax) of an axis-aligned box around s in world coordinates, e.g. for the sampling grid of the rendering. The SDF is probed from ±1000 m along the axes, which gives the extent of the shape if the SDF is exact outside of it. A type whose SDF is not exact far away returns the box around its bounding_sphere_of instead.
BeamletOptics.bounding_sphere_of Method
bounding_sphere_of(shape::AbstractShape)
bounding_sphere_of(object::AbstractObject)
bounding_sphere_of(group::AbstractObjectGroup)Computes a sphere that encloses the shape, object or group in its current pose and returns it as a SingleBoundingSphere or MultiBoundingSphere, or returns NoBoundingSphere() if there is none.
For a shape, the method is an optional part of the AbstractShape interface. With the default NoBoundingSphere() every ray is tested via intersect3d. With a sphere, a solve tests a ray against the sphere first and skips the shape if it misses, which pays off for shapes with a costly intersect3d. The sphere is computed once per solve_system! and not stored in the shape, hence the method may take some time, e.g. look at all vertices of a mesh. The table holds spheres of floating-point shapes only: for other number types, e.g. dual numbers under ForwardDiff, the shape is tested without a sphere.
The sphere must enclose every point of the shape, for all its parameters: a hit outside of the sphere is lost without a warning. It should also be tight, since a ray that hits the sphere is tested as before. A safety margin is not needed, the solver adds its own tolerance. Draw the result with render!(ax, sphere) to look at it.
# a cylinder of the radius `r` and the height `h`, with the origin at the center of its base
function BeamletOptics.bounding_sphere_of(c::MyCylinder)
return BeamletOptics.SingleBoundingSphere(c, Point3(0, c.h / 2, 0), sqrt(c.r^2 + (c.h / 2)^2))
endFor an object, the result follows from its shapes, see AbstractShapeTrait: the sphere of the shape of a SingleShape object, and for a MultiShape object or an object group the MultiBoundingSphere that encloses the spheres of all its parts, or NoBoundingSphere() if one part has none. The solver skips an object whose sphere the ray misses or enters only beyond a hit found already, also if the object has an intersect3d method of its own. Hence the sphere of an object must enclose every hit of its intersect3d. A SingleShape object whose own intersect3d hits points outside of its shape, e.g. an unbounded plane, returns NoBoundingSphere(); the sphere of a MultiShape object is always the one around its parts, hence its own intersect3d must hit its parts only:
BeamletOptics.bounding_sphere_of(::MyPlane) = BeamletOptics.NoBoundingSphere()BeamletOptics.bounding_sphere_of Method
bounding_sphere_of(d::DifferenceSDF)Returns the bounding_sphere_of of d.base in its current pose: the result of a subtraction is always a subset of the base, so the bounding sphere of the base (or NoBoundingSphere(), if it has none) also bounds d.
BeamletOptics.bounding_sphere_of Method
bounding_sphere_of(ml::MeniscusLensSDF)Returns the sphere that encloses the bounding spheres of the convex and the cylindrical part, which are positioned in the local frame of the lens; the concave part only removes volume.
sourceBeamletOptics.bounding_sphere_of Method
bounding_sphere_of(u::UnionSDF)Returns the sphere that encloses the bounding spheres of all operands in their current poses, or NoBoundingSphere() if one of the operands has none.
BeamletOptics.bounding_sphere_of Method
bounding_sphere_of(table::BoundingSphereTable, x)
bounding_sphere_of(::Nothing, x)Returns the sphere that the table holds for x, or NoBoundingSphere() if there is none. Nothing is computed.
BeamletOptics.bounding_sphere_of Method
bounding_sphere_of(s::AbstractAcylindricalSurfaceSDF)Returns the sphere through the corners of the box around the surface volume: the cylinder height along x, the axial extent of the sag along y and the diameter along z.
sourceBeamletOptics.bounding_sphere_of Method
bounding_sphere_of(s::AbstractAsphericalSurfaceSDF)Returns the sphere around the cylinder of the lens diameter that spans the axial extent of the surface volume, centered on the axis.
sourceBeamletOptics.bounding_sphere_of Method
bounding_sphere_of(mesh::AbstractMesh)Returns the sphere around the center of the axis-aligned box of the vertices that passes through the farthest vertex. All vertices are read, i.e. the cost grows with the size of the mesh.
sourceBeamletOptics.bounding_sphere_of Method
bounding_sphere_of(box::BoxSDF)Returns the sphere through the eight corners of the box, centered at the local origin.
sourceBeamletOptics.bounding_sphere_of Method
bounding_sphere_of(s::ConcaveCylinderSDF)Returns the sphere through the eight corners of the box that the cylinder is cut out of, which extends from y = 0 to the sagitta, on the side given by the sign of the radius.
BeamletOptics.bounding_sphere_of Method
bounding_sphere_of(css::ConcaveSphericalSurfaceSDF)Returns the sphere through both rims of the surface, which lie at y = 0 and y = -sag, centered on the axis in between.
BeamletOptics.bounding_sphere_of Method
bounding_sphere_of(s::ConicSDF)Returns the sphere around the cylinder of the segment diameter that extends from the lowest point of the reflecting surface to the back side at y = thickness, centered on the local y-axis.
BeamletOptics.bounding_sphere_of Method
bounding_sphere_of(s::ConvexCylinderSDF)Returns the sphere through the four corners of the flat side, centered in that side. In the local frame the cylinder axis is the x-axis and the flat side is normal to the z-axis.
sourceBeamletOptics.bounding_sphere_of Method
bounding_sphere_of(css::ConvexSphericalSurfaceSDF)Returns the smallest sphere around the spherical cap, which extends from its vertex at the local origin to its flat side at y = sag: the sphere through the rim, centered in the plane of the rim.
BeamletOptics.bounding_sphere_of Method
bounding_sphere_of(cs::CutSphereSDF)Returns the smallest sphere around the spherical cap y ≥ height: the sphere through the rim, centered in the cut plane, for a cap of at most a hemisphere (height ≥ 0), and the full sphere otherwise.
BeamletOptics.bounding_sphere_of Method
bounding_sphere_of(cylinder::CylinderSDF)Returns the sphere through both rims of the cylinder, centered at the local origin. Note that the height field stores half of the cylinder height.
BeamletOptics.bounding_sphere_of Method
bounding_sphere_of(ps::PlanoSurfaceSDF)Returns the sphere through both rims of the cylinder, centered on the axis at half of the thickness.
sourceBeamletOptics.bounding_sphere_of Method
bounding_sphere_of(prism::PolygonPrismSDF)Returns the sphere around the prism over a circle that encloses the cross-section (the smaller one of the circles around the mean of the vertices and around the center of their bounding box), centered in the local plane z = 0. It passes through at least two corners of the prism.
BeamletOptics.bounding_sphere_of Method
bounding_sphere_of(prism::RightAnglePrismSDF)Returns the sphere through the four corners of the hypotenuse face, centered at the local origin, which is the center of that face.
sourceBeamletOptics.bounding_sphere_of Method
bounding_sphere_of(ring::RingSDF)Returns the sphere through both outer rims of the ring, centered at the local origin. Note that the inner_radius field stores the mean radius of the ring.
BeamletOptics.bounding_sphere_of Method
bounding_sphere_of(sphere::SphereSDF)Returns the sphere itself.
sourceBeamletOptics.bounding_spheres Method
bounding_spheres(system::AbstractSystem) -> BoundingSphereTableComputes the bounding spheres of all objects of the system in their current poses. The spheres are stored as Float64, with the radius enlarged by the rounding error of the shape's number type.
BeamletOptics.calc_center_point Method
calc_center_point(::AbstractCenterAlgorithm, xs::Vector{T}, zs::Vector{T}, projection_factor::Vector{T}) where TCalculates a central 2D point based on a distribution of points, specified by xs and zs. The algorithm can be selected by specifying a concrete AbstractCenterAlgorithm. In addition, projection factors for each hit point can be passed.
Returns (x0, z0).
BeamletOptics.calc_local_lims Method
calc_local_lims(pd::Detector)Calculates the limiting values for the flat E-field evaluation grid based on the detector data, with the default crop_factor of the hit type.
BeamletOptics.calc_local_lims Method
calc_local_lims(pd::Detector, hits::Vector{<:AbstractBeamletHit}, crop_factor; center=Centroid())Computes a 2D bounding box around the circular or elliptical waist of GaussianBeamlet hits. Assumes that the beamlet is approximately cylindrical around its optical axis at the point of intersection. The box reaches crop_factor beam radii beyond each hit point, divided by the cos θ of the angle of incidence, which stretches the footprint of the beam on the detector. nothing selects the default crop_factor of 3.
The center keyword is ignored and only accepted so that all hit types share one signature.
BeamletOptics.calc_local_lims Method
calc_local_lims(pd::Detector, hits::Vector{<:AbstractRayHit}, crop_factor; center=Centroid())Compute a symmetric [x_min,x_max]×[z_min,z_max] box around the hit positions weighted centroid for ray-based spot diagrams.
• If center==Centroid() (the default), uses x0 = ∑ wᵢ·xᵢ / ∑ wᵢ, z0 = ∑ wᵢ·yᵢ / ∑ wᵢ with wᵢ = projection_factor. • If center==MinMax(), falls back to the midpoint of [min,max].
crop_factor scales the half-widths of the box, nothing selects the default of 1.
Returns (x_min, x_max, z_min, z_max).
BeamletOptics.calc_local_lims Method
calc_local_lims(pd::Detector, ::Nothing, crop_factor; center=Centroid())The window of a Detector without hits: the bounding box of its active surface in local coordinates. crop_factor and center are ignored, since there are no hits to scale or center on.
BeamletOptics.calc_local_pos Method
calc_local_pos(pd::Detector; kwargs...)Calculates the hit position of all registered hits in local detector coordinates.
sourceBeamletOptics.calc_local_pos Method
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 on the Detector.
BeamletOptics.calc_local_pos Method
calc_local_pos(pd::Detector, hits::Vector{GaussianBeamletHit}; crop_factor=1, num_spots=50)Calculates a projected circle or ellipse of 2D hit spots for each hit of a GaussianBeamlet on the Detector. The spot coordinates are returned in a left-handed (x, z) coordinate system where the detector surface normal points towards the incoming beamlets.
Keyword arguments
crop_factor=1: scales the beam waist radius used to determine the bounding boxnum_spots=50: determines the number of 2D hits used to determine the bounding circle/ellipse
BeamletOptics.check_half_angle Method
check_half_angle(θ) -> θReturns the half spread angle θ [rad] of a cone sampling, or throws an ArgumentError unless θ < π in the precision of θ.
BeamletOptics.check_kinematic_members Method
check_kinematic_members(members)Throws an ArgumentError if some members of a container are Static and some are Movable. Empty collections pass. The constructor of an own AbstractObjectGroup calls it on its objects.
BeamletOptics.check_lagrange_invariants Method
check_lagrange_invariants(beam, i)Compares the lagrange_invariants of the beamlet beam at segment i with their values at the start of the root beam. If one deviates by more than the share get_lagrange_tolerance() of its start value, for any M2 and λ, the beamlet has left the range of its model: warns and returns false, otherwise returns true.
BeamletOptics.check_num_rays Method
check_num_rays(sampling, num_rays)Throws an ArgumentError if num_rays is below min_num_rays(sampling).
BeamletOptics.check_optical_invariant Method
check_optical_invariant(agb, i; threshold = get_invariant_threshold())Evaluate the complex optical invariant h1 . u2 - h2 . u1 = 0 at segment i and the lagrange_invariants against their values at the start of the root beam with check_lagrange_invariants, as for a GaussianBeamlet. threshold is the limit of the complex invariant only. Returns true if the invariants hold, and false otherwise.
BeamletOptics.check_orientation Method
check_orientation(M, T) -> SMatrix{3,3,T,9}Validates that M is a right-handed orthonormal 3x3 matrix, i.e. MᵀM ≈ I and det M ≈ 1 within √eps(T), and converts it into an SMatrix{3,3,T,9}. Throws an ArgumentError otherwise.
BeamletOptics.children! Method
children!(beam::B, child::B) where {B<:AbstractBeam}
children!(beam::B, children::AbstractVector{B}) where {B<:AbstractBeam}Attaches the child or the children to beam and links beam as their parent, e.g. the transmitted and the reflected beam at a beamsplitter. The children continue beam: its length, optical path and reference plane are counted on, see relaunch! for beams that start their own reference.
A beam is split once, at its end: a beam that already has children throws an ArgumentError.
BeamletOptics.closest_hits Method
closest_hits(parts, ray, result, skip)
closest_hits(group::AbstractObjectGroup, ray, result, skip)
closest_hits(object::AbstractObject, ray, result, skip)Merges the hits of the ray with the parts (objects and groups) into the hits result (or nothing), see merge_hits, and returns them. The object skip (or nothing) is not tested, since result holds its hits already. Once a hit is found, a part whose bounding sphere the ray enters only beyond it, see isbeyond, is not tested either. A group whose sphere the ray misses is skipped as a whole, else its objects are tested one by one, hence both rules apply to them as well. An object without a hit so far is tested by intersect3d, which tests its sphere itself.
BeamletOptics.closest_operand Method
closest_operand(u::UnionSDF, ds, pos; ρ = 1e-6)Returns the index of the operand of u closest to pos, for its SDF values ds at pos; ties go to the operand closest at probes ρ [m] outside.
BeamletOptics.coincident_hits Method
coincident_hits(intersection::Intersection)Iterates over the hits of a ray at the same point: the intersection itself, followed by the other surfaces that the ray hits within get_coincidence_tolerance(), e.g. the touching faces of a cemented doublet. Each hit is an Intersection with its own object, shape and normal. A ray that hits a single surface has a single hit.
BeamletOptics.cone_beamlets Method
cone_beamlets(pos, dir, dirs, λ, w0s, P0, E0, randomize_axes, rng, T)The beamlets of a cone source at pos of the total power P0: a central beamlet along dir and one along each of dirs, of the waist w0s, normalized for their coherent superposition in the far field.
BeamletOptics.cone_ring_directions Method
cone_ring_directions(dir, b1, θ, num_rings, num_rays) -> VectorThe num_rays directions on the cones around the unit vector dir of a ring sampling with the half spread angle θ [rad], without the center: num_rings - 1 cones, the outermost at θ, each starting at the azimuth of b1. The rays per cone follow rays_per_ring. The angles are computed in the precision of dir and θ.
BeamletOptics.convex_aspheric_surface_distance Function
convex_aspheric_surface_distance(r, z, c, k, d, α_coeffs, max_sag, edge)Calculates the 2D distance field for an aspheric surface at radius r away from the optical axis position z. The asphere is defined by:
c: The curvature (1/radius) of the surfacek: The conic constant of the surfaced: The diameter of the asphereα_coeffs: The (even) aspheric coefficients, starting with A2.max_sag: the extremal sag and its radius, seemax_aspheric_valueedge: the sag and the gradient norm at the edge, seeaspheric_edge
Note that this is not just an infinite aspheric surface and also not a surface segment but a closed 2D perimeter.
It is intended to pair the SDF derived from this distance field with a cylinder SDF to build a real lens.
sourceBeamletOptics.cos_angle3d Method
cos_angle3d(target::AbstractArray, start::AbstractArray)Returns the cosine of angle3d(target, start), without the acos: differentiable also for parallel vectors, e.g. at normal incidence, where the derivative of the angle is not defined.
BeamletOptics.countlines_in_dir Function
countlines_in_dir(dir, ext=[".jl", ".md"])Counts the number of lines and files of all files in dir that have the specified file extension.
BeamletOptics.current_bounding_spheres Method
current_bounding_spheres() -> Union{Nothing, BoundingSphereTable}Returns the table of the solve that is running in the current task, or nothing outside of a solve.
BeamletOptics.default_properties Method
default_properties(x) -> Vector{Pair{String, Any}}Returns the properties that properties lists for any object, shape, beam, source or object group x, see its conventions:
"Type": the name of the type ofxdepending on the
BeamletOptics.AbstractKinematicTraitofx:"Position [m]"and"Optical axis"(local +y axis) for oriented objects,"Position [m]"and"Direction"for directed ones (beams), only"Position [m]"for static objectsfor an
AbstractObject, depending on itsBeamletOptics.AbstractShapeTrait: thepropertiesof its shape ("Shape"and the stored dimensions, e.g."Diameter [m]") or the number of its"Parts"for an object group: the number of its objects as
"Parts"
Methods of properties for specific types start from this list, see properties.
BeamletOptics.direction Method
direction(x)Returns the direction of x. For BeamletOptics.Oriented values this is the local y-axis, i.e. orientation(x)[:, 2]; rays and beams return their own direction.
BeamletOptics.direction Method
direction(ray::AbstractRay)Returns the direction vector of the ray.
BeamletOptics.edge_sag Method
Returns the sagitta of the surface at it edge, i.e. at diameter(s)
BeamletOptics.eikonal_direction Function
eikonal_direction(Δφ, i, j, nx, ny, dx, dy, k, e1, e2, dir_n, ∇φ0 = (0, 0))Local propagation direction at the grid index (i, j) from the phase steps Δφ(a, b) between neighbors plus the known gradient ∇φ0, or nothing if it is grazing, evanescent or NaN.
BeamletOptics.electric_field Function
electric_field(I::Real, Z=Z_vacuum, ϕ=0)Calculates the E-field phasor in [V/m] for a given intensity I and phase ϕ. Vacuum wave impedance is assumed.
BeamletOptics.electric_field Function
electric_field(pd::Detector, sampling::AbstractDetectorSampling = RegularGrid(); progress = true)Samples the electric field of the hits of the Detector pd at the points of sampling in its local (x, z) plane, by default a RegularGrid 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,
with the position p_d of the detector and its local axes x̂, ẑ, which form a left-handed system with the detector normal. Eⱼ is defined per hit type in electric_field(::BeamletOptics.AbstractDetectorHit, ::AbstractVector). 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, which takes the angle of incidence of each hit into account. To sample on a grid of one's own, pass a RectilinearGrid; other samplings are subtypes of BeamletOptics.AbstractDetectorSampling.
Coherent sum
All hits are summed as one monochromatic, mutually coherent field, also hits of different wavelengths or of sources that are mutually incoherent. For those, evaluate the intensity of each wavelength or source on its own and add the intensities.
Resetting detectors
Be sure to call empty!(pd) (or initialize!(system) for all detectors) before each new measurement if reusing the same detector.
Keyword arguments
progress::Bool = true: shows a progress bar once the calculation has run forget_progress_threshold()seconds (default 5 s). It is only drawn ifstderris a terminal.
The grid, its window and its resolution are set by the sampling, e.g. electric_field(pd, RegularGrid(num_points = 200, crop_factor = 5)), see RegularGrid.
Scaling
The returned values for ray hits correspond to the E-field of the point spread function. The values are raw/unscaled and not equal to a Strehl ratio: a Ray has the amplitude 1, a PolarizedRay its field vector E0, which carries the Fresnel/Jones amplitude factors but not the ray-tube area or the pupil sampling density.
Returns
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. The values are complex scalars for Rays and GaussianBeamlets, Point3{Complex{T}} 3D vectors in global coordinates for PolarizedRays and AstigmaticGaussianBeamlets, which carry a polarization. A detector that no beam hit has the field zero at every point, as complex scalars, since without hits there is no polarization.
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(pd, sampling) with the same RectilinearGrid sampling after each trace and add the results.
BeamletOptics.electric_field Method
electric_field(hits::AbstractVector{<:AbstractDetectorHit}, p::AbstractVector)Coherent sum of the fields of the detector hits at the global point p [m], see electric_field(::BeamletOptics.AbstractDetectorHit, ::AbstractVector).
BeamletOptics.electric_field Method
electric_field(agb, r, z)Convenience wrapper for parabasal_field.
BeamletOptics.electric_field Method
electric_field(hit::AbstractDetectorHit, p::AbstractVector)Electric field Eⱼ(p) of a single detector hit at the global point p [m], not projected onto the detector: a complex scalar for RayHits and GaussianBeamletHits, a complex 3D vector in global coordinates for PolarizedRayHits and AstigmaticGaussianBeamletHits. It is a phasor with the time dependence exp(-iωt), so that a plane wave in a medium of index n carries the intensity n|E|²/(2Z₀). With the vacuum wavenumber k₀ = 2π/λ, the direction s of the hit, the refractive index n in front of the detector and the optical path length L from the source to the hit point p_hit:
RayHit: a plane wave of amplitude1,PolarizedRayHit: the same plane wave times the field vectorE₀of the ray,GaussianBeamletHit: the TEM₀₀ field of the traced segment, at the distancelalong its chief ray and the distancerfrom it,with the field
E₀and waistw₀of the beamlet, the beam radiusw, the radius of curvatureRand the Gouy phaseψof the segment (seegauss_parameters), the indexnof the segment and the optical pathL(l)along the chief ray.AstigmaticGaussianBeamletHit: the field vector of the chief ray of the segment,E₀, times the general astigmatic Gaussian beam of its parabasal rays, , with the Gouy factorg, which also holds the change of the amplitude with the beam area, the transverse phaseW, the spot matrixSat the offsetrfrom the chief ray andκ = det S / |a|²of the complex beam areaa, see Astigmatic polarized beamlets.
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(pd, sampling).
A new hit type implements this method and the other functions listed in BeamletOptics.AbstractDetectorHit; the readouts of a Detector on a grid (electric_field, intensity, optical_power) then work for it.
BeamletOptics.electric_field Method
electric_field(pd::Detector, points::AbstractArray{<:AbstractVector}; progress = true)The field of the hits of the Detector pd at the local detector coordinates points in [m], an array of vectors (x, z) (e.g. Point2s), see electric_field(pd, sampling). Returns the values only, in the shape of points.
BeamletOptics.electric_field Method
electric_field(gauss::GaussianBeamlet, r, z)Calculates the electric field phasor [V/m] of the GaussianBeamlet at the radial and longitudinal positions r and z. It is the physical field, like that of an AstigmaticGaussianBeamlet: with the irradiance n |E|² / (2 Z₀) of a medium of refractive index n, a beam of fixed power has the amplitude ∝ 1/√n, hence the field of a segment in a medium is the reference amplitude E0 of the beamlet divided by √n. The phase contains the optical_path_length from the start of the beam (parents included) up to z: within a medium of refractive index n it advances with the wavenumber n k₀, along the beam and across it. The Gouy phase is collected along the beam as well, i.e. it is continuous at every surface and from a parent beam to its children, and equals the ψ of gauss_parameters.
Warning
Note that z and r must be specified as cartesian distances. Using the optical path length for z can lead to false results.
BeamletOptics.electric_field Method
electric_field(r, z, E0, w0, w, k, ψ, R) -> ComplexF64Computes the analytical complex electric field distribution of a stigmatic TEM₀₀ Gaussian beam which is described by:
Arguments
r: radial distance from beam originz: axial distance from beam originE0: peak electric field amplitudew0: waist radiusw: local beam radiusk: wave number, equal to2π/λψ: Gouy phase shift (defined as!) R: wavefront curvature, i.e. 1/r (radius of curvature)
BeamletOptics.ellipse Method
ellipse(t, a, b, c)Returns a point in Rⁿ that lies on an n-dim. ellipse that is parametrized by
t: circumference control variable ∈ [0, 2π]a: center pointb, c: conjugate diameter vectors
BeamletOptics.enclosing_circle Method
enclosing_circle(vertices)Returns the center and the radius of a circle that encloses the 2D points vertices and passes through at least one of them. Of the circles around the mean of the points (exact for regular polygons) and around the center of their bounding box (exact for rectangles and right triangles) the smaller one is returned, which is not the smallest enclosing circle in general.
BeamletOptics.fan_coordinates Method
fan_coordinates(n, T) -> Vector{T}The n sample positions of a line or fan on [-1, 1]: the center first, then equidistant samples from -1 to 1. An even n repeats the center.
BeamletOptics.find_zero_bisection Method
find_zero_bisection(f, a, b; tol=1e-10, max_iter=1000)Finds a root of the scalar function f on [a, b] using the bisection method. Requires sign(f(a)) ≠ sign(f(b)). Stops when abs(f(mid)) < tol or after max_iter iterations, returning the current midpoint.
Arguments
f: functionReal -> Reala: lower interval boundb: upper interval boundtol: absolute function tolerance (default1e-10)max_iter: maximum iterations (default1000)
Errors
Throws if there is no sign change on [a, b] or if convergence is not reached within max_iter.
BeamletOptics.first_of Method
first_of(hit::Intersection, chosen::Intersection)Returns the chain of coincident_hits hit with its hit chosen first.
BeamletOptics.first_of_shape Method
first_of_shape(hit, target::AbstractShape)Returns the chain of coincident_hits hit with the hit of the shape target first, if the chain holds one, else hit unchanged. No hit (nothing) stays nothing.
BeamletOptics.first_ray Method
first_ray(beam::AbstractBeam)Returns the start ray on the optical axis of the beam; for beamlets the first chief ray. Defines the generic position and direction of the beam, which are used as the pivot for rotations.
BeamletOptics.fresnel_coefficients Method
fresnel_coefficients(θ, n)
Calculates the complex Fresnel coefficients for reflection and transmission based on the incident angle θ in [rad] and the refractive index ratio n = n₂ / n₁. Returns rₛ, rₚ, tₛ and tₚ.
Signs
Info
The signs of rₛ, rₚ are based on the definition by Fowles (1975, 2nd Ed. p. 44) and Peatross (2015, 2023 Ed. p. 78)
BeamletOptics.gauss_parameters Method
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 axesR1,R2: radii of curvature along the principal axesψ: total Gouy phase shift, collected continuously along the beam: it does not jump behind a focus or at a mirror, and a child beam continues its parentw01,w02: waist radii along the principal axes
BeamletOptics.gauss_parameters Method
gauss_parameters(segment::GaussianSegment, l)Returns (w, R, ψ, w0) of the GaussianSegment at the distance l behind the start of its chief ray, as gauss_parameters(gauss, z) does, but with the Gouy phase ψ relative to the local waist of the segment.
BeamletOptics.gauss_parameters Method
gauss_parameters(gauss::GaussianBeamlet, z, ψ0; hint)As gauss_parameters(gauss, z), but the returned Gouy phase is the one relative to the waist of the local segment plus ψ0. With ψ0 = 0 it is the local Gouy phase, which jumps at every surface, e.g. at a lens; gauss_parameters(gauss, z) passes the Gouy phase that the beam has collected in front of the segment.
BeamletOptics.gauss_parameters Method
gauss_parameters(gauss::GaussianBeamlet, z; hint = point_on_beam(gauss, z))Calculate the local waist radius and Gouy phase of an unastigmatic Gaussian beamlet at a specific cartesian distance z based on the method of J. Arnaud (1985) and D. DeJager (1992).
Arguments
gauss: the GaussianBeamlet object for which parameters are to be calculated.z: the position along the beam at which to calculate the parameters.hint: optional tuple(point, index)of the point on the beam and the index of its segment, as returned bypoint_on_beam. Default ispoint_on_beam(gauss, z).
Returns
w: local radiusR: curvature, i.e. 1/r where r is the radius of curvatureψ: Gouy phase (note that -atan definition is used), collected along the beam from the start of the root beam: continuous at every surface and from a parent beam to its children, i.e. the Gouy phase thatelectric_fieldcontains. The same holds for anAstigmaticGaussianBeamlet.w0: local beam waist radius
BeamletOptics.gauss_parameters Method
gauss_parameters(gauss::GaussianBeamlet, zs::AbstractArray)Return the parameters of the GaussianBeamlet along the specified positions in zs.
BeamletOptics.get_view Method
get_view(ls)Returns the current camera view matrix of an LScene ls, if a suitable backend is loaded.
Handy at the REPL to freeze a view found interactively: rotate the scene by hand, call get_view(ax), and paste the printed matrix into the script as a literal passed to set_view.
Only an LScene has these camera controls, any other Makie axis, e.g. Axis3, throws an InvalidAxisError. If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.grid_axes Method
grid_axes(dir, basis) -> (e1, e2)The unit axes of a beamlet grid normal to the unit vector dir: normal3d(dir) and dir × e1 for basis = nothing, else the normalized axes of the tuple basis.
BeamletOptics.hide_axis Function
hide_axis(ls, hide::Bool=true)Hides the axis markers of an LScene ls, if a suitable backend is loaded. Can be toggled via hide. Any other Makie axis throws an InvalidAxisError. If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.hit_point Method
hit_point(ray::AbstractRay)Returns the point where the ray ends, i.e. where it hits the surface of its Intersection.
BeamletOptics.initialize! Method
initialize!(x)Brings x into the state that a new solve starts from, by discarding the data that its objects have stored during previous calls of solve_system!. x can be a System or StaticSystem, an ObjectGroup (nested groups are included) or a single object. Currently this empties all Detectors. Objects that store no such data are left unchanged. Returns nothing.
solve_system! does not call this function unless its keyword initialize is set: a Detector accumulates the hits of several solves on purpose, such that several sources solved one after another superpose. Initialize before solving again after the setup was changed, e.g. in a parameter scan. The beams are not touched, solve_system! resets them itself.
A new object type that stores data during a solve implements initialize!(object). For an AbstractDetector it calls empty!(detector).
Examples
for shift in shifts
translate_to3d!(mirror, shift)
initialize!(system) # instead of empty!(pd) for every detector
solve_system!(system, beam)
P = optical_power(pd)
endor in one call via solve_system!(system, beam; initialize = true).
BeamletOptics.install_agent_skill Function
install_agent_skill(dest = joinpath(pwd(), ".claude", "skills"))Copies the agent skill that ships with the installed BeamletOptics version into joinpath(dest, "beamletoptics") and returns that path. The skill teaches AI coding assistants (e.g. Claude Code) how to write BeamletOptics simulations.
The default dest is the project-level skill directory of Claude Code in the current working directory. Use e.g. joinpath(homedir(), ".claude", "skills") for a personal installation.
An existing beamletoptics skill in dest is replaced, so calling this function again after Pkg.update keeps the skill in sync with the installed package version. Local edits to the copy are lost.
File permissions
Pkg installs packages read-only. The files are written anew instead of copied with their permissions, so that the copy can be edited and replaced later.
BeamletOptics.intensity Function
Calculates the intensity |E|²/(2Z) in [W/m²] of a plane wave with the complex electric field vector E (e.g. a PolarizedRay field) in a medium of the wave impedance Z (default: vacuum). It is not projected onto a surface; the irradiance on a Detector is intensity(pd).
BeamletOptics.intensity Function
Calculates the intensity |E|²/(2Z) in [W/m²] of a plane wave with the complex electric field phasor E in a medium of the wave impedance Z (default: vacuum, use Z₀/n in a medium of index n). It is not projected onto a surface; the irradiance on a Detector is intensity(pd).
BeamletOptics.intensity Function
intensity(pd::Detector, sampling::AbstractDetectorSampling = RegularGrid(); progress = true)Samples the irradiance on the Detector pd, the power per detector area in [W/m²], at the points of sampling, by default a RegularGrid 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(pd, sampling).
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 polarization (PolarizedRays, AstigmaticGaussianBeamlets) give
with the field Eⱼ of hit j (see electric_field(hit, p)), its direction sⱼ, the refractive index nⱼ in front of the detector, the vacuum impedance Z₀ and σⱼ = sign(sⱼ ⋅ n̂), i.e. a hit on the back side of the detector counts like one on its front side. Hits without a polarization (Rays, GaussianBeamlets) have no vector H and give the scalar form of the same flux,
A single hit under the angle θ to the normal gives I = n|E|² cos θ / (2Z₀), the power of the beam per detector area, so that optical_power is the power of the beam for any angle of incidence. No projection factor is applied to the field. For two scalar hits, the cross term is Re(E₁* E₂) (n₁ cos θ₁ + n₂ cos θ₂) / (2Z₀), i.e. hits under different angles interfere with the 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. A detector that no beam hit has I = 0 at every point.
BeamletOptics.intensity Method
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(pd, sampling).
BeamletOptics.intensity Method
intensity(agb::AstigmaticGaussianBeamlet, r, z)Compute the optical intensity n |E|² / (2 Z₀) [W/m²] of the beamlet at position (r, z), with the refractive index n of the segment at z.
BeamletOptics.intensity Method
The irradiance on the Detector pd in [W/m²] at the local detector coordinates points in [m], an array of vectors (x, z) (e.g. Point2s), see intensity(pd, sampling). Returns the values only, in the shape of points.
BeamletOptics.interact3d Method
interact3d(::AbstractSystem, object::AbstractObject, ::AbstractBeam, ::AbstractRay)Defines the optical interaction between an incoming/outgoing beam/ray of light and an optical element, must return an AbstractInteraction or nothing. The default behavior is that no interaction occurs, i.e. return of nothing, which should stop the system tracing procedure. Refer to the AbstractInteraction typedocs for more information on the return type value.
A MultiShape object receives this call for whichever of its parts was hit. Its method finds that part, e.g. via shape(intersection(ray)), and hands the beam to it, see CubeBeamsplitter. Parts that do not interact as one belong in an ObjectGroup or another AbstractObjectGroup instead, where each part interacts on its own.
BeamletOptics.interact3d Method
interact3d(::AbstractSystem, bs::ThinBeamsplitter, agb::AstigmaticGaussianBeamlet, ray_id::Int)Models the interaction between a ThinBeamsplitter and an AstigmaticGaussianBeamlet. The reflection phase jump θᵣ = π is applied to the reflected child beam if the beam faces the normal vector of the splitter, i.e. dot(dir, normal) < 0, otherwise θᵣ = 0.
BeamletOptics.interact3d Method
interact3d(::AbstractSystem, bs::ThinBeamsplitter, gauss::GaussianBeamlet, ray_id::Int)Models the interaction between a ThinBeamsplitter and a GaussianBeamlet.
Reflection phase jump
The reflection phase jump is modeled here as θᵣ = π for simplicity. This is since in practice it will have only a relative effect on the signal at the detector for interferometric setups. The phase jump is applied to the reflected portion of any incoming beam that faces the ThinBeamsplitter 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.
BeamletOptics.interact3d Method
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.
BeamletOptics.interact3d Method
interact3d(system::AbstractSystem, object::AbstractObject, gauss::GaussianBeamlet{R}, ray_id::Int)Generic dispatch for the interact3d method of a GaussianBeamlet with an AbstractObject. Unless a more concrete implementation exists, the interaction of the Gaussian is assumed to be the interaction of the chief, waist and divergence rays with an object.
Returns
The interact3d method for the GaussianBeamlet must return a GaussianBeamletInteraction.
BeamletOptics.interact3d Method
Implements the ideal reflection of a PolarizedRay via the normal at the intersection point on an optical surface. A Jones matrix of [-1 0 0; 0 1 0] is assumed as per Peatross (2015, 2023 Ed. p. 154) and Yun et al. (see PolarizedRay for more information).
BeamletOptics.interact3d Method
interact3d(AbstractReflectiveOptic, Ray)Implements the reflection of a Ray via the normal at the intersection point on an optical surface.
BeamletOptics.interact3d Method
Implements the refraction of a PolarizedRay at an uncoated optical surface. The "outside" ref. index is obtained from the system unless specified otherwise. Reflection and transmission values are calculated via the fresnel_coefficients. Stray light is not tracked. In the case of total internal reflection, only the reflected light is traced.
BeamletOptics.interact3d Method
Implements the refraction of a Ray at an optical surface. The "outside" ref. index is obtained from the system unless specified otherwise. At the critical angle, total internal reflection occurs (see refraction3d).
BeamletOptics.interact3d Method
interact3d(system::AbstractSystem, lp::LinearPolarizer, beam::Beam, ray::AbstractRay)Dispatches the optical interaction between a Beam/AbstractRay and a LinearPolarizer depending on which sub-shape (front, filter or back) was intersected.
Additional information
Cemented interface
The front and back substrates sit flush against the film. Refraction at the outer, uncoated surfaces is handled by the standard AbstractRefractiveOptic interaction logic. When a ray reaches the flat inner face cemented to the film, the film's Jones matrix is applied to the field before it is refracted (or, in case of total internal reflection, reflected without crossing the film) directly from the current substrate's refractive index into the other substrate's.
BeamletOptics.intersect3d Function
intersect3d(object::AbstractSDF, ray::AbstractRay, t_max = Config.get_sdf_miss_distance())Intersection algorithm for sdf based shapes. A ray that starts outside of the object is a miss once it has travelled the path length t_max in [m] without a hit. A ray that starts inside, or on the surface pointing inside, hits the surface where it leaves the object first, see raymarch_inside. A ray counts as starting on the surface within Config.get_sdf_surface_threshold().
BeamletOptics.intersect3d Method
intersect3d(sphere::AbstractBoundingSphere, object::AbstractSDF, ray::AbstractRay)Tests the ray against the bounding sphere of the object, see intersect3d(sphere, shape, ray). If the ray passes through the sphere, it is marched as in intersect3d(object, ray), but is a miss as soon as it has left the sphere, since the object lies within. A ray that leaves the object is thus a miss after a few steps.
The radius is enlarged by the surface threshold of the marching algorithm (Config.get_sdf_surface_threshold()), below which a ray counts as starting on the surface.
BeamletOptics.intersect3d Method
intersect3d(object::AbstractObject, ray::AbstractRay)In general, the intersection logic between an AbstractObject and an AbstractRay depends on the AbstractShapeTrait. Refer to the respective documentation.
BeamletOptics.intersect3d Method
intersect3d(group::AbstractObjectGroup, ray::AbstractRay)Returns the closest intersection of the ray with the objects of the group. In contrast to a MultiShape object, the intersection keeps the object of the group that was hit, since this object, not the group, interacts with the ray. No object is tested if the ray misses the bounding sphere of the group, which the table of a running solve holds, see bounding_sphere_of(table, x).
BeamletOptics.intersect3d Method
intersect3d(shape::AbstractShape, ::AbstractRay)Defines the intersection between an AbstractShape and an AbstractRay, must return an Intersection or nothing. The default behavior for concrete shapes and rays is to log a warning (No intersect3d method defined for: ...) and to indicate no intersection, that is nothing, which will inform the tracing algorithm to stop. Refer to the Intersection documentation for more information on the return type value.
BeamletOptics.intersect3d Method
intersect3d(sphere::AbstractBoundingSphere, x::Union{AbstractShape, Tuple, AbstractVector, Leaves, LeafObjects}, ray::AbstractRay)Returns the intersection between x and the ray like intersect3d(x, ray), but tests the ray against the bounding sphere of x first. x is a shape, or the parts of a MultiShape object or of an object group, see intersect3d(parts, ray):
NoBoundingSphere:xis tested viaintersect3d(x, ray)the
raymisses theSingleBoundingSphereorMultiBoundingSphere, or the sphere lies behind it: returnsnothingwithout a test ofx, i.e. of any of the partsotherwise
xis tested viaintersect3d(x, ray)
BeamletOptics.intersect3d Method
intersect3d(mesh::Mesh, ray::Ray)This function is a generic implementation to check if a ray intersects the mesh.
BeamletOptics.intersect3d Method
intersect3d(parts, ray::AbstractRay)Returns the closest Intersection of the ray with the parts, or nothing if it hits none of them. The parts are a tuple, a vector, the Leaves of shapes or objects or the objects of a system, e.g. the shapes of a MultiShape object or the objects of a group. Each part is tested via its own intersect3d method, hence parts that consist of parts, e.g. the groups of a system, are tested as a whole. No parts give nothing. Parts that the ray hits within get_coincidence_tolerance() of the closest hit are kept as its coincident_hits.
BeamletOptics.intersect3d Method
intersect3d(plane_position, plane_normal, ray)Returns the intersection between a ray and an infinitely large plane which is characterized by its position and normal.
BeamletOptics.is_cancelled Method
is_cancelled(e)true if the exception e stems from a cancelled ProgressSink, also if it is wrapped in a TaskFailedException or a CompositeException (as thrown by Threads.@threads).
BeamletOptics.isbeyond Method
isbeyond(sphere::AbstractBoundingSphere, ray, t)Returns true if nothing within the sphere can be hit by the ray at a path length up to t in [m]: the ray misses the sphere, the sphere lies behind its start, or the ray enters it only beyond t. Without a sphere (NoBoundingSphere) the result is false. The solver skips such parts once it has found a hit at t, and those that the ray misses for t = Inf.
BeamletOptics.iscircular Method
iscircularTests if the polarization state is circular. Refer to Yun paper.
sourceBeamletOptics.iselliptical Method
isellipticalTests if the polarization state is elliptical.
sourceBeamletOptics.isentering Method
isentering(ray)Tests whether the ray is entering a shape based on the orientation of the ray direction and surface normal. If no intersection is present, default behavior is to return false.
BeamletOptics.isinfrontof Method
isinfrontof(point::AbstractVector, pos::AbstractVector, dir::AbstractVector)Tests if a point is in front of the plane defined by the position and direction vectors.
BeamletOptics.isinfrontof Method
isinfrontof(shape::AbstractShape, ray::AbstractRay)A simple test to check if a shape lies "in front of" a ray. The forward direction is here defined as the ray orientation. Only works well if ray is outside of the volume of shape. Can be dispatched to return more accurate results for subtypes of AbstractShape.
BeamletOptics.islinear Method
islinearTests if the polarization state is linear. Refer to Yun paper.
sourceBeamletOptics.isorthogonal3d Method
isorthogonal3d(v1, v2; atol=eps())Tests if v1 and v2 are orthogonal. Additional abs. tolerance can be passed via atol
BeamletOptics.isparallel3d Method
isparallel3d(v1, v2; atol = √eps)Tests if v1 is parallel (or anti-parallel) to v2, i.e. if the sine of the angle between both vectors, norm(cross(v1, v2)) of the normalized vectors, is at most atol. The test uses the squared norm, because norm of a vanishing cross product is NaN for dual numbers whose derivative does not vanish, e.g. at normal incidence in automatic differentiation.
BeamletOptics.isparaxial Function
isparaxial(system, beam, threshold=π/4)Tests the angle between the beam direction and surface normal at each intersection. Mainly intended as a check for GaussianBeamlet.
BeamletOptics.isparaxial Function
isparaxial(system, gb::GaussianBeamlet, threshold=π/4)Tests the angle between the waist and divergence beams and refractive surfaces. A target threshold of π/4 or 45° is assumed before abberations become dominant.
sourceBeamletOptics.isparentbeam Method
isparentbeam(beam, ray)Tests if the given beam contains the ray as a part of its solution.
BeamletOptics.istilted Method
istilted(system::System, gb::GaussianBeamlet)Tests if refractive elements are tilted with respect to the beamlet optical axis, i.e. introduce simple astigmatism.
sourceBeamletOptics.jones_field Method
jones_field(E0, d, a)The field of the amplitude a [V/m] along the direction d with the polarization and the phase of the Jones vector E0: its component transverse to d, normalized. Throws an ArgumentError for an E0 along d; returns nothing for E0 = nothing.
BeamletOptics.kinematic_trait_of Method
kinematic_trait_of(x) -> AbstractKinematicTraitReturns the AbstractKinematicTrait of x. A type takes part in the kinematic API only if it opts in with a typed method: movable types declare Movable(Oriented()) or Movable(Directed()), static types Static(). Throws an ErrorException for any other type.
BeamletOptics.kinematic_trait_of Method
kinematic_trait_of(c::AbstractCompositeSDF)A composite takes the kinematic class of its operands, which the constructor ensures to be either all static or all movable, see BeamletOptics.AbstractKinematicTrait.
BeamletOptics.lagrange_invariants Method
lagrange_invariants(agb, i)Lagrange invariants H = n Im(h* . u) of the x and y axes of agb at segment i. At the start of a beamlet they are M2 λ / π, up to the paraxial error of the divergence rays.
BeamletOptics.lagrange_invariants Method
lagrange_invariants(segment::GaussianSegment)Lagrange invariant H = n (y_w ⋅ v_d - y_d ⋅ v_w) of the GaussianSegment as a 1-tuple, from the offsets y and slopes v of its waist and divergence rays. It is constant along the segment, since both rays are straight. At the start of a beamlet it is M2 λ / π.
BeamletOptics.lagrange_invariants Method
lagrange_invariants(gauss::GaussianBeamlet, i)Lagrange invariant of segment i of the GaussianBeamlet, see lagrange_invariants(::GaussianSegment).
BeamletOptics.length_before Method
length_before(beam::AbstractBeam, id::Integer)Returns the geometric length of the beam, its parents included, up to the start of ray id.
BeamletOptics.lensmakers_eq Method
lensmakers_eq(R1, R2, n)Calculates the thin lens focal length based on the radius of curvature R1/R2 and the lens refractive index n. If center of sphere is on left then R < 0. If center of sphere is on right then R > 0.
BeamletOptics.line_plane_distance3d Method
line_plane_distance3d(plane_position, plane_normal, line_position, line_direction)Returns the distance between a line and an infinitely large plane which are characterized by their position and normal/direction.
BeamletOptics.line_point_distance3d Method
line_point_distance3d(pos, dir, point)Computes the shortes distance between a line described by pos+t*dir and a point in 3D. This function is slow and should be used only for debugging purposes.
BeamletOptics.line_point_distance3d Method
line_point_distance3d(ray, point)Returns value for the shortest distance between the ray (extended to ∞) and point.
BeamletOptics.list_subtypes Function
list_subtypes(T::Type; max_depth::Int=5)Prints a tree of all subtypes, e.g. list_subtypes(AbstractObject). Maximum exploration depth can be limited by passing max_depth. Returns the total number of types encountered.
BeamletOptics.live_render! Method
live_render!(axis, thing; kwargs...)Renders thing into the axis like render!, but returns an AbstractRenderHandle that can be updated in place via update_render!. Intended for animations and interactive applications, e.g. moving components that require the system to be solved repeatedly.
objects and systems: the geometry is generated once, kinematic changes are applied as a model transformation of the existing plots
rays, beams and beam groups: all segments are bundled into a single plot
GaussianBeamlet,AstigmaticGaussianBeamletandAstigmaticBeamGroup: the envelope of all segments is bundled into a single mesh
Keyword arguments are passed on as for render!, but the envelope meshes of Gaussian beamlets are drawn with coarser default resolutions r_res/z_res: 24/40 for a GaussianBeamlet (render!: 50/100) and 10/8 per beamlet of an AstigmaticBeamGroup (render!: 64/100). Change them via the keywords or later via render_settings!.
If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.live_render! Method
live_render!(h::AbstractSystemRenderHandle, obj; kwargs...) -> Vector{<:AbstractObjectRenderHandle}Live-renders obj, an object or object group, into the axis of the system handle h and adds it to h, e.g. an object that was added to the system via push!(system, obj) after h was created. An object group is rendered per object, with its hierarchy known to render_parent, like the groups of live_render!(ax, system). Returns the new object handles, one per rendered object. The system of h is not changed. An obj that h already renders throws an ArgumentError.
Keyword arguments are passed on as for render!. Implemented by the handle returned by live_render!(ax, system). A system handle that does not implement it throws an ArgumentError: render obj via live_render!(ax, obj) and add its handle via push!(h, oh) instead.
BeamletOptics.live_render! Method
live_render!(draw, axis, x) -> AbstractObjectRenderHandleLive-renders x via the function draw: draw() plots x in its current pose into the axis, and the returned handle moves these plots with x like those of an object, see live_render!, e.g. a marker of a thing that render! does not draw. x has a position and an orientation (or a direction), e.g. a source or an own movable type (see kinematic_trait_of):
h = live_render!(ax, src) do
scatter!(ax, [Point3f(position(src))]; color = :orange)
endIf no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.local_axes Method
local_axes(pd::Detector) -> (x̂, ẑ)The axes of the local (x, z) coordinates of pd in global coordinates, with x̂ × ẑ = direction(pd). x̂ is flipped since the detector mesh is rotated by π.
BeamletOptics.look_at! Method
look_at!(ax, target, offset; up = [0, 0, 1])Aims the camera of ax at target from target + offset, if a suitable backend is loaded. A deterministic replacement for manually orbiting the scene to find a viewpoint, handy for reproducible close-up figures. ax must be an LScene, any other Makie axis throws an InvalidAxisError. If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.look_colors Method
look_colors() -> Dict{Symbol, RGBf}The colors of the material classes (:refractive, :reflective, :coating, :polarizer, :detector, :mechanics, :interface) of the active look, see set_render_look, e.g. to recolor the rendered objects of a class for a dark background.
If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.mechanical_diameter Method
Returns the mechanical diameter of the surface.
Note
It is assumed that mechanical_diameter(s) >= diameter(s) always holds.
sourceBeamletOptics.merge_hits Method
merge_hits(a, b, tol = get_coincidence_tolerance())Merges the hits a and b of the same ray, each nothing or a chain of coincident_hits, into one chain. Its first hit is the closer of a and b, a if both lie equally far. It holds all hits of both chains within tol of the first hit, the others are dropped. The chains are linked anew, hence a and b must not be used afterwards.
BeamletOptics.min_num_rays Method
min_num_rays(src) -> Union{Nothing, Int}The fewest rays with which num_rays! 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.AbstractSourceSampling of a source.
BeamletOptics.normal3d Method
normal3d(input)Returns a vector with unit length that is perpendicular to the input vector. The orientation is chosen deterministically to guarantee reproducible bases.
BeamletOptics.normal3d Method
normal3d(target, reference)Returns a vector with unit length that is perpendicular to the target and an additional reference vector. Vector orientation is determined according to right-hand rule.
sourceBeamletOptics.normal3d Method
normal3d(s::AbstractSDF, pos)Computes the normal vector of s at pos.
BeamletOptics.normal3d Method
normal3d(mesh::AbstractMesh, fID::Int)Returns a vector with unit length that is perpendicular to the target face according to the right-hand rule. The vertices must be listed row-wise within the face matrix.
The normal is (v2 - v1) × (v3 - v1) of the vertices v1, v2, v3 of the face, so it points outwards of a closed mesh if the vertices of each face run counter-clockwise seen from outside.
BeamletOptics.normalize_coherent_power! Method
normalize_coherent_power!(beams, vs, width)Scales the fields of beams, of equal power and in phase, such that their coherent superposition carries the sum of their powers; vs are their positions or directions, width the 1/e² half width of their profiles.
BeamletOptics.num_rays! Method
num_rays!(group, n)Regenerates the rays of the source group with n rays: a CollimatedSource or PointSource, including UniformDiscSource, UniformPointSource, UniformLineSource and UniformFanSource. The rays are sampled as by the constructor of the source (concentric rings with the same num_rings, the sunflower pattern, or the line or fan), in the current pose of the source and at its wavelength, i.e. the source equals a new one with num_rays = n at its position and orientation. The rays start at the emission point of the current rays, also if set_pivot3d! moved the pivot of the source away from it. The previous beams, including their traced rays, are replaced: solve the system again afterwards. Returns group.
n must be at least BeamletOptics.min_num_rays of the source, i.e. 20 num_rings for ring sources and 1 for sunflower, line and fan sources, otherwise an ArgumentError is thrown, like by the constructors, and the source keeps its rays. A source built from given beams, e.g. CollimatedSource(beams, diameter, pos, dir), can not be regenerated and throws an ArgumentError.
BeamletOptics.numerical_aperture Function
numerical_aperture(θ, n=1)Returns the NA for a opening half-angle θ and scalar ref. index n. For more information refer to this website.
BeamletOptics.numerical_aperture Method
numerical_aperture(s::AbstractSourceSampling)Returns the numerical aperture sin θ of the half spread angle θ of a PointSource sampling. A sampling for a PointSource implements it; the fallback throws.
BeamletOptics.numerical_aperture Method
numerical_aperture(ps::PointSource)Returns the numerical aperture of the half spread angle of ps.
BeamletOptics.object! Method
object!(intersection, object) -> intersectionSets the object of the intersection and of its coincident_hits, i.e. of all hits of the ray at this point within the object. No intersection (nothing) stays nothing.
BeamletOptics.objects Method
objects(group::AbstractObjectGroup)Returns the objects and subgroups stored directly in the group, without flattening the subgroups. See also objects(system), which flattens all groups of a system.
BeamletOptics.objects Method
Exposes all objects stored within the system. By exposing the Leaves of the tree only, it is ensured that AbstractObjectGroups are flattened into a regular vector. An empty system exposes no objects, nor does an empty group, e.g. one whose objects were removed.
BeamletOptics.op_extrude_x Method
op_extrude_x(p, sdf2d::Function, height)Calculates the SDF at point p for the given 2D-SDF function and extrudes the shape to height along the x-axis.
BeamletOptics.op_extrude_z Method
op_extrude_z(p, sdf2d::Function, height)Calculates the SDF at point p for the given 2D-SDF function and extrudes the shape to height along the z-axis.
BeamletOptics.op_revolve_y Method
op_revolve_y(p, sdf2d::Function, offset)Calculates the SDF at point p for the given 2D-SDF function with offset by revolving the 2D shape around the y-axis.
BeamletOptics.op_revolve_z Method
op_revolve_z(p, sdf2d::Function, offset)Calculates the SDF at point p for the given 2D-SDF function with offset by revolving the 2D shape around the z-axis.
BeamletOptics.operands Method
operands(c::AbstractCompositeSDF)Returns a Tuple of every child AbstractSDF that the composite c combines, in any order. This is the accessor the shared kinematics of AbstractCompositeSDF iterate over, so every concrete composite must implement it; the order carries no meaning and must not be relied upon to identify an operand's role in the boolean expression.
BeamletOptics.optical_path_length Method
optical_path_length(beam::AbstractBeam)Calculate the optical path length of the beam, i.e.
BeamletOptics.optical_path_length Method
optical_path_length(ray::AbstractRay{T}) where {T}Calculate the optical path length of the ray, i.e.
BeamletOptics.optical_power Function
optical_power(pd::Detector, sampling::AbstractDetectorSampling = RegularGrid(); progress = true)Calculates the total optical power on pd in [W] as the integral of its intensity over the window of sampling in the local detector coordinates,
with the points (xᵢ, zᵢ) and the weights wᵢ [m²] of the sampling, see sample_points: the trapezoidal rule for RegularGrid and RectilinearGrid. 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 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. For ray hits, P has no absolute unit, see intensity. A detector that no beam hit gives P = 0, e.g. when a scan moves the beam off the detector.
BeamletOptics.optical_power Method
optical_power(agb)Compute the total integrated optical power of the beamlet at its start, from the irradiance n |E|² / (2 Z₀) with the refractive index n of its first segment. For a Gaussian beamlet, this is typically constant through lossless propagation.
BeamletOptics.optical_power Method
optical_power(samples::DetectorSamples, I::AbstractArray{<:Real})The power in [W] of the irradiance I [W/m²] at the points of samples, P ≈ Σᵢ wᵢ Iᵢ with the weights of the sampling, see optical_power(pd, sampling). I has the shape of samples.points, e.g. the values of intensity(pd, samples.points), so that a field that was computed once gives its power without being computed again:
samples = BeamletOptics.sample_points(pd, RegularGrid(num_points = 200))
I = intensity(pd, samples.points)
P = optical_power(samples, I) # == optical_power(pd, RegularGrid(num_points = 200))
x, z = samples.coordinatesThrows a DimensionMismatch if I does not have the shape of the points. I is real: a field of electric_field has no method.
BeamletOptics.optical_power Method
optical_power(gauss::GaussianBeamlet)Power of the beamlet in [W] at its start. The reference amplitude E0 is normalized to the power, hence the power does not depend on the medium of the beamlet.
BeamletOptics.orientation! Method
orientation!(bg::AbstractBeamGroup, M)Overwrites the orientation matrix of the beam group bg with M, see orientation.
Warning
This only sets the bookkeeping of the group, the beams are not moved. Use rotate3d! to rotate a group including its beams. M is not validated and must be a right-handed orthonormal matrix.
BeamletOptics.orientation Method
orientation(bg::AbstractBeamGroup) -> SMatrix{3,3}Returns the orientation matrix of the beam group bg. Its columns are the local x-axis (the azimuthal sampling reference vector), the local y-axis (the central source direction, see direction) and the local z-axis, forming a right-handed orthonormal basis.
The orientation tracks the full rotational state of the group, including a roll about its own optical axis. It is updated by rotate3d! and returned to the identity by reset_rotation3d!.
BeamletOptics.orientation Method
orientation(object) -> MatrixReturns the current orientation of the object in R³ as a matrix. The matrix represents the local fixed-body coordinate system.
In general, orientation(object) returns orientation(shape(object)) unless specified otherwise.
BeamletOptics.orientation Method
Enforces that shape has to have the field dir or implement orientation().
BeamletOptics.parabasal_field Method
parabasal_field(agb, r, z; E_ref_amp)Compute the complex scalar electric field [V/m] of the AstigmaticGaussianBeamlet at a transverse offset r (a 3D vector in the plane perpendicular to the chief ray) and longitudinal position z.
The amplitude is that of the polarization of the chief ray of the segment at z, which holds everything that changed the field at the surfaces on the way (Fresnel coefficients, polarizers, beamsplitters), times the change with the beam area within the segments since the start of the root beam. A child beamlet continues its parent, in amplitude and in Gouy phase.
Arguments
agb: the astigmatic Gaussian beamletr: transverse offset vector (must be orthogonal to the chief ray direction atz)z: distance along the beamE_ref_amp: complex field amplitude of the segment (ifnothing: the norm of the polarization of its chief ray with the phase of its largest component)
Formalism
The field is computed using the Parabasal Gaussian Beamlet formalism: ψ(r, z) = √(area_ref / area(z)) * (|area(z)|² / det S(z))^(1/4) * exp(i * k * [z + 1/2 * rᵀ * Re Q(z) * r]) * exp(-rᵀ * S(z)⁻¹ * r) where area(z) = (h1 × h2) · dir is the complex beam area, area_ref its value at the start of the segment, continued over all segments in front of it, and S = Re(H H†) the spot matrix.
BeamletOptics.parabasal_ray_parameters Method
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).
BeamletOptics.parabasal_ray_parameters Method
parabasal_ray_parameters(agb, z)Compute the parabasal ray parameters at distance z along the beam.
BeamletOptics.parent! Method
parent!(child::AstigmaticGaussianBeamlet, parent::AstigmaticGaussianBeamlet)Links parent for tree navigation and ensures the chief beam parent is also linked.
sourceBeamletOptics.parent! Method
parent!(beam::GaussianBeamlet, parent::GaussianBeamlet)Ensures that the GaussianBeamlet knows about its parent beam. In addition, links the chief beams of child and parent. Important for correct functioning of point_on_beam and length.
BeamletOptics.pass_through Method
pass_through(ray::AbstractRay) -> BeamInteractionThe interaction of a ray that passes a Detector with stop = false unchanged: a new ray from the hit point with the direction, wavelength, refractive index and polarization of ray.
BeamletOptics.path_excess_before Method
path_excess_before(beam::AbstractBeam, id::Integer)Returns the optical minus the geometric path length of the beam, its parents included, up to the start of ray id.
BeamletOptics.path_segments Method
path_segments(beam::AbstractBeam; flen = 1.0) -> Vector{PathSegment}
path_segments(group::AbstractBeamGroup; flen = 1.0) -> Vector{PathSegment}Flattens the traced beam and all of its child beams (e.g. after beam splitting) into a vector of straight segments, one per ray, in depth-first order. For a GaussianBeamlet or an AstigmaticGaussianBeamlet the segments are those of the chief ray. For a beam group the segments of all its beams are concatenated, the beam_index field gives the index of the beam.
Each segment is a BeamletOptics.PathSegment with the start and end point, the accumulated geometric path length s_start, s_stop and optical path length opl_start, opl_stop (refractive index of the medium of the ray times its length), the wavelength λ, the depth in the beam tree, the parent segment index, from which the branches can be rebuilt, and the object hit at the end of the segment. The last segment of a branch is flagged by leaf = true. A child beam continues from the end of its parent beam, i.e. its first segment starts at the path length at which its parent ends. A beam attached with relaunch! (e.g. the output of a fiber) instead starts its own path: its first segment has s_start = 0 and opl_start = 0, like length and optical_path_length of that beam, while its parent still names the segment it was launched from and its depth counts the levels of the beam tree. A final ray without an intersection has no length of its own: it is flen [m] long and flagged by final = true.
Note
The beam must have been traced with solve_system!; an untraced beam consists of a single final segment. The path lengths are those of the ray tracer: length and BeamletOptics.optical_path_length of the beam equal s_stop and opl_stop of the last non-final segments of its branch.
Examples
beam = Beam([0, 0, 0], [0, 1, 0])
solve_system!(system, beam)
segs = path_segments(beam; flen = 0.1)
# position of the beam at the geometric path length s along the first branch
s = 0.25
seg = first(filter(sg -> sg.s_start <= s < sg.s_stop, segs))
point = seg.start + (s - seg.s_start) * (seg.stop - seg.start) / (seg.s_stop - seg.s_start)BeamletOptics.pick_object Method
pick_object(handle, plot)Returns the object of a live-rendered object or system handle that is visualized by the plot (one of its pickable_plots, or a child plot of one), or nothing if the plot does not belong to the handle. For a system handle, the top-level object, i.e. the outermost group of the picked object, see render_parent. Beams cannot be picked, a beam handle returns nothing.
If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.pickable_plots Method
pickable_plots(x, plots) -> AbstractVectorThe plots among the plots of x that select x in pick_object, by default all. Add a method for the type of x to exclude plots, e.g. the outline of a marker, whose clicks should reach what lies behind it.
BeamletOptics.point_on_beam Method
point_on_beam(beam::AbstractBeam, t::Real)Function to find a point given a specific distance t along the beam. Return the ray index aswell. For negative distances, assume first ray backwards.
BeamletOptics.polarized_field Method
polarized_field(agb, r, z)Compute the complex vector electric field [V/m] of the AstigmaticGaussianBeamlet at position (r, z). Returns a 3D vector.
BeamletOptics.progress_state Method
progress_state(s::ProgressSink)State of the loop that currently reports to s: nothing between loops, otherwise (; desc, count, n, t0) with desc the description without its trailing ": " (e.g. "Tracing beams"), count finished of n items and t0 the time() at which the loop started. Safe to call from any task while the loop runs.
BeamletOptics.projection_factor Method
projection_factor(ray::AbstractRay)Returns |d · n| of the direction d of the ray and the normal n of the surface it ends on; 1 if the ray ends without an intersection.
BeamletOptics.properties Method
properties(x) -> Vector{Pair{String, Any}}Returns the properties of x (an AbstractObject, shape, beam, source or object group) as a list of name => value pairs for display, e.g. in the inspector of the GUI package BeamletOpticsGUI. Only stored or cheaply derived values are listed, e.g. the reflectance of a beamsplitter (the power ratio R, as passed to its constructor) or the number of hits of a Detector, no design parameters that the object does not store. The list is computed on each call, i.e. it shows the current pose and hits.
Conventions
values are numbers in SI units, vectors of them (e.g. a position),
Strings orBoolsthe unit of a value is given in brackets at the end of its name, e.g.
"Diameter [m]"or"Angle [rad]"; names without brackets are dimensionless, e.g."Reflectance"the list starts with
default_properties:"Type", the pose and, for objects, the shape
julia> BeamletOptics.properties(SphericalLens(50e-3, -50e-3, 5e-3, 25.4e-3))
8-element Vector{Pair{String, Any}}:
"Type" => "Lens"
"Position [m]" => [0.0, 0.0, 0.0]
"Optical axis" => [0.0, 1.0, 0.0]
"Shape" => "UnionSDF"
"Thickness [m]" => 0.005
"Index model" => "ConstantRefractiveIndex"
"n(λ₀)" => 1.5
"λ₀ [m]" => 1.0e-6The refractive index is evaluated at λ₀ = get_default_wavelength(). The radii and the diameter of a lens are not listed, since its shape does not store them.
Custom components
Add a method for your type that extends the default list, e.g.
BeamletOptics.properties(x::MyFilter) =
[BeamletOptics.default_properties(x); "Optical density" => x.od; "Center wavelength [m]" => x.λc]Without a method, default_properties is shown.
BeamletOptics.radius Method
Returns the radius of curvature of the surface. This might return Inf for planar surfaces or surfaces which cannot be described by just one curvature radius.
BeamletOptics.radius Method
Returns the radius of curvature R = 2f of the parent conic at its vertex [m].
BeamletOptics.random_support Method
random_support(dir, rng)A unit vector normal to the unit vector dir at a random azimuth, from one draw of rng: the support of the principal axes of a beamlet with randomized axes.
BeamletOptics.ray_hits Method
Where each ray crossed the Detector pd and in which direction it went, in the coordinates of the detector. points[i] is the local (x, z) of hit i in [m], as in spot_diagram, and directions[i] its unit direction in the right-handed frame (x̂, n̂, ẑ), with the local axes x̂, ẑ and the normal n̂ = -direction(pd), along which beams arrive on the front side. For a detector in its initial orientation this frame is the global one, so a beam along the optical axis has the direction (0, 1, 0). A hit on the back side, which the detector also records, has d[2] < 0. The angle of a ray to the detector normal, in [0, π/2] for either side, is atan(hypot(d[1], d[3]), abs(d[2])) (accurate also near 0, unlike acos), its distance from the detector center norm(p), e.g. to judge how far a beam is from collimated.
For GaussianBeamlets and AstigmaticGaussianBeamlets, each hit gives the point and direction of the chief ray of the beamlet, whereas spot_diagram gives its waist contour. The pairs follow the order of the stored hits, which is not deterministic for beam groups. A detector that no beam hit returns two empty vectors.
BeamletOptics.rayleigh_range Method
rayleigh_range(agb::AstigmaticGaussianBeamlet)Returns the Rayleigh range for the x and y axes of the first beam section of the beamlet as a tuple (z_rx, z_ry), from its waist radii and divergence (M2 included).
BeamletOptics.rayleigh_range Method
rayleigh_range(g::GaussianBeamlet; M2=1)Returns the Rayleigh range for the first beam section of the GaussianBeamlet g. Note: M2 is not stored in g during construction and must be specified by the user.
BeamletOptics.raymarch_inside Method
raymarch_inside(shape::AbstractSDF, pos, dir, t_max = Config.get_sdf_miss_distance(), num_iter = 10_000, eps = Config.get_sdf_raymarch_eps(), h = Config.get_sdf_surface_threshold())Perform the ray marching algorithm if the starting pos is inside of shape, or on its surface with dir pointing inside, and return the intersection where the ray leaves shape first. The ray is marched by the distance -sdf, which is not larger than the distance to the surface for an SDF that is exact or a lower bound inside, hence no step passes the exit. A point where the SDF is about 0 is an exit only if the ray leaves the object there, not at an internal seam of a composite SDF. If a step ends outside, e.g. for an SDF that overestimates the distance inside or after a minimum step, the exit within this step is found within the bracket of this step, see bracketed_exit. The ray is a miss once it has travelled the path length t_max in [m] without leaving shape. A ray that grazes the surface of a thin part from inside takes steps of about its depth, hence the many iterations. A ray that starts on the surface may start up to the surface threshold h outside of it, see intersect3d(object::AbstractSDF, ray).
BeamletOptics.raymarch_outside Method
raymarch_outside(shape::AbstractSDF, pos, dir, t_max = Config.get_sdf_miss_distance(), num_iter = 1000, eps = Config.get_sdf_raymarch_eps())Perform the ray marching algorithm if the starting pos is outside of shape. The ray is a miss once it has travelled the path length t_max in [m] without a hit. The hit is the root of the SDF along the ray, refined from the last two probes of the marching.
BeamletOptics.rays Method
rays(beam::AbstractBeam)Returns the rays of the beam; for beamlets the rays of the chief beam.
BeamletOptics.rays_per_ring Method
rays_per_ring(weights, num_rays) -> Vector{Int}The numbers of rays on the rings of a ring sampling, num_rays in total, in proportion to the weights (circumferences) of the rings, half of it for the outermost ring (trapezoidal rule).
BeamletOptics.reflection3d Method
reflection3d(dir, normal)Calculates the reflection between an input vector dir and surface normal vector in R³. Vectors dir and normal must have unit length!
BeamletOptics.refract_transmitted! Method
refract_transmitted!(child, ray, dir)Sets the direction of the transmitted child ray of the coating to the refracted direction dir. For a PolarizedRay, the field is transformed into the new direction as well, and scaled for the medium behind the coating: the coating transmits a fraction of the power, and the power of a beam is proportional to n cos(θ) |E|². The refractive index of the child must be set before.
BeamletOptics.refraction3d Method
refraction3d(dir, normal, n1, n2)Calculates the refraction between an input vector dir and surface normal vector in R³. n1 is the "outside" refractive index and n2 is the "inside" refractive index. The function returns the new direction of propagation and a boolean flag to indicate if internal refraction has occured.
Vectors dir and normal must have unit length!
Total internal reflection
If the critical angle for n1, n2 and the incident angle is reached, the ray is reflected internally instead!
Arguments
dir: direction vector of incoming raynormal: surface normal at point of intersectionn1: index of ref. before refractionn2: index of ref. after refraction
BeamletOptics.refraction3d Method
refraction3d(ray, n2)Calculates the new direction of a ray entering into a new medium with ref. index n2.
BeamletOptics.relaunch! Method
relaunch!(beam::B, new_beams::AbstractVector{B}) where {B <: AbstractBeam}Attaches new_beams as children of beam that start their own optical reference: they are traced and removed together with beam, but their length, optical path and phase are counted from their own start instead of being continued from beam. The new beams carry the full phase in their amplitude.
Use it in the interact3d of a component that re-emits light elsewhere, e.g. the output end of a fiber or a solver coupled through a field: the light leaves at another place than where beam ended, so the geometric continuation of children! (parent length, reference plane of a beamlet) does not apply.
The new_beams replace any children that beam already has. A beam that the component keeps and attaches again is solved from its first ray, like every beam.
BeamletOptics.remove_render! Method
remove_render!(handle)Deletes all plots of the handle from its axis.
If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.remove_render! Method
remove_render!(h::AbstractSystemRenderHandle, obj)Removes obj, an object or object group, from the system handle h: deletes the plots of obj (of all objects of an object group) from the axis and removes their object handles from h, e.g. after delete!(system, obj). The system of h is not changed. Nothing happens for an obj that h does not render. An object within a group can not be removed on its own and throws an ArgumentError: remove the group instead.
BeamletOptics.render! Method
render!(ax, sphere::AbstractBoundingSphere; color = :magenta, linewidth = 1, kwargs...)Draws the bounding sphere into ax (an LScene or Axis3), if a suitable backend is loaded, as a wireframe of three great circles (parallel to the xy-, yz- and zx-plane of the world frame) in one lines plot. A SingleBoundingSphere or MultiBoundingSphere is drawn as it is, a NoBoundingSphere gives no plot.
The solver skips a shape for every ray that misses its sphere, see BeamletOptics.bounding_sphere_of, hence the plot shows what the solver tests, e.g. to check the bounding_sphere_of method of an own shape type: the sphere must enclose the whole shape and should be tight. The sphere is computed for the current pose of the shape and does not follow a shape that is moved afterwards.
Keyword args
color = :magenta: color of the lineslinewidth = 1: line width in screen units
All other kwargs are passed on to the lines plot of Makie. Returns nothing.
render!(ax, BeamletOptics.bounding_sphere_of(lens); color = :orange)
# the spheres of all objects, one per part and the main sphere of each object of several parts
render!(ax, system; show_bounding_sphere = true)If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.render! Method
render!(axis, thing; kwargs...)The render! function allows for the visualization of optical system and beams under the condition that a suitable backend is loaded. This means that either one of the following packages must be loaded in combination with BeamletOptics via using:
GLMakie
preferred for 3D viewing
use
LSceneorAxis3environments
CairoMakie
preferred for the generation of high-quality .pngs
only
Axis3is supported
If no suitable backend is loaded, a MissingBackendError will be thrown.
Implementation reqs.
All concrete implementations of render! must adhere to the following minimal interface:
render!(axis, thing; kwargs...)
axis: an axis type of the union ofLSceneorAxis3thing: an abstract or concrete object or beam typekwargs: custom orMakiekeyword arguments that are passed to the underlying backend
Refer to the BeamletOptics extension docs for Makie for more information.
BeamletOptics.render_lcs! Function
render_lcs!(ax, pos, lcs; scale = 10, show_labels = false)
render_lcs!(ax, object; scale = 10, show_labels = false)Draws the local coordinate system of an object or object group (or of an explicit pos/orientation pair) into ax as a red/green/yellow arrow triad, if a suitable backend is loaded. Useful to make the reference frame of an imported CAD mesh visible in the scene. ax must be an LScene, any other Makie axis throws an InvalidAxisError. If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.render_parent Function
render_parent(h::AbstractSystemRenderHandle, obj)The object group of the system of h that holds obj (an object or a group), or nothing if obj is at the top level or not in h. The handle returned by live_render!(ax, system) looks the group up when it is called, hence it follows push! and delete! of an ObjectGroup.
BeamletOptics.render_plots Function
render_plots(h::AbstractRenderHandle) -> AbstractVectorThe plots of the render handle h; of a system handle, the plots of all its object handles. The plots of an object handle may be replaced by update_render! and rerender!, hence do not keep them.
BeamletOptics.render_settings Function
render_settings(h::AbstractBeamRenderHandle) -> NamedTupleThe settings with which the beam handle h draws its beam, at least flen (length of a final ray without intersection [m]) and render_every (every how many beams of a beam group are drawn, 1 for other beams), e.g. to find the drawn segments of a beam, and color (the color of the rays or of the envelope as it was given, e.g. :blue or :wavelength). The handles of Gaussian beamlets and of beam groups of beamlets also report the resolution of the envelope, r_res and z_res. Change them via render_settings!.
BeamletOptics.render_settings! Method
render_settings!(h::AbstractBeamRenderHandle; kwargs...) -> hChanges the settings of the beam handle h and draws the beam again with them, without creating new plots: the plots of render_plots(h) stay in the axis, with their other attributes (visibility, opacity, line width, clip planes, ...) unchanged. The keywords are among the keys of render_settings(h):
flen: length of a final ray without intersection [m], positive and finiterender_every: every how many beams of a beam group are drawn, a positive integer (no effect on other beams)r_res,z_res: radial and longitudinal resolution of an envelope mesh, integers of at least 2color: the color of the rays or of the envelope, a single color thatMakieknows (e.g.:red,(:red, 0.3)), or:wavelengthor(:wavelength, alpha)for the color of the wavelength of each ray, seewavelength_color
Any other keyword, e.g. r_res for a ray, throws an ArgumentError, and then h is not changed. The beam is drawn as it is, i.e. nothing is solved, like update_render!. The overlays of the handle, e.g. show_beams or show_pos, follow the settings; the generating rays of show_beams and the polarization curve keep their colors.
The plots of a handle that draw the color hold one color per vertex, which the handle sets together with the positions. Change the color via render_settings!, not via the color attribute of the plots, which the next update overwrites. A color that is neither a single color nor the wavelength, e.g. a vector of colors, is passed on to Makie by live_render! and can not be changed here.
h = live_render!(ax, beam; flen = 0.1)
render_settings!(h; flen = 0.5) # the final ray is now 0.5 m long
render_settings!(h; color = :wavelength) # each ray in the color of its wavelength
render_settings!(h; color = :orange) # and all in one color againIf no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.rendered Function
rendered(h::AbstractRenderHandle)The object, system or beam that the render handle h shows, see AbstractRenderHandle.
BeamletOptics.rerender! Method
rerender!(handle)Draws the object of the handle again from its current shape, at its current pose, e.g. after the leg length of a prism or the radius of a lens was changed. update_render! applies only the pose and keeps the plots, hence use it after moving components, and rerender! after a change of the shape. Returns the handle.
The handle stays the same object, in the same place among the children of its system handle. Its plots are replaced: render_plots(handle) returns the new plots, and attributes that were set on the old plots (e.g. visibility or a highlight) are not carried over. If drawing the object throws, the handle keeps its old plots. A system handle draws all its objects again, a beam handle draws its beam as update_render! does.
If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.reset_root! Method
reset_root!(beam::AbstractBeam)Resets the root beam to its untraced start state before a move; throws an ArgumentError for a child beam.
BeamletOptics.reset_rotation3d! Method
reset_rotation3d!(x)Rotates x about its position such that its orientation is the identity. The inverse of the orientation is its transpose, which is exact for all angles, including π. Only available for BeamletOptics.Oriented values, see BeamletOptics.Movable.
BeamletOptics.reset_translation3d! Method
reset_translation3d!(x)Moves x such that its position is the global origin. The result is exact, because p + (-p) is zero in IEEE arithmetic. See BeamletOptics.Movable.
BeamletOptics.rotate3d! Method
rotate3d!(x, R::AbstractMatrix)
rotate3d!(x, axis::AbstractVector, θ::Real)
rotate3d!(x, R::AbstractMatrix, pivot::AbstractVector)
rotate3d!(x, axis::AbstractVector, θ::Real, pivot::AbstractVector)Rotates x by the rotation matrix R (or by the angle θ [rad] about axis) about its own position, or about pivot if given. See BeamletOptics.Movable.
BeamletOptics.rotate3d! Method
rotate3d!(::Movable, beam::AbstractBeam, R::AbstractMatrix)Resets the root beam to its untraced start state and rotates the start ray of every component beam by R about the position of the beam (the chief ray start for beamlets). Throws an ArgumentError for child beams.
BeamletOptics.rotate3d! Method
rotate3d!(::Movable, bg::AbstractBeamGroup, R::AbstractMatrix)Rotates all beams of the group by R about the group center and updates the group orientation to R * orientation(bg), a beam listed several times once. Every beam is reset to its untraced start state.
BeamletOptics.rotate3d! Method
rotate3d!(::Movable, c::AbstractCompositeSDF, R::AbstractMatrix)Rotates c and all of its operands around c's own origin (pivot), by the rotation matrix R, an operand listed several times once.
BeamletOptics.rotate3d! Method
rotate3d!(::Movable, detector::AbstractDetector, R::AbstractMatrix)Empties the detector (see empty!) and rotates it by R about its position, see translate3d!(::Movable, ::AbstractDetector, offset).
BeamletOptics.rotate3d! Method
rotate3d!(::Movable, mesh::AbstractMesh, R::AbstractMatrix)Rotate the mesh vertices and orientation around its current position using R.
BeamletOptics.rotate3d! Method
rotate3d!(::Movable, group::AbstractObjectGroup, R::AbstractMatrix)Rotates all objects of the group by R about the group center and updates the group orientation to R * orientation(group). Every object and subgroup moves once, see translate3d!(::Movable, group::AbstractObjectGroup, offset).
BeamletOptics.rotate3d! Method
rotate3d!(::Movable, shape::AbstractShape, R::AbstractMatrix)Rotates the dir-matrix of shape by the rotation matrix R.
BeamletOptics.rotate3d! Method
rotate3d!(::MultiShape, object, R::AbstractMatrix)All parts of the MultiShape object are rotated around the pivot center via the rotation matrix R, a part that shape(object) lists several times once.
BeamletOptics.rotate3d! Method
rotate3d!(::Movable, ray::AbstractRay, R::AbstractMatrix)Rotates the direction of the ray by R about its own start position and clears its intersection. Subtypes carrying direction-dependent data (e.g. the field vector of a PolarizedRay) dispatch their own method that also rotates this data.
BeamletOptics.rotate3d! Method
rotate3d!(::Movable, ray::PolarizedRay, R::AbstractMatrix)Rotates the direction and the field vector E0 of the ray by R about its start position and clears its intersection. E0 stays orthogonal to the direction and is not renormalized, i.e. its amplitude is kept.
BeamletOptics.rotate3d Method
rotate3d(reference::Vector, θ)Returns the rotation matrix that will rotate a vector around the reference axis at an angle θ in radians. Vector length is maintained. Counter-clockwise rotation in a right-hand coord. system. The reference axis is normalized internally, i.e. it can have any non-zero length.
BeamletOptics.sag Method
sag(r::Real, l::Real)Calculates the sag of a cut circle with radius r and chord length l
BeamletOptics.sample_points Method
sample_points(pd::Detector, sampling::AbstractDetectorSampling) -> DetectorSamplesThe points at which the readouts of the Detector pd are evaluated for the sampling sampling, with their weights and the coordinates that the readouts return, see DetectorSamples. Every AbstractDetectorSampling implements a method; the fallback throws an error.
BeamletOptics.sampling_args Method
sampling_args(src)The arguments of source_beams between b1 and λ for the source src: the diameter of a CollimatedSource, none for a PointSource.
BeamletOptics.sampling_basis Method
sampling_basis(dir, basis, T)Returns the unit-length reference vector that seeds the azimuthal sampling of a beam group. dir must already be normalized.
If basis is nothing, a vector normal to dir is picked deterministically via normal3d. Otherwise basis is projected into the plane normal to dir, which lets a caller rotate the sampling pattern of a source about its own axis. For a tuple of grid axes (ex, ey), the first axis is used.
Throws an ArgumentError if basis has no significant component in that plane, i.e. if it is zero or parallel to dir. The test is relative to norm(basis) because projecting an unnormalized vector leaves a residual that scales with its length; an absolute tolerance would let a parallel basis through and yield NaN sampling.
BeamletOptics.scale3d! Method
scale3d!(mesh::AbstractMesh, scale)Allows rescaling of mesh data around "center of gravity".
sourceBeamletOptics.sd_line_segment Method
sd_line_segment(p, a, b)Returns the signed distance from point p to the line segment described by the points a and b.
BeamletOptics.sdf Method
sdf(::AbstractRotationallySymmetricSurface, ::Union{Nothing, AbstractOrientationType})Takes the surface specification and an optional AbstractOrientationType as trait parameter and returns a corresponding AbstractSDF type.
Surface vs. volume based tracing
This function is a mere convenience provider for users coming from other optic simulations frameworks which are surface oriented. The goal of this function is to return the best matching closed volume SDF which posesses a surface with the given specs on one side and most often a boundary and planar surface on the other side.
Info
Always keep in mind that this package performs closed-volume baced ray tracing using either SDFs or meshes.
BeamletOptics.sdf_convex_polygon Method
sdf_convex_polygon(q, vertices, normals)Exact signed distance of the 2D point q to the convex polygon with the counter-clockwise vertices and the outward unit normals of its edges, see PolygonPrismSDF.
BeamletOptics.set_new_origin3d! Method
set_new_origin3d!(mesh::AbstractMesh)Resets the mesh directional matrix and position vector to their initial values.
Warning: this operation is non-reversible!
sourceBeamletOptics.set_orthographic Method
set_orthographic(ls)Switches the camera of an LScene ls to an orthographic projection, if a suitable backend is loaded. Any other Makie axis throws an InvalidAxisError. If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.set_pivot3d! Method
set_pivot3d!(bg::AbstractBeamGroup, pivot)Moves the kinematic pivot (center) of the beam group bg to pivot, without moving or resetting any of its beams. The pivot is the reference point used by rotate3d! and reset_translation3d!; the group orientation is unchanged.
Unlike translate3d! or rotate3d!, this only changes bookkeeping and does not reset already traced beams.
BeamletOptics.set_pivot3d! Method
set_pivot3d!(group::AbstractObjectGroup, pivot)Moves the kinematic pivot (center) of group to pivot, without moving any of its objects. The pivot is the reference point used by rotate3d!, translate_to3d! and reset_translation3d!; the group orientation is unchanged.
Example
Rotate a lens group about its first surface instead of the group's default center:
group = ObjectGroup([lens1, lens2])
set_pivot3d!(group, position(lens1))
rotate3d!(group, [0, 0, 1], deg2rad(5)) # rotates about lens1's position, not the old centerBeamletOptics.set_render_look Method
set_render_look(look::Symbol)Sets the look of all subsequently rendered objects, :modern (default) or :cad. The :modern look renders clear glass with faint silhouettes, metallic mirrors and neutral mechanics without edge lines, the :cad look saturated materials with feature edge lines. Explicit kwargs of render!, e.g. color, material or edges, override the look.
If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.set_view Method
Sets the camera of an LScene ls, if a suitable backend is loaded, either directly from a view matrix (e.g. one obtained via get_view) or from an eye/lookat/up triple. See also look_at! to aim the camera at a known point instead of specifying the triple directly.
Any other Makie axis than an LScene throws an InvalidAxisError. If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.shape Method
shape(::AbstractObject)Returns all component shapes of the object for a MultiShape or a single shape for a SingleShape. E.g. for a custom multi-shape object the user of this API needs to define:
BeamletOptics.shape(obj::MyObject) = (obj.front, obj.back)
Shared parts
The kinematic API moves every part once per motion, compared by identity (===): a part that shape(object) lists several times, and an object that an ObjectGroup holds along several paths. Two different parts of one motion must not reach the same shape at any level, e.g. a group that holds a DoubletLens and its front lens, or an object whose shape is an operand of a UnionSDF of another object; moving them throws an ArgumentError before anything moves.
BeamletOptics.shift_phase! Method
shift_phase!(agb, Δϕ)Apply a global phase shift Δϕ to the AstigmaticGaussianBeamlet by rotating the chief ray's polarization.
BeamletOptics.solve_system! Method
solve_system!(system::AbstractSystem, bg::AbstractBeamGroup; progress=true, initialize=false, kwargs...)Trace every beam of the beam group bg through the system, multithreaded over the member beams. All other kwargs are passed on to solve_system! for each beam. Every beam of the group is reset with empty! and solved from its start. The reset happens before the first beam is traced, such that a cancelled or failed solve leaves no beam with an old path.
The hits of all beams accumulate on the same Detectors, and so do the hits of earlier solves unless initialize = true.
Keyword Arguments
progress = true: show a progress bar once tracing has run forget_progress_threshold()seconds (default 5 s). It is only drawn ifstderris a terminal, so documentation builds, CI logs and piped output stay clean.initialize = false: iftrue,initialize!(system)is called once, before the first beam is traced. The beams themselves are solved without initializing, otherwise each beam would discard the hits of the others.
BeamletOptics.solve_system! Method
solve_system!(system::AbstractSystem, beam::AbstractBeam; initialize=false, r_max=get_default_r_max(), depth_max=get_default_depth_max(), check_invariant=true, threshold=get_invariant_threshold())Trace an AbstractBeam and all sub-beams it generates through an optical system. Every call solves the beam from its start: the beam is first reset to its untraced state with empty!, so nothing of an earlier solve is reused. A call after objects were moved, added or removed therefore gives the same result as solving a newly constructed beam. The condition to stop ray tracing is that the last beam intersection is nothing or the beam interaction is nothing. Then, the system is considered to be solved. A maximum number of rays per beam (r_max) can be specified in order to avoid infinite calculations under resonant conditions, i.e. two facing mirrors. Likewise, depth_max limits how many branching levels are explored when new sub-beams are generated (for example, by beamsplitters) so that the tree cannot grow without bound. Sub-beams beyond the depth limit are dropped from the tree.
Between two calls only the beam itself and its first ray keep their identity. The child beams and all later rays are new objects after every call: read children(beam) again instead of keeping a child. The objects of the system are not reset by default: a Detector keeps the hits of earlier solves, such that several sources solved one after another superpose on it. With initialize = true the system is initialized first (see initialize!), i.e. all its detectors are emptied. Otherwise the hits of both solves add up.
Arguments
system::AbstractSystem: The optical system in which the beam will be traced.beam::AbstractBeam: The beam object to be traced through the system.
Keyword Arguments
initialize = false: iftrue,initialize!(system)is called before thebeamis tracedr_max = get_default_r_max(): Maximum number of rays of each beam of the tree.depth_max = get_default_depth_max(): Maximum number of branching levels explored from the root beamcheck_invariant = true: enables or disables optical invariant checks where applicablethreshold = get_invariant_threshold(): limit of the complex invariant of anAstigmaticGaussianBeamlet. The Lagrange invariants of both beamlets useget_lagrange_toleranceinstead
BeamletOptics.source_beams Method
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 reference vector normal to dir, see BeamletOptics.sampling_basis; it sets the azimuth of the pattern about dir. args depend on the source: the diameter [m] of a CollimatedSource, none for a PointSource. The first beam is the center ray, which starts at pos along dir.
Throws an ArgumentError if num_rays is below BeamletOptics.min_num_rays of the sampling or for BeamletOptics.NoSampling, and an ErrorException if the sampling type has no method. Used by the constructors of the sources and by num_rays!.
BeamletOptics.source_beams Method
source_beams(sampling::Union{ConeRings, ConeSunflower, ConeFan}, pos, dir, b1, λ, num_rays, T)Beams of a PointSource at pos [m] around the unit vector dir with the wavelength λ [m], sampled by sampling (which holds the half spread angle) with num_rays rays. b1 is the unit sampling reference vector normal to dir, see sampling_basis. For ConeFan, the rays lie in the plane spanned by dir and b1. The angles are computed in T.
BeamletOptics.source_beams Method
source_beams(sampling::Union{DiscRings, DiscSunflower, DiscLine}, pos, dir, b1, diameter, λ, num_rays, T)Beams of a CollimatedSource whose disc with the diameter [m] is centered at pos [m] normal to the unit vector dir, with the wavelength λ [m], sampled by sampling with num_rays rays. b1 is the unit sampling reference vector normal to dir, see sampling_basis. For DiscLine, the rays lie on the diameter of the disc along b1.
BeamletOptics.sphere_chord Function
sphere_chord(sphere::AbstractBoundingSphere, ray, margin = 0)Returns (b, s) such that the line of the ray passes through the sphere between the path lengths b - s and b + s in [m], or nothing if the line misses the sphere. The radius is enlarged by the margin in [m] and by the rounding error of the test, such that a ray towards a point on the sphere still passes through it.
BeamletOptics.sphere_phase Method
sphere_phase(x, y, R, k)Phase sign(R) k (√(ρ² + R²) − |R|) of a reference sphere with the radius R about the axis through x = y = 0, without cancellation for ρ ≪ |R|. Zero for R = Inf.
BeamletOptics.spot_diagram Method
spot_diagram(d::Detector; num_spots = 50, crop_factor = 1)Returns an array of 2D points in the local (x, z) coordinates of the detector in [m] that represent where the incoming beams hit it.
Beams
For Beams, the point of intersection on the screen surface is returned. The keywords are ignored.
Beamlets
For GaussianBeamlets and AstigmaticGaussianBeamlets, each hit gives a contour of num_spots points: the 1/e² beam radius at the detector, scaled by crop_factor and projected onto the detector along the chief ray.
A detector that no beam hit returns no points, an empty vector.
sourceBeamletOptics.studio_lighting! Method
studio_lighting!(ax::Union{LScene, Axis3}; preset = :studio)Sets up a CAD-like lighting rig in the 3D view ax, if a suitable backend is loaded: an ambient light, a key light from the upper right front, a fill light from the left and a rim light from behind, all relative to the camera. Backends with a single directional light (e.g. CairoMakie) get the ambient and the key light only. preset = :none leaves the lights unchanged. The GUI of the package BeamletOpticsGUI applies the rig by default, scenes created via render! call it explicitly.
If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.sunflower_fraction Method
sunflower_fraction(k, n, T)The area (or solid angle) fraction of the k-th of n sunflower samples (k = 0 … n-1) in the number type T: 0 for the center, (k + ½)/n for the others.
BeamletOptics.thickness Method
thickness(s::AbstractSDF)Returns the material of s on its optical axis (local y) in [m]. Throws for a shape without its own method.
BeamletOptics.thickness Method
thickness(cylinder::CylinderSDF)Returns the height of the cylinder, i.e. twice the height field.
BeamletOptics.thickness Method
thickness(difference)Calculates the thickness of a DifferenceSDF as the thickness of its base — removing material cannot increase the axial extent.
BeamletOptics.thickness Method
Returns 0: the ring has no material on its optical axis, hence a mount ring does not add to the thickness of a lens.
sourceBeamletOptics.thickness Method
thickness(union)Calculates the thickness of a union of AbstractLensSDFs as the sum of the thicknesses of its operands, e.g. 0 for a mount ring. Throws for an operand without its own thickness.
BeamletOptics.trace_all Method
trace_all(system::AbstractSystem, ray::AbstractRay)Returns the closest Intersection of the ray with the objects of the system, or nothing. The objects that the ray hits within get_coincidence_tolerance() of the closest hit, e.g. touching faces, are its coincident_hits. An object whose bounding sphere the ray enters only beyond the closest hit found so far is not tested.
BeamletOptics.trace_one Method
trace_one(system::AbstractSystem, ray::AbstractRay, hint::Hint)Returns the closest Intersection of the ray with the objects of the system like trace_all, but tests the hinted object first. Its hit lets the solver skip all objects that lie beyond it, hence the hint speeds up the trace but does not change the closest hit. Among the coincident_hits at the closest point, the hit of the hinted shape comes first.
BeamletOptics.trace_system! Method
trace_system!(system::AbstractSystem, beam::Beam{T}; r_max = get_default_r_max()) where {T <: Real}Trace a Beam through an optical system. The number of rays of the beam 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 further objects are hit, the tracing procedure is stopped.
Arguments
system: The optical system through which theBeamis traced.beam: TheBeamobject to be traced.r_max: Maximum number of rays of thebeam, which ends the tracing.
BeamletOptics.trace_system! Method
trace_system!(system, agb::AstigmaticGaussianBeamlet; r_max = get_default_r_max(), check_invariant = true, threshold = get_invariant_threshold())Trace an AstigmaticGaussianBeamlet through an optical system. The number of rays of each component beam can be capped by r_max. 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.
BeamletOptics.trace_system! Method
trace_system!(system::AbstractSystem, gauss::GaussianBeamlet{T}; r_max = get_default_r_max(), check_invariant = true) where {T <: Real}Trace a GaussianBeamlet through an optical system. The number of rays of each component beam can be capped by r_max.
Tracing logic
The chief, waist and divergence beams are traced step-by-step through the system. For each intersection after a tracing_step!, the intersections are compared. If all rays hit the same target, the optical interaction is analyzed, else the tracing stops. Tracing also stops with a warning if the Lagrange invariant of a new segment leaves get_lagrange_tolerance of its start value.
Arguments
system: The optical system through which theGaussianBeamletis traced.gauss: TheGaussianBeamletobject to be traced.r_max: Maximum number of rays of each component beam, which ends the tracing.check_invariant: enables or disables the check of the Lagrange invariant.
BeamletOptics.tracing_step! Method
tracing_step!(system::AbstractSystem, ray::AbstractRay{R}, hint::Hint)Tests if the ray intersects an object in the optical system. Stores the closest intersection, or nothing if there is none, in the ray via intersection! and returns nothing.
Hint
An optional Hint only speeds up the test, see trace_one: the hinted object is tested first, and the objects beyond its hit are skipped. A closer hit of another object wins. Among the coincident_hits at the closest point, the hit of the hinted shape comes first, hence the solver calls interact3d for the object of the hint there. For a MultiShape component the hint names the composite, not the part.
BeamletOptics.translate3d! Method
translate3d!(x, offset)Moves x by the offset vector. See BeamletOptics.Movable.
BeamletOptics.translate3d! Method
translate3d!(::Movable, beam::AbstractBeam, offset)Resets the root beam to its untraced start state and moves the start ray of every component beam by offset. Throws an ArgumentError for child beams.
BeamletOptics.translate3d! Method
translate3d!(::Movable, bg::AbstractBeamGroup, offset)Moves all beams of the group and its center by offset, a beam listed several times once. Every beam is reset to its untraced start state.
BeamletOptics.translate3d! Method
translate3d!(::Movable, c::AbstractCompositeSDF, offset)Translates c and all of its operands by offset, an operand listed several times once.
BeamletOptics.translate3d! Method
translate3d!(::Movable, detector::AbstractDetector, offset)Empties the detector (see empty!) and moves it by offset. Its hits lie on the surface where it was during the solve, hence they are discarded when it moves. All kinematic functions are derived from this one and rotate3d!(::Movable, ::AbstractDetector, R), so each of them empties the detector, also when it moves as a member of an ObjectGroup.
BeamletOptics.translate3d! Method
translate3d!(::Movable, mesh::AbstractMesh, offset)Mutating function that translates the vertices of an mesh in relation to the offset vector. In addition, the mesh position vector is overwritten to reflect the new "center of gravity".
sourceBeamletOptics.translate3d! Method
translate3d!(::Movable, group::AbstractObjectGroup, offset)Moves all objects of the group and its center by offset. Every object and subgroup moves once, also if the group holds it along several paths, see the containers in BeamletOptics.AbstractKinematicTrait.
BeamletOptics.translate3d! Method
translate3d!(::Movable, shape::AbstractShape, offset)Translates the position of shape by the offset-vector.
BeamletOptics.translate3d! Method
translate3d!(::MultiShape, object, offset)Moves all parts of the MultiShape object along the specified offset vector, a part that shape(object) lists several times once.
BeamletOptics.translate3d! Method
translate3d!(::Movable, ray::AbstractRay, offset)Moves the start position of the ray by offset and clears its intersection.
BeamletOptics.translate_to3d! Method
translate_to3d!(x, target)Moves x such that its position coincides with target. See BeamletOptics.Movable.
BeamletOptics.transmission_axis Method
transmission_axis(lp::LinearPolarizer)Returns the unit vector (in global coordinates) along which LinearPolarizer lp transmits polarization. Refer to transmission_axis(::PolarizationFilter) for details.
BeamletOptics.transmission_axis Method
transmission_axis(pf::PolarizationFilter)Returns the unit vector (in global coordinates) along which PolarizationFilter pf transmits polarization, derived from its Jones matrix so that it stays correct for any filter orientation or custom GlobalJonesBasis. The sign of the returned vector is arbitrary, since it represents an axis rather than a direction.
BeamletOptics.transverse_field Method
transverse_field(E1, E2, e1, e2, n, d)The field with the tangential components E1, E2 along e1, e2 of a plane with the normal n, completed by the normal component that makes it transverse to the direction d.
BeamletOptics.transverse_profile Method
transverse_profile(h1, u1, h2, u2, r, d, area, nk)Transverse factor of the field at the offset r from the chief ray with direction d, with the wavenumber nk of the medium. The phase is the real part of r^T Q r / 2. The decay is exp(-r^T S⁻¹ r) with the spot matrix S = Re(H H†), so that the field follows the beam radius for any M2: Im Q is S⁻¹ only for M2 = 1 and while the Lagrange invariants hold. As H H† = S + i c J, det S = |area|² + c² with c = [Re h1, Im h1] + [Re h2, Im h2], which is nonzero e.g. for M2_x ≠ M2_y behind a rotated astigmatic element. The factor (|area|² / det S)^(1/4) then keeps the power of the beam area.
BeamletOptics.unwind Method
unwind(group) -> (subgroups, leaves)Unwinds the tree of group for one rigid motion, each node once, compared by identity (===): the subgroups, including group, move their center and dir; the leaves are its objects, which are moved with their public verbs, see _movable_parts.
BeamletOptics.update_render! Method
update_render!(handle)Re-synchronizes the plots of the handle with the current state of the rendered object or beam, e.g. after moving components or calling solve_system!. Keep render handles on root beams and groups: child beams and all rays after the first are new objects after every solve.
If no suitable backend is loaded, a MissingBackendError will be thrown.
BeamletOptics.visibility Method
visibility(opt_pwr)Calculates e.g. the interferometric contrast from a series of optical power measurements. For more information go here.
sourceBeamletOptics.waist_parameters Method
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.
BeamletOptics.waist_parameters Method
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).
BeamletOptics.wavefront_beamlets Method
wavefront_beamlets(x, y, amp, pos, dir, λ, T, Δφ, ∇φ0, skip, field, waist; threshold, overlap, basis, randomize_axes, rng)The beamlet group of a sampled field with the amplitude amp on the grid x, y at pos. The calling method supplies the phase step Δφ(a, b), the known gradient ∇φ0(i, j, k), an extra skip(i, j), the field field(i, j, d, c, axes, k) scaled by c and the waist waist(w0s, i, j) -> (w0, z0) of a sub-waist w0s.
BeamletOptics.wavelength Method
wavelength(x)The wavelength [m] of the ray x, of a Beam (its first ray), of a GaussianBeamlet, an AstigmaticGaussianBeamlet or of a beam group (its first beam).
BeamletOptics.wavelength_color Method
wavelength_color(λ) -> NTuple{3, Float64}The display color (r, g, b) (each in [0, 1], sRGB) of light of the vacuum wavelength λ [m], e.g. to draw rays in the color of their wavelength, see the color = :wavelength option of render!. Uses the piecewise linear approximation of Dan Bruton (violet at 380 nm over blue, cyan, green, yellow and orange to red at 780 nm) with a gamma of 0.8, and the intensity falls off to 30 % towards both ends of the visible range (380 to 420 nm and 700 to 780 nm).
Outside of 380 to 780 nm there is no visible color: the color of the nearest end of the spectrum is returned, i.e. a dim violet for UV and a dim red for IR, such that rays of an invisible wavelength are still drawn, and the color stays continuous. The result is a perceptual approximation for plots, not a colorimetric conversion.
The function is plain Julia and needs no plotting backend. Throws an ArgumentError unless λ is positive and finite.
wavelength_color(450e-9) # blue
wavelength_color(650e-9) # redBeamletOptics.with_bounding_spheres Method
with_bounding_spheres(f, system::AbstractSystem)
with_bounding_spheres(f, table::BoundingSphereTable)Calls f() with the bounding spheres of the system, or the given table, as the table of the current task. A table that is already set is kept when a system is given.
BeamletOptics.with_hit_buffers Method
with_hit_buffers(f)Calls f() such that the hits that the current task pushes to a Detector are collected in a buffer of the task, and appends them to their detectors when f returns or throws, one append! per detector. The solve of a beam group calls it in each of its tasks, which then do not wait for the lock of a detector at every hit. The hits are stored when with_hit_buffers returns, not while f runs.
BeamletOptics.xrotate3d! Method
xrotate3d!(x, θ)Rotates x by the angle θ [rad] about the global x-axis through its position. See BeamletOptics.Movable.
BeamletOptics.yrotate3d! Method
yrotate3d!(x, θ)Rotates x by the angle θ [rad] about the global y-axis through its position. See BeamletOptics.Movable.
BeamletOptics.zrotate3d! Method
zrotate3d!(x, θ)Rotates x by the angle θ [rad] about the global z-axis through its position. See BeamletOptics.Movable.
BeamletOptics.Config Module
ConfigGlobal configuration settings for the BeamletOptics package using Preferences.jl.
sourceBeamletOptics.Config.get_coincidence_tolerance Method
get_coincidence_tolerance()Returns the path length in [m] within which the hits of a ray with several surfaces count as one point, e.g. the faces of two cemented lenses or a coating on a substrate. Gaps below this length are taken as contact. The default of 1 nm lies far below any gap that matters optically.
The tolerance must exceed the error of the hits in path length. A refined SDF hit lies much closer to the surface, but the exit of a ray that grazes an SDF surface from inside can lie up to get_sdf_surface_threshold() off the surface, i.e. this length divided by the cosine of the angle of incidence along the ray. Raising the surface threshold therefore calls for a larger tolerance.
BeamletOptics.Config.get_default_depth_max Method
get_default_depth_max()Returns the default maximum number of branching levels of the beam tree, the keyword depth_max of solve_system!: the children of a beam at level depth_max + 1 (the root beam is at level 1), e.g. those attached by a beamsplitter, are dropped. Defaults to 100 (configurable via the default_depth_max preference).
BeamletOptics.Config.get_default_power Method
get_default_power()Returns the default beam total power in Watts.
sourceBeamletOptics.Config.get_default_r_max Method
get_default_r_max()Returns the default maximum number of rays (segments) per beam, the keyword r_max of solve_system!. Defaults to 100 (configurable via the default_r_max preference).
BeamletOptics.Config.get_default_waist Method
get_default_waist()Returns the default beam waist radius in meters.
sourceBeamletOptics.Config.get_default_wavelength Method
get_default_wavelength()Returns the default wavelength in meters.
sourceBeamletOptics.Config.get_internal_reflection_threshold Method
Returns the global configuration threshold for total internal reflection detection, dimensionless: a reflection counts as total if the reflectances |rs|² and |rp|² both deviate from 1 by at most this value. Defaults to 1e-6 (configurable via the internal_reflection_threshold preference).
BeamletOptics.Config.get_invariant_threshold Method
get_invariant_threshold()Returns the global configuration threshold for the paraxial optical invariant check: the limit in [m] of the complex coupling invariant h1 ⋅ u2 - h2 ⋅ u1 of an astigmatic beamlet, with the ray heights h in [m] and the dimensionless slopes u. Defaults to 1e-6. The Lagrange invariants of both beamlets use get_lagrange_tolerance.
BeamletOptics.Config.get_lagrange_tolerance Method
get_lagrange_tolerance()Returns the largest relative deviation of the Lagrange invariant of a GaussianBeamlet, or of an axis of an AstigmaticGaussianBeamlet, from its value at the start of the root beam, beyond which the beamlet has left the range of its model and tracing stops. Defaults to 0.5 (configurable via the lagrange_tolerance preference, see set_lagrange_tolerance!).
BeamletOptics.Config.get_line_plane_intersection_threshold Method
Returns the global configuration threshold for line-plane intersection calculations, dimensionless: a line whose direction has a dot product with the plane normal of at most this magnitude counts as parallel to the plane and does not intersect it. Defaults to 1e-6 (configurable via the line_plane_intersection_threshold preference).
BeamletOptics.Config.get_orthogonality_threshold Method
get_orthogonality_threshold()Returns the global configuration threshold for orthogonality checks (e.g., beam support axes), dimensionless: the largest magnitude of the dot product of two unit vectors that still counts as orthogonal. For the field E0 of a PolarizedRay it is scaled by |E0|. Defaults to 1e-10 (configurable via the orthogonality_threshold preference).
BeamletOptics.Config.get_progress_threshold Method
get_progress_threshold()Returns the runtime in seconds after which long-running calls (solve_system! on a beam group, electric_field, intensity and optical_power on a detector) show a progress bar in the terminal. Defaults to 5 s (configurable via the progress_threshold preference, see set_progress_threshold!). Inf disables all progress bars.
BeamletOptics.Config.get_sdf_miss_distance Method
get_sdf_miss_distance()Returns the path length in [m] after which a ray that is marched towards an SDF shape counts as a miss: a shape farther from the start of the ray than this is not hit. Defaults to 1e15 (configurable via the sdf_miss_distance preference).
BeamletOptics.Config.get_sdf_raymarch_eps Method
get_sdf_raymarch_eps()Returns the global configuration epsilon for the SDF ray marching algorithm, a distance in [m]: the SDF value below which the marched ray has reached the surface, and the minimum step. Defaults to 1e-10 (configurable via the sdf_raymarch_eps preference).
BeamletOptics.Config.get_sdf_surface_threshold Method
get_sdf_surface_threshold()Returns the global configuration threshold for the Signed Distance Field (SDF) surface detection: a ray whose start has an SDF value below this distance in [m] counts as starting on the surface. Defaults to 1e-9 (configurable via the sdf_surface_threshold preference).
BeamletOptics.Config.set_invariant_threshold! Method
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.
sourceBeamletOptics.Config.set_lagrange_tolerance! Method
set_lagrange_tolerance!(val::Real)Sets the largest relative deviation of the Lagrange invariant of a beamlet, see get_lagrange_tolerance. This preference is persistent. Please restart Julia for this to take effect.
BeamletOptics.Config.set_preference! Method
set_preference!(key::String, val)Stores the preference key with the value val for this package via Preferences.jl (it is kept in a LocalPreferences.toml, i.e. across Julia sessions) and logs a message. The configuration constants are read when the package is loaded, hence Julia must be restarted for a new value to take effect.
BeamletOptics.Config.set_progress_threshold! Method
set_progress_threshold!(val::Real)Sets the runtime in seconds after which long-running calls show a progress bar, see get_progress_threshold. Use Inf to disable progress bars globally. This preference is persistent. Please restart Julia for this to take effect.