Optics API Reference
The deeplens.optics module contains the differentiable lens models, optical surfaces, light 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.optics.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 :meth: |
Source code in deeplens/optics/base.py
__str__
Called when using print() and str()
Source code in deeplens/optics/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/optics/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/optics/base.py
Abstract base class for all lens types. Defines the shared interface: psf(), psf_rgb(), render(), etc.
deeplens.optics.Lens
Bases: DeepObj
Initialize a lens class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
dtype
|
Data type. Defaults to torch.float32. |
float32
|
device
|
str
|
Device to run the lens. Defaults to None. |
None
|
Source code in deeplens/optics/lens.py
read_lens_json
write_lens_json
set_sensor
Set sensor size and resolution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sensor_size
|
tuple
|
Sensor size (w, h) in [mm]. |
required |
sensor_res
|
tuple
|
Sensor resolution (W, H) in [pixels]. |
required |
Source code in deeplens/optics/lens.py
set_sensor_res
Set sensor resolution (and aspect ratio) while keeping sensor radius unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sensor_res
|
tuple
|
Sensor resolution (W, H) in [pixels]. |
required |
Source code in deeplens/optics/lens.py
calc_fov
Compute FoV (radian) of the lens.
Reference
[1] https://en.wikipedia.org/wiki/Angle_of_view_(photography)
Source code in deeplens/optics/lens.py
psf
Compute the monochromatic PSF for one or more point sources.
Subclasses must override this method with a differentiable implementation. Three computation models are common in practice: geometric ray binning, coherent ray-wave, and Huygens spherical-wave integration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
Tensor
|
Point source coordinates, shape |
required |
wvln
|
float
|
Wavelength in micrometers. Defaults to
|
DEFAULT_WAVE
|
ks
|
int
|
Output PSF kernel size in pixels. Defaults
to |
PSF_KS
|
**kwargs
|
Additional keyword arguments forwarded to the underlying
PSF computation (e.g. |
{}
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: PSF intensity map, shape |
|
|
point or |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
This base implementation must be overridden. |
Notes
The method is differentiable with respect to all optimisable lens parameters so it can be used directly inside a training loop.
Example
point = torch.tensor([0.0, 0.0, -10000.0]) psf = lens.psf(points=point, ks=64, model="geometric") print(psf.shape) # torch.Size([64, 64])
Source code in deeplens/optics/lens.py
psf_rgb
Compute the RGB (tri-chromatic) PSF by stacking three wavelength calls.
Calls :meth:psf three times for the RGB primary wavelengths defined
in WAVE_RGB and stacks the results along the channel axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
Tensor
|
Point source coordinates, shape |
required |
ks
|
int
|
PSF kernel size. Defaults to |
PSF_KS
|
**kwargs
|
Forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: RGB PSF, shape |
|
|
or |
Source code in deeplens/optics/lens.py
point_source_grid
Generate point source grid for PSF calculation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
float
|
Depth of the point source. |
required |
grid
|
tuple
|
Grid size (grid_w, grid_h). Defaults to (9, 9), meaning 9x9 grid. |
(9, 9)
|
normalized
|
bool
|
Return normalized object source coordinates. Defaults to True, meaning object sources xy coordinates range from [-1, 1]. |
True
|
quater
|
bool
|
Use quater of the sensor plane to save memory. Defaults to False. |
False
|
center
|
bool
|
Use center of each patch. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
point_source |
Normalized object source coordinates. Shape of [grid_h, grid_w, 3], [-1, 1], [-1, 1], [-Inf, 0]. |
Source code in deeplens/optics/lens.py
psf_map
Compute monochrome PSF map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid
|
tuple
|
Grid size (grid_w, grid_h). Defaults to (5, 5), meaning 5x5 grid. |
(5, 5)
|
wvln
|
float
|
Wavelength. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
depth
|
float
|
Depth of the object. Defaults to DEPTH. |
DEPTH
|
ks
|
int
|
Kernel size. Defaults to PSF_KS. |
PSF_KS
|
Returns:
| Name | Type | Description |
|---|---|---|
psf_map |
Shape of [grid_h, grid_w, 3, ks, ks]. |
Source code in deeplens/optics/lens.py
psf_map_rgb
Compute RGB PSF map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid
|
tuple
|
Grid size (grid_w, grid_h). Defaults to (5, 5), meaning 5x5 grid. |
(5, 5)
|
ks
|
int
|
Kernel size. Defaults to PSF_KS, meaning PSF_KS x PSF_KS kernel size. |
PSF_KS
|
depth
|
float
|
Depth of the object. Defaults to DEPTH. |
DEPTH
|
**kwargs
|
Additional arguments for psf_map(). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
psf_map |
Shape of [grid_h, grid_w, 3, ks, ks]. |
Source code in deeplens/optics/lens.py
draw_psf_map
draw_psf_map(grid=(7, 7), ks=PSF_KS, depth=DEPTH, log_scale=False, save_name='./psf_map.png', show=False)
Draw RGB PSF map of the lens.
Source code in deeplens/optics/lens.py
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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 | |
point_source_radial
Compute point radial [0, 1] in the object space to compute PSF grid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid
|
int
|
Grid size. Defaults to 9. |
9
|
Returns:
| Name | Type | Description |
|---|---|---|
point_source |
Shape of [grid, 3]. |
Source code in deeplens/optics/lens.py
draw_psf_radial
Draw radial PSF (45 deg). Will draw M PSFs, each of size ks x ks.
Source code in deeplens/optics/lens.py
render
Differentiable image simulation for a 2D (flat) scene.
Performs only the optical component of image simulation and is fully
differentiable. Sensor noise is handled separately by the
:class:~deeplens.camera.Camera class.
For incoherent imaging the intensity PSF is convolved with the object-space image. For coherent imaging the complex PSF is convolved with the complex object image before squaring for intensity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_obj
|
Tensor
|
Input image in linear (raw) space,
shape |
required |
depth
|
float
|
Object depth in mm (negative value).
Defaults to |
DEPTH
|
method
|
str
|
Rendering method. One of:
|
'psf_patch'
|
**kwargs
|
Method-specific keyword arguments:
|
{}
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Rendered image, shape |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If method is |
Exception
|
If method is not recognised. |
References
[1] "Optical Aberration Correction in Postprocessing using Imaging Simulation", TOG 2021. [2] "Efficient depth- and spatially-varying image simulation for defocus deblur", ICCVW 2025.
Example
img_rendered = lens.render(img, depth=-10000.0, method="psf_patch", ... patch_center=(0.3, 0.0), psf_ks=64)
Source code in deeplens/optics/lens.py
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 490 491 492 | |
render_psf
Render image patch using PSF convolution. Better not use this function to avoid confusion.
Source code in deeplens/optics/lens.py
render_psf_patch
Render an image patch using PSF convolution, and return positional encoding channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_obj
|
tensor
|
Input image object in raw space. Shape of [B, C, H, W]. |
required |
depth
|
float
|
Depth of the object. |
DEPTH
|
patch_center
|
tensor
|
Center of the image patch. Shape of [2] or [B, 2]. |
(0, 0)
|
psf_ks
|
int
|
PSF kernel size. Defaults to PSF_KS. |
PSF_KS
|
Returns:
| Name | Type | Description |
|---|---|---|
img_render |
Rendered image. Shape of [B, C, H, W]. |
Source code in deeplens/optics/lens.py
render_psf_map
Render image using PSF block convolution.
Note
Larger psf_grid and psf_ks are typically better for more accurate rendering, but slower.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_obj
|
tensor
|
Input image object in raw space. Shape of [B, C, H, W]. |
required |
depth
|
float
|
Depth of the object. |
DEPTH
|
psf_grid
|
int
|
PSF grid size. |
7
|
psf_ks
|
int
|
PSF kernel size. Defaults to PSF_KS. |
PSF_KS
|
Returns:
| Name | Type | Description |
|---|---|---|
img_render |
Rendered image. Shape of [B, C, H, W]. |
Source code in deeplens/optics/lens.py
render_rgbd
Render RGBD image.
TODO: add obstruction-aware image simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_obj
|
tensor
|
Object image. Shape of [B, C, H, W]. |
required |
depth_map
|
tensor
|
Depth map [mm]. Shape of [B, 1, H, W]. Values should be positive. |
required |
method
|
str
|
Image simulation method. Defaults to "psf_patch". |
'psf_patch'
|
**kwargs
|
Additional arguments for different methods. - interp_mode (str): "depth" or "disparity". Defaults to "depth". |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
img_render |
Rendered image. Shape of [B, C, H, W]. |
Reference
[1] "Aberration-Aware Depth-from-Focus", TPAMI 2023. [2] "Efficient Depth- and Spatially-Varying Image Simulation for Defocus Deblur", ICCVW 2025.
Source code in deeplens/optics/lens.py
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 | |
activate_grad
get_optimizer_params
Lens Models
Differentiable multi-element refractive lens via geometric ray tracing. This is the primary lens model in DeepLens.
GeoLens uses a mixin architecture — functionality is split across GeoLensEval, GeoLensOptim, GeoLensVis, GeoLensIO, GeoLensTolerance, and GeoLensVis3D.
deeplens.optics.GeoLens
Bases: Lens, GeoLensEval, GeoLensOptim, GeoLensVis, GeoLensIO, GeoLensTolerance, GeoLensVis3D
Differentiable geometric lens using vectorised ray tracing.
The primary lens model in DeepLens. Supports multi-element refractive
(and partially reflective) systems loaded from JSON, Zemax .zmx, or
Code V .seq files. Accuracy is aligned with Zemax OpticStudio.
Uses a mixin architecture – six specialised mixin classes are composed at class definition time to keep each concern isolated:
- :class:
~deeplens.optics.geolens_pkg.eval.GeoLensEval– optical performance evaluation (spot, MTF, distortion, vignetting). - :class:
~deeplens.optics.geolens_pkg.optim.GeoLensOptim– loss functions and gradient-based optimisation. - :class:
~deeplens.optics.geolens_pkg.vis.GeoLensVis– 2-D layout and ray visualisation. - :class:
~deeplens.optics.geolens_pkg.io.GeoLensIO– read/write JSON, Zemax.zmx. - :class:
~deeplens.optics.geolens_pkg.tolerance.GeoLensTolerance– manufacturing tolerance analysis. - :class:
~deeplens.optics.geolens_pkg.view_3d.GeoLensVis3D– 3-D mesh visualisation.
Key differentiability trick: Ray-surface intersection
(:meth:~deeplens.optics.geometric_surface.base.Surface.newtons_method)
uses a non-differentiable Newton loop followed by one differentiable
Newton step to enable gradient flow.
Attributes:
| Name | Type | Description |
|---|---|---|
surfaces |
list[Surface]
|
Ordered list of optical surfaces. |
materials |
list[Material]
|
Optical materials between surfaces. |
d_sensor |
Tensor
|
Back focal distance [mm]. |
foclen |
float
|
Effective focal length [mm]. |
fnum |
float
|
F-number. |
rfov |
float
|
Half-diagonal field of view [radians]. |
sensor_size |
tuple
|
Physical sensor size (W, H) [mm]. |
sensor_res |
tuple
|
Sensor resolution (W, H) [pixels]. |
pixel_size |
float
|
Pixel pitch [mm]. |
References
Xinge Yang et al., "Curriculum learning for ab initio deep learned refractive optics," Nature Communications 2024.
Initialize a refractive lens.
There are two ways to initialize a GeoLens
- Read a lens from .json/.zmx/.seq file
- Initialize a lens with no lens file, then manually add surfaces and materials
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to lens file (.json, .zmx, or .seq). Defaults to None. |
None
|
device
|
device
|
Device for tensor computations. Defaults to None. |
None
|
dtype
|
dtype
|
Data type for computations. Defaults to torch.float32. |
float32
|
Source code in deeplens/optics/geolens.py
read_lens
Read a GeoLens from a file.
Supported file formats
- .json: DeepLens native JSON format
- .zmx: Zemax lens file format
- .seq: CODE V sequence file format
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the lens file. |
required |
Note
Sensor size and resolution will usually be overwritten by values from the file.
Source code in deeplens/optics/geolens.py
post_computation
Compute derived optical properties after loading or modifying lens.
Calculates and caches
- Effective focal length (EFL)
- Entrance and exit pupil positions and radii
- Field of view (FoV) in horizontal, vertical, and diagonal directions
- F-number
Note
This method should be called after any changes to the lens geometry.
Source code in deeplens/optics/geolens.py
__call__
Trace rays through the lens system.
Makes the GeoLens callable, allowing ray tracing with function call syntax.
sample_grid_rays
sample_grid_rays(depth=float('inf'), num_grid=(11, 11), num_rays=SPP_PSF, wvln=DEFAULT_WAVE, uniform_fov=True, sample_more_off_axis=False, scale_pupil=1.0)
Sample grid rays from object space. (1) If depth is infinite, sample parallel rays at different field angles. (2) If depth is finite, sample point source rays from the object plane.
This function is usually used for (1) PSF map, (2) RMS error map, and (3) spot diagram calculation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
float
|
sampling depth. Defaults to float("inf"). |
float('inf')
|
num_grid
|
tuple
|
number of grid points. Defaults to [11, 11]. |
(11, 11)
|
num_rays
|
int
|
number of rays. Defaults to SPP_PSF. |
SPP_PSF
|
wvln
|
float
|
ray wvln. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
uniform_fov
|
bool
|
If True, sample uniform FoV angles. |
True
|
sample_more_off_axis
|
bool
|
If True, sample more off-axis rays. |
False
|
scale_pupil
|
float
|
Scale factor for pupil radius. |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
ray |
Ray object
|
Ray object. Shape [num_grid[1], num_grid[0], num_rays, 3] |
Source code in deeplens/optics/geolens.py
sample_radial_rays
Sample radial (meridional, y direction) rays at different field angles.
This function is usually used for (1) PSF radial map, and (2) RMS error radial map calculation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_field
|
int
|
number of field angles. Defaults to 5. |
5
|
depth
|
float
|
sampling depth. Defaults to float("inf"). |
float('inf')
|
num_rays
|
int
|
number of rays. Defaults to SPP_PSF. |
SPP_PSF
|
wvln
|
float
|
ray wvln. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
Returns:
| Name | Type | Description |
|---|---|---|
ray |
Ray object
|
Ray object. Shape [num_field, num_rays, 3] |
Source code in deeplens/optics/geolens.py
sample_from_points
sample_from_points(points=[[0.0, 0.0, -10000.0]], num_rays=SPP_PSF, wvln=DEFAULT_WAVE, scale_pupil=1.0)
Sample rays from point sources in object space (absolute physical coordinates).
Used for PSF and chief ray calculation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
list or Tensor
|
Ray origins in shape [3], [N, 3], or [Nx, Ny, 3]. |
[[0.0, 0.0, -10000.0]]
|
num_rays
|
int
|
Number of rays per point. Default: SPP_PSF. |
SPP_PSF
|
wvln
|
float
|
Wavelength of rays. Default: DEFAULT_WAVE. |
DEFAULT_WAVE
|
scale_pupil
|
float
|
Scale factor for pupil radius. |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
Ray |
Sampled rays with shape |
Source code in deeplens/optics/geolens.py
sample_parallel
sample_parallel(fov_x=[0.0], fov_y=[0.0], num_rays=SPP_CALC, wvln=DEFAULT_WAVE, entrance_pupil=True, depth=-1.0, scale_pupil=1.0)
Sample parallel rays in object space for geometric optics calculations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fov_x
|
float or list
|
Field angle(s) in the xz plane (degrees). Default: [0.0]. |
[0.0]
|
fov_y
|
float or list
|
Field angle(s) in the yz plane (degrees). Default: [0.0]. |
[0.0]
|
num_rays
|
int
|
Number of rays per field point. Default: SPP_CALC. |
SPP_CALC
|
wvln
|
float
|
Wavelength of rays. Default: DEFAULT_WAVE. |
DEFAULT_WAVE
|
entrance_pupil
|
bool
|
If True, sample origins on entrance pupil; otherwise, on surface 0. Default: True. |
True
|
depth
|
float
|
Propagation depth in z. Default: -1.0. |
-1.0
|
scale_pupil
|
float
|
Scale factor for pupil radius. Default: 1.0. |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
Ray |
Rays with shape [..., num_rays, 3], where leading dims are: - both fov_x and fov_y scalars: [num_rays, 3] - fov_x scalar: [len(fov_y), num_rays, 3] - fov_y scalar: [len(fov_x), num_rays, 3] - both lists: [len(fov_y), len(fov_x), num_rays, 3] Ordered as (u, v). |
Source code in deeplens/optics/geolens.py
sample_point_source
sample_point_source(fov_x=[0.0], fov_y=[0.0], depth=DEPTH, num_rays=SPP_PSF, wvln=DEFAULT_WAVE, entrance_pupil=True, scale_pupil=1.0)
Sample point source rays from object space with given field angles.
Used for (1) spot/rms/magnification calculation, (2) distortion/sensor sampling.
This function is equivalent to self.point_source_grid() + self.sample_from_points().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fov_x
|
float or list
|
field angle in x0z plane. |
[0.0]
|
fov_y
|
float or list
|
field angle in y0z plane. |
[0.0]
|
depth
|
float
|
sample plane z position. Defaults to -10.0. |
DEPTH
|
num_rays
|
int
|
number of rays sampled from each grid point. Defaults to 16. |
SPP_PSF
|
entrance_pupil
|
bool
|
whether to use entrance pupil. Defaults to False. |
True
|
wvln
|
float
|
ray wvln. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
Returns:
| Name | Type | Description |
|---|---|---|
ray |
Ray object
|
Ray object. Shape [len(fov_y), len(fov_x), num_rays, 3], arranged in uv order. |
Source code in deeplens/optics/geolens.py
sample_sensor
Sample rays from sensor pixels (backward rays). Used for ray tracing rendering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spp
|
int
|
sample per pixel. Defaults to 64. |
64
|
pupil
|
bool
|
whether to use pupil. Defaults to True. |
required |
wvln
|
float
|
ray wvln. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
sub_pixel
|
bool
|
whether to sample multiple points inside the pixel. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
ray |
Ray object
|
Ray object. Shape [H, W, spp, 3] |
Source code in deeplens/optics/geolens.py
sample_circle
Sample points inside a circle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r
|
float
|
Radius of the circle. |
required |
z
|
float
|
Z-coordinate for all sampled points. |
required |
shape
|
list
|
Shape of the output tensor. |
[16, 16, 512]
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Sampled points, shape |
Source code in deeplens/optics/geolens.py
trace
Trace rays through the lens.
Forward or backward tracing is automatically determined by the ray direction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray object
|
Ray object. |
required |
surf_range
|
list
|
Surface index range. |
None
|
record
|
bool
|
record ray path or not. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
ray_final |
Ray object
|
ray after optical system. |
ray_o_rec |
list
|
list of intersection points. |
Source code in deeplens/optics/geolens.py
trace2obj
Traces rays backwards through all lens surfaces from sensor side to object side.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
Ray object to trace backwards. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Ray |
Ray object after backward propagation through the lens. |
Source code in deeplens/optics/geolens.py
trace2sensor
Forward trace rays through the lens to sensor plane.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray object
|
Ray object. |
required |
record
|
bool
|
record ray path or not. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
ray_out |
Ray object
|
ray after optical system. |
ray_o_record |
list
|
list of intersection points. |
Source code in deeplens/optics/geolens.py
trace2exit_pupil
Forward trace rays through the lens to exit pupil plane.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
Ray object to trace. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Ray |
Ray object propagated to the exit pupil plane. |
Source code in deeplens/optics/geolens.py
forward_tracing
Forward traces rays through each surface in the specified range from object side to image side.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
Ray object to trace. |
required |
surf_range
|
range
|
Range of surface indices to trace through. |
required |
record
|
bool
|
If True, record ray positions at each surface. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(ray_out, ray_o_record) where: - ray_out (Ray): Ray after propagation through all surfaces. - ray_o_record (list or None): List of ray positions at each surface, or None if record is False. |
Source code in deeplens/optics/geolens.py
backward_tracing
Backward traces rays through each surface in reverse order from image side to object side.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray
|
Ray
|
Ray object to trace. |
required |
surf_range
|
range
|
Range of surface indices to trace through. |
required |
record
|
bool
|
If True, record ray positions at each surface. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(ray_out, ray_o_record) where: - ray_out (Ray): Ray after backward propagation through all surfaces. - ray_o_record (list or None): List of ray positions at each surface, or None if record is False. |
Source code in deeplens/optics/geolens.py
render
Differentiable image simulation.
Image simulation methods
[1] PSF map block convolution. [2] PSF patch convolution. [3] Ray tracing rendering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_obj
|
Tensor
|
Input image object in raw space. Shape of [N, C, H, W]. |
required |
depth
|
float
|
Depth of the object. Defaults to DEPTH. |
DEPTH
|
method
|
str
|
Image simulation method. One of 'psf_map', 'psf_patch', or 'ray_tracing'. Defaults to 'ray_tracing'. |
'ray_tracing'
|
**kwargs
|
Additional arguments for different methods: - psf_grid (tuple): Grid size for PSF map method. Defaults to (10, 10). - psf_ks (int): Kernel size for PSF methods. Defaults to PSF_KS. - patch_center (tuple): Center position for PSF patch method. - spp (int): Samples per pixel for ray tracing. Defaults to SPP_RENDER. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Tensor |
Rendered image tensor. Shape of [N, C, H, W]. |
Source code in deeplens/optics/geolens.py
render_raytracing
Render RGB image using ray tracing rendering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
tensor
|
RGB image tensor. Shape of [N, 3, H, W]. |
required |
depth
|
float
|
Depth of the object. Defaults to DEPTH. |
DEPTH
|
spp
|
int
|
Sample per pixel. Defaults to 64. |
SPP_RENDER
|
vignetting
|
bool
|
whether to consider vignetting effect. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
img_render |
tensor
|
Rendered RGB image tensor. Shape of [N, 3, H, W]. |
Source code in deeplens/optics/geolens.py
render_raytracing_mono
Render monochrome image using ray tracing rendering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
tensor
|
Monochrome image tensor. Shape of [N, 1, H, W] or [N, H, W]. |
required |
wvln
|
float
|
Wavelength of the light. |
required |
depth
|
float
|
Depth of the object. Defaults to DEPTH. |
DEPTH
|
spp
|
int
|
Sample per pixel. Defaults to 64. |
64
|
Returns:
| Name | Type | Description |
|---|---|---|
img_mono |
tensor
|
Rendered monochrome image tensor. Shape of [N, 1, H, W] or [N, H, W]. |
Source code in deeplens/optics/geolens.py
render_compute_image
Computes the intersection points between rays and the object image plane, then generates the rendered image following rendering equation.
Back-propagation gradient flow: image -> w_i -> u -> p -> ray -> surface
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
tensor
|
[N, C, H, W] or [N, H, W] shape image tensor. |
required |
depth
|
float
|
depth of the object. |
required |
scale
|
float
|
scale factor. |
required |
ray
|
Ray object
|
Ray object. Shape [H, W, spp, 3]. |
required |
vignetting
|
bool
|
whether to consider vignetting effect. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
image |
tensor
|
[N, C, H, W] or [N, H, W] shape rendered image tensor. |
Source code in deeplens/optics/geolens.py
unwarp
Unwarp rendered images using distortion map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
tensor
|
Rendered image tensor. Shape of [N, C, H, W]. |
required |
depth
|
float
|
Depth of the object. Defaults to DEPTH. |
DEPTH
|
grid_size
|
int
|
Grid size. Defaults to 256. |
required |
crop
|
bool
|
Whether to crop the image. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
img_unwarpped |
tensor
|
Unwarped image tensor. Shape of [N, C, H, W]. |
Source code in deeplens/optics/geolens.py
analysis_rendering
analysis_rendering(img_org, save_name=None, depth=DEPTH, spp=SPP_RENDER, unwarp=False, noise=0.0, method='ray_tracing', show=False)
Render a single image for visualization and analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_org
|
Tensor
|
Original image with shape [H, W, 3]. |
required |
save_name
|
str
|
Path prefix for saving rendered images. Defaults to None. |
None
|
depth
|
float
|
Depth of object image. Defaults to DEPTH. |
DEPTH
|
spp
|
int
|
Sample per pixel. Defaults to SPP_RENDER. |
SPP_RENDER
|
unwarp
|
bool
|
If True, unwarp the image to correct distortion. Defaults to False. |
False
|
noise
|
float
|
Gaussian noise standard deviation. Defaults to 0.0. |
0.0
|
method
|
str
|
Rendering method ('ray_tracing', etc.). Defaults to 'ray_tracing'. |
'ray_tracing'
|
show
|
bool
|
If True, display the rendered image. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
Tensor |
Rendered image tensor with shape [1, 3, H, W]. |
Source code in deeplens/optics/geolens.py
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 | |
psf
Calculate Point Spread Function (PSF) for given point sources.
Supports multiple PSF calculation models
- geometric: Incoherent intensity ray tracing (fast, differentiable)
- coherent: Coherent ray tracing with free-space propagation (accurate, differentiable)
- huygens: Huygens-Fresnel integration (accurate, not differentiable)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
Tensor
|
Point source positions. Shape [N, 3] with x, y in [-1, 1] and z in [-Inf, 0]. Normalized coordinates. |
required |
ks
|
int
|
Output kernel size in pixels. Defaults to PSF_KS. |
PSF_KS
|
wvln
|
float
|
Wavelength in [um]. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
spp
|
int
|
Samples per pixel. If None, uses model-specific default. |
None
|
recenter
|
bool
|
If True, center PSF using chief ray. Defaults to True. |
True
|
model
|
str
|
PSF model type. One of 'geometric', 'coherent', 'huygens'. Defaults to 'geometric'. |
'geometric'
|
Returns:
| Name | Type | Description |
|---|---|---|
Tensor |
PSF normalized to sum to 1. Shape [ks, ks] or [N, ks, ks]. |
Source code in deeplens/optics/geolens.py
psf_geometric
Single wavelength geometric PSF calculation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
Tensor
|
Normalized point source position. Shape of [N, 3], x, y in range [-1, 1], z in range [-Inf, 0]. |
required |
ks
|
int
|
Output kernel size. |
PSF_KS
|
wvln
|
float
|
Wavelength. |
DEFAULT_WAVE
|
spp
|
int
|
Sample per pixel. |
SPP_PSF
|
recenter
|
bool
|
Recenter PSF using chief ray. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
psf |
Shape of [ks, ks] or [N, ks, ks]. |
References
[1] https://optics.ansys.com/hc/en-us/articles/42661723066515-What-is-a-Point-Spread-Function
Source code in deeplens/optics/geolens.py
psf_coherent
Alias for psf_pupil_prop. Calculates PSF by coherent ray tracing to exit pupil followed by Angular Spectrum Method (ASM) propagation.
Source code in deeplens/optics/geolens.py
psf_pupil_prop
Single point monochromatic PSF using exit-pupil diffraction model. This function is differentiable.
Steps
1, Calculate complex wavefield at exit-pupil plane by coherent ray tracing. 2, Free-space propagation to sensor plane and calculate intensity PSF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
Tensor
|
[x, y, z] coordinates of the point source. Defaults to torch.Tensor([0,0,-10000]). |
required |
ks
|
int
|
size of the PSF patch. Defaults to PSF_KS. |
PSF_KS
|
wvln
|
float
|
wvln. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
spp
|
int
|
number of rays to sample. Defaults to SPP_COHERENT. |
SPP_COHERENT
|
recenter
|
bool
|
Recenter PSF using chief ray. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
psf_out |
Tensor
|
PSF patch. Normalized to sum to 1. Shape [ks, ks] |
Reference
[1] "End-to-End Hybrid Refractive-Diffractive Lens Design with Differentiable Ray-Wave Model", SIGGRAPH Asia 2024.
Note
[1] This function is similar to ZEMAX FFT_PSF but implement free-space propagation with Angular Spectrum Method (ASM) rather than FFT transform. Free-space propagation using ASM is more accurate than doing FFT, because FFT (as used in ZEMAX) assumes far-field condition (e.g., chief ray perpendicular to image plane).
Source code in deeplens/optics/geolens.py
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 | |
pupil_field
Compute complex wavefront at exit pupil plane by coherent ray tracing.
The wavefront is flipped for subsequent PSF calculation and has the same size as the image sensor. This function is differentiable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
Tensor or list
|
Single point source position. Shape [3] or [1, 3], with x, y in [-1, 1] and z in [-Inf, 0]. |
required |
wvln
|
float
|
Wavelength in [um]. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
spp
|
int
|
Number of rays to sample. Must be >= 1,000,000 for accurate coherent simulation. Defaults to SPP_COHERENT. |
SPP_COHERENT
|
recenter
|
bool
|
If True, center using chief ray. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(wavefront, psf_center) where: - wavefront (Tensor): Complex wavefront at exit pupil. Shape [H, H]. - psf_center (list): Normalized PSF center coordinates [x, y] in [-1, 1]. |
Note
Default dtype must be torch.float64 for accurate phase calculation.
Source code in deeplens/optics/geolens.py
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 | |
psf_huygens
Single wavelength Huygens PSF calculation.
This function is not differentiable due to its heavy computational cost.
Steps
1, Trace coherent rays to exit-pupil plane. 2, Treat every ray as a secondary point source emitting a spherical wave.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
Tensor
|
Normalized point source position. Shape of [N, 3], x, y in range [-1, 1], z in range [-Inf, 0]. |
required |
ks
|
int
|
Output kernel size. |
PSF_KS
|
wvln
|
float
|
Wavelength. |
DEFAULT_WAVE
|
spp
|
int
|
Sample per pixel. |
SPP_COHERENT
|
recenter
|
bool
|
Recenter PSF using chief ray. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
psf |
Shape of [ks, ks] or [N, ks, ks]. |
References
[1] "Optical Aberrations Correction in Postprocessing Using Imaging Simulation", TOG 2021
Note
This is different from ZEMAX Huygens PSF, which traces rays to image plane and do plane wave integration.
Source code in deeplens/optics/geolens.py
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 | |
psf_map
Compute the geometric PSF map at given depth.
Overrides the base method in Lens class to improve efficiency by parallel ray tracing over different field points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
float
|
Depth of the object plane. Defaults to DEPTH. |
DEPTH
|
grid
|
(int, tuple)
|
Grid size (grid_w, grid_h). Defaults to 7. |
(7, 7)
|
ks
|
int
|
Kernel size. Defaults to PSF_KS. |
PSF_KS
|
spp
|
int
|
Sample per pixel. Defaults to SPP_PSF. |
SPP_PSF
|
recenter
|
bool
|
Recenter PSF using chief ray. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
psf_map |
PSF map. Shape of [grid_h, grid_w, 1, ks, ks]. |
Source code in deeplens/optics/geolens.py
psf_center
Compute reference PSF center (flipped to match the original point) for given point source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points_obj
|
[..., 3] un-normalized point in object plane. [-Inf, Inf] * [-Inf, Inf] * [-Inf, 0] |
required | |
method
|
"chief_ray" or "pinhole". Defaults to "chief_ray". |
'chief_ray'
|
Returns:
| Name | Type | Description |
|---|---|---|
psf_center |
[..., 2] un-normalized psf center in sensor plane. |
Source code in deeplens/optics/geolens.py
analysis_spot
Compute sensor plane ray spot RMS error and radius.
Analyzes spot sizes across the field of view for multiple wavelengths (red, green, blue) and reports statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_field
|
int
|
Number of field positions to analyze along the radial direction. Defaults to 3. |
3
|
depth
|
float
|
Depth of the point source. Use float('inf') for collimated light. Defaults to float('inf'). |
float('inf')
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Spot analysis results keyed by field position (e.g., 'fov0.0', 'fov0.5'). Each entry contains 'rms' (RMS radius in um) and 'radius' (geometric radius in um). |
Source code in deeplens/optics/geolens.py
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 | |
find_diff_surf
Get differentiable/optimizable surface indices.
Returns a list of surface indices that can be optimized during lens design. Excludes the aperture surface from optimization.
Returns:
| Type | Description |
|---|---|
|
list or range: Surface indices excluding the aperture. |
Source code in deeplens/optics/geolens.py
calc_foclen
Compute effective focal length (EFL).
Traces a paraxial chief ray and computes the image height, then uses the image height to compute the EFL.
Updates
self.efl: Effective focal length. self.foclen: Alias for effective focal length. self.bfl: Back focal length (distance from last surface to sensor).
Reference
[1] https://wp.optics.arizona.edu/optomech/wp-content/uploads/sites/53/2016/10/Tutorial_MorelSophie.pdf [2] https://rafcamera.com/info/imaging-theory/back-focal-length
Source code in deeplens/optics/geolens.py
calc_numerical_aperture
Compute numerical aperture (NA).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
float
|
Refractive index. Defaults to 1.0. |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
NA |
float
|
Numerical aperture. |
Reference
[1] https://en.wikipedia.org/wiki/Numerical_aperture
Source code in deeplens/optics/geolens.py
calc_focal_plane
Compute the focus distance in the object space. Ray starts from sensor center and traces to the object space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wvln
|
float
|
Wavelength. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
Returns:
| Name | Type | Description |
|---|---|---|
focal_plane |
float
|
Focal plane in the object space. |
Source code in deeplens/optics/geolens.py
calc_sensor_plane
Calculate in-focus sensor plane.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
float
|
Depth of the object plane. Defaults to float("inf"). |
float('inf')
|
Returns:
| Name | Type | Description |
|---|---|---|
d_sensor |
Tensor
|
Sensor plane in the image space. |
Source code in deeplens/optics/geolens.py
calc_fov
Compute field of view (FoV) of the lens in radians.
Calculates FoV using two methods
- Perspective projection — from focal length and sensor size (effective FoV, ignoring distortion).
- Ray tracing — traces rays from the sensor edge backwards to determine the real FoV including distortion effects.
Updates
self.vfov (float): Vertical FoV in radians. self.hfov (float): Horizontal FoV in radians. self.dfov (float): Diagonal FoV in radians. self.rfov (float): Half-diagonal (radius) FoV in radians. self.real_rfov (float): Real half-diagonal FoV from ray tracing. self.real_dfov (float): Real diagonal FoV from ray tracing. self.eqfl (float): 35mm equivalent focal length in mm.
Reference
[1] https://en.wikipedia.org/wiki/Angle_of_view_(photography)
Source code in deeplens/optics/geolens.py
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 | |
calc_scale
Calculate the scale factor (object height / image height).
Uses the pinhole camera model to compute magnification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
float
|
Object distance from the lens (negative z direction). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
Scale factor relating object height to image height. |
Source code in deeplens/optics/geolens.py
calc_pupil
Compute entrance and exit pupil positions and radii.
The entrance and exit pupils must be recalculated whenever
- First-order parameters change (e.g., field of view, object height, image height),
- Lens geometry or materials change (e.g., surface curvatures, refractive indices, thicknesses),
- Or generally, any time the lens configuration is modified.
Updates
self.aper_idx: Index of the aperture surface. self.exit_pupilz, self.exit_pupilr: Exit pupil position and radius. self.entr_pupilz, self.entr_pupilr: Entrance pupil position and radius. self.exit_pupilz_parax, self.exit_pupilr_parax: Paraxial exit pupil. self.entr_pupilz_parax, self.entr_pupilr_parax: Paraxial entrance pupil. self.fnum: F-number calculated from focal length and entrance pupil.
Source code in deeplens/optics/geolens.py
get_entrance_pupil
Get entrance pupil location and radius.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paraxial
|
bool
|
If True, return paraxial approximation values. If False, return real ray-traced values. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(z_position, radius) of the entrance pupil in [mm]. |
Source code in deeplens/optics/geolens.py
get_exit_pupil
Get exit pupil location and radius.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paraxial
|
bool
|
If True, return paraxial approximation values. If False, return real ray-traced values. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(z_position, radius) of the exit pupil in [mm]. |
Source code in deeplens/optics/geolens.py
calc_exit_pupil
Calculate exit pupil location and radius.
Paraxial mode
Rays are emitted from near the center of the aperture stop and are close to the optical axis. This mode estimates the exit pupil position and radius under ideal (first-order) optical assumptions. It is fast and stable.
Non-paraxial mode
Rays are emitted from the edge of the aperture stop in large quantities. The exit pupil position and radius are determined based on the intersection points of these rays. This mode is slower and affected by aperture-related aberrations.
Use paraxial mode unless precise ray aiming is required.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paraxial
|
bool
|
center (True) or edge (False). |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
avg_pupilz |
float
|
z coordinate of exit pupil. |
avg_pupilr |
float
|
radius of exit pupil. |
Reference
[1] Exit pupil: how many rays can come from sensor to object space. [2] https://en.wikipedia.org/wiki/Exit_pupil
Source code in deeplens/optics/geolens.py
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 | |
calc_entrance_pupil
Calculate entrance pupil of the lens.
The entrance pupil is the optical image of the physical aperture stop, as seen through the optical elements in front of the stop. We sample backward rays from the aperture stop and trace them to the first surface, then find the intersection points of the reverse extension of the rays. The average of the intersection points defines the entrance pupil position and radius.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paraxial
|
bool
|
Ray sampling mode. If |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(z_position, radius) of entrance pupil. |
Note
[1] Use paraxial mode unless precise ray aiming is required. [2] This function only works for object at a far distance. For microscopes, this function usually returns a negative entrance pupil.
References
[1] Entrance pupil: how many rays can come from object space to sensor. [2] https://en.wikipedia.org/wiki/Entrance_pupil: "In an optical system, the entrance pupil is the optical image of the physical aperture stop, as 'seen' through the optical elements in front of the stop." [3] Zemax LLC, OpticStudio User Manual, Version 19.4, Document No. 2311, 2019.
Source code in deeplens/optics/geolens.py
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 | |
compute_intersection_points_2d
staticmethod
Compute the intersection points of 2D lines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
origins
|
Tensor
|
Origins of the lines. Shape: [N, 2] |
required |
directions
|
Tensor
|
Directions of the lines. Shape: [N, 2] |
required |
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Intersection points. Shape: [N*(N-1)/2, 2] |
Source code in deeplens/optics/geolens.py
refocus
Refocus the lens to a depth distance by changing sensor position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
foc_dist
|
float
|
focal distance. |
float('inf')
|
Note
In DSLR, phase detection autofocus (PDAF) is a popular and efficient method. But here we simplify the problem by calculating the in-focus position of green light.
Source code in deeplens/optics/geolens.py
set_fnum
Set F-number and aperture radius using binary search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fnum
|
float
|
target F-number. |
required |
Source code in deeplens/optics/geolens.py
set_target_fov_fnum
Set FoV, ImgH and F number, only use this function to assign design targets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rfov
|
float
|
half diagonal-FoV in radian. |
required |
fnum
|
float
|
F number. |
required |
Source code in deeplens/optics/geolens.py
set_fov
Set half-diagonal field of view as a design target.
Unlike calc_fov() which derives FoV from focal length and sensor
size, this method directly assigns the target FoV for lens optimisation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rfov
|
float
|
Half-diagonal FoV in radians. |
required |
Source code in deeplens/optics/geolens.py
prune_surf
Prune surfaces to allow all valid rays to go through.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expand_factor
|
float
|
height expansion factor. - For cellphone lens, we usually expand by 5% - For camera lens, we usually expand by 20%. |
None
|
Source code in deeplens/optics/geolens.py
correct_shape
Correct wrong lens shape during lens design optimization.
Applies correction rules to ensure valid lens geometry
- Move the first surface to z = 0.0
- Fix aperture distance if aperture is at the front
- Prune all surfaces to allow valid rays through
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expand_factor
|
float
|
Height expansion factor for surface pruning. If None, auto-selects based on lens type. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
True if any shape corrections were made, False otherwise. |
Source code in deeplens/optics/geolens.py
match_materials
Match lens materials to a glass catalog.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mat_table
|
str
|
Glass catalog name. Common options include 'CDGM', 'SCHOTT', 'OHARA'. Defaults to 'CDGM'. |
'CDGM'
|
Source code in deeplens/optics/geolens.py
analysis
analysis(save_name='./lens', depth=float('inf'), render=False, render_unwarp=False, lens_title=None, show=False)
Analyze the optical lens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
str
|
save name. |
'./lens'
|
depth
|
float
|
object depth distance. |
float('inf')
|
render
|
bool
|
whether render an image. |
False
|
render_unwarp
|
bool
|
whether unwarp the rendered image. |
False
|
lens_title
|
str
|
lens title |
None
|
show
|
bool
|
whether to show the rendered image. |
False
|
Source code in deeplens/optics/geolens.py
2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 | |
get_optimizer_params
get_optimizer_params(lrs=[0.0001, 0.0001, 0.01, 0.0001], decay=0.01, optim_mat=False, optim_surf_range=None)
Get optimizer parameters for different lens surface.
Recommendation
For cellphone lens: [d, c, k, a], [1e-4, 1e-4, 1e-1, 1e-4] For camera lens: [d, c, 0, 0], [1e-3, 1e-4, 0, 0]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lrs
|
list
|
learning rate for different parameters. |
[0.0001, 0.0001, 0.01, 0.0001]
|
decay
|
float
|
decay rate for higher order a. Defaults to 0.01. |
0.01
|
optim_mat
|
bool
|
whether to optimize material. Defaults to False. |
False
|
optim_surf_range
|
list
|
surface indices to be optimized. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
optimizer parameters |
Source code in deeplens/optics/geolens.py
2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 | |
get_optimizer
get_optimizer(lrs=[0.0001, 0.0001, 0.1, 0.0001], decay=0.01, optim_surf_range=None, optim_mat=False)
Get optimizers and schedulers for different lens parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lrs
|
list
|
learning rate for different parameters [c, d, k, a]. Defaults to [1e-4, 1e-4, 0, 1e-4]. |
[0.0001, 0.0001, 0.1, 0.0001]
|
decay
|
float
|
decay rate for higher order a. Defaults to 0.2. |
0.01
|
optim_surf_range
|
list
|
surface indices to be optimized. Defaults to None. |
None
|
optim_mat
|
bool
|
whether to optimize material. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
optimizer parameters |
Source code in deeplens/optics/geolens.py
read_lens_json
Read the lens from a JSON file.
Loads lens configuration including surfaces, materials, and optical properties from the DeepLens native JSON format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the JSON lens file. Defaults to './test.json'. |
'./test.json'
|
Note
After loading, the lens is moved to self.device and post_computation is called to calculate derived properties.
Source code in deeplens/optics/geolens.py
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 | |
write_lens_json
Write the lens to a JSON file.
Saves the complete lens configuration including all surfaces, materials, focal length, F-number, and sensor properties to the DeepLens JSON format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path for the output JSON file. Defaults to './test.json'. |
'./test.json'
|
Source code in deeplens/optics/geolens.py
deeplens.optics.geolens_pkg.eval.GeoLensEval
Mixin providing classical optical performance evaluation for GeoLens.
Provides spot diagrams, RMS error maps, MTF curves, distortion analysis, vignetting, and field curvature — results are accuracy-aligned with Zemax OpticStudio.
This class is not instantiated directly; it is mixed into
:class:~deeplens.optics.geolens.GeoLens.
draw_spot_radial
draw_spot_radial(save_name='./lens_spot_radial.png', num_fov=5, depth=float('inf'), num_rays=SPP_PSF, wvln_list=WAVE_RGB, show=False)
Draw spot diagram of the lens at different field angles along meridional (y) direction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
string
|
filename to save. Defaults to "./lens_spot_radial.png". |
'./lens_spot_radial.png'
|
num_fov
|
int
|
field of view number. Defaults to 4. |
5
|
depth
|
float
|
depth of the point source. Defaults to float("inf"). |
float('inf')
|
num_rays
|
int
|
number of rays to sample. Defaults to SPP_PSF. |
SPP_PSF
|
wvln_list
|
list
|
wavelength list to render. |
WAVE_RGB
|
show
|
bool
|
whether to show the plot. Defaults to False. |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
draw_spot_map
draw_spot_map(save_name='./lens_spot_map.png', num_grid=5, depth=DEPTH, num_rays=SPP_PSF, wvln_list=WAVE_RGB, show=False)
Draw spot diagram of the lens at different field angles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
string
|
filename to save. Defaults to "./lens_spot_map.png". |
'./lens_spot_map.png'
|
num_grid
|
int
|
number of grid points. Defaults to 5. |
5
|
depth
|
float
|
depth of the point source. Defaults to DEPTH. |
DEPTH
|
num_rays
|
int
|
number of rays to sample. Defaults to SPP_PSF. |
SPP_PSF
|
wvln_list
|
list
|
wavelength list to render. Defaults to WAVE_RGB. |
WAVE_RGB
|
show
|
bool
|
whether to show the plot. Defaults to False. |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
rms_map_rgb
Calculate the RMS spot error map across RGB wavelengths. Reference to the centroid of green rays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_grid
|
int
|
Number of grid points. Defaults to 64. |
32
|
depth
|
float
|
Depth of the point source. Defaults to DEPTH. |
DEPTH
|
Returns:
| Name | Type | Description |
|---|---|---|
rms_map |
Tensor
|
RMS map for RGB channels. Shape [3, num_grid, num_grid]. |
Source code in deeplens/optics/geolens_pkg/eval.py
rms_map
Calculate the RMS spot error map for a specific wavelength.
Currently this function is not used, but it can be used as the weight mask during optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_grid
|
int
|
Resolution of the grid used for sampling fields/points. Defaults to 64. |
32
|
depth
|
float
|
Depth of the point source. Defaults to DEPTH. |
DEPTH
|
wvln
|
float
|
Wavelength of the ray. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
Returns:
| Name | Type | Description |
|---|---|---|
rms_map |
Tensor
|
RMS map for the specified wavelength. Shape [num_grid, num_grid]. |
Source code in deeplens/optics/geolens_pkg/eval.py
calc_distortion_2D
Calculate distortion at a specific field angle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rfov
|
float
|
view angle (degree) |
required |
wvln
|
float
|
wavelength |
DEFAULT_WAVE
|
plane
|
str
|
meridional or sagittal |
'meridional'
|
ray_aiming
|
bool
|
whether the chief ray through the center of the stop. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
distortion |
float
|
distortion at the specific field angle |
Source code in deeplens/optics/geolens_pkg/eval.py
draw_distortion_radial
draw_distortion_radial(rfov, save_name=None, num_points=GEO_GRID, wvln=DEFAULT_WAVE, plane='meridional', ray_aiming=True, show=False)
Draw distortion. zemax format(default): ray_aiming = False.
Note: this function is provided by a community contributor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rfov
|
view angle (degrees) |
required | |
save_name
|
Save filename. Defaults to None. |
None
|
|
num_points
|
Number of points. Defaults to GEO_GRID. |
GEO_GRID
|
|
plane
|
Meridional or sagittal. Defaults to meridional. |
'meridional'
|
|
ray_aiming
|
Whether to use ray aiming. Defaults to False. |
True
|
Source code in deeplens/optics/geolens_pkg/eval.py
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
distortion_map
Compute distortion map at a given depth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_grid
|
int
|
number of grid points. |
16
|
depth
|
float
|
depth of the point source. |
DEPTH
|
wvln
|
float
|
wavelength. |
DEFAULT_WAVE
|
Returns:
| Name | Type | Description |
|---|---|---|
distortion_grid |
Tensor
|
distortion map. shape (grid_size, grid_size, 2) |
Source code in deeplens/optics/geolens_pkg/eval.py
distortion_center
Calculate the distortion center for given normalized points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
Normalized point source positions. Shape [N, 3] or [..., 3]. x, y in [-1, 1], z (depth) in [-Inf, 0]. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
distortion_center |
Normalized distortion center positions. Shape [N, 2] or [..., 2]. x, y in [-1, 1]. |
Source code in deeplens/optics/geolens_pkg/eval.py
draw_distortion
Draw distortion map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
str
|
filename to save. Defaults to None. |
None
|
num_grid
|
int
|
number of grid points. Defaults to 16. |
16
|
depth
|
float
|
depth of the point source. Defaults to DEPTH. |
DEPTH
|
wvln
|
float
|
wavelength. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
show
|
bool
|
whether to show the plot. Defaults to False. |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
mtf
Calculate Modulation Transfer Function at a specific field of view.
Computes the geometric MTF by first generating a PSF at the given field position, then converting it to tangential and sagittal MTF curves via FFT.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fov
|
float
|
Field of view angle in radians. |
required |
wvln
|
float
|
Wavelength in micrometers. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(freq, mtf_tan, mtf_sag) where: - freq (ndarray): Spatial frequency axis in cycles/mm. - mtf_tan (ndarray): Tangential (meridional) MTF values. - mtf_sag (ndarray): Sagittal MTF values. |
Source code in deeplens/optics/geolens_pkg/eval.py
psf2mtf
staticmethod
Calculate MTF from PSF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psf
|
tensor
|
2D PSF tensor (e.g., ks x ks). Assumes standard orientation where the array's y-axis corresponds to the tangential/meridional direction and the x-axis to the sagittal direction. |
required |
pixel_size
|
float
|
Pixel size in mm. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
freq |
ndarray
|
Frequency axis (cycles/mm). |
tangential_mtf |
ndarray
|
Tangential MTF. |
sagittal_mtf |
ndarray
|
Sagittal MTF. |
Reference
[1] https://en.wikipedia.org/wiki/Optical_transfer_function [2] https://www.edmundoptics.com/knowledge-center/application-notes/optics/introduction-to-modulation-transfer-function/?srsltid=AfmBOoq09vVDVlh_uuwWnFoMTg18JVgh18lFSw8Ci4Sdlry-AmwGkfDd
Source code in deeplens/optics/geolens_pkg/eval.py
draw_mtf
draw_mtf(save_name='./lens_mtf.png', relative_fov_list=[0.0, 0.7, 1.0], depth_list=[DEPTH], psf_ks=128, show=False)
Draw a grid of MTF curves. Each subplot in the grid corresponds to a specific (depth, FOV) combination. Each subplot displays MTF curves for R, G, B wavelengths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relative_fov_list
|
list
|
List of relative field of view values. Defaults to [0.0, 0.7, 1.0]. |
[0.0, 0.7, 1.0]
|
depth_list
|
list
|
List of depth values. Defaults to [DEPTH]. |
[DEPTH]
|
save_name
|
str
|
Filename to save the plot. Defaults to "./mtf_grid.png". |
'./lens_mtf.png'
|
psf_ks
|
int
|
Kernel size for intermediate PSF calculation. Defaults to 256. |
128
|
show
|
bool
|
whether to show the plot. Defaults to False. |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 | |
draw_field_curvature
draw_field_curvature(save_name=None, num_points=32, z_span=1.0, z_steps=1001, wvln_list=WAVE_RGB, spp=SPP_CALC, show=False)
Draw field curvature: best-focus defocus vs field angle, RGB overlaid.
For each wavelength and field angle, sweeps defocus positions around the sensor plane and finds the position that minimizes the tangential ray spread. Plots tangential curves as solid lines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
str
|
Path to save the figure. Defaults to
|
None
|
num_points
|
int
|
Number of field angle samples. Defaults to 32. |
32
|
z_span
|
float
|
Half-range of defocus sweep in mm. Defaults to 1.0. |
1.0
|
z_steps
|
int
|
Number of defocus steps. Defaults to 1001. |
1001
|
wvln_list
|
list
|
Wavelengths to evaluate. Defaults to WAVE_RGB. |
WAVE_RGB
|
spp
|
int
|
Number of rays per field point. Defaults to SPP_CALC. |
SPP_CALC
|
show
|
bool
|
If True, display plot interactively. Defaults to False. |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 | |
vignetting
Compute relative illumination (vignetting) map.
Measures the fraction of rays that successfully reach the sensor for each field position, indicating light falloff from center to edge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
float
|
Object distance. Defaults to DEPTH. |
DEPTH
|
num_grid
|
int
|
Grid resolution for field sampling. Defaults to 64. |
64
|
Returns:
| Name | Type | Description |
|---|---|---|
Tensor |
Vignetting map with values in [0, 1]. Shape [num_grid, num_grid]. A value of 1.0 means no vignetting; 0.0 means fully vignetted. |
Source code in deeplens/optics/geolens_pkg/eval.py
draw_vignetting
Draw vignetting (relative illumination) map as a grayscale image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to save the figure. If None, auto-generates a name based on depth. Defaults to None. |
None
|
depth
|
float
|
Object distance. Defaults to DEPTH. |
DEPTH
|
resolution
|
int
|
Output image resolution in pixels. Defaults to 512. |
512
|
show
|
bool
|
If True, display the plot interactively. Defaults to False. |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
wavefront_error
field_curvature
aberration_histogram
calc_chief_ray
Compute chief ray for an incident angle.
If chief ray is only used to determine the ideal image height, we can warp this function into the image height calculation function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fov
|
float
|
incident angle in degree. |
required |
plane
|
str
|
"sagittal" or "meridional". |
'sagittal'
|
Returns:
| Name | Type | Description |
|---|---|---|
chief_ray_o |
Tensor
|
origin of chief ray. |
chief_ray_d |
Tensor
|
direction of chief ray. |
Note
It is 2D ray tracing, for 3D chief ray, we can shrink the pupil, trace rays, calculate the centroid as the chief ray.
Source code in deeplens/optics/geolens_pkg/eval.py
calc_chief_ray_infinite
calc_chief_ray_infinite(rfov, depth=0.0, wvln=DEFAULT_WAVE, plane='meridional', num_rays=SPP_CALC, ray_aiming=True)
Compute chief ray for an incident angle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rfov
|
float
|
incident angle in degree. |
required |
depth
|
float
|
depth of the object. |
0.0
|
wvln
|
float
|
wavelength of the light. |
DEFAULT_WAVE
|
plane
|
str
|
"sagittal" or "meridional". |
'meridional'
|
num_rays
|
int
|
number of rays. |
SPP_CALC
|
ray_aiming
|
bool
|
whether the chief ray through the center of the stop. |
True
|
Source code in deeplens/optics/geolens_pkg/eval.py
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 | |
deeplens.optics.geolens_pkg.optim.GeoLensOptim
Mixin providing differentiable optimisation for GeoLens.
Implements gradient-based lens design using PyTorch autograd:
- Loss functions – RMS spot error, focus, surface regularity, gap constraints, material validity.
- Constraint initialisation – edge-thickness and self-intersection guards.
- Optimizer helpers – parameter groups with per-type learning rates and cosine annealing schedules.
- High-level
optimize()– curriculum-learning training loop.
This class is not instantiated directly; it is mixed into
:class:~deeplens.optics.geolens.GeoLens.
References
Xinge Yang et al., "Curriculum learning for ab initio deep learned refractive optics," Nature Communications 2024.
init_constraints
Initialize constraints for the lens design.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
constraint_params
|
dict
|
Constraint parameters. |
None
|
Source code in deeplens/optics/geolens_pkg/optim.py
loss_reg
Compute combined regularization loss for lens design.
Aggregates multiple constraint losses to keep the lens physically valid during gradient-based optimisation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
w_focus
|
float
|
Weight for focus loss. Defaults to 10.0. |
10.0
|
w_ray_angle
|
float
|
Weight for chief ray angle loss. Defaults to 2.0. |
2.0
|
w_intersec
|
float
|
Weight for self-intersection loss. Defaults to 1.0. |
1.0
|
w_gap
|
float
|
Weight for air gap / thickness loss. Defaults to 0.1. |
0.1
|
w_surf
|
float
|
Weight for surface shape loss. Defaults to 1.0. |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(loss_reg, loss_dict) where: - loss_reg (Tensor): Scalar combined regularization loss. - loss_dict (dict): Per-component loss values for logging. |
Source code in deeplens/optics/geolens_pkg/optim.py
loss_infocus
Sample parallel rays and compute RMS loss on the sensor plane, minimize focus loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
float
|
target of RMS loss. Defaults to 0.005 [mm]. |
0.005
|
Source code in deeplens/optics/geolens_pkg/optim.py
loss_surface
Penalize extreme surface shapes that are difficult to manufacture.
Checks four constraints for each optimisable surface
- Sag-to-diameter ratio exceeding
sag2diam_max. - Maximum surface gradient exceeding
grad_max. - Diameter-to-thickness ratio exceeding
diam2thick_max. - Maximum-to-minimum thickness ratio exceeding
tmax2tmin_max.
Returns:
| Name | Type | Description |
|---|---|---|
Tensor |
Scalar surface shape penalty loss. |
Source code in deeplens/optics/geolens_pkg/optim.py
loss_intersec
Loss function to avoid self-intersection.
This function penalizes when surfaces are too close to each other, which could cause self-intersection or manufacturing issues.
Source code in deeplens/optics/geolens_pkg/optim.py
loss_gap
Loss function to penalize too large air gap and thickness.
This function penalizes when air gaps or lens thicknesses are too large, which could make the lens system impractically large.
Source code in deeplens/optics/geolens_pkg/optim.py
loss_ray_angle
Penalize large chief ray angles and low obliquity factors.
Ensures that rays arrive at the sensor within acceptable incidence angles, which is critical for sensor coupling and colour cross-talk.
Returns:
| Name | Type | Description |
|---|---|---|
Tensor |
Scalar chief-ray-angle penalty loss. |
Source code in deeplens/optics/geolens_pkg/optim.py
loss_mat
Penalize material parameters outside manufacturable ranges.
Constrains refractive index n to [1.5, 1.9] and Abbe number V to [30, 70] for each non-air surface material.
Returns:
| Name | Type | Description |
|---|---|---|
Tensor |
Scalar material penalty loss. |
Source code in deeplens/optics/geolens_pkg/optim.py
loss_rms
Loss function to compute RGB spot error RMS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_grid
|
int
|
Number of grid points. Defaults to GEO_GRID. |
GEO_GRID
|
depth
|
float
|
Depth of the lens. Defaults to DEPTH. |
DEPTH
|
num_rays
|
int
|
Number of rays. Defaults to SPP_CALC. |
SPP_PSF
|
sample_more_off_axis
|
bool
|
Whether to sample more off-axis rays. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
avg_rms_error |
Tensor
|
RMS error averaged over wavelengths and grid points. |
Source code in deeplens/optics/geolens_pkg/optim.py
sample_ring_arm_rays
sample_ring_arm_rays(num_ring=8, num_arm=8, spp=2048, depth=DEPTH, wvln=DEFAULT_WAVE, scale_pupil=1.0, sample_more_off_axis=True)
Sample rays from object space using a ring-arm pattern.
This method distributes sampling points (origins of ray bundles) on a polar grid in the object plane,
defined by field of view. This is useful for capturing lens performance across the full field.
The points include the center and num_ring rings with num_arm points on each.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_ring
|
int
|
Number of rings to sample in the field of view. |
8
|
num_arm
|
int
|
Number of arms (spokes) to sample for each ring. |
8
|
spp
|
int
|
Total number of rays to be sampled, distributed among field points. |
2048
|
depth
|
float
|
Depth of the object plane. |
DEPTH
|
wvln
|
float
|
Wavelength of the rays. |
DEFAULT_WAVE
|
scale_pupil
|
float
|
Scale factor for the pupil size. |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
Ray |
A Ray object containing the sampled rays. |
Source code in deeplens/optics/geolens_pkg/optim.py
optimize
optimize(lrs=[0.001, 0.0001, 0.1, 0.0001], decay=0.01, iterations=5000, test_per_iter=100, centroid=False, optim_mat=False, shape_control=True, result_dir=None)
Optimise the lens by minimising RGB RMS spot errors.
Runs a curriculum-learning training loop with Adam optimiser and cosine annealing. Periodically evaluates the lens, saves intermediate results, and optionally corrects surface shapes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lrs
|
list
|
Learning rates for [d, c, k, a] parameter groups. Defaults to [1e-3, 1e-4, 1e-1, 1e-4]. |
[0.001, 0.0001, 0.1, 0.0001]
|
decay
|
float
|
Decay factor for higher-order aspheric coefficients. Defaults to 0.01. |
0.01
|
iterations
|
int
|
Total training iterations. Defaults to 5000. |
5000
|
test_per_iter
|
int
|
Evaluate and save every N iterations. Defaults to 100. |
100
|
centroid
|
bool
|
If True, use chief-ray centroid as PSF centre reference; otherwise use pinhole model. Defaults to False. |
False
|
optim_mat
|
bool
|
If True, include material parameters (n, V) in optimisation. Defaults to False. |
False
|
shape_control
|
bool
|
If True, call |
True
|
result_dir
|
str
|
Directory to save results. If None, auto-generates a timestamped directory. Defaults to None. |
None
|
Note
Debug hints: 1. Slowly optimise with small learning rate. 2. FoV and thickness should match well. 3. Keep parameter ranges reasonable. 4. Higher aspheric order is better but more sensitive. 5. More iterations with larger ray sampling improves convergence.
Source code in deeplens/optics/geolens_pkg/optim.py
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 | |
deeplens.optics.geolens_pkg.io.GeoLensIO
Mixin providing file I/O for GeoLens.
Supports reading and writing lens prescriptions in three formats:
- JSON (primary): human-readable, supports parenthesised optimisable
parameters, e.g.
"(d)": 5.0. - Zemax .zmx: industry-standard sequential lens file.
- Code V .seq: Code V sequential format (read-only).
This class is not instantiated directly; it is mixed into
:class:~deeplens.optics.geolens.GeoLens.
read_lens_zmx
Load the lens from a Zemax .zmx sequential lens file.
Parses STANDARD and EVENASPH surface types, glass materials, field definitions (YFLN), and entrance pupil settings (ENPD/FLOA).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the .zmx file. Supports both UTF-8 and UTF-16 encoded files. Defaults to './test.zmx'. |
'./test.zmx'
|
Returns:
| Name | Type | Description |
|---|---|---|
GeoLens |
|
Source code in deeplens/optics/geolens_pkg/io.py
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 119 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 | |
write_lens_zmx
Write the lens to a Zemax .zmx sequential lens file.
Exports surfaces (STANDARD or EVENASPH), materials, field definitions, and entrance pupil settings in Zemax OpticStudio format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Output file path. Defaults to './test.zmx'. |
'./test.zmx'
|
Source code in deeplens/optics/geolens_pkg/io.py
read_lens_seq
Load the lens from a CODE V .seq sequential file.
Parses standard and aspheric surfaces (with conic and polynomial coefficients A–I), entrance pupil diameter (EPD), field angles (YAN), aperture stop (STO), and image surface (SI).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the .seq file. Supports both UTF-8 and Latin-1 encoded files. Defaults to './test.seq'. |
'./test.seq'
|
Returns:
| Name | Type | Description |
|---|---|---|
GeoLens |
|
Source code in deeplens/optics/geolens_pkg/io.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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 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 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 | |
write_lens_seq
Write the lens to a CODE V .seq sequential file.
Exports surfaces, materials, field definitions, and entrance pupil settings in CODE V format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Output file path. Defaults to './test.seq'. |
'./test.seq'
|
Returns:
| Name | Type | Description |
|---|---|---|
GeoLens |
|
Source code in deeplens/optics/geolens_pkg/io.py
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 | |
deeplens.optics.geolens_pkg.vis.GeoLensVis
Mixin providing 2-D lens layout and ray visualisation for GeoLens.
Generates publication-quality cross-section plots showing lens surfaces and traced ray bundles in either the meridional or sagittal plane.
This class is not instantiated directly; it is mixed into
:class:~deeplens.optics.geolens.GeoLens.
sample_parallel_2D
sample_parallel_2D(fov=0.0, num_rays=7, wvln=DEFAULT_WAVE, plane='meridional', entrance_pupil=True, depth=0.0)
Sample parallel rays (2D) in object space.
Used for (1) drawing lens setup, (2) 2D geometric optics calculation, for example, refocusing to infinity
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fov
|
float
|
incident angle (in degree). Defaults to 0.0. |
0.0
|
depth
|
float
|
sampling depth. Defaults to 0.0. |
0.0
|
num_rays
|
int
|
ray number. Defaults to 7. |
7
|
wvln
|
float
|
ray wvln. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
plane
|
str
|
sampling plane. Defaults to "meridional" (y-z plane). |
'meridional'
|
entrance_pupil
|
bool
|
whether to use entrance pupil. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
ray |
Ray object
|
Ray object. Shape [num_rays, 3] |
Source code in deeplens/optics/geolens_pkg/vis.py
sample_point_source_2D
Sample point source rays (2D) in object space.
Used for (1) drawing lens setup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fov
|
float
|
incident angle (in degree). Defaults to 0.0. |
0.0
|
depth
|
float
|
sampling depth. Defaults to DEPTH. |
DEPTH
|
num_rays
|
int
|
ray number. Defaults to 7. |
7
|
wvln
|
float
|
ray wvln. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
entrance_pupil
|
bool
|
whether to use entrance pupil. Defaults to False. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
ray |
Ray object
|
Ray object. Shape [num_rays, 3] |
Source code in deeplens/optics/geolens_pkg/vis.py
draw_layout
draw_layout(filename, depth=float('inf'), zmx_format=True, multi_plot=False, lens_title=None, show=False)
Plot 2D lens layout with ray tracing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
Output filename |
required | |
depth
|
Depth for ray tracing |
float('inf')
|
|
entrance_pupil
|
Whether to use entrance pupil |
required | |
zmx_format
|
Whether to use ZMX format |
True
|
|
multi_plot
|
Whether to create multiple plots |
False
|
|
lens_title
|
Title for the lens plot |
None
|
|
show
|
Whether to show the plot |
False
|
Source code in deeplens/optics/geolens_pkg/vis.py
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 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 275 276 277 278 279 280 281 282 283 284 285 | |
draw_lens_2d
Draw lens cross-section layout in a 2D plot.
Renders each surface profile, connects lens elements with edge lines, and draws the sensor plane.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes
|
Existing axes to draw on. If None, creates a new figure. Defaults to None. |
None
|
fig
|
Figure
|
Existing figure. Defaults to None. |
None
|
color
|
str
|
Line colour for lens outlines. Defaults to 'k'. |
'k'
|
linestyle
|
str
|
Line style. Defaults to '-'. |
'-'
|
zmx_format
|
bool
|
If True, draw stepped edge connections matching Zemax layout style. Defaults to False. |
False
|
fix_bound
|
bool
|
If True, use fixed axis limits [-1,7]x[-4,4]. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(ax, fig) matplotlib axes and figure objects. |
Source code in deeplens/optics/geolens_pkg/vis.py
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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | |
draw_ray_2d
Plot ray paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ray_o_record
|
list
|
list of intersection points. |
required |
ax
|
Axes
|
matplotlib axes. |
required |
fig
|
Figure
|
matplotlib figure. |
required |
Source code in deeplens/optics/geolens_pkg/vis.py
draw_layout_3d
Draw 3D layout of the lens system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to save the figure. Defaults to None. |
None
|
view_angle
|
int
|
Viewing angle for the 3D plot |
30
|
show
|
bool
|
Whether to display the figure |
False
|
Returns:
| Type | Description |
|---|---|
|
fig, ax: Matplotlib figure and axis objects |
Source code in deeplens/optics/geolens_pkg/vis.py
405 406 407 408 409 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 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 | |
create_barrier
Create a 3D barrier for the lens system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
Path to save the figure |
required | |
barrier_thickness
|
Thickness of the barrier |
1.0
|
|
ring_height
|
Height of the annular ring |
0.5
|
|
ring_size
|
Size of the annular ring |
1.0
|
Source code in deeplens/optics/geolens_pkg/vis.py
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 | |
deeplens.optics.geolens_pkg.tolerance.GeoLensTolerance
Mixin providing tolerance analysis for GeoLens.
Implements two complementary approaches:
- Sensitivity analysis – first-order gradient-based estimation of how each manufacturing error affects optical performance.
- Monte-Carlo analysis – statistical sampling of random manufacturing errors to predict yield and worst-case performance.
This class is not instantiated directly; it is mixed into
:class:~deeplens.optics.geolens.GeoLens.
References
Jun Dai et al., "Tolerance-Aware Deep Optics," arXiv:2502.04719, 2025.
init_tolerance
Initialize manufacturing tolerance parameters for all surfaces.
Sets up tolerance ranges (e.g., curvature, thickness, decenter, tilt)
on each surface. These are used by sample_tolerance() to simulate
random manufacturing errors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tolerance_params
|
dict
|
Custom tolerance specifications. If None, each surface uses its own defaults. Defaults to None. |
None
|
Source code in deeplens/optics/geolens_pkg/tolerance.py
sample_tolerance
Apply random manufacturing errors to all surfaces.
Randomly perturbs each surface according to its tolerance ranges and then refocuses the lens to compensate for the focus shift.
Source code in deeplens/optics/geolens_pkg/tolerance.py
zero_tolerance
Reset all manufacturing errors to zero (nominal lens state).
Clears the perturbations on every surface and refocuses the lens.
Source code in deeplens/optics/geolens_pkg/tolerance.py
tolerancing_sensitivity
Use sensitivity analysis (1st order gradient) to compute the tolerance score.
References
[1] Page 10 from: https://wp.optics.arizona.edu/optomech/wp-content/uploads/sites/53/2016/08/8-Tolerancing-1.pdf [2] Fast sensitivity control method with differentiable optics. Optics Express 2025. [3] Optical Design Tolerancing. CODE V.
Source code in deeplens/optics/geolens_pkg/tolerance.py
tolerancing_monte_carlo
Use Monte Carlo simulation to compute the tolerance.
Note: we can multiplex sampled rays to improve the speed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trials
|
int
|
Number of Monte Carlo trials |
1000
|
tolerance_params
|
dict
|
Tolerance parameters |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Monte Carlo tolerance analysis results |
References
[1] https://optics.ansys.com/hc/en-us/articles/43071088477587-How-to-analyze-your-tolerance-results [2] Optical Design Tolerancing. CODE V.
Source code in deeplens/optics/geolens_pkg/tolerance.py
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 198 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 | |
tolerancing_wavefront
Use wavefront differential method to compute the tolerance.
Wavefront differential method is proposed in [1], while the detailed implementation remains unknown. I (Xinge Yang) assume a symbolic differentiation is used to compute the gradient/Jacobian of the wavefront error. With AutoDiff, we can easily calculate Jacobian with gradient backpropagation, therefore I leave the implementation of this method as future work.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tolerance_params
|
dict
|
Tolerance parameters |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Wavefront tolerance analysis results |
References
[1] Optical Design Tolerancing. CODE V.
Source code in deeplens/optics/geolens_pkg/tolerance.py
deeplens.optics.geolens_pkg.view_3d.GeoLensVis3D
Mixin providing 3-D mesh visualisation for GeoLens.
Creates lens surface, aperture, barrier, sensor, and ray-path meshes as
polygon data and optionally renders them with PyVista. All geometry is
expressed in millimetres and stored as :class:CrossPoly (vertex/face)
objects that can be saved to .obj files for external renderers.
This class is not instantiated directly; it is mixed into
:class:~deeplens.optics.geolens.GeoLens.
create_mesh
Create all lens/bridge/sensor/aperture meshes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lens
|
GeoLens
|
The lens object. |
required |
mesh_rings
|
int
|
The number of rings in the mesh. |
32
|
mesh_arms
|
int
|
The number of arms in the mesh. |
128
|
is_wrap
|
bool
|
Whether to wrap the lens bridge around the lens as cylinder. |
False
|
Returns: surf_meshes (List[Surface]): Lens surfaces meshes. bridge_meshes (List[FaceMesh]): Lens bridges meshes. (NOT support wrap around for now) sensor_mesh (RectangleMesh): Sensor meshes. (only support rectangular sensor for now)
Source code in deeplens/optics/geolens_pkg/view_3d.py
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 | |
draw_lens_3d
draw_lens_3d(plotter=None, save_dir: Optional[str] = None, mesh_rings: int = 32, mesh_arms: int = 128, surface_color: List[float] = [0.06, 0.3, 0.6], draw_rays: bool = True, fovs: List[float] = [0.0], fov_phis: List[float] = [0.0], ray_rings: int = 6, ray_arms: int = 8, is_wrap: bool = False)
Draw lens 3D layout with rays using pyvista.
Note: PyVista is imported lazily only when this method is called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plotter
|
pv.Plotter. Optional pyvista Plotter instance. If None, a new one is created. |
None
|
|
save_dir
|
str
|
The directory to save the image. |
None
|
mesh_rings
|
int
|
The number of rings in the mesh. |
32
|
mesh_arms
|
int
|
The number of arms in the mesh. |
128
|
surface_color
|
List[float]
|
The color of the surfaces. |
[0.06, 0.3, 0.6]
|
draw_rays
|
bool
|
Whether to show the rays. |
True
|
fovs
|
List[float]
|
The FoV angles to be sampled, unit: degree. |
[0.0]
|
fov_phis
|
List[float]
|
The FoV azimuthal angles to be sampled, unit: degree. |
[0.0]
|
ray_rings
|
int
|
The number of pupil rings to be sampled. |
6
|
ray_arms
|
int
|
The number of pupil arms to be sampled. |
8
|
is_wrap
|
bool
|
Whether to wrap the lens bridge around the lens as cylinder. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
plotter |
pv.Plotter. The pyvista Plotter instance. |
Source code in deeplens/optics/geolens_pkg/view_3d.py
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 | |
save_lens_obj
save_lens_obj(save_dir: str, mesh_rings: int = 64, mesh_arms: int = 128, save_rays: bool = False, fovs: List[float] = [0.0], fov_phis: List[float] = [0.0], ray_rings: int = 6, ray_arms: int = 8, is_wrap: bool = False, save_elements: bool = True)
Save lens geometry and rays as .obj files using pyvista.
Note: use #F2F7FFFF as the color for lens when rendering in Blender.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lens
|
GeoLens
|
The lens object. |
required |
save_dir
|
str
|
The directory to save the image. |
required |
mesh_rings
|
int
|
The number of rings in the mesh. (default: 128) |
64
|
mesh_arms
|
int
|
The number of arms in the mesh. (default: 256) |
128
|
save_rays
|
bool
|
Whether to save the rays. |
False
|
fovs
|
List[float]
|
The FoV angles to be sampled, unit: degree. |
[0.0]
|
fov_phis
|
List[float]
|
The FoV azimuthal angles to be sampled, unit: degree. |
[0.0]
|
ray_rings
|
int
|
The number of pupil rings to be sampled. (default: 6) |
6
|
ray_arms
|
int
|
The number of pupil arms to be sampled. (default: 8) |
8
|
is_wrap
|
bool
|
Whether to wrap the lens bridge around the lens as cylinder. |
False
|
save_elements
|
bool
|
Whether to save the elements. |
True
|
Source code in deeplens/optics/geolens_pkg/view_3d.py
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 | |
Combines a GeoLens with a diffractive optical element (DOE). Performs coherent ray tracing to the DOE plane, then Angular Spectrum Method (ASM) propagation to the sensor.
deeplens.optics.HybridLens
Bases: Lens
Hybrid refractive-diffractive lens using a differentiable ray–wave model.
Combines a :class:~deeplens.optics.geolens.GeoLens (refractive module)
with a diffractive optical element (DOE) placed behind it. The pipeline
is:
- Coherent ray tracing through the embedded
GeoLensto obtain a complex wavefront at the DOE plane (including all geometric aberrations). - DOE phase modulation applied to the wavefront.
- Angular Spectrum Method (ASM) propagation from the DOE to the sensor plane to produce the final intensity PSF.
This enables end-to-end gradient flow from image quality metrics back to both refractive surface parameters and the DOE phase profile.
Attributes:
| Name | Type | Description |
|---|---|---|
geolens |
GeoLens
|
Embedded refractive module. |
doe |
Diffractive optical element (one of |
Notes
Operates in torch.float64 by default for numerical stability of
the wave-propagation step.
References
Xinge Yang et al., "End-to-End Hybrid Refractive-Diffractive Lens Design with Differentiable Ray-Wave Model," SIGGRAPH Asia 2024.
Initialize a hybrid refractive-diffractive lens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the lens configuration JSON file. Defaults to None. |
None
|
device
|
str
|
Computation device ('cpu' or 'cuda'). Defaults to None. |
None
|
dtype
|
dtype
|
Data type for computations. Defaults to torch.float64. |
float64
|
Source code in deeplens/optics/hybridlens.py
read_lens_json
Read the lens configuration from a JSON file.
Loads a :class:GeoLens and associated DOE from the specified file.
A Plane surface is appended to the GeoLens surface list as a
placeholder for the DOE plane.
Supported DOE types: binary2, pixel2d, fresnel,
zernike, grating.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the JSON configuration file. Must
contain a |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the DOE type in the file is not supported. |
Source code in deeplens/optics/hybridlens.py
write_lens_json
Write the lens configuration to a JSON file.
Serialises the GeoLens surfaces (excluding the DOE placeholder)
and the DOE configuration into a single JSON file that can be
reloaded with :meth:read_lens_json.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lens_path
|
str
|
Output file path. |
required |
Source code in deeplens/optics/hybridlens.py
analysis
Run a quick visual analysis of the hybrid lens.
Generates two figures: the 2D lens layout (saved to save_name) and
the DOE phase map (saved to <save_name>_doe.png).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
str
|
Base file path for the layout image.
The DOE phase-map image is derived by appending |
'./test.png'
|
Source code in deeplens/optics/hybridlens.py
double
Convert the GeoLens and DOE to float64 precision.
Double precision is required for numerically stable phase
accumulation during coherent ray tracing and ASM propagation.
Called automatically by :meth:__init__.
Source code in deeplens/optics/hybridlens.py
refocus
Refocus the hybrid lens to a given object distance.
Only the GeoLens sensor-to-last-surface spacing is adjusted; the
DOE remains fixed relative to the refractive group (it is physically
cemented to the lens barrel).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
foc_dist
|
float
|
Target focus distance in [mm] (negative, towards the object). |
required |
Source code in deeplens/optics/hybridlens.py
calc_scale
Calculate the object-to-image magnification scale factor.
Delegates to the embedded :class:GeoLens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
float
|
Object distance in [mm] (negative, towards the object). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
Scale factor mapping normalised sensor coordinates
|
Source code in deeplens/optics/hybridlens.py
doe_field
Compute the complex wave field at the DOE plane via coherent ray tracing.
Similar to GeoLens.pupil_field(), but evaluates the field at the
last surface (DOE plane) instead of the exit pupil. The returned
wavefront encodes amplitude, phase, and all diffraction-order
information needed for subsequent DOE modulation and ASM propagation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
point
|
Tensor
|
Point source position, shape |
required |
wvln
|
float
|
Wavelength in [um]. Defaults to
|
DEFAULT_WAVE
|
spp
|
int
|
Number of rays to sample. Must be
|
SPP_COHERENT
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If spp < 1,000,000 or the default dtype is not
|
Source code in deeplens/optics/hybridlens.py
psf
Compute a single-point monochromatic PSF using the ray-wave model.
The returned PSF includes all diffraction orders with physically correct diffraction efficiencies. The pipeline is:
- Coherent ray tracing through the
GeoLensto obtain the complex wavefront at the DOE plane. - DOE phase modulation applied to the wavefront.
- ASM propagation to the sensor, intensity calculation, cropping, and normalisation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
list or Tensor
|
|
[0.0, 0.0, -10000.0]
|
ks
|
int or None
|
Output PSF patch size. If |
PSF_KS
|
wvln
|
float
|
Wavelength in [um]. Defaults to
|
DEFAULT_WAVE
|
spp
|
int
|
Number of coherent rays to sample. Defaults
to |
SPP_COHERENT
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Normalised PSF patch (sums to 1), shape
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the default dtype is not |
Source code in deeplens/optics/hybridlens.py
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 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 | |
draw_layout
Draw the hybrid-lens layout with ray paths and wave-propagation arcs.
Renders the refractive elements via GeoLens.draw_lens_2d(), traces
rays at three field angles (on-axis, 0.707x, 0.99x full field), and
overlays concentric arcs between the DOE and sensor to illustrate the
wave-propagation region.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
str
|
File path to save the figure (used only
when ax is |
'./DOELens.png'
|
depth
|
float
|
Object depth [mm] for the traced rays.
Defaults to |
-10000.0
|
ax
|
Axes
|
Pre-existing axes to draw
into. If |
None
|
fig
|
Figure
|
Pre-existing figure. Required when ax is provided. |
None
|
Returns:
| Type | Description |
|---|---|
|
tuple or None: |
Source code in deeplens/optics/hybridlens.py
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 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 | |
get_optimizer
Build an Adam optimiser for joint lens + DOE design.
Collects trainable parameters from both the GeoLens (surface
thicknesses, curvatures, conic constants, aspheric coefficients) and
the DOE phase profile into a single optimiser with per-group learning
rates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
doe_lr
|
float
|
Learning rate for DOE phase parameters.
Defaults to |
0.0001
|
lens_lr
|
list[float]
|
Per-parameter-group learning
rates for the GeoLens, ordered as
|
[0.0001, 0.0001, 0.01, 1e-05]
|
lr_decay
|
float
|
Multiplicative decay applied to
higher-order aspheric coefficients. Defaults to |
0.01
|
Returns:
| Type | Description |
|---|---|
|
torch.optim.Adam: Configured optimiser over all trainable parameters. |
Source code in deeplens/optics/hybridlens.py
Pure wave-optics lens using diffractive surfaces and scalar diffraction propagation.
deeplens.optics.DiffractiveLens
Bases: Lens
Paraxial diffractive lens in which each element is modelled as a phase surface.
Every optical element (converging lens, DOE, metasurface, …) is represented by a phase function applied to an incoming complex wavefront. Propagation between surfaces uses the Angular Spectrum Method (ASM). This model is simple and fast, but accurate only in the paraxial regime (it does not account for higher-order geometric aberrations).
Attributes:
| Name | Type | Description |
|---|---|---|
surfaces |
list
|
Ordered list of diffractive/phase surfaces. |
d_sensor |
Tensor
|
Distance from the last surface to the sensor plane [mm]. |
Notes
Operates in torch.float64 by default for numerical stability of
the wave-propagation step.
Initialize a diffractive lens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the lens configuration JSON file. If provided, loads the lens configuration from file. Defaults to None. |
None
|
device
|
str
|
Computation device ('cpu' or 'cuda'). Defaults to 'cpu'. |
None
|
Source code in deeplens/optics/diffraclens.py
load_example1
classmethod
Create an example diffractive lens with a single Fresnel DOE.
Returns:
| Name | Type | Description |
|---|---|---|
DiffractiveLens |
A configured diffractive lens with a Fresnel surface at f=50mm, 4mm size, and 4000 resolution. |
Source code in deeplens/optics/diffraclens.py
load_example2
classmethod
Create an example diffractive lens with a thin lens and binary DOE combination.
Returns:
| Name | Type | Description |
|---|---|---|
DiffractiveLens |
A configured diffractive lens with a ThinLens (f=50mm) and a Binary2 DOE, both at 4mm size and 4000 resolution. |
Source code in deeplens/optics/diffraclens.py
read_lens_json
Load the lens configuration from a JSON file.
Reads lens parameters including sensor configuration and diffractive surfaces from the specified JSON file. If sensor_size or sensor_res are not provided, defaults of 8mm x 8mm and 2000x2000 pixels will be used.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the JSON configuration file. |
required |
Source code in deeplens/optics/diffraclens.py
write_lens_json
Write the lens configuration to a JSON file.
Saves all lens parameters including sensor configuration and diffractive surface data to the specified file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Output path for the JSON file. |
required |
Source code in deeplens/optics/diffraclens.py
__call__
forward
Propagate a wave through the diffractive lens system to the sensor.
Sequentially applies phase modulation from each diffractive surface, then propagates the wave to the sensor plane using wave optics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wave
|
ComplexWave
|
Input wave field entering the lens system. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ComplexWave |
Output wave field at the sensor plane. |
Source code in deeplens/optics/diffraclens.py
render_mono
Simulate monochromatic lens blur by convolving an image with the point spread function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
Tensor
|
Input image. Shape: (B, 1, H, W) |
required |
wvln
|
float
|
Wavelength. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
ks
|
int
|
PSF kernel size. Defaults to PSF_KS. |
PSF_KS
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Rendered image after applying lens blur with shape (B, 1, H, W). |
Source code in deeplens/optics/diffraclens.py
psf
Calculate monochromatic point PSF by wave propagation approach.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
float
|
Depth of the point source. Defaults to float('inf'). |
float('inf')
|
wvln
|
float
|
Wavelength in micrometers. Defaults to DEFAULT_WAVE. |
DEFAULT_WAVE
|
ks
|
int
|
PSF kernel size. Defaults to PSF_KS. |
PSF_KS
|
upsample_factor
|
int
|
Upsampling factor to meet Nyquist sampling constraint. Defaults to 1. |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
psf_out |
tensor
|
PSF. shape [ks, ks] |
Note
[1] Usually we only consider the on-axis PSF because paraxial approximation is implicitly applied for wave optical model. For the shifted phase issue, refer to "Modeling off-axis diffraction with the least-sampling angular spectrum method".
Source code in deeplens/optics/diffraclens.py
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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 | |
draw_layout
Draw the lens layout diagram.
Visualizes the DOE and sensor positions in a 2D layout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
str
|
Path to save the figure. Defaults to './doelens.png'. |
'./doelens.png'
|
Source code in deeplens/optics/diffraclens.py
draw_psf
Draw on-axis RGB PSF.
Computes and saves a visualization of the RGB PSF for a given depth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
float
|
Depth of the point source. Defaults to DEPTH. |
DEPTH
|
ks
|
int
|
Size of the PSF kernel in pixels. Defaults to PSF_KS. |
PSF_KS
|
save_name
|
str
|
Path to save the PSF image. Defaults to './psf_doelens.png'. |
'./psf_doelens.png'
|
log_scale
|
bool
|
If True, display PSF in log scale. Defaults to True. |
True
|
eps
|
float
|
Small value for log scale to avoid log(0). Defaults to 1e-4. |
0.0001
|
Source code in deeplens/optics/diffraclens.py
get_optimizer
Get optimizer for the lens parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lr
|
float
|
Learning rate. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Optimizer |
Optimizer object for lens parameters. |
Thin-lens / circle-of-confusion model for simple depth-of-field and bokeh simulation.
deeplens.optics.ParaxialLens
Bases: Lens
Thin-lens / ABCD-matrix model for fast defocus simulation.
Models the circle of confusion (CoC) caused by defocus but not higher-order optical aberrations. Useful as a fast baseline renderer for depth-of-field effects, as commonly used in Blender and similar tools.
Attributes:
| Name | Type | Description |
|---|---|---|
foclen |
float
|
Focal length [mm]. |
fnum |
float
|
F-number. |
sensor_size |
tuple
|
Physical sensor size (W, H) [mm]. |
sensor_res |
tuple
|
Pixel resolution (W, H). |
pixel_size |
float
|
Pixel pitch [mm]. |
Initialize a paraxial lens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
foclen
|
float
|
Focal length in [mm]. |
required |
fnum
|
float
|
F-number. |
required |
sensor_size
|
tuple
|
Physical sensor size as (W, H) in [mm]. Defaults to (8.0, 8.0). |
None
|
sensor_res
|
tuple
|
Sensor resolution as (W, H) in pixels. Defaults to (2000, 2000). |
None
|
device
|
str
|
Computation device. Defaults to "cpu". |
'cpu'
|
Source code in deeplens/optics/paraxiallens.py
refocus
Refocus the lens to a given object distance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
foc_dist
|
float
|
Focus distance in [mm]. Must be less than the focal length (i.e. beyond the focal point). |
required |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If foc_dist >= |
Source code in deeplens/optics/paraxiallens.py
psf
PSF is modeled as a 2D uniform circular disk with diameter CoC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
Tensor
|
Points of the object. Shape [N, 3] or [3]. |
required |
ks
|
int
|
Kernel size. |
PSF_KS
|
psf_type
|
str
|
PSF type. "gaussian" or "pillbox". |
'gaussian'
|
**kwargs
|
Additional arguments for psf(). Currently not used. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
psf |
Tensor
|
PSF kernels. Shape [ks, ks] or [N, ks, ks]. |
Source code in deeplens/optics/paraxiallens.py
coc
Calculate circle of confusion (CoC) [mm].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
Tensor
|
Depth of the object. Shape [B]. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
coc |
Tensor
|
Circle of confusion. Shape [B]. |
Reference
[1] https://en.wikipedia.org/wiki/Circle_of_confusion
Source code in deeplens/optics/paraxiallens.py
dof
Calculate depth of field [mm].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
Tensor
|
Depth of the object. Shape [B]. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dof |
Tensor
|
Depth of field. Shape [B]. |
Reference
[1] https://en.wikipedia.org/wiki/Depth_of_field
Source code in deeplens/optics/paraxiallens.py
psf_rgb
Compute RGB PSF by replicating the monochrome PSF across three channels.
The paraxial model is achromatic, so all channels share the same PSF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
Tensor
|
Point source positions, shape |
required |
ks
|
int
|
Kernel size. Defaults to |
PSF_KS
|
**kwargs
|
Forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: RGB PSFs, shape |
Source code in deeplens/optics/paraxiallens.py
psf_map
Compute a spatially-uniform monochrome PSF map.
Because the paraxial model has no spatially-varying aberrations, every grid position receives the same on-axis PSF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid
|
tuple
|
Grid dimensions |
(5, 5)
|
ks
|
int
|
Kernel size. Defaults to |
PSF_KS
|
depth
|
float
|
Object depth [mm]. Defaults to |
DEPTH
|
**kwargs
|
Forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: PSF map, shape |
Source code in deeplens/optics/paraxiallens.py
psf_dp
Generate dual-pixel PSF for left and right sub-apertures.
This function generates separate PSFs for left and right sub-apertures of a dual pixel sensor, which enables depth estimation and improved autofocus capabilities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
Tensor
|
Input tensor with shape [N, 3], where columns are [x, y, z] coordinates. |
required |
ks
|
int
|
Kernel size for PSF generation. |
PSF_KS
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(left_psf, right_psf) where each PSF tensor has shape [N, ks, ks]. |
Source code in deeplens/optics/paraxiallens.py
psf_rgb_dp
Compute RGB dual-pixel PSFs for left and right sub-apertures.
Replicates the monochrome dual-pixel PSFs across three colour channels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
Tensor
|
Point source positions, shape |
required |
ks
|
int
|
Kernel size. Defaults to |
PSF_KS
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
|
Source code in deeplens/optics/paraxiallens.py
psf_map_dp
Compute spatially-uniform dual-pixel PSF maps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid
|
tuple
|
Grid dimensions |
(5, 5)
|
ks
|
int
|
Kernel size. Defaults to |
PSF_KS
|
depth
|
float
|
Object depth [mm]. Defaults to |
DEPTH
|
**kwargs
|
Forwarded to :meth: |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
|
Source code in deeplens/optics/paraxiallens.py
render_rgbd
Occlusion-aware RGBD rendering for paraxial lens.
Uses back-to-front layered compositing to prevent color bleeding at depth
discontinuities. Since paraxial lenses have no spatially varying
aberrations, all methods (psf_patch, psf_map, psf_pixel) produce
identical results; the method parameter is accepted for API
compatibility but ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_obj
|
tensor
|
Object image. Shape [B, C, H, W]. |
required |
depth_map
|
tensor
|
Depth map [mm]. Shape [B, 1, H, W]. Values should be positive. |
required |
method
|
str
|
Ignored (no spatial variation). Defaults to "psf_patch". |
'psf_patch'
|
**kwargs
|
Additional keyword arguments: - psf_ks (int): PSF kernel size. Defaults to PSF_KS. - num_layers (int): Number of depth layers. Defaults to 16. - depth_min (float): Minimum depth. Defaults to depth_map.min(). - depth_max (float): Maximum depth. Defaults to depth_map.max(). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
img_render |
tensor
|
Rendered image. Shape [B, C, H, W]. |
Reference
[1] "Dr.Bokeh: DiffeRentiable Occlusion-aware Bokeh Rendering", CVPR 2024.
Source code in deeplens/optics/paraxiallens.py
render_rgbd_dp
Render RGBD image with dual-pixel PSF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rgb_img
|
tensor
|
[B, 3, H, W] |
required |
depth
|
tensor
|
[B, 1, H, W] |
required |
Returns:
| Name | Type | Description |
|---|---|---|
img_left |
tensor
|
[B, 3, H, W] |
img_right |
tensor
|
[B, 3, H, W] |
Source code in deeplens/optics/paraxiallens.py
Neural surrogate that wraps a GeoLens with an MLP to predict PSFs. Useful for fast, differentiable PSF evaluation during end-to-end training.
deeplens.optics.PSFNetLens
Bases: Lens
Neural surrogate lens that predicts PSFs via a small MLP/MLPConv network.
Wraps a :class:~deeplens.optics.geolens.GeoLens with a neural network
trained to predict RGB PSFs from (fov, depth, focus_distance) inputs.
After training, PSF prediction is ~100× faster than ray tracing, making
it suitable for real-time applications and large-scale optimisation.
Attributes:
| Name | Type | Description |
|---|---|---|
lens |
GeoLens
|
The underlying refractive lens (used for training data generation and for sensor metadata). |
psfnet |
Module
|
Neural network for PSF prediction. |
pixel_size |
float
|
Pixel pitch [mm] (copied from the embedded lens). |
rfov |
float
|
Half-diagonal field of view [radians]. |
Notes
Use :meth:train_psfnet to train the surrogate from ray-traced PSF
samples. Use :meth:load_net to load pre-trained weights.
Initialize a PSF network lens.
In the default settings, the PSF network takes (fov, depth, foc_dist) as input and outputs RGB PSF on y-axis at (fov, depth, foc_dist).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lens_path
|
str
|
Path to the lens file. |
required |
in_chan
|
int
|
Number of input channels. |
3
|
psf_chan
|
int
|
Number of output channels. |
3
|
model_name
|
str
|
Name of the model. |
'mlp_conv'
|
kernel_size
|
int
|
Kernel size. |
64
|
Source code in deeplens/optics/psfnetlens.py
set_sensor_res
Set sensor resolution for both PSFNetLens and the embedded GeoLens.
Updates the pixel size accordingly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sensor_res
|
tuple
|
New sensor resolution as |
required |
Source code in deeplens/optics/psfnetlens.py
init_net
Initialize a PSF network.
PSF network
Input: [B, 3], (fov, depth, foc_dist). fov from [0, pi/2], depth from [-20000, -100], foc_dist from [-20000, -500] Output: psf kernel [B, 3, ks, ks]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_chan
|
int
|
number of input channels |
2
|
psf_chan
|
int
|
number of output channels |
3
|
kernel_size
|
int
|
kernel size |
64
|
model_name
|
str
|
name of the network architecture |
'mlpconv'
|
Returns:
| Name | Type | Description |
|---|---|---|
psfnet |
Module
|
network |
Source code in deeplens/optics/psfnetlens.py
load_net
Load pretrained network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
net_path
|
str
|
path to load the network |
required |
Source code in deeplens/optics/psfnetlens.py
save_psfnet
Save the PSF network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psfnet_path
|
str
|
path to save the PSF network |
required |
Source code in deeplens/optics/psfnetlens.py
train_psfnet
train_psfnet(iters=100000, bs=128, lr=5e-05, evaluate_every=500, spp=16384, concentration_factor=2.0, result_dir='./results/psfnet')
Train the PSF surrogate network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iters
|
int
|
number of training iterations |
100000
|
bs
|
int
|
batch size |
128
|
lr
|
float
|
learning rate |
5e-05
|
evaluate_every
|
int
|
evaluate every how many iterations |
500
|
spp
|
int
|
number of samples per pixel |
16384
|
concentration_factor
|
float
|
concentration factor for training data sampling |
2.0
|
result_dir
|
str
|
directory to save the results |
'./results/psfnet'
|
Source code in deeplens/optics/psfnetlens.py
sample_training_data
Sample training data for PSF surrogate network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_points
|
int
|
number of training points |
512
|
concentration_factor
|
float
|
concentration factor for training data sampling |
2.0
|
Returns:
| Name | Type | Description |
|---|---|---|
sample_input |
tensor
|
[B, 3] tensor, (fov, depth, foc_dist). - fov from [0, rfov] on 0y-axis, [radians] - depth from [d_far, d_close], [mm] - foc_dist from [foc_d_far, foc_d_close], [mm] - We use absolute fov and depth. |
sample_psf |
tensor
|
[B, 3, ks, ks] tensor |
Source code in deeplens/optics/psfnetlens.py
eval
Switch the PSF surrogate network to evaluation mode.
Disables dropout and batch normalisation updates in the internal
psfnet module. Call this before inference.
points2input
Convert points to input tensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
tensor
|
[N, 3] tensor, [-1, 1] * [-1, 1] * [depth_min, depth_max] |
required |
Returns:
| Name | Type | Description |
|---|---|---|
input |
tensor
|
[N, 3] tensor, (fov, depth, foc_dist). - fov from [0, rfov] on y-axis, [radians] - depth/1000.0 from [d_far, d_close], [mm] - foc_dist/1000.0 from [foc_d_far, foc_d_close], [mm] |
Source code in deeplens/optics/psfnetlens.py
refocus
Refocus the lens to a given object distance.
Delegates to the embedded :class:GeoLens and stores the focus
distance for subsequent PSF predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
foc_dist
|
float
|
Focus distance in [mm] (negative, towards the object). |
required |
Source code in deeplens/optics/psfnetlens.py
psf_rgb
Calculate RGB PSF using the PSF network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
tensor
|
[N, 3] tensor, [-1, 1] * [-1, 1] * [depth_min, depth_max] |
required |
foc_dist
|
float
|
focus distance |
required |
Returns:
| Name | Type | Description |
|---|---|---|
psf |
tensor
|
[N, 3, ks, ks] tensor |
Source code in deeplens/optics/psfnetlens.py
psf_map_rgb
Compute monochrome PSF map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid
|
tuple
|
Grid size. Defaults to (11, 11), meaning 11x11 grid. |
(11, 11)
|
wvln
|
float
|
Wavelength. Defaults to DEFAULT_WAVE. |
required |
depth
|
float
|
Depth of the object. Defaults to DEPTH. |
DEPTH
|
ks
|
int
|
Kernel size. Defaults to PSF_KS, meaning PSF_KS x PSF_KS kernel size. |
PSF_KS
|
Returns:
| Name | Type | Description |
|---|---|---|
psf_map |
Shape of [grid, grid, 3, ks, ks]. |
Source code in deeplens/optics/psfnetlens.py
render_rgbd
Render image with aif image and depth map. Receive [N, C, H, W] image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
tensor
|
[1, C, H, W] |
required |
depth
|
tensor
|
[1, H, W], depth map, unit in mm, range from [-20000, -200] |
required |
foc_dist
|
tensor
|
[1], unit in mm, range from [-20000, -200] |
required |
ks
|
int
|
kernel size |
64
|
high_res
|
bool
|
whether to use high resolution rendering |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
render |
tensor
|
[1, C, H, W] |
Source code in deeplens/optics/psfnetlens.py
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.optics.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 :meth:_sag and :meth:_dfdxy to define
their shape.
Ray–surface interaction is handled by three stages, implemented in
:meth:ray_reaction:
- Coordinate transform – ray is brought into the local surface frame.
- Intersection – solved via Newton's method (:meth:
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 (:meth:
refract) or specular reflection (:meth: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 |
tolerancing |
bool
|
When |
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/optics/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/optics/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/optics/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/optics/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/optics/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/optics/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/optics/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/optics/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/optics/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/optics/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/optics/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/optics/geometric_surface/base.py
is_valid
is_within_boundary
Valid points within the boundary of the surface.
Source code in deeplens/optics/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/optics/geometric_surface/base.py
surface_sag
Calculate sag of the surface at (x, y).
This function is currently not used.
Source code in deeplens/optics/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/optics/geometric_surface/base.py
get_optimizer
update_r
init_tolerance
Initialize tolerance parameters for the surface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tolerance_params
|
dict or None
|
Tolerance for surface parameters. Supported keys (all optional, default values shown): .. code-block:: python |
None
|
References
[1] https://www.edmundoptics.com/knowledge-center/application-notes/optics/understanding-optical-specifications/?srsltid=AfmBOorBa-0zaOcOhdQpUjmytthZc07oFlmPW_2AgaiNHHQwobcAzWII [2] https://wp.optics.arizona.edu/optomech/wp-content/uploads/sites/53/2016/08/8-Tolerancing-1.pdf [3] https://wp.optics.arizona.edu/jsasian/wp-content/uploads/sites/33/2016/03/L17_OPTI517_Lens-_Tolerancing.pdf
Source code in deeplens/optics/geometric_surface/base.py
sample_tolerance
Sample one example manufacturing error for the surface.
Source code in deeplens/optics/geometric_surface/base.py
zero_tolerance
Zero tolerance.
Source code in deeplens/optics/geometric_surface/base.py
sensitivity_score
Tolerance squared sum.
Reference
[1] Page 10 from: https://wp.optics.arizona.edu/optomech/wp-content/uploads/sites/53/2016/08/8-Tolerancing-1.pdf
Source code in deeplens/optics/geometric_surface/base.py
draw_widget
Draw widget for the surface on the 2D plot.
Source code in deeplens/optics/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/optics/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/optics/geometric_surface/base.py
zmx_str
Spherical surface defined by curvature \(c = 1/R\).
deeplens.optics.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/optics/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/optics/geometric_surface/spheric.py
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 198 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 | |
is_within_data_range
Invalid when shape is non-defined.
max_height
init_tolerance
Initialize tolerance parameters for the surface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tolerance_params
|
dict
|
Tolerance for surface parameters. |
None
|
Source code in deeplens/optics/geometric_surface/spheric.py
sample_tolerance
Randomly perturb surface parameters to simulate manufacturing errors.
zero_tolerance
sensitivity_score
Tolerance squared sum.
Source code in deeplens/optics/geometric_surface/spheric.py
get_optimizer_params
Activate gradient computation for c and d and return optimizer parameters.
Source code in deeplens/optics/geometric_surface/spheric.py
surf_dict
Return surface parameters.
Source code in deeplens/optics/geometric_surface/spheric.py
zmx_str
Return Zemax surface string.
Source code in deeplens/optics/geometric_surface/spheric.py
Even-asphere surface: spherical base with polynomial corrections.
deeplens.optics.geometric_surface.Aspheric
Aspheric(r, d, c, k, ai, mat2, 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=1}^{n} a_{2i}\,\rho^{2i},
\quad \rho^2 = x^2 + y^2
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. |
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
|
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/optics/geometric_surface/aspheric.py
is_within_data_range
Invalid when shape is non-defined.
max_height
get_optimizer_params
Get optimizer parameters for different parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lrs
|
list
|
learning rates for d, c, k, ai2, (ai4, ai6, ai8, ai10, ai12). |
[0.0001, 0.0001, 0.01, 0.0001]
|
optim_mat
|
bool
|
whether to optimize material. Defaults to False. |
False
|
Source code in deeplens/optics/geometric_surface/aspheric.py
init_tolerance
Perturb the surface with some tolerance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tolerance_params
|
dict
|
Tolerance for surface parameters. |
None
|
References
[1] https://www.edmundoptics.com/capabilities/precision-optics/capabilities/aspheric-lenses/ [2] https://www.edmundoptics.com/knowledge-center/application-notes/optics/all-about-aspheric-lenses/?srsltid=AfmBOoon8AUXVALojol2s5K20gQk7W1qUisc6cE4WzZp3ATFY5T1pK8q
Source code in deeplens/optics/geometric_surface/aspheric.py
sample_tolerance
Randomly perturb surface parameters to simulate manufacturing errors.
Source code in deeplens/optics/geometric_surface/aspheric.py
zero_tolerance
sensitivity_score
Tolerance squared sum.
Source code in deeplens/optics/geometric_surface/aspheric.py
surf_dict
Return a dict of surface.
Source code in deeplens/optics/geometric_surface/aspheric.py
zmx_str
Return Zemax surface string.
Source code in deeplens/optics/geometric_surface/aspheric.py
deeplens.optics.geometric_surface.Aperture
Bases: Plane
Aperture surface.
Source code in deeplens/optics/geometric_surface/aperture.py
ray_reaction
Compute output ray after intersection and refraction.
Source code in deeplens/optics/geometric_surface/aperture.py
draw_widget
Draw aperture wedge on the figure.
Source code in deeplens/optics/geometric_surface/aperture.py
draw_widget3D
Draw the aperture as a circle in a 3D plot.
Source code in deeplens/optics/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/optics/geometric_surface/aperture.py
get_optimizer_params
Activate gradient computation for d and return optimizer parameters.
Source code in deeplens/optics/geometric_surface/aperture.py
surf_dict
Dict of surface parameters.
Source code in deeplens/optics/geometric_surface/aperture.py
zmx_str
Light Representations
Geometric ray representation carrying origin, direction, wavelength, validity mask, energy, and optical path length (OPL).
deeplens.optics.Ray
Bases: DeepObj
Batched ray bundle for optical simulation.
Stores ray origins, directions, wavelength, validity mask, energy, obliquity,
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 |
obliq |
Tensor
|
Obliquity factor, shape |
opl |
Tensor
|
Optical path length (coherent mode only),
shape |
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]. |
DEFAULT_WAVE
|
coherent
|
bool
|
Enable optical path length tracking for coherent
tracing. Defaults to |
False
|
device
|
str
|
Compute device. Defaults to |
'cpu'
|
Source code in deeplens/optics/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/optics/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/optics/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/optics/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/optics/light/ray.py
clone
Clone the ray.
Can spercify 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/optics/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/optics/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/optics/light/ray.py
Complex electromagnetic field with Angular Spectrum Method (ASM), Fresnel, and Fraunhofer propagation via torch.fft.
deeplens.optics.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/optics/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/optics/light/wave.py
plane_wave
classmethod
Create a planar wave field on x0y plane.
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)
|
valid_r
|
float
|
Valid circle radius. [mm]. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
field |
ComplexWave
|
Complex field. |
Source code in deeplens/optics/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/optics/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/optics/light/wave.py
prop_to
Propagate the field to plane z.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
float
|
destination plane z coordinate. |
required |
gen_xy_grid
Generate the x and y grid.
Source code in deeplens/optics/light/wave.py
gen_freq_grid
load_npz
Load data from npz file.
Source code in deeplens/optics/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/optics/light/wave.py
show
Save the field as an image.
Source code in deeplens/optics/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/optics/light/wave.py
flip
Flip the field horizontally and vertically.
Source code in deeplens/optics/light/wave.py
PSF Utilities
Functions for convolving images with point spread functions.
deeplens.optics.imgsim.psf.conv_psf
Convolve an image batch with a single spatially-uniform PSF.
Applies a per-channel 2-D convolution using reflect boundary 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 a true 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/optics/imgsim/psf.py
deeplens.optics.imgsim.psf.conv_psf_map
Convolve 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 results are
assembled back into a full-resolution output via a weighted blending step.
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 |