Optics Core
Shared building blocks used by every lens model: base classes, optical surfaces, light/wave representations, and image-simulation utilities.
Base Classes
Base class for all optical objects. Provides device transfer, dtype conversion, and cloning by introspecting instance tensors.
deeplens.DeepObj
Base class for all differentiable optical objects in DeepLens.
Provides device management, dtype conversion, and deep-copy support via
automatic introspection over instance tensors and nested DeepObj
sub-objects. All lens, surface, material, ray, and wave objects inherit
from this class.
Attributes:
| Name | Type | Description |
|---|---|---|
dtype |
dtype
|
Current floating-point dtype of all owned tensors. |
device |
dtype
|
Current compute device (set by |
Source code in deeplens-src/deeplens/base.py
__str__
Called when using print() and str()
Source code in deeplens-src/deeplens/base.py
__call__
clone
to
Move all tensors and nested objects to device.
Recursively walks over every instance attribute and moves tensors,
nn.Module sub-objects, and nested DeepObj objects to the
requested device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
Target device, e.g. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
DeepObj |
|
Example
lens = GeoLens(filename="lens.json") lens.to("cuda") # move all tensors to GPU
Source code in deeplens-src/deeplens/base.py
astype
Convert all floating-point tensors to dtype.
Also calls torch.set_default_dtype(dtype) so that subsequent
tensor creation uses the same precision.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
dtype
|
Target floating-point dtype. Must be one of
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
DeepObj |
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If dtype is not a recognised floating-point dtype. |
Example
lens = GeoLens(filename="lens.json") lens.astype(torch.float64) # switch to double precision
Source code in deeplens-src/deeplens/base.py
Optical material model (refractive index and dispersion) used by refractive surfaces.
deeplens.Material
Bases: DeepObj
Optical material defined by its wavelength-dependent refractive index.
Materials are looked up by name in the bundled CDGM, SCHOTT, or MISC AGF
catalogs, in a custom JSON catalog, or specified inline as "n/V"
(Cauchy approximation from Abbe number V).
Supported dispersion models: "sellmeier", "cauchy", "schott",
and "interp" (lookup table).
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Lowercase material name. |
dispersion |
str
|
Dispersion model used ( |
n |
float
|
Refractive index at the d-line (587 nm). |
V |
float
|
Abbe number. |
Initialize an optical material.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str or None
|
Material name (case-insensitive). Accepted forms:
Defaults to |
None
|
device
|
str
|
Compute device. Defaults to |
'cpu'
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If name is not found in any catalog. |
Example
mat = Material("N-BK7") n_green = mat.get_ri(0.587) # refractive index at 587 nm
Source code in deeplens-src/deeplens/material/materials.py
load_dispersion
Load material dispersion equation.
Source code in deeplens-src/deeplens/material/materials.py
set_material_param_agf
Set the material parameters and dispersion equation from AGF file.
Source code in deeplens-src/deeplens/material/materials.py
set_sellmeier_param
Manually set sellmeier parameters k1, l1, k2, l2, k3, l3.
This function is used when we want to manually set the sellmeier parameters for a custom material.
Source code in deeplens-src/deeplens/material/materials.py
refractive_index
Compute the refractive index at given wvln.
ior
Compute the refractive index at given wvln.
Source code in deeplens-src/deeplens/material/materials.py
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | |
nV_to_AB
staticmethod
Convert (n ,V) paramters to (A, B) parameters to find the material.
Source code in deeplens-src/deeplens/material/materials.py
match_material
Find the closest material in the CDGM common glasses database.
Source code in deeplens-src/deeplens/material/materials.py
get_optimizer_params
Optimize the material parameters (n, V).
Optimizing refractive index is more important than optimizing Abbe number.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lrs
|
list
|
learning rates for n and V. Defaults to [1e-4, 1e-4]. |
[0.0001, 0.01]
|
Source code in deeplens-src/deeplens/material/materials.py
Surfaces
Geometric Surfaces
Base class for all geometric optical surfaces. Implements surface intersection (Newton's method with one differentiable step) and differentiable vector Snell's law refraction.
deeplens.geometric_surface.Surface
Bases: DeepObj
Base class for all geometric optical surfaces.
A surface sits at axial position d (mm) in the global coordinate
system, has an aperture radius r (mm), and separates two optical
media. Subclasses override _sag and _dfdxy to define
their shape.
Ray–surface interaction is handled by three stages, implemented in
ray_reaction:
- Coordinate transform – ray is brought into the local surface frame.
- Intersection – solved via Newton's method (
newtons_method), using a non-differentiable iteration loop followed by a single differentiable Newton step to enable gradient flow. - Refraction / reflection – vector Snell's law (
refract) or specular reflection (reflect).
Attributes:
| Name | Type | Description |
|---|---|---|
d |
Tensor
|
Axial position of the surface vertex [mm]. |
r |
float
|
Aperture radius [mm]. |
mat2 |
Material
|
Optical material on the transmission side. |
is_square |
bool
|
If |
Initialize a generic optical surface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r
|
float
|
Aperture radius [mm]. |
required |
d
|
float
|
Axial position of the surface vertex [mm]. |
required |
mat2
|
str or Material
|
Material on the transmission side
(e.g. |
required |
pos_xy
|
list[float]
|
Lateral offset |
[0.0, 0.0]
|
vec_local
|
list[float]
|
Local normal direction.
Defaults to |
[0.0, 0.0, 1.0]
|
is_square
|
bool
|
Use a square aperture.
Defaults to |
False
|
device
|
str
|
Compute device. Defaults to |
'cpu'
|
Source code in deeplens-src/deeplens/geometric_surface/base.py
init_from_dict
classmethod
ray_reaction
Compute the output ray after intersection and refraction/reflection.
Transforms the ray to the local surface frame, solves the intersection via Newton's method, applies vector Snell's law (or specular reflection), then transforms back to global coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
Incident ray bundle. |
required |
n1
|
float
|
Refractive index of the incident medium. |
required |
n2
|
float
|
Refractive index of the transmission medium. |
required |
refraction
|
bool
|
If |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
Ray |
Updated ray bundle after the surface interaction. |
Source code in deeplens-src/deeplens/geometric_surface/base.py
intersect
Solve ray-surface intersection in local coordinate system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
input ray. |
required |
n
|
float
|
refractive index. Defaults to 1.0. |
1.0
|
Source code in deeplens-src/deeplens/geometric_surface/base.py
newtons_method
Solve intersection by Newton's method in local coordinate system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
input ray. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
t |
tensor
|
intersection time. |
valid |
tensor
|
valid mask. |
Source code in deeplens-src/deeplens/geometric_surface/base.py
refract
Calculate refracted ray according to Snell's law in local coordinate system.
Normal vector points from the surface toward the side where the light is coming from. d is already normalized if both n and ray.d are normalized.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
incident ray. |
required |
eta
|
float
|
ratio of indices of refraction, eta = n_i / n_t |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ray |
Ray
|
refracted ray. |
References
[1] https://registry.khronos.org/OpenGL-Refpages/gl4/html/refract.xhtml [2] https://en.wikipedia.org/wiki/Snell%27s_law, "Vector form" section.
Source code in deeplens-src/deeplens/geometric_surface/base.py
bend_penalty
Accumulate soft per-surface bend penalty onto ray.
Penalty rises smoothly once the bend angle between old_d and the
refracted ray.d exceeds bend_angle_max and stays near zero for
mild refractions. Normalization by bend_scale = 1 - cos_bend_min keeps
the gradient magnitude consistent with the CRA loss in optim.py.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
ray after refraction (ray.d is the new direction). |
required |
old_d
|
Tensor
|
pre-refraction ray directions, same shape as ray.d. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Ray |
ray with updated bend_penalty. |
Source code in deeplens-src/deeplens/geometric_surface/base.py
reflect
Calculate reflected ray in local coordinate system.
Normal vector points from the surface toward the side where the light is coming from.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
incident ray. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ray |
Ray
|
reflected ray. |
References
[1] https://registry.khronos.org/OpenGL-Refpages/gl4/html/reflect.xhtml [2] https://en.wikipedia.org/wiki/Snell%27s_law, "Vector form" section.
Source code in deeplens-src/deeplens/geometric_surface/base.py
normal_vec
Calculate surface normal vector at the intersection point in local coordinate system.
Normal vector points from the surface toward the side where the light is coming from.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
input ray. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
n_vec |
tensor
|
surface normal vector. |
Source code in deeplens-src/deeplens/geometric_surface/base.py
to_local_coord
Transform ray to local coordinate system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
input ray in global coordinate system. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ray |
Ray
|
transformed ray in local coordinate system. |
Source code in deeplens-src/deeplens/geometric_surface/base.py
to_global_coord
Transform ray to global coordinate system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
input ray in local coordinate system. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ray |
Ray
|
transformed ray in global coordinate system. |
Source code in deeplens-src/deeplens/geometric_surface/base.py
sag
Calculate sag (z) of the surface: z = f(x, y).
Valid term is used to avoid NaN when x, y exceed the data range, which happens in spherical and aspherical surfaces.
Calculating r = sqrt(x2, y2) may cause an NaN error during back-propagation. Because dr/dx = x / sqrt(x2 + y2), NaN will occur when x=y=0.
Source code in deeplens-src/deeplens/geometric_surface/base.py
dfdxyz
Compute derivatives of surface function. Surface function: f(x, y, z): sag(x, y) - z = 0. This function is used in Newton's method and normal vector calculation.
There are several methods to compute derivatives of surfaces
[1] Analytical derivatives: The current implementation is based on this method. But the implementation only works for surfaces which can be written as z = sag(x, y). For implicit surfaces, we need to compute derivatives (df/dx, df/dy, df/dz). [2] Numerical derivatives: Use finite difference method to compute derivatives. This can be used for those very complex surfaces, for example, NURBS. But it may suffer from numerical instability when the surface is very steep. [3] Automatic differentiation: Use torch.autograd to compute derivatives. This can work for almost all the surfaces and is accurate, but it requires an extra backward pass to compute the derivatives of the surface function.
Source code in deeplens-src/deeplens/geometric_surface/base.py
d2fdxyz2
Compute second-order partial derivatives of the surface function f(x, y, z): sag(x, y) - z = 0. This function is currently only used for surfaces constraints.
Source code in deeplens-src/deeplens/geometric_surface/base.py
is_valid
Valid points within the data range and boundary of the surface.
is_within_boundary
Valid points within the boundary of the surface.
Source code in deeplens-src/deeplens/geometric_surface/base.py
is_within_data_range
max_height
surface_with_offset
Calculate z coordinate of the surface at (x, y).
This function is used in lens setup plotting and lens self-intersection detection.
Source code in deeplens-src/deeplens/geometric_surface/base.py
surface_sag
Calculate sag of the surface at (x, y).
This function is currently not used.
Source code in deeplens-src/deeplens/geometric_surface/base.py
get_optimizer_params
Get optimizer parameters for different parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lrs
|
list
|
learning rates for different parameters. |
[0.0001]
|
optim_mat
|
bool
|
whether to optimize material. Defaults to False. |
False
|
Source code in deeplens-src/deeplens/geometric_surface/base.py
get_optimizer
update_r
draw_r
draw_widget
Draw widget for the surface on the 2D plot.
Source code in deeplens-src/deeplens/geometric_surface/base.py
create_mesh
Create triangulated surface mesh.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_rings
|
int
|
Number of concentric rings for sampling. |
32
|
n_arms
|
int
|
Number of angular divisions. |
128
|
color
|
List[float]
|
The color of the mesh. |
[0.06, 0.3, 0.6]
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
The surface with mesh data. |
Source code in deeplens-src/deeplens/geometric_surface/base.py
get_polydata
Get PyVista PolyData object from previously generated vertices and faces.
PolyData object will be used to draw the surface and export as .obj file.
Source code in deeplens-src/deeplens/geometric_surface/base.py
zmx_str
Spherical surface defined by curvature \(c = 1/R\).
deeplens.geometric_surface.Spheric
Bases: Surface
Spherical refractive surface parameterized by curvature.
The sag function is:
.. math::
z(x, y) = \frac{c \rho^2}{1 + \sqrt{1 - c^2 \rho^2}}, \quad
\rho^2 = x^2 + y^2
Attributes:
| Name | Type | Description |
|---|---|---|
c |
Tensor
|
Surface curvature |
Initialize a spherical surface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
c
|
float
|
Surface curvature |
required |
r
|
float
|
Aperture radius [mm]. |
required |
d
|
float
|
Axial vertex position [mm]. |
required |
mat2
|
str or Material
|
Material on the transmission side. |
required |
pos_xy
|
list[float]
|
Lateral offset |
[0.0, 0.0]
|
vec_local
|
list[float]
|
Local normal direction.
Defaults to |
[0.0, 0.0, 1.0]
|
is_square
|
bool
|
Square aperture flag. Defaults to
|
False
|
device
|
str
|
Compute device. Defaults to |
'cpu'
|
Source code in deeplens-src/deeplens/geometric_surface/spheric.py
intersect
Solve ray-surface intersection in local coordinate system using analytical method.
Sphere equation: (x)^2 + (y)^2 + (z - R)^2 = R^2, where R = 1/c Ray equation: p(t) = o + t*d Solve quadratic equation for intersection parameter t.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
input ray. |
required |
n
|
float
|
refractive index. Defaults to 1.0. |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
ray |
Ray
|
ray with updated position and opl. |
Source code in deeplens-src/deeplens/geometric_surface/spheric.py
is_within_data_range
max_height
get_optimizer_params
Activate gradient computation for c and d and return optimizer parameters.
Source code in deeplens-src/deeplens/geometric_surface/spheric.py
surf_dict
Return surface parameters.
Source code in deeplens-src/deeplens/geometric_surface/spheric.py
zmx_str
Return Zemax surface string.
Source code in deeplens-src/deeplens/geometric_surface/spheric.py
Even-asphere surface: spherical base with polynomial corrections.
deeplens.geometric_surface.Aspheric
Aspheric(r, d, c, k, ai, mat2, ai2=None, pos_xy=[0.0, 0.0], vec_local=[0.0, 0.0, 1.0], is_square=False, device='cpu')
Bases: Surface
Even-order aspheric surface.
The sag function is:
.. math::
z(\rho) = \frac{c\,\rho^2}{1 + \sqrt{1-(1+k)c^2\rho^2}}
+ \sum_{i=2}^{n} a_{2i}\,\rho^{2i},
\quad \rho^2 = x^2 + y^2
The polynomial starts at the 4th-order term (a4) because the 2nd-order
term competes with the base curvature c.
All coefficients c, k, and ai are differentiable torch
tensors so they can be optimised with gradient descent.
Attributes:
| Name | Type | Description |
|---|---|---|
c |
Tensor
|
Base curvature [1/mm]. |
k |
Tensor
|
Conic constant. |
ai2 |
Tensor or None
|
2nd-order aspheric coefficient (legacy). |
ai |
Tensor
|
Even-order aspheric coefficients
|
Initialize an aspheric surface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r
|
float
|
Aperture radius [mm]. |
required |
d
|
float
|
Axial vertex position [mm]. |
required |
c
|
float
|
Base curvature |
required |
k
|
float
|
Conic constant ( |
required |
ai
|
list[float] or None
|
Even-order aspheric coefficients
starting from the 4th-order term: |
required |
mat2
|
str or Material
|
Material on the transmission side. |
required |
ai2
|
float or None
|
2nd-order aspheric coefficient
from legacy data. Included in sag but not optimised.
Defaults to |
None
|
pos_xy
|
list[float]
|
Lateral offset |
[0.0, 0.0]
|
vec_local
|
list[float]
|
Local normal direction.
Defaults to |
[0.0, 0.0, 1.0]
|
is_square
|
bool
|
Square aperture flag.
Defaults to |
False
|
device
|
str
|
Compute device. Defaults to |
'cpu'
|
Source code in deeplens-src/deeplens/geometric_surface/aspheric.py
is_within_data_range
Invalid when shape is non-defined.
Fully tensorized (no Python branch on the tensor value of k) so
the function is safe to trace through torch.compile. When
k <= -1 the conic has no real boundary, so every point is
treated as valid.
Source code in deeplens-src/deeplens/geometric_surface/aspheric.py
max_height
get_optimizer_params
Get optimizer parameters for different parameters.
The learning rate for each aspheric coefficient a_{2n} is scaled
by 1 / max(r, 1)^{2n} so that the effective sag perturbation per
Adam step is approximately constant (~lr_base mm) regardless of
surface semi-diameter. Without this normalisation, gradients scale
as O(r^{2n}) and can reach 10^5 for camera-sized surfaces,
causing NaN within a few dozen iterations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lrs
|
list
|
learning rates for |
[0.0001, 0.0001, 0.01, 0.0001]
|
optim_mat
|
bool
|
whether to optimize material. Defaults to False. |
False
|
Source code in deeplens-src/deeplens/geometric_surface/aspheric.py
surf_dict
Return a dict of surface.
Source code in deeplens-src/deeplens/geometric_surface/aspheric.py
zmx_str
Return Zemax surface string.
Source code in deeplens-src/deeplens/geometric_surface/aspheric.py
deeplens.geometric_surface.Aperture
Bases: Plane
Aperture surface.
Source code in deeplens-src/deeplens/geometric_surface/aperture.py
ray_reaction
Compute output ray after intersection and refraction.
Source code in deeplens-src/deeplens/geometric_surface/aperture.py
draw_widget
Draw aperture wedge on the figure.
Source code in deeplens-src/deeplens/geometric_surface/aperture.py
draw_widget3D
Draw the aperture as a circle in a 3D plot.
Source code in deeplens-src/deeplens/geometric_surface/aperture.py
create_mesh
Create triangulated surface mesh.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_rings
|
int
|
Number of concentric rings for sampling. |
32
|
n_arms
|
int
|
Number of angular divisions. |
128
|
color
|
List[float]
|
The color of the mesh. |
[0.0, 0.0, 0.0]
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
The surface with mesh data. |
Source code in deeplens-src/deeplens/geometric_surface/aperture.py
get_optimizer_params
Activate gradient computation for d and return optimizer parameters.
Source code in deeplens-src/deeplens/geometric_surface/aperture.py
surf_dict
Dict of surface parameters.
Source code in deeplens-src/deeplens/geometric_surface/aperture.py
zmx_str
Phase Surfaces
Phase surfaces model flat diffractive optical elements (DOEs) and metasurfaces
via a wavelength-scaled phase profile. All classes inherit from Phase and
implement phi() (phase map) and dphi_dxy() (phase gradient) for the
generalized Snell's law deflection in diffract().
Note:
Phase.diffract()treats the phase profile as wavelength-independent. Only the λ scaling in the generalized Snell's law and the OPL accumulation vary with wavelength. For a physical DOE whose phase profile changes with wavelength via the height–index relation(n(λ)−1)·h, useDiffractiveSurfaceinstead.
deeplens.phase_surface.Phase
Phase(r, d, norm_radii=None, mat2='air', pos_xy=(0.0, 0.0), vec_local=(0.0, 0.0, 1.0), is_square=True, device='cpu')
Bases: DeepObj
Base phase profile for diffractive surfaces (metasurface or DOE).
This is the base class that provides common functionality for all phase parameterizations. Specific parameterizations should inherit from this class.
Reference
[1] https://support.zemax.com/hc/en-us/articles/1500005489061-How-diffractive-surfaces-are-modeled-in-OpticStudio [2] https://optics.ansys.com/hc/en-us/articles/360042097313-Small-Scale-Metalens-Field-Propagation [3] https://optics.ansys.com/hc/en-us/articles/18254409091987-Large-Scale-Metalens-Ray-Propagation
Source code in deeplens-src/deeplens/phase_surface/phase.py
phi
Reference phase map at design wavelength. Must be implemented by subclasses.
dphi_dxy
Calculate phase derivatives. Must be implemented by subclasses.
ray_reaction
Ray reaction on DOE surface.
Source code in deeplens-src/deeplens/phase_surface/phase.py
intersect
Solve ray-plane intersection in local coordinate system and update ray data.
Source code in deeplens-src/deeplens/phase_surface/phase.py
diffract
Diffraction of a phase surface.
Step 1. The phase φ in radians adds to the optical path length of the ray.
Step 2. The gradient of the phase profile (phase slope) changes the direction
of rays via the generalized Snell's law:
n₂·sin(θ₂) = n₁·sin(θ₁) + m · λ / (2π) · dφ/dx
After standard refraction has already been applied, the remaining
phase deflection on the unit direction vector is:
Δl = m · λ / (2π · n₂) · dφ/dx
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray object with position, direction, and wavelength. |
required | |
n2
|
Refractive index of the medium after the surface. Required for correct generalized Snell's law: deflection scales as 1/n₂. |
1.0
|
Note
Material dispersion is not modelled here. The phase profile φ(x,y)
is treated as wavelength-independent; only the λ scaling in the
generalized Snell's law and the OPL accumulation vary with wavelength.
For a physical DOE whose phase profile itself changes with wavelength
(via (n(λ)-1)·h), use DiffractiveSurface instead.
Reference
[1] https://support.zemax.com/hc/en-us/articles/1500005489061-How-diffractive-surfaces-are-modeled-in-OpticStudio [2] Light propagation with phase discontinuities: generalized laws of reflection and refraction. Science 2011.
Source code in deeplens-src/deeplens/phase_surface/phase.py
refract
Calculate refracted ray according to Snell's law in local coordinate system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
incident ray. |
required |
eta
|
float
|
ratio of indices of refraction, eta = n_i / n_t |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ray |
Ray
|
refracted ray. |
Source code in deeplens-src/deeplens/phase_surface/phase.py
normal_vec
Calculate surface normal vector at intersection points.
Normal vector points from the surface toward the side where the light is coming from.
Source code in deeplens-src/deeplens/phase_surface/phase.py
to_local_coord
Transform ray to local coordinate system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
input ray in global coordinate system. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ray |
Ray
|
transformed ray in local coordinate system. |
Source code in deeplens-src/deeplens/phase_surface/phase.py
to_global_coord
Transform ray to global coordinate system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
input ray in local coordinate system. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ray |
Ray
|
transformed ray in global coordinate system. |
Source code in deeplens-src/deeplens/phase_surface/phase.py
get_optimizer_params
Generate optimizer parameters. Must be implemented by subclasses.
Source code in deeplens-src/deeplens/phase_surface/phase.py
get_optimizer
Generate optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lrs
|
list or float
|
Learning rates for different parameters. |
required |
Source code in deeplens-src/deeplens/phase_surface/phase.py
update_r
Update surface radius. A flat phase surface has no geometric
height constraint, and because the polynomial is normalized by a
fixed norm_radii, phase coefficients do not need rescaling.
Source code in deeplens-src/deeplens/phase_surface/phase.py
phase2height_map
Convert the phase map to a physical height map for DOE fabrication.
Derived from the phase-height relation of a transmissive DOE in air
φ = 2π/λ · (n−1) · h → h = φ · λ / (2π · (n−1))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
design_wvln
|
Design wavelength [um]. |
required | |
refractive_idx
|
Refractive index of the DOE material at |
1.5
|
|
res
|
Pixel resolution of the returned height map (square grid). |
512
|
Returns:
| Type | Description |
|---|---|
|
Tensor of shape |
|
|
as |
Source code in deeplens-src/deeplens/phase_surface/phase.py
draw_r
surface_with_offset
draw_phase_map
Draw phase map. Range from [0, 2*pi].
Source code in deeplens-src/deeplens/phase_surface/phase.py
draw_widget
Draw DOE as a two-side surface.
Source code in deeplens-src/deeplens/phase_surface/phase.py
save_ckpt
Save DOE parameters. Must be implemented by subclasses.
load_ckpt
Load DOE parameters. Must be implemented by subclasses.
surf_dict
deeplens.phase_surface.Binary2Phase
Binary2Phase(r, d, order2=0.0, order4=0.0, order6=0.0, order8=0.0, order10=0.0, order12=0.0, norm_radii=None, mat2='air', pos_xy=(0.0, 0.0), vec_local=(0.0, 0.0, 1.0), is_square=True, device='cpu')
Bases: Phase
Binary2 phase on a plane substrate.
Source code in deeplens-src/deeplens/phase_surface/binary2.py
init_from_dict
classmethod
Initialize Binary2 phase surface from dictionary.
Source code in deeplens-src/deeplens/phase_surface/binary2.py
phi
Reference phase map at design wavelength.
Source code in deeplens-src/deeplens/phase_surface/binary2.py
dphi_dxy
Calculate phase derivatives (dphi/dx, dphi/dy) for given points.
Source code in deeplens-src/deeplens/phase_surface/binary2.py
get_optimizer_params
Generate optimizer parameters.
Source code in deeplens-src/deeplens/phase_surface/binary2.py
save_ckpt
Save Binary2 DOE parameters.
Source code in deeplens-src/deeplens/phase_surface/binary2.py
load_ckpt
Load Binary2 DOE parameters.
Source code in deeplens-src/deeplens/phase_surface/binary2.py
zmx_str
Return Zemax BINARY_2 surface string.
PARM 1–8 are set to zero (flat substrate, no aspheric sag) so that Zemax interprets the XDAT entries purely as phase polynomial coefficients.
Source code in deeplens-src/deeplens/phase_surface/binary2.py
surf_dict
Return surface parameters.
Source code in deeplens-src/deeplens/phase_surface/binary2.py
deeplens.phase_surface.FresnelPhase
FresnelPhase(r, d, f0=100.0, norm_radii=None, mat2='air', pos_xy=(0.0, 0.0), vec_local=(0.0, 0.0, 1.0), is_square=True, device='cpu')
Bases: Phase
Fresnel phase on a plane substrate.
Source code in deeplens-src/deeplens/phase_surface/fresnel.py
init_from_dict
classmethod
Initialize FresnelPhase from a dictionary of parameters.
Source code in deeplens-src/deeplens/phase_surface/fresnel.py
phi
Reference phase map at design wavelength.
dphi_dxy
Calculate phase derivatives (dphi/dx, dphi/dy) for given points.
Source code in deeplens-src/deeplens/phase_surface/fresnel.py
get_optimizer_params
Generate optimizer parameters.
Source code in deeplens-src/deeplens/phase_surface/fresnel.py
save_ckpt
Save Fresnel DOE parameters.
load_ckpt
Load Fresnel DOE parameters.
surf_dict
Return surface parameters.
Source code in deeplens-src/deeplens/phase_surface/fresnel.py
deeplens.phase_surface.ZernikePhase
ZernikePhase(r, d, zernike_order=37, zernike_coeff=None, norm_radii=None, mat2='air', pos_xy=(0.0, 0.0), vec_local=(0.0, 0.0, 1.0), is_square=False, device='cpu')
Bases: Phase
Zernike phase on a plane substrate.
This class implements a diffractive surface using Zernike polynomials to represent the phase profile. It supports up to 37 Zernike terms. Inherits core ray-tracing functionality from Phase class.
Reference
[1] https://support.zemax.com/hc/en-us/articles/1500005489061-How-diffractive-surfaces-are-modeled-in-OpticStudio [2] https://optics.ansys.com/hc/en-us/articles/360042097313-Small-Scale-Metalens-Field-Propagation [3] https://optics.ansys.com/hc/en-us/articles/18254409091987-Large-Scale-Metalens-Ray-Propagation
Initialize Zernike phase surface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r
|
Radius of the surface |
required | |
d
|
Distance to next surface |
required | |
zernike_order
|
Number of Zernike terms (default: 37) |
37
|
|
norm_radii
|
Normalization radius (default: r) |
None
|
|
mat2
|
Material on the right side (default: "air") |
'air'
|
|
pos_xy
|
Position in xy plane |
(0.0, 0.0)
|
|
vec_local
|
Local coordinate system vector |
(0.0, 0.0, 1.0)
|
|
is_square
|
Whether the aperture is square |
False
|
|
device
|
Computation device |
'cpu'
|
Source code in deeplens-src/deeplens/phase_surface/zernike.py
init_from_dict
classmethod
Initialize Zernike phase surface from dictionary.
Source code in deeplens-src/deeplens/phase_surface/zernike.py
phi
Reference phase map at design wavelength using Zernike polynomials.
Overrides the parent Phase.phi() method to use Zernike polynomial representation.
Source code in deeplens-src/deeplens/phase_surface/zernike.py
dphi_dxy
Calculate phase derivatives (dphi/dx, dphi/dy) for given points.
Overrides the parent Phase.dphi_dxy() method to use Zernike derivatives.
Source code in deeplens-src/deeplens/phase_surface/zernike.py
get_optimizer_params
Generate optimizer parameters for Zernike coefficients.
Source code in deeplens-src/deeplens/phase_surface/zernike.py
save_ckpt
Save Zernike DOE coefficients.
Source code in deeplens-src/deeplens/phase_surface/zernike.py
load_ckpt
Load Zernike DOE coefficients.
surf_dict
Return surface parameters.
Source code in deeplens-src/deeplens/phase_surface/zernike.py
deeplens.phase_surface.PolyPhase
PolyPhase(r, d, order2=0.0, order3=0.0, order4=0.0, order5=0.0, order6=0.0, order7=0.0, norm_radii=None, mat2='air', pos_xy=(0.0, 0.0), vec_local=(0.0, 0.0, 1.0), is_square=True, device='cpu')
Bases: Phase
Polynomial phase on a plane substrate.
Source code in deeplens-src/deeplens/phase_surface/poly.py
phi
Reference phase map at design wavelength.
Source code in deeplens-src/deeplens/phase_surface/poly.py
dphi_dxy
Calculate phase derivatives (dphi/dx, dphi/dy) for given points.
Source code in deeplens-src/deeplens/phase_surface/poly.py
get_optimizer_params
Generate optimizer parameters.
Source code in deeplens-src/deeplens/phase_surface/poly.py
save_ckpt
Save Poly1D DOE parameters.
Source code in deeplens-src/deeplens/phase_surface/poly.py
load_ckpt
Load Poly1D DOE parameters.
Source code in deeplens-src/deeplens/phase_surface/poly.py
surf_dict
Return surface parameters.
Source code in deeplens-src/deeplens/phase_surface/poly.py
deeplens.phase_surface.CubicPhase
CubicPhase(r, d, coeff_x3=0.0, coeff_y3=0.0, coeff_x2y=0.0, coeff_xy2=0.0, coeff_x3y=0.0, coeff_xy3=0.0, norm_radii=None, mat2='air', pos_xy=(0.0, 0.0), vec_local=(0.0, 0.0, 1.0), is_square=True, device='cpu')
Bases: Phase
Cubic phase on a plane substrate.
Source code in deeplens-src/deeplens/phase_surface/cubic.py
phi
Reference phase map at design wavelength.
Source code in deeplens-src/deeplens/phase_surface/cubic.py
dphi_dxy
Calculate phase derivatives (dphi/dx, dphi/dy) for given points.
Source code in deeplens-src/deeplens/phase_surface/cubic.py
get_optimizer_params
Generate optimizer parameters.
Source code in deeplens-src/deeplens/phase_surface/cubic.py
save_ckpt
Save cubic DOE parameters.
Source code in deeplens-src/deeplens/phase_surface/cubic.py
load_ckpt
Load cubic DOE parameters.
Source code in deeplens-src/deeplens/phase_surface/cubic.py
surf_dict
Return surface parameters.
Source code in deeplens-src/deeplens/phase_surface/cubic.py
deeplens.phase_surface.GratingPhase
GratingPhase(r, d, theta=0.0, alpha=0.0, norm_radii=None, mat2='air', pos_xy=(0.0, 0.0), vec_local=(0.0, 0.0, 1.0), is_square=True, device='cpu')
Bases: Phase
Grating phase on a plane substrate.
Source code in deeplens-src/deeplens/phase_surface/grating.py
init_from_dict
classmethod
Initialize GratingPhase from a dictionary of parameters.
Source code in deeplens-src/deeplens/phase_surface/grating.py
phi
Reference phase map at design wavelength.
Source code in deeplens-src/deeplens/phase_surface/grating.py
dphi_dxy
Calculate phase derivatives (dphi/dx, dphi/dy) for given points.
Source code in deeplens-src/deeplens/phase_surface/grating.py
get_optimizer_params
Generate optimizer parameters.
Source code in deeplens-src/deeplens/phase_surface/grating.py
save_ckpt
Save grating DOE parameters.
Source code in deeplens-src/deeplens/phase_surface/grating.py
load_ckpt
Load grating DOE parameters.
Source code in deeplens-src/deeplens/phase_surface/grating.py
surf_dict
Return surface parameters.
Source code in deeplens-src/deeplens/phase_surface/grating.py
deeplens.phase_surface.NURBSPhase
NURBSPhase(r, d, control_points_u=8, control_points_v=8, degree_u=3, degree_v=3, control_points=None, weights=None, norm_radii=None, mat2='air', pos_xy=(0.0, 0.0), vec_local=(0.0, 0.0, 1.0), is_square=True, device='cpu')
Bases: Phase
NURBS phase on a plane substrate.
This class implements a diffractive surface where the phase profile is represented by a NURBS surface. The NURBS surface is defined by control points arranged in a 2D grid, with knot vectors for both u and v directions.
The surface is evaluated using B-spline basis functions and Cox-de Boor recursion algorithm.
Reference
[1] The NURBS Book by Piegl and Tiller [2] https://en.wikipedia.org/wiki/Non-uniform_rational_B-spline
Initialize NURBS phase surface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r
|
Radius of the surface |
required | |
d
|
Distance to next surface |
required | |
control_points_u
|
Number of control points in u direction (default: 8) |
8
|
|
control_points_v
|
Number of control points in v direction (default: 8) |
8
|
|
degree_u
|
Degree of B-spline in u direction (default: 3) |
3
|
|
degree_v
|
Degree of B-spline in v direction (default: 3) |
3
|
|
control_points
|
Optional 3D tensor of shape (control_points_u, control_points_v, 3) containing control point coordinates (x, y, z) where z is phase. If None, initialized with small random values. |
None
|
|
weights
|
Optional 2D tensor of shape (control_points_u, control_points_v) containing weights for rational B-splines. If None, all weights = 1. |
None
|
|
norm_radii
|
Normalization radius (default: r) |
None
|
|
mat2
|
Material on the right side (default: "air") |
'air'
|
|
pos_xy
|
Position in xy plane |
(0.0, 0.0)
|
|
vec_local
|
Local coordinate system vector |
(0.0, 0.0, 1.0)
|
|
is_square
|
Whether the aperture is square |
True
|
|
device
|
Computation device |
'cpu'
|
Source code in deeplens-src/deeplens/phase_surface/nurbs.py
init_from_dict
classmethod
Initialize NURBS phase surface from dictionary.
Source code in deeplens-src/deeplens/phase_surface/nurbs.py
phi
Reference phase map at design wavelength using NURBS surface evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x, y
|
Coordinate tensors |
required |
Returns:
| Type | Description |
|---|---|
|
Phase values in radians at the specified coordinates |
Source code in deeplens-src/deeplens/phase_surface/nurbs.py
dphi_dxy
Calculate phase derivatives (dphi/dx, dphi/dy) using NURBS surface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x, y
|
Coordinate tensors |
required |
Returns:
| Type | Description |
|---|---|
|
dphidx, dphidy: Phase derivatives in x and y directions |
Source code in deeplens-src/deeplens/phase_surface/nurbs.py
get_optimizer_params
Generate optimizer parameters for NURBS control points.
Source code in deeplens-src/deeplens/phase_surface/nurbs.py
save_ckpt
Save NURBS DOE parameters.
Source code in deeplens-src/deeplens/phase_surface/nurbs.py
load_ckpt
Load NURBS DOE parameters.
Source code in deeplens-src/deeplens/phase_surface/nurbs.py
surf_dict
Return surface parameters.
Source code in deeplens-src/deeplens/phase_surface/nurbs.py
deeplens.phase_surface.VortexPhase
VortexPhase(r, d, charge=1, f0=None, norm_radii=None, mat2='air', pos_xy=(0.0, 0.0), vec_local=(0.0, 0.0, 1.0), is_square=True, device='cpu')
Bases: Phase
Vortex phase surface combining a spiral phase and an optional Fresnel lens.
The phase profile is:
φ(x, y) = charge · atan2(y, x) − π · (x² + y²) / f₀
where the first term imparts orbital angular momentum (topological charge charge)
and the second term is a Fresnel focusing phase. f0 directly sets the phase
curvature (units: mm²); no design wavelength is assumed — chromatic behaviour
emerges naturally from the ray wavelength in diffract().
Setting f0=None disables the Fresnel term (pure vortex).
Reference
Yu et al., "Light Propagation with Phase Discontinuities," Science 2011.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r
|
Aperture radius [mm]. |
required | |
d
|
Axial position [mm]. |
required | |
charge
|
Topological charge (integer). Positive for left-handed, negative for right-handed helix. |
1
|
|
f0
|
Phase curvature parameter [mm²] of the co-centered Fresnel term.
Physically equivalent to λ·f for a thin lens at wavelength λ and
focal length f. |
None
|
|
norm_radii
|
Normalisation radius for phase map display. Defaults to |
None
|
|
mat2
|
Material name after the surface. |
'air'
|
|
pos_xy
|
(x, y) position offset in the global frame [mm]. |
(0.0, 0.0)
|
|
vec_local
|
Local surface normal direction. |
(0.0, 0.0, 1.0)
|
|
is_square
|
If True, use a square aperture; else circular. |
True
|
|
device
|
Torch device. |
'cpu'
|
Source code in deeplens-src/deeplens/phase_surface/vortex.py
init_from_dict
classmethod
Initialize VortexPhase from a parameter dictionary.
Source code in deeplens-src/deeplens/phase_surface/vortex.py
phi
Phase map (wrapped to [0, 2π]).
Source code in deeplens-src/deeplens/phase_surface/vortex.py
dphi_dxy
Analytical phase gradient (unwrapped) for generalized Snell's law.
Source code in deeplens-src/deeplens/phase_surface/vortex.py
get_optimizer_params
Return optimizer parameter groups.
Only f0 is differentiable; the topological charge charge is discrete.
Source code in deeplens-src/deeplens/phase_surface/vortex.py
save_ckpt
Save VortexPhase parameters.
Source code in deeplens-src/deeplens/phase_surface/vortex.py
load_ckpt
Load VortexPhase parameters.
Source code in deeplens-src/deeplens/phase_surface/vortex.py
surf_dict
Return surface parameters as a serialisable dictionary.
Source code in deeplens-src/deeplens/phase_surface/vortex.py
Light
Geometric ray representation carrying origin, direction, wavelength, validity mask, energy, and optical path length (OPL).
deeplens.Ray
Bases: DeepObj
Batched ray bundle for optical simulation.
Stores ray origins, directions, wavelength, validity mask, energy, bend penalty,
and (in coherent mode) optical path length. All tensor attributes share the
same batch shape (*batch_size, num_rays).
Attributes:
| Name | Type | Description |
|---|---|---|
o |
Tensor
|
Ray origins, shape |
d |
Tensor
|
Unit ray directions, shape |
wvln |
Tensor
|
Wavelength scalar [µm]. |
is_valid |
Tensor
|
Binary validity mask, shape |
en |
Tensor
|
Energy weight, shape |
bend_penalty |
Tensor
|
Accumulated per-surface bend penalty, shape |
opl |
Tensor
|
Optical path length (coherent mode only),
shape |
is_coherent |
bool
|
Whether OPL tracking is enabled. |
Initialize a ray object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
o
|
Tensor
|
Ray origin, shape |
required |
d
|
Tensor
|
Ray direction, shape |
required |
wvln
|
float
|
Ray wavelength [µm]. Required — must be passed
explicitly (the Lens carries |
required |
is_coherent
|
bool
|
Enable optical path length tracking for coherent
tracing. Defaults to |
False
|
device
|
str
|
Compute device. Defaults to |
'cpu'
|
Source code in deeplens-src/deeplens/light/ray.py
prop_to
Ray propagates to a given depth plane.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
float
|
depth. |
required |
n
|
float
|
refractive index. Defaults to 1. |
1.0
|
Source code in deeplens-src/deeplens/light/ray.py
centroid
Calculate the centroid of the ray, shape (..., num_rays, 3)
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Centroid of the ray, shape (..., 3) |
Source code in deeplens-src/deeplens/light/ray.py
rms_error
Calculate the RMS error of the ray.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
center_ref
|
Tensor
|
Reference center of the ray, shape (..., 3). If None, use the centroid of the ray as reference. |
None
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: average RMS error of the ray |
Source code in deeplens-src/deeplens/light/ray.py
flip_xy
Flip the x and y coordinates of the ray.
This function is used when calculating point spread function and wavefront distribution.
Source code in deeplens-src/deeplens/light/ray.py
clone
Clone the ray.
Can specify which device we want to clone. Sometimes we want to store all rays in CPU, and when using it, we move it to GPU.
Source code in deeplens-src/deeplens/light/ray.py
squeeze
Squeeze the ray.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
int
|
dimension to squeeze. Defaults to None. |
None
|
Source code in deeplens-src/deeplens/light/ray.py
unsqueeze
Unsqueeze the ray.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
int
|
dimension to unsqueeze. Defaults to None. |
None
|
Source code in deeplens-src/deeplens/light/ray.py
Complex electromagnetic field with Angular Spectrum Method (ASM), Fresnel, and
Fraunhofer propagation via torch.fft.
deeplens.ComplexWave
Bases: DeepObj
Complex scalar wave field for diffraction simulation.
Represents a monochromatic, coherent complex amplitude on a uniform
rectangular grid. Propagation methods (ASM, Fresnel, Fraunhofer) are
implemented as member functions and use torch.fft for efficiency.
Attributes:
| Name | Type | Description |
|---|---|---|
u |
Tensor
|
Complex amplitude, shape |
wvln |
float
|
Wavelength [µm]. |
k |
float
|
Wave number |
phy_size |
tuple
|
Physical aperture size (W, H) [mm]. |
ps |
float
|
Pixel pitch [mm] (must be square). |
res |
tuple
|
Grid resolution (H, W) in pixels. |
z |
float
|
Current axial position [mm]. |
Initialize a complex wave field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
Tensor or None
|
Initial complex amplitude.
Accepted shapes: |
None
|
wvln
|
float
|
Wavelength [µm]. Defaults to |
0.55
|
z
|
float
|
Initial axial position [mm]. Defaults to
|
0.0
|
phy_size
|
tuple
|
Physical aperture (W, H) [mm].
Defaults to |
(4.0, 4.0)
|
res
|
tuple
|
Grid resolution (H, W) [pixels]. Only
used when u is |
(2000, 2000)
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the pixel pitch is not square or the
wavelength is outside the range |
Source code in deeplens-src/deeplens/light/wave.py
point_wave
classmethod
point_wave(point=(0, 0, -1000.0), wvln=0.55, z=0.0, phy_size=(4.0, 4.0), res=(2000, 2000), valid_r=None)
Create a spherical wave field on x0y plane originating from a point source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
point
|
tuple
|
Point source position in object space. [mm]. Defaults to (0, 0, -1000.0). |
(0, 0, -1000.0)
|
wvln
|
float
|
Wavelength. [um]. Defaults to 0.55. |
0.55
|
z
|
float
|
Field z position. [mm]. Defaults to 0.0. |
0.0
|
phy_size
|
tuple
|
Valid plane on x0y plane. [mm]. Defaults to (2, 2). |
(4.0, 4.0)
|
res
|
tuple
|
Valid plane resoltution. Defaults to (1000, 1000). |
(2000, 2000)
|
valid_r
|
float
|
Valid circle radius. [mm]. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
field |
ComplexWave
|
Complex field on x0y plane. |
Source code in deeplens-src/deeplens/light/wave.py
plane_wave
classmethod
plane_wave(wvln=0.55, z=0.0, phy_size=(4.0, 4.0), res=(2000, 2000), theta_x=0.0, theta_y=0.0, valid_r=None)
Create a planar wave field on x0y plane.
With theta_x = theta_y = 0 the result is a uniform unit-amplitude
plane wave travelling along +z. Non-zero angles produce a tilted
(obliquely incident / off-axis) plane wave whose wavevector makes the
given angles with the optical axis; this adds the linear phase ramp
exp(i k (x sinθx + y sinθy)) while the amplitude stays uniform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wvln
|
float
|
Wavelength. [um]. |
0.55
|
z
|
float
|
Field z position. [mm]. |
0.0
|
phy_size
|
tuple
|
Physical size of the field. [mm]. |
(4.0, 4.0)
|
res
|
tuple
|
Resolution. |
(2000, 2000)
|
theta_x
|
float
|
Tilt angle of the wavevector in the x-z plane. [rad]. Defaults to 0.0. |
0.0
|
theta_y
|
float
|
Tilt angle of the wavevector in the y-z plane. [rad]. Defaults to 0.0. |
0.0
|
valid_r
|
float
|
Valid circle radius. [mm]. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
field |
ComplexWave
|
Complex field. |
Source code in deeplens-src/deeplens/light/wave.py
image_wave
classmethod
Initialize a complex wave field from an image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
Tensor
|
Input image with shape [H, W] or [B, C, H, W]. Data range is [0, 1]. |
required |
wvln
|
float
|
Wavelength. [um]. |
0.55
|
z
|
float
|
Field z position. [mm]. |
0.0
|
phy_size
|
tuple
|
Physical size of the field. [mm]. |
(4.0, 4.0)
|
Returns:
| Name | Type | Description |
|---|---|---|
field |
ComplexWave
|
Complex field. |
Source code in deeplens-src/deeplens/light/wave.py
prop
Propagate the field by distance z. Can only propagate planar wave.
Reference
[1] Modeling and propagation of near-field diffraction patterns: A more complete approach. Table 1. [2] https://github.com/kaanaksit/odak/blob/master/odak/wave/classical.py [3] https://spie.org/samples/PM103.pdf [4] "Non-approximated Rayleigh Sommerfeld diffraction integral: advantages and disadvantages in the propagation of complex wave fields"
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prop_dist
|
float
|
propagation distance, unit [mm]. |
required |
n
|
float
|
refractive index. |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
propagated complex wave field. |
Source code in deeplens-src/deeplens/light/wave.py
prop_to
Propagate the field to plane z.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
float
|
destination plane z coordinate. |
required |
Source code in deeplens-src/deeplens/light/wave.py
gen_xy_grid
Generate the x and y grid.
Source code in deeplens-src/deeplens/light/wave.py
gen_freq_grid
load_npz
Load data from npz file.
Source code in deeplens-src/deeplens/light/wave.py
save
Save the complex wave field to a npz file.
save_npz
Save the complex wave field to a npz file.
Source code in deeplens-src/deeplens/light/wave.py
show
Save the field as an image.
Source code in deeplens-src/deeplens/light/wave.py
pad
Pad the input field by (Hpad, Hpad, Wpad, Wpad). This step will also expand physical size of the field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Hpad
|
int
|
Number of pixels to pad on the top and bottom. |
required |
Wpad
|
int
|
Number of pixels to pad on the left and right. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
self |
Padded complex wave field. |
Source code in deeplens-src/deeplens/light/wave.py
flip
Flip the field horizontally and vertically.
Source code in deeplens-src/deeplens/light/wave.py
Image Simulation
PSF Rendering
Functions for rendering images with point spread functions.
deeplens.imgsim.psf.conv_psf
Render an image batch with one spatially invariant PSF.
Applies a per-channel 2-D convolution using reflect padding so that the
output has the same spatial dimensions as the input. The PSF is internally
flipped to convert the cross-correlation implemented by F.conv2d into
convolution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
Tensor
|
Input image batch, shape |
required |
psf
|
Tensor
|
PSF kernel, shape |
required |
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Rendered image, shape |
Example
psf = lens.psf_rgb(points=torch.tensor([0.0, 0.0, -10000.0])) img_blur = conv_psf(img, psf)
Source code in deeplens-src/deeplens/imgsim/psf.py
deeplens.imgsim.psf.conv_psf_map
Render an image batch with a spatially varying PSF map.
Divides the image into grid_h × grid_w non-overlapping patches and
convolves each patch with its corresponding PSF kernel. The full image is
padded before patch extraction to avoid artificial seams from independent
per-patch padding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
Tensor
|
Input image batch, shape |
required |
psf_map
|
Tensor
|
PSF map, shape |
required |
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Rendered image, shape |
Source code in deeplens-src/deeplens/imgsim/psf.py
deeplens.imgsim.psf.conv_psf_depth_interp
conv_psf_depth_interp(img, depth, psf_kernels, psf_depths, interp_mode='depth', padding_mode='reflect')
Depth-interpolated PSF convolution for a spatially-uniform but depth-varying blur.
Pre-convolves the image with PSFs at each reference depth, then blends the results using per-pixel linear interpolation weights derived from depth. This approximates defocus blur for a single field position across a depth range without computing a separate PSF per pixel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
Tensor
|
Image batch, shape |
required |
depth
|
Tensor
|
Depth map, shape |
required |
psf_kernels
|
Tensor
|
PSF stack at reference depths, shape
|
required |
psf_depths
|
Tensor
|
Depth of each PSF layer, shape
|
required |
interp_mode
|
str
|
Interpolation space. |
'depth'
|
padding_mode
|
str or None
|
Padding mode passed to
|
'reflect'
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Blurred image, shape |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If depth or psf_depths contain non-negative values,
or if interp_mode is not |
Source code in deeplens-src/deeplens/imgsim/psf.py
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | |
deeplens.imgsim.psf.conv_psf_map_depth_interp
Render with a spatially varying, depth-interpolated PSF map.
The image is divided into PSF-map grid cells. For each cell, the image patch is convolved with all reference-depth PSFs for that cell, then the convolved results are blended per pixel using interpolation weights from the depth map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
Tensor
|
Image batch, shape |
required |
depth
|
Tensor
|
Depth map, shape |
required |
psf_map
|
Tensor
|
PSF map, shape
|
required |
psf_depths
|
Tensor
|
Reference depths, shape |
required |
interp_mode
|
str
|
|
'depth'
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Rendered image, shape |
Source code in deeplens-src/deeplens/imgsim/psf.py
deeplens.imgsim.psf.conv_psf_occlusion
Occlusion-aware bokeh rendering using back-to-front layered compositing.
Discretizes the scene into depth layers and composites them from back (far) to front (near). Each layer is blurred independently with its depth-specific PSF, and composited using the over-operator. This prevents color bleeding at depth discontinuities.
Reference
[1] "Dr.Bokeh: DiffeRentiable Occlusion-aware Bokeh Rendering", CVPR 2024.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
Tensor
|
Input image, shape (B, C, H, W), values in [0, 1]. |
required |
depth
|
Tensor
|
Depth map, shape (B, 1, H, W), values in (-inf, 0). |
required |
psf_kernels
|
Tensor
|
PSF at each depth layer, shape (num_layers, C, ks, ks). |
required |
psf_depths
|
Tensor
|
Depth values for each layer, shape (num_layers,). Must be negative and sorted ascending (far to near, i.e. -5000 ... -200). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
img_render |
Tensor
|
Rendered image, shape (B, C, H, W). |
Source code in deeplens-src/deeplens/imgsim/psf.py
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 | |
deeplens.imgsim.psf.splat_psf_per_pixel
Render an image batch by splatting each pixel through its own PSF.
Uses a different PSF kernel for each source pixel and accumulates the
scattered contributions with F.fold. When chunk_size is set, source
pixels are processed tile by tile to reduce peak memory while preserving
PSF contributions that cross tile boundaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
Tensor
|
The image to be blurred (B, C, H, W). |
required |
psf
|
Tensor
|
Per-pixel local PSFs, shape
|
required |
chunk_size
|
int
|
Source tile size for memory-efficient
rendering. If |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
img_render |
Tensor
|
Rendered image (B, C, H, W). |
Source code in deeplens-src/deeplens/imgsim/psf.py
deeplens.imgsim.psf.interp_psf_map
Resample a PSF map to a different spatial grid size.
Supports either a packed map [C, grid_old*ks, grid_old*ks] or an
unpacked map [grid_old, grid_old, C, ks, ks]. Each kernel sample
location is bilinearly interpolated across the PSF grid, and the result is
returned in packed-map layout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psf_map
|
Tensor
|
Packed or unpacked PSF map. |
required |
grid_old
|
int
|
Input grid size. Ignored for unpacked input, where the
grid size is read from |
required |
grid_new
|
int
|
Output grid size. |
required |
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Interpolated packed PSF map, shape
|
Source code in deeplens-src/deeplens/imgsim/psf.py
deeplens.imgsim.psf.rotate_psf
Rotate a batch of RGB PSF kernels counter-clockwise.
Rotation is performed around the center of each square PSF kernel using
F.grid_sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psf
|
Tensor
|
PSF batch, shape |
required |
theta
|
Tensor
|
Rotation angles in radians, shape |
required |
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Rotated PSFs, shape |
Source code in deeplens-src/deeplens/imgsim/psf.py
Monte Carlo Integrals
Utilities for ray-bundle accumulation and ray-traced image sampling.
deeplens.imgsim.monte_carlo.forward_integral
Differentiable Monte-Carlo integral over a ray bundle onto a pixel grid.
Bins ray hit positions into a ks × ks grid centred on pointc (or the
ray centroid when pointc is None). In coherent mode the complex
amplitude is accumulated instead of intensity.
All N field points scatter into their own output slices in a single
index_put_(accumulate=True) call with 3-D (batch, row, col)
indices. This removes the per-field Python loop the earlier
implementation used and fuses the scatter across all field points into
one kernel launch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
Traced ray bundle with origin |
required |
ps
|
float
|
Pixel size [mm]. |
required |
ks
|
int
|
Output grid size in pixels (square). |
required |
pointc
|
Tensor or None
|
Reference centre for each
field point, shape |
None
|
interpolate
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Accumulated field, shape |
|
|
|
|
|
|
Source code in deeplens-src/deeplens/imgsim/monte_carlo.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
deeplens.imgsim.monte_carlo.backward_integral
Backward Monte Carlo integration, for ray tracing based rendering.
The input image is always replicate-padded by one pixel on each side so that rays landing within half a pixel of the edge can still be bilinearly sampled without silently truncating.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray object. Shape of |
required | |
img_obj
|
[B, C, H, W]. Spatial size |
required | |
ps
|
pixel size |
required | |
interpolate
|
whether to interpolate |
True
|
|
energy_correction
|
Optional per-ray weight tensor of shape
|
None
|
|
vignetting
|
If True, divide by a fixed denominator
( |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
output |
shape [B, C, h, w] |
Source code in deeplens-src/deeplens/imgsim/monte_carlo.py
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | |
deeplens.imgsim.monte_carlo.assign_points_to_pixels
Assign points to pixels, supports both incoherent and coherent ray tracing. Use advanced indexing to increment the count for each corresponding pixel.
This function can only compute single point source, constrained by advanced indexing operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
shape [spp, 2] |
required | |
mask
|
shape [spp] |
required | |
ks
|
kernel size |
required | |
x_range
|
x range |
required | |
y_range
|
y range |
required | |
value
|
shape [spp], values we want to assign to each pixel (intensity or complex amplitude) |
required | |
interpolate
|
whether to interpolate |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
field |
intensity or complex amplitude, shape [ks, ks] |
Source code in deeplens-src/deeplens/imgsim/monte_carlo.py
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | |