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
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 | |
point_source_radial
Generate radial point sources from center to edge of the field.
Produces grid evenly-spaced points along a chosen radial direction
(diagonal, meridional, or sagittal) in normalized or physical object-space
coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
float
|
Object depth (z-coordinate) in mm. |
required |
grid
|
int
|
Number of sample points. Defaults to 9. |
9
|
center
|
bool
|
If |
False
|
direction
|
str
|
Sampling direction —
|
'diagonal'
|
normalized
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Point source positions, shape |
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
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 | |
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
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 | |
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 GeoLensPSF, GeoLensEval, GeoLensSeidel, GeoLensOptim, GeoLensSurfOps, GeoLensVis, GeoLensIO, GeoLensTolerance, and GeoLensVis3D.
deeplens.optics.GeoLens
Bases: GeoLensPSF, GeoLensEval, GeoLensSeidel, GeoLensOptim, GeoLensSurfOps, GeoLensVis, GeoLensIO, GeoLensTolerance, GeoLensVis3D, Lens
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 – eight specialised mixin classes are composed at class definition time to keep each concern isolated:
- :class:
~deeplens.optics.geolens_pkg.psf_compute.GeoLensPSF– PSF computation (geometric, coherent, Huygens models). - :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.optim_ops.GeoLensSurfOps– surface geometry operations (aspheric conversion, pruning, shape correction, material matching). - :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.eval_tolerance.GeoLensTolerance– manufacturing tolerance analysis. - :class:
~deeplens.optics.geolens_pkg.vis3d.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_rays(num_field=5, depth=float('inf'), num_rays=SPP_PSF, wvln=DEFAULT_WAVE, direction='y')
Sample radial rays at evenly-spaced field angles along a chosen direction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_field
|
int
|
Number of field angles from on-axis to full-field. Defaults to 5. |
5
|
depth
|
float
|
Object distance in mm. Use |
float('inf')
|
num_rays
|
int
|
Rays per field position. Defaults to |
SPP_PSF
|
wvln
|
float
|
Wavelength in micrometers. Defaults to |
DEFAULT_WAVE
|
direction
|
str
|
Sampling direction —
|
'y'
|
Returns:
| Name | Type | Description |
|---|---|---|
Ray |
Ray object with shape |
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_from_points_by_fov
sample_from_points_by_fov(fov_x=[0.0], fov_y=[0.0], depth=DEPTH, num_rays=SPP_PSF, wvln=DEFAULT_WAVE, scale_pupil=1.0)
Sample point-source rays specified by field angles and depth.
Converts field angles to physical object-space coordinates, then
delegates to :meth:sample_from_points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fov_x
|
float or list
|
Field angle(s) in the xz plane (degrees). |
[0.0]
|
fov_y
|
float or list
|
Field angle(s) in the yz plane (degrees). |
[0.0]
|
depth
|
float
|
Object distance in mm. Default: |
DEPTH
|
num_rays
|
int
|
Number of rays per field point. Default: SPP_PSF. |
SPP_PSF
|
wvln
|
float
|
Wavelength of rays. Default: DEFAULT_WAVE. |
DEFAULT_WAVE
|
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 follow
the same scalar-squeeze convention as :meth: |
Source code in deeplens/optics/geolens.py
sample_from_fov
sample_from_fov(fov_x=[0.0], fov_y=[0.0], depth=float('inf'), num_rays=SPP_CALC, wvln=DEFAULT_WAVE, entrance_pupil=True, prop_to=-1.0, scale_pupil=1.0)
Sample rays from object space at given field angles.
Unified entry point for both collimated (infinite-depth) and diverging (finite-depth) ray bundles specified by field-of-view angles.
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]
|
depth
|
float
|
Object distance in mm. |
float('inf')
|
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. Only used for infinite depth. Default: True. |
True
|
prop_to
|
float
|
Propagation depth in z (only for infinite depth). 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
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 | |
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
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
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 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 | |
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
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 1323 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 | |
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
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 | |
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
deeplens.optics.geolens_pkg.psf_compute.GeoLensPSF
Mixin providing PSF computation for GeoLens.
All three PSF models are exposed through a single :meth:psf dispatcher.
The geometric and coherent models are differentiable; Huygens is not.
This class is not instantiated directly; it is mixed into
:class:~deeplens.optics.geolens.GeoLens.
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_pkg/psf_compute.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_pkg/psf_compute.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_pkg/psf_compute.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_pkg/psf_compute.py
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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | |
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_pkg/psf_compute.py
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | |
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_pkg/psf_compute.py
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 | |
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_pkg/psf_compute.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_pkg/psf_compute.py
deeplens.optics.geolens_pkg.eval.GeoLensEval
Mixin that adds classical optical evaluation methods to GeoLens.
This class is never instantiated on its own. It is mixed into
GeoLens via multiple inheritance, so every method can access lens
geometry (self.d_sensor, self.rfov, …) and ray-tracing routines
(self.trace(), self.trace2sensor(), …) directly through self.
All evaluation functions follow the same pattern
- Sample rays from object space (parallel / grid / radial).
- Trace rays through the lens (
self.traceorself.trace2sensor). - Analyze ray positions / directions at the sensor plane.
- Optionally produce a matplotlib figure saved to disk.
Results are accuracy-aligned with Zemax OpticStudio for the same lens prescriptions and ray-sampling densities.
Attributes consumed from GeoLens (via self):
d_sensor (float): Axial position of the sensor plane (mm).
sensor_size (tuple[float, float]): Sensor (width, height) in mm.
pixel_size (float): Pixel pitch in mm.
sensor_res (tuple[int, int]): Sensor resolution (H, W) in pixels.
rfov (float): Half field-of-view in radians.
foclen (float): Equivalent focal length in mm.
fnum (float): F-number.
aper_idx (int): Index of the aperture stop surface.
device (torch.device): Compute device (CPU / CUDA).
spot_points
Trace rays from object points to sensor and return the traced Ray.
Samples rays from each physical object point toward the entrance pupil, traces through all lens surfaces (refraction + clipping), and returns the resulting Ray object on the sensor plane.
This is the shared computational core for spot diagrams
(draw_spot_radial, draw_spot_map) and RMS error maps
(rms_map, rms_map_rgb).
Algorithm
self.sample_from_points(points, num_rays, wvln)generates a fan ofnum_raysrays per object point, aimed at the entrance pupil.self.trace2sensor()propagates through all surfaces and clips vignetted rays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
Tensor
|
Physical 3D object-space coordinates with
shape |
required |
num_rays
|
int
|
Number of rays sampled per object point.
Defaults to |
SPP_PSF
|
wvln
|
float
|
Wavelength in micrometers.
Defaults to |
DEFAULT_WAVE
|
Returns:
| Name | Type | Description |
|---|---|---|
Ray |
Traced ray on the sensor plane, with shape
|
Source code in deeplens/optics/geolens_pkg/eval.py
draw_spot_radial
draw_spot_radial(save_name='./lens_spot_radial.png', num_fov=5, depth=DEPTH, num_rays=SPP_PSF, wvln_list=WAVE_RGB, direction='y', show=False)
Draw spot diagrams at evenly-spaced field angles along a chosen direction.
A spot diagram visualizes the transverse ray-intercept distribution on the sensor plane for a point source at a given field angle and depth. It reveals the combined effect of all aberrations (spherical, coma, astigmatism, field curvature, chromatic, …).
Algorithm
For each wavelength in wvln_list:
1. self.point_source_radial(direction, normalized=False)
generates physical object-space points along the chosen
direction.
2. self.spot_points() samples rays and traces to sensor.
3. Valid ray (x, y) positions are scatter-plotted per subplot.
All wavelengths are overlaid in a single figure with RGB coloring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
str
|
File path for the output PNG.
Defaults to |
'./lens_spot_radial.png'
|
num_fov
|
int
|
Number of field positions sampled uniformly from on-axis (0) to full-field. Defaults to 5. |
5
|
depth
|
float
|
Object distance in mm (negative = real object).
Defaults to |
DEPTH
|
num_rays
|
int
|
Rays per field position per wavelength.
Defaults to |
SPP_PSF
|
wvln_list
|
list[float]
|
Wavelengths in micrometers.
Defaults to |
WAVE_RGB
|
direction
|
str
|
Sampling direction —
|
'y'
|
show
|
bool
|
If |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
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 | |
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 a 2-D grid of spot diagrams across the full field of view.
Unlike draw_spot_radial (which samples only a radial slice),
this method samples a num_grid × num_grid grid of field positions
covering both the x (sagittal) and y (meridional) axes, revealing
off-axis aberrations that are invisible in a 1-D radial scan.
Algorithm
For each wavelength in wvln_list:
1. self.point_source_grid(normalized=False) creates physical
object-space grid points, shape [grid_h, grid_w, 3].
2. self.spot_points() samples rays and traces to sensor.
3. Valid (x, y) positions are scatter-plotted in the
corresponding subplot of the num_grid × num_grid figure.
All wavelengths are overlaid with RGB coloring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
str
|
File path for the output PNG.
Defaults to |
'./lens_spot_map.png'
|
num_grid
|
int | tuple[int, int]
|
Number of grid points along each
axis. Total subplots = |
5
|
depth
|
float
|
Object distance in mm. Defaults to |
DEPTH
|
num_rays
|
int
|
Rays per grid cell per wavelength.
Defaults to |
SPP_PSF
|
wvln_list
|
list[float]
|
Wavelengths in micrometers.
Defaults to |
WAVE_RGB
|
show
|
bool
|
If |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
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 | |
rms_map
Compute per-field-position RMS spot radius for a single wavelength.
Traces SPP_PSF rays per grid cell and computes the root-mean-square
distance of valid ray hits from a reference centroid. When center
is None, each cell uses its own centroid (monochromatic blur).
When an external center is provided (e.g. the green-channel
centroid), the RMS includes the chromatic shift from that reference.
Algorithm
self.point_source_grid(normalized=False)generates physical object points on a[num_grid, num_grid]field grid.self.spot_points()samplesSPP_PSFrays per point and traces to sensor.- If
centerisNone, compute per-cell centroidc = mean(valid ray_xy); otherwise use the providedcenter. RMS = sqrt( mean( ||ray_xy - c||^2 ) ).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_grid
|
int | tuple[int, int]
|
Spatial resolution of the field sampling grid. Defaults to 32. |
32
|
depth
|
float
|
Object distance in mm. Defaults to |
DEPTH
|
wvln
|
float
|
Wavelength in micrometers. Defaults to |
DEFAULT_WAVE
|
center
|
Tensor | None
|
External reference centroid with shape
|
None
|
Returns:
| Type | Description |
|---|---|
|
tuple[torch.Tensor, torch.Tensor]:
- rms: RMS spot error map, shape |
Source code in deeplens/optics/geolens_pkg/eval.py
rms_map_rgb
Compute per-field-position RMS spot radius for R, G, B wavelengths.
The RMS spot radius is a standard measure of geometrical image quality.
For each field position in a num_grid × num_grid grid, this method
traces SPP_PSF rays per wavelength and computes the root-mean-square
distance of valid ray hits from a common reference centroid.
The reference centroid is the green-channel centroid. Using a common reference means the returned RMS values include lateral chromatic aberration (the shift between R/G/B centroids), making the map useful as a polychromatic image-quality metric.
Algorithm
- Call
rms_map(wvln=green)to get the green RMS map and the green centroid. - Call
rms_map(wvln=red, center=green_centroid)andrms_map(wvln=blue, center=green_centroid)to measure R/B blur relative to the green reference. - Stack as
[R, G, B].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_grid
|
int
|
Spatial resolution of the field sampling grid. Defaults to 32. |
32
|
depth
|
float
|
Object distance in mm. Defaults to |
DEPTH
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: RMS spot error map with shape |
Source code in deeplens/optics/geolens_pkg/eval.py
calc_distortion_radial
Compute fractional distortion at evenly-spaced field angles along the meridional direction.
Distortion is defined as (h_actual - h_ideal) / h_ideal, where
h_ideal = f * tan(theta) (rectilinear projection) and h_actual
is the chief-ray image height on the sensor. A positive value means
pincushion distortion; negative means barrel distortion.
This is the computational counterpart to draw_spot_radial: it
samples num_points field angles uniformly from 0 to self.rfov
and returns both the sampled angles and the corresponding distortion
values, making it easy to pair with other radial evaluation functions.
Algorithm
- Derive
rfov_degfromself.rfov(radians → degrees). - Sample
num_pointsfield angles uniformly in[0, rfov_deg]. The on-axis sample (0°) is replaced by a tiny positive angle to avoid 0/0. - Compute
h_ideal = foclen * tan(angle)for each sample. - Trace the chief ray (via
calc_chief_ray_infinite) through the full lens to the sensor plane. - Extract
h_actualfrom the appropriate transverse coordinate (x for sagittal, y for meridional). - Return
(h_actual - h_ideal) / h_ideal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_points
|
int
|
Number of evenly-spaced field-angle samples from
on-axis (0°) to full-field ( |
GEO_GRID
|
wvln
|
float
|
Wavelength in micrometers. Defaults to |
DEFAULT_WAVE
|
plane
|
str
|
|
'meridional'
|
ray_aiming
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
|
tuple[np.ndarray, np.ndarray]:
- rfov_samples: Field angles in degrees, shape |
Source code in deeplens/optics/geolens_pkg/eval.py
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 | |
draw_distortion_radial
draw_distortion_radial(save_name=None, num_points=GEO_GRID, wvln=DEFAULT_WAVE, plane='meridional', ray_aiming=True, show=False)
Draw distortion-vs-field-angle curve in Zemax style.
Produces a plot with field angle on the y-axis and percent distortion on the x-axis, matching the layout convention used in Zemax OpticStudio. Useful for quick visual assessment of barrel / pincushion distortion.
Algorithm
- Call
calc_distortion_radialto obtain field angles and fractional distortion values. - Convert distortion to percent and plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
str | None
|
File path for the output PNG. If |
None
|
num_points
|
int
|
Number of field-angle samples.
Defaults to |
GEO_GRID
|
wvln
|
float
|
Wavelength in micrometers. Defaults to |
DEFAULT_WAVE
|
plane
|
str
|
|
'meridional'
|
ray_aiming
|
bool
|
Whether to use ray aiming for chief-ray
computation. Defaults to |
True
|
show
|
bool
|
If |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
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 | |
calc_distortion_map
Compute a 2-D distortion grid mapping ideal to actual image positions.
For each cell in a num_grid × num_grid field grid, rays are traced
to the sensor and their centroid is computed. The centroid is then
normalized to [-1, 1] sensor coordinates, producing a map that
shows how each ideal image point is displaced by lens distortion.
This map can be used with torch.nn.functional.grid_sample to warp
or unwarp rendered images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_grid
|
int
|
Grid resolution along each axis. Defaults to 16. |
16
|
depth
|
float
|
Object distance in mm. Defaults to |
DEPTH
|
wvln
|
float
|
Wavelength in micrometers. Defaults to |
DEFAULT_WAVE
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Distortion grid with shape |
Source code in deeplens/optics/geolens_pkg/eval.py
distortion_center
Compute the distorted image centroid for arbitrary normalized object points.
Given object points in normalized coordinates, this method converts them
to physical object-space positions, traces rays from each point through
the lens, and returns the ray centroid on the sensor in normalized
[-1, 1] coordinates. This is the inverse mapping needed for
distortion correction (unwarping).
Algorithm
- Convert normalized
(x, y)∈ [-1, 1] to physical object-space positions usingself.calc_scale(depth)andself.sensor_size. self.sample_from_points()generates rays from each point.self.trace2sensor()propagates rays.- Compute centroid and normalize back to
[-1, 1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
Tensor
|
Normalized point source positions with shape
|
required |
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Normalized distortion centroid positions with shape
|
Source code in deeplens/optics/geolens_pkg/eval.py
draw_distortion_map
Draw a scatter plot of the distortion grid.
Visualizes the output of calc_distortion_map() as a scatter plot on
[-1, 1] normalized sensor coordinates. An undistorted lens would
show a perfect rectilinear grid; deviations reveal barrel or pincushion
distortion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
str | None
|
File path for the output PNG. If |
None
|
num_grid
|
int
|
Grid resolution per axis. Defaults to 16. |
16
|
depth
|
float
|
Object distance in mm. Defaults to |
DEPTH
|
wvln
|
float
|
Wavelength in micrometers. Defaults to |
DEFAULT_WAVE
|
show
|
bool
|
If |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
mtf
Compute the geometric MTF at a single field position.
The Modulation Transfer Function describes how well the lens preserves contrast as a function of spatial frequency. MTF = 1 at low frequencies (perfect contrast) and falls toward 0 near the diffraction limit or the Nyquist frequency of the sensor.
This implementation uses the geometric (ray-based) approach:
1. Compute the PSF at the given field position via self.psf().
2. Convert PSF → MTF via psf2mtf() (project onto tangential and
sagittal axes, then take the magnitude of the 1-D FFT).
Tangential MTF captures resolution in the meridional (radial) direction; sagittal MTF captures resolution perpendicular to it. The difference between the two indicates astigmatism.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fov
|
float
|
Field position as a fraction of |
required |
wvln
|
float
|
Wavelength in micrometers. Defaults to |
DEFAULT_WAVE
|
Returns:
| Type | Description |
|---|---|
|
tuple[np.ndarray, np.ndarray, np.ndarray]: - freq: Spatial frequency axis in cycles/mm (positive frequencies only, excluding DC). - mtf_tan: Tangential (meridional) MTF values, normalized so that MTF → 1 at low frequency. - mtf_sag: Sagittal MTF values, same normalization. |
Source code in deeplens/optics/geolens_pkg/eval.py
psf2mtf
staticmethod
Convert a 2-D point-spread function to tangential and sagittal MTF curves.
The MTF is the magnitude of the optical transfer function (OTF), which
is the Fourier transform of the PSF. For separable 1-D analysis:
1. Integrate the PSF along the x-axis → tangential line-spread
function (LSF_tan).
2. Integrate the PSF along the y-axis → sagittal LSF_sag.
3. Take |FFT(LSF)| and normalize by the DC component so that
MTF(0) = 1.
Only positive frequencies (excluding DC) are returned, following the convention used in Zemax MTF plots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psf
|
Tensor | ndarray
|
2-D PSF with shape |
required |
pixel_size
|
float
|
Pixel pitch in mm. Determines the frequency
axis scaling: |
required |
Returns:
| Type | Description |
|---|---|
|
tuple[np.ndarray, np.ndarray, np.ndarray]:
- freq: Spatial frequency in cycles/mm (positive, excluding
DC). Length is roughly |
References
- https://en.wikipedia.org/wiki/Optical_transfer_function
- Edmund Optics: Introduction to Modulation Transfer Function.
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 tangential MTF curves for multiple depths and field positions.
Produces a len(depth_list) × len(relative_fov_list) subplot grid.
Each subplot shows the tangential MTF for R, G, B wavelengths plus a
vertical line at the sensor Nyquist frequency
(0.5 / pixel_size cycles/mm).
Algorithm per subplot
- Compute the RGB PSF via
self.psf_rgb()at the specified(depth, relative_fov)with kernel sizepsf_ks. - For each wavelength channel, call
psf2mtf()to obtain the tangential MTF curve. - Plot frequency vs MTF with RGB coloring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
str
|
File path for the output PNG.
Defaults to |
'./lens_mtf.png'
|
relative_fov_list
|
list[float]
|
Relative field positions in
|
[0.0, 0.7, 1.0]
|
depth_list
|
list[float]
|
Object distances in mm.
|
[DEPTH]
|
psf_ks
|
int
|
PSF kernel size in pixels (controls frequency resolution of the resulting MTF). Defaults to 128. |
128
|
show
|
bool
|
If |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
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 933 934 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 | |
draw_field_curvature
draw_field_curvature(save_name=None, num_points=64, z_span=1.0, z_steps=201, wvln_list=WAVE_RGB, spp=256, show=False)
Draw field curvature: best-focus defocus (Δz) vs field angle for RGB.
Field curvature (Petzval curvature) causes off-axis image points to focus on a curved surface rather than the flat sensor. This method finds the axial position of minimum RMS spot size at each field angle and plots the deviation from the nominal sensor plane.
Algorithm (fully vectorized per wavelength):
1. Construct a meridional ray fan at num_points field angles,
each with spp rays spanning the entrance pupil.
2. Trace all rays through the lens in a single batched call.
3. For each of z_steps defocus planes within ±z_span mm of
self.d_sensor, propagate rays analytically (linear
extension) and compute the variance of the y-coordinate.
4. The defocus with minimum variance is the best-focus plane.
Parabolic interpolation on the three-point neighborhood gives
sub-grid-step precision.
5. Repeat for each wavelength; overlay R/G/B curves on a single plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
str | None
|
File path for the output PNG. If |
None
|
num_points
|
int
|
Number of field-angle samples from 0 to
|
64
|
z_span
|
float
|
Half-range of the defocus sweep in mm. If the best-focus hits the boundary, a warning is printed. Defaults to 1.0. |
1.0
|
z_steps
|
int
|
Number of uniformly-spaced defocus planes within
|
201
|
wvln_list
|
list[float]
|
Wavelengths in micrometers.
Defaults to |
WAVE_RGB
|
spp
|
int
|
Rays per field point (sampled uniformly across the entrance pupil in the meridional plane). Defaults to 256. |
256
|
show
|
bool
|
If |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
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 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 | |
vignetting
Compute the relative-illumination (vignetting) map across the field.
Vignetting measures how much light is lost at each field position due to rays being clipped by lens apertures or barrel edges. It is computed as the fraction of traced rays that remain valid (not vignetted) at each grid cell, normalized by the total number of launched rays.
A value of 1.0 means all rays reach the sensor (no vignetting); 0.0 means complete light blockage. Real lenses typically show 1.0 on-axis and fall off toward the field edges due to mechanical vignetting and the cos⁴ illumination law.
Algorithm
self.sample_grid_rays()withuniform_fov=False(uniform image-space sampling) to ensure correct sensor-plane mapping.self.trace2sensor()propagates rays and marks clipped ones as invalid.- Per-cell throughput =
count(valid) / num_rays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
float
|
Object distance in mm. Defaults to |
DEPTH
|
num_grid
|
int
|
Grid resolution per axis. Defaults to 32. |
32
|
num_rays
|
int
|
Rays launched per grid cell. Higher values reduce Monte-Carlo noise. Defaults to 512. |
512
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Vignetting map with shape |
Source code in deeplens/optics/geolens_pkg/eval.py
draw_vignetting
Draw the vignetting map as a grayscale image with a colorbar.
Computes the vignetting map via self.vignetting(), bilinearly
upsamples it to resolution × resolution, and displays it as a
grayscale image where white = no vignetting and black = fully vignetted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str | None
|
File path for the output PNG. If |
None
|
depth
|
float
|
Object distance in mm. Defaults to |
DEPTH
|
resolution
|
int
|
Output image size in pixels (square). Defaults to 512. |
512
|
show
|
bool
|
If |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
wavefront_error
Compute wavefront error (OPD) at the exit pupil for a given field position.
The wavefront error is the optical path difference between the actual wavefront and the ideal spherical reference wavefront. The reference sphere is centered at the ideal image point (chief ray intersection with the sensor) and passes through the exit pupil center.
By Fermat's principle, a perfect lens has equal total optical path (object → lens → image) for all rays. The deviation from this equal-path condition is the wavefront error:
``OPD(x,y) = [OPL(x,y) + r(x,y)] - mean_over_pupil``
where OPL(x,y) is the accumulated optical path from the object through
the lens to the exit pupil, and r(x,y) is the geometric distance from
the exit pupil point to the ideal image point. Piston (mean) is removed.
Uses the same coherent ray-tracing infrastructure as :meth:pupil_field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relative_fov
|
float
|
Relative field of view in |
0.0
|
depth
|
float
|
Object distance [mm]. Use |
DEPTH
|
wvln
|
float
|
Wavelength [µm]. |
DEFAULT_WAVE
|
num_rays
|
int
|
Number of rays to sample through the pupil. |
SPP_COHERENT
|
ks
|
int
|
Grid resolution for the OPD map at the exit pupil. |
256
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
|
Note
This function sets the default dtype to torch.float64 for phase
accuracy (consistent with :meth:pupil_field).
References
[1] V. N. Mahajan, "Optical Imaging and Aberrations, Part II", Ch. 1. [2] Zemax OpticStudio, "Wavefront Error Analysis".
Source code in deeplens/optics/geolens_pkg/eval.py
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 1323 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 | |
rms_wavefront_error
Compute scalar RMS wavefront error at a given field position.
Convenience wrapper around :meth:wavefront_error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relative_fov
|
float
|
Relative field of view in |
0.0
|
depth
|
float
|
Object distance [mm]. |
DEPTH
|
wvln
|
float
|
Wavelength [µm]. |
DEFAULT_WAVE
|
num_rays
|
int
|
Number of rays to sample. |
SPP_COHERENT
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
RMS wavefront error in waves. |
Source code in deeplens/optics/geolens_pkg/eval.py
draw_wavefront_error
draw_wavefront_error(save_name='./wavefront_error.png', num_fov=5, depth=DEPTH, wvln=DEFAULT_WAVE, num_rays=SPP_COHERENT, ks=256, show=False)
Draw wavefront error (OPD) maps at multiple field positions.
Evaluates the wavefront error along the meridional (y) direction from on-axis to full field, and displays each OPD map with RMS and PV annotations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
str
|
Filename to save the figure. |
'./wavefront_error.png'
|
num_fov
|
int
|
Number of field positions to evaluate. |
5
|
depth
|
float
|
Object distance [mm]. |
DEPTH
|
wvln
|
float
|
Wavelength [µm]. |
DEFAULT_WAVE
|
num_rays
|
int
|
Number of rays to sample per field position. |
SPP_COHERENT
|
ks
|
int
|
Grid resolution for each OPD map. |
256
|
show
|
bool
|
If True, display the figure interactively. |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
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 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 | |
field_curvature
Compute field curvature data (best-focus defocus vs field angle).
Field curvature is the axial shift of the best-focus surface away from the flat sensor plane as a function of field angle. It is caused by the Petzval sum of lens surface curvatures and refractive indices.
Not yet implemented. See draw_field_curvature() for a plotting
version that already performs the underlying computation.
Source code in deeplens/optics/geolens_pkg/eval.py
calc_chief_ray
Find the chief ray for a given field angle using 2-D ray tracing.
The chief ray (also called the principal ray) is the ray from an off-axis object point that passes through the center of the aperture stop. It defines the image height for distortion calculations and sets the reference axis for coma and lateral color analysis.
Algorithm
- Sample a fan of parallel rays at the specified
fovin the chosen plane, entering through the entrance pupil. - Trace the fan up to (but not through) the aperture stop.
- Select the ray whose transverse position at the stop is closest to the optical axis — this is the chief ray.
- Return its incident (object-space) origin and direction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fov
|
float
|
Incident half-angle in degrees. |
required |
plane
|
str
|
|
'sagittal'
|
Returns:
| Type | Description |
|---|---|
|
tuple[torch.Tensor, torch.Tensor]:
- chief_ray_o: Origin of the chief ray in object space,
shape |
Note
This is a 2-D (meridional or sagittal plane) search. For a full 3-D chief ray, one would shrink the pupil and trace the centroid 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 rays for one or more field angles with optional ray aiming.
This is the batched, production version of calc_chief_ray. It
supports vectorized evaluation over multiple field angles and implements
ray aiming — an iterative procedure that launches a fan of rays
toward the entrance pupil and selects the one that passes closest to
the aperture-stop center. Ray aiming is essential for accurate
distortion measurement in wide-angle or fisheye lenses where the
paraxial approximation breaks down.
Algorithm
- For on-axis (
rfov = 0): chief ray is trivially along the z-axis. - For off-axis angles with
ray_aiming=False: the chief ray is aimed at the entrance pupil center (paraxial approximation). - For off-axis angles with
ray_aiming=True: a. Estimate the object-space y (or x) position from the entrance pupil geometry. b. Create a narrow fan ofnum_raysrays bracketing that estimate (width = 5 % of y_distance, clamped to0.05 * pupil_radius). c. Trace the fan to the aperture stop. d. Pick the ray closest to the optical axis at the stop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rfov
|
float | Tensor
|
Field angle(s) in degrees.
A scalar is converted to |
required |
depth
|
float | Tensor
|
Object depth(s) in mm. Defaults to 0.0 (object at the first surface). |
0.0
|
wvln
|
float
|
Wavelength in micrometers. Defaults to |
DEFAULT_WAVE
|
plane
|
str
|
|
'meridional'
|
num_rays
|
int
|
Size of the search fan for ray aiming.
Defaults to |
SPP_CALC
|
ray_aiming
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
|
tuple[torch.Tensor, torch.Tensor]:
- chief_ray_o: Origins, shape |
Source code in deeplens/optics/geolens_pkg/eval.py
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 | |
analysis_rendering
analysis_rendering(img_org, save_name=None, depth=DEPTH, spp=SPP_RENDER, unwarp=False, method='ray_tracing', show=False)
Render a test image through the lens and report PSNR / SSIM.
Simulates what the sensor would capture if the given image were placed
at the specified object distance. The rendering accounts for all
geometric aberrations (blur, distortion, vignetting, chromatic effects).
Optionally applies an inverse distortion warp (unwarp) and reports
quality metrics for both the raw and unwarped renderings.
Algorithm
- Convert
img_orgto a[1, 3, H, W]float tensor and temporarily set the sensor resolution to match. - Call
self.render()with the chosen method (ray tracing or PSF convolution). - Compute PSNR and SSIM between the original and rendered images.
- If
unwarp=True, applyself.unwarp()to correct geometric distortion and report metrics again. - Restore the original sensor resolution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_org
|
ndarray | Tensor
|
Source image with shape
|
required |
save_name
|
str | None
|
Path prefix for saved PNGs. If not
|
None
|
depth
|
float
|
Object distance in mm. Defaults to |
DEPTH
|
spp
|
int
|
Samples (rays) per pixel for rendering.
Defaults to |
SPP_RENDER
|
unwarp
|
bool
|
If |
False
|
method
|
str
|
Rendering backend — |
'ray_tracing'
|
show
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
|
torch.Tensor: Rendered (and optionally unwarped) image with shape
|
Source code in deeplens/optics/geolens_pkg/eval.py
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 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 | |
analysis_spot
Compute RMS and geometric spot radii at multiple field positions for RGB.
Traces rays at num_field evenly-spaced field positions along the
meridional direction for three wavelengths (G, R, B), computes per-
wavelength RMS and maximum (geometric) spot radii referenced to the
green centroid, then averages the three wavelengths.
This provides a quick polychromatic spot-size summary used for design
comparisons and printed to stdout during analysis().
Algorithm
- For each wavelength (G first, then R, B):
a.
self.sample_radial_rays()→[num_field, SPP_PSF, 3]. b.self.trace2sensor()→ sensor-plane positions. c. Green centroidc_Gis computed on the first iteration and used as the common reference for all wavelengths. d.RMS = sqrt(mean(||xy - c_G||^2))per field position. e.radius = max(||xy - c_G||)per field position. - Average RMS and radius over the three wavelengths.
- Convert from mm to μm (× 1000).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_field
|
int
|
Number of field positions sampled from on-axis to full-field. Defaults to 3. |
3
|
depth
|
float
|
Object distance in mm. Use |
float('inf')
|
Returns:
| Type | Description |
|---|---|
|
dict[str, dict[str, float]]: Spot analysis results keyed by field
position string (e.g., |
Source code in deeplens/optics/geolens_pkg/eval.py
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 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 | |
analysis
analysis(save_name='./lens', depth=float('inf'), full_eval=False, render=False, render_unwarp=False, lens_title=None, show=False)
Run a comprehensive optical analysis pipeline for the lens.
This is the main entry point for evaluating a lens design. It chains
multiple evaluation steps in order, saving all plots with a common
save_name prefix.
Execution flow
- Always: draw the lens layout (
draw_layout) and compute polychromatic spot RMS/radius (analysis_spot). - If
full_eval=True: additionally generate: - Spot diagram (
draw_spot_radial). - MTF grid (
draw_mtf). - Distortion curve (
draw_distortion_radial). - Field curvature plot (
draw_field_curvature). - Vignetting map (
draw_vignetting). - If
render=True: render a test chart image through the lens and report PSNR/SSIM (analysis_rendering).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_name
|
str
|
Path prefix for all output files. Each plot
appends a suffix (e.g., |
'./lens'
|
depth
|
float
|
Object distance in mm. |
float('inf')
|
full_eval
|
bool
|
If |
False
|
render
|
bool
|
If |
False
|
render_unwarp
|
bool
|
If |
False
|
lens_title
|
str | None
|
Title string for the layout plot.
Defaults to |
None
|
show
|
bool
|
If |
False
|
Source code in deeplens/optics/geolens_pkg/eval.py
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 2019 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 | |
deeplens.optics.geolens_pkg.eval_seidel.GeoLensSeidel
Mixin for Seidel (third-order) aberration analysis.
seidel_coefficients
Compute per-surface Seidel (third-order) aberration coefficients.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wvln
|
float
|
Reference wavelength in µm (default: d-line 0.5876 µm). |
WVLN_d
|
include_chromatic
|
bool
|
If True, also compute longitudinal and transverse chromatic aberration (C_L, C_T). |
True
|
Returns:
| Type | Description |
|---|---|
Dict
|
Dict with keys: S1..S5 — per-surface lists of Seidel sums [mm] CL, CT — per-surface chromatic aberrations [mm] labels — surface labels (e.g. ["S1", "S2", ...]) sums — dict of system totals for each aberration |
Source code in deeplens/optics/geolens_pkg/eval_seidel.py
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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | |
aberration_histogram
aberration_histogram(wvln: float = WVLN_d, save_name: Optional[str] = None, show: bool = False, include_chromatic: bool = True) -> Dict
Draw a Zemax-style Seidel aberration bar chart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wvln
|
float
|
Reference wavelength in µm. |
WVLN_d
|
save_name
|
Optional[str]
|
Path to save the figure. Defaults to
|
None
|
show
|
bool
|
If True, call |
False
|
include_chromatic
|
bool
|
Include C_L and C_T bars. |
True
|
Returns:
| Type | Description |
|---|---|
Dict
|
The Seidel coefficients dict (same as |
Source code in deeplens/optics/geolens_pkg/eval_seidel.py
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 | |
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_thickness
|
float
|
Weight for thickness / TTL 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_thickness
Penalize excessive air gaps, lens thicknesses, and total track length.
Checks three types of upper-bound constraints
- Per-gap air and glass thickness (center and edge).
- Back focal length (BFL).
- Total track length (TTL) from first surface to sensor.
Returns:
| Name | Type | Description |
|---|---|---|
Tensor |
Scalar thickness penalty loss. |
Source code in deeplens/optics/geolens_pkg/optim.py
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 | |
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], 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]
|
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
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 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 | |
get_optimizer_params
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]
|
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_pkg/optim.py
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 | |
get_optimizer
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]
|
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_pkg/optim.py
deeplens.optics.geolens_pkg.optim_ops.GeoLensSurfOps
Mixin providing surface geometry operations for GeoLens.
Methods:
| Name | Description |
|---|---|
- add_aspheric |
Convert a spherical surface to aspheric. |
- increase_aspheric_order |
Add higher-order polynomial terms. |
- prune_surf |
Size clear apertures by ray tracing. |
- correct_shape |
Fix lens geometry during optimisation. |
add_aspheric
Convert a spherical surface to aspheric for improved aberration correction.
If surf_idx is given, converts that specific surface. Otherwise,
automatically selects the best candidate following established optical
design principles:
- First asphere: placed near the aperture stop (corrects spherical aberration).
- Subsequent aspheres: placed far from the stop (corrects field-dependent aberrations like coma, astigmatism, distortion).
- Prefer air-glass interfaces over cemented surfaces.
- Among candidates at similar stop-distances, prefer larger semi-diameter (higher marginal ray height → more SA contribution).
The new surface starts with k=0 and all polynomial coefficients at
zero, so it is initially identical to the original spherical surface.
Note
After calling this method, any existing optimizer is stale.
Call get_optimizer() again to include the new parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
surf_idx
|
int or None
|
Surface index to convert. If |
None
|
ai_degree
|
int
|
Number of even-order aspheric coefficients
|
4
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
Index of the converted surface. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If |
ValueError
|
If |
References
Design principles from research/aspheric_design_principles.md.
Source code in deeplens/optics/geolens_pkg/optim_ops.py
increase_aspheric_order
Add higher-order polynomial terms to existing Aspheric surfaces.
Appends increment additional even-order coefficients (initialised
to zero). For example, degree 4 [a4, a6, a8, a10] becomes degree 5
[a4, a6, a8, a10, a12] after increment=1.
Follows the principle of start low, add incrementally: increase order only when residual higher-order aberrations persist after optimisation at the current order.
Note
After calling this method, any existing optimizer is stale.
Call get_optimizer() again to include the new parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
surf_idx
|
int or None
|
Surface index. If |
None
|
increment
|
int
|
Number of additional coefficients to add. Defaults to 1. |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
Index of the surface whose order was increased. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If |
ValueError
|
If |
Source code in deeplens/optics/geolens_pkg/optim_ops.py
prune_surf
Prune surfaces to allow all valid rays to go through.
Determines the clear aperture for each surface by ray tracing, then applies margins and enforces manufacturability constraints (edge thickness and air-gap clearance).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expand_factor
|
float
|
Fractional expansion applied to the ray-traced clear aperture radius. Auto-selected if None: 10 % for all lenses. |
None
|
mounting_margin
|
float
|
Absolute margin [mm] added to
the clear aperture for mechanical mounting. When given, this
replaces the proportional |
None
|
Source code in deeplens/optics/geolens_pkg/optim_ops.py
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 | |
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
|
mounting_margin
|
float
|
Absolute mounting margin [mm] for
surface pruning. Passed through to :meth: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
True if any shape corrections were made, False otherwise. |
Source code in deeplens/optics/geolens_pkg/optim_ops.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_pkg/optim_ops.py
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
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 191 192 193 194 | |
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
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 623 624 625 626 | |
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
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 | |
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_pkg/io.py
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 809 810 811 812 813 814 815 816 817 818 819 820 821 822 | |
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_pkg/io.py
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
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 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 | |
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
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 | |
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
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
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 | |
deeplens.optics.geolens_pkg.eval_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/eval_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/eval_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/eval_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/eval_tolerance.py
tolerancing_monte_carlo
Use Monte Carlo simulation to compute the tolerance.
The default trials=200 is tuned for ~3 min runtime on GPU.
For production-quality yield estimates (especially 95th/99th
percentile tails), increase to 1000+.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trials
|
int
|
Number of Monte Carlo trials. Defaults to 200. |
200
|
spp
|
int
|
Samples per pixel for PSF calculation. Lower values run faster at the cost of noisier MTF estimates. Defaults to SPP_CALC (1024), which is ~16x faster than the full SPP_PSF. |
SPP_CALC
|
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/eval_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 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | |
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/eval_tolerance.py
deeplens.optics.geolens_pkg.vis3d.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/vis3d.py
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 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 | |
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/vis3d.py
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 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 | |
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/vis3d.py
848 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 | |
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]
|
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
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 | |
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.
When tolerancing is active, mat2_n_error is added to n2 to
simulate refractive-index manufacturing error.
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.
When tolerancing is active, applies manufacturing error perturbations: d_error (axial shift), decenter_x/y_error (lateral shift), and tilt_error (rotation about the x-axis).
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.
When tolerancing is active, reverses the manufacturing error
perturbations applied in :meth:to_local_coord.
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/ [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 set of random manufacturing errors for the surface.
Error distributions
- r_error: Uniform[-r_tole, 0] (aperture only shrinks).
- d_error: Normal(0, d_tole) axial position shift [mm].
- decenter_x/y_error: Normal(0, decenter_tole) lateral shift [mm].
- tilt_error: Normal(0, tilt_tole) tilt about x-axis [arcmin → rad].
- mat2_n_error: Normal(0, mat2_n_tole) refractive index offset.
Source code in deeplens/optics/geometric_surface/base.py
zero_tolerance
Reset all manufacturing errors to zero (nominal state).
Source code in deeplens/optics/geometric_surface/base.py
sensitivity_score
Compute first-order tolerance sensitivity scores via RSS formula.
For each parameter with a gradient, the score is:
tolerance_range² × gradient², which approximates the variance of
the loss contribution from that parameter's manufacturing error.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Sensitivity gradients and RSS scores keyed by surface index. |
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_r
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, ai2=None, pos_xy=[0.0, 0.0], vec_local=[0.0, 0.0, 1.0], is_square=False, device='cpu')
Bases: Surface
Even-order aspheric surface.
The sag function is:
.. math::
z(\rho) = \frac{c\,\rho^2}{1 + \sqrt{1-(1+k)c^2\rho^2}}
+ \sum_{i=2}^{n} a_{2i}\,\rho^{2i},
\quad \rho^2 = x^2 + y^2
The polynomial starts at the 4th-order term (a4) because the 2nd-order
term competes with the base curvature c.
All coefficients c, k, and ai are differentiable torch
tensors so they can be optimised with gradient descent.
Attributes:
| Name | Type | Description |
|---|---|---|
c |
Tensor
|
Base curvature [1/mm]. |
k |
Tensor
|
Conic constant. |
ai2 |
Tensor or None
|
2nd-order aspheric coefficient (legacy). |
ai |
Tensor
|
Even-order aspheric coefficients
|
Initialize an aspheric surface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r
|
float
|
Aperture radius [mm]. |
required |
d
|
float
|
Axial vertex position [mm]. |
required |
c
|
float
|
Base curvature |
required |
k
|
float
|
Conic constant ( |
required |
ai
|
list[float] or None
|
Even-order aspheric coefficients
starting from the 4th-order term: |
required |
mat2
|
str or Material
|
Material on the transmission side. |
required |
ai2
|
float or None
|
2nd-order aspheric coefficient
from legacy data. Included in sag but not optimised.
Defaults to |
None
|
pos_xy
|
list[float]
|
Lateral offset |
[0.0, 0.0]
|
vec_local
|
list[float]
|
Local normal direction.
Defaults to |
[0.0, 0.0, 1.0]
|
is_square
|
bool
|
Square aperture flag.
Defaults to |
False
|
device
|
str
|
Compute device. Defaults to |
'cpu'
|
Source code in deeplens/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.
The learning rate for each aspheric coefficient a_{2n} is scaled
by 1 / max(r, 1)^{2n} so that the effective sag perturbation per
Adam step is approximately constant (~lr_base mm) regardless of
surface semi-diameter. Without this normalisation, gradients scale
as O(r^{2n}) and can reach 10^5 for camera-sized surfaces,
causing NaN within a few dozen iterations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lrs
|
list
|
learning rates for |
[0.0001, 0.0001, 0.01, 0.0001]
|
optim_mat
|
bool
|
whether to optimize material. Defaults to False. |
False
|
Source code in deeplens/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 |
Source code in deeplens/optics/light/wave.py
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 |