GeoLens API Reference
The GeoLens class is the primary lens model in AutoLens — a differentiable multi-element refractive lens via geometric ray tracing.
GeoLens
Differentiable multi-element refractive lens. Composes nine mixin classes for PSF computation, evaluation, optimization, I/O, visualization, and tolerancing.
src.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_eff |
float
|
Effective half-diagonal field of view [radians] (pinhole model). |
rfov |
float
|
Half-diagonal field of view [radians] (ray-traced). |
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 src/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 src/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 src/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 src/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 src/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 src/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, scale_pupil=1.0)
Sample rays from object space at given field angles.
For infinite depth, generates collimated parallel rays: origins are distributed on the entrance pupil and all rays in a field share the same direction determined by the FOV angle.
For finite depth, generates diverging point-source rays: the point source position is determined by FOV angle and depth, and rays fan out toward the entrance pupil.
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. |
float('inf')
|
num_rays
|
int
|
Number of rays per field point. |
SPP_CALC
|
wvln
|
float
|
Wavelength in micrometers. |
DEFAULT_WAVE
|
entrance_pupil
|
bool
|
If True, sample on entrance pupil; otherwise on surface 0. Default: True. |
True
|
scale_pupil
|
float
|
Scale factor for pupil radius. |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
Ray |
Rays with shape |
Source code in src/geolens.py
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 | |
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 src/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 src/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 src/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 src/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 src/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 src/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 src/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 src/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 src/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 src/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 src/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 src/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 src/geolens.py
find_aperture
Find and set the aperture stop index.
Called after loading when no surface was marked with is_aperture
in the lens file. Looks for an Aperture surface instance first,
then falls back to the surface with the smallest semi-diameter.
Sets
self.aper_idx (int): Index of the aperture surface.
Source code in src/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 src/geolens.py
calc_foclen
Compute effective focal length (EFL).
Two-step approach: 1. Trace on-axis parallel rays to find the paraxial focal point z. This is necessary because the sensor may not be at the focal plane (e.g. finite-conjugate designs or defocused systems). 2. Trace off-axis rays at a small angle to the focal point, measure image height, and compute EFL = imgh / tan(angle).
The default 1-degree field avoids the numerical noise of truly paraxial angles (0.01 rad) while remaining small enough to approximate the paraxial regime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
test_fov_deg
|
float
|
Chief-ray field angle used for the focal-length estimate. Defaults to 1.0 degree. |
1.0
|
Updates
self.efl: Effective focal length. self.foclen: Alias for effective focal length. self.bfl: Back focal length (distance from last surface to sensor).
Source code in src/geolens.py
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 | |
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 src/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 src/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 src/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_eff (float): Half-diagonal (radius) FoV in radians. self.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 src/geolens.py
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 1195 1196 | |
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 src/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 src/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 src/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 src/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 src/geolens.py
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 | |
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 src/geolens.py
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 | |
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 src/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 src/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 src/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_eff
|
float
|
half diagonal-FoV in radian. |
required |
fnum
|
float
|
F number. |
required |
Source code in src/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_eff
|
float
|
Half-diagonal FoV in radians. |
required |
Source code in src/geolens.py
Constructor
| Parameter | Type | Description |
|---|---|---|
filename |
str or None |
Path to .json, .zmx, or .seq lens file. None creates an empty lens. |
device |
str or None |
PyTorch device. Auto-selects CUDA/MPS/CPU if None. |
dtype |
torch.dtype |
Floating-point precision. Default torch.float32. |
Key Attributes
| Attribute | Type | Description |
|---|---|---|
surfaces |
list[Surface] |
Ordered list of optical surfaces |
materials |
list[Material] |
Materials between surfaces |
d_sensor |
Tensor |
Back focal distance (mm) |
foclen |
float |
Effective focal length (mm) |
fnum |
float |
F-number |
rfov |
float |
Half-diagonal FoV, ray-traced (radians) |
rfov_eff |
float |
Half-diagonal FoV, pinhole model (radians) |
sensor_size |
tuple |
Physical sensor size (W, H) in mm |
r_sensor |
float |
Sensor half-diagonal (mm) |
aper_idx |
int |
Index of aperture stop surface |
Ray Tracing
Core ray tracing methods for propagating rays through the lens system.
trace(ray, surf_range, record)
Forward or backward ray trace through a range of surfaces.
trace2sensor(ray, record)
Trace rays forward from object space to the sensor plane.
ray = lens.sample_from_fov(fov_x=0.0, fov_y=10.0, num_rays=1000, wvln=0.587)
ray_out = lens.trace2sensor(ray)
trace2obj(ray)
Backward trace from sensor side to object space.
forward_tracing(ray, surf_range, record)
Sequential forward ray trace through surfaces. Returns modified ray.
backward_tracing(ray, surf_range, record)
Sequential backward ray trace through surfaces.
Ray Sampling
Methods for generating ray bundles from various source configurations.
sample_from_fov(fov_x, fov_y, depth, num_rays, wvln)
Sample rays from a point source at a given field angle (degrees).
sample_grid_rays(depth, num_grid, num_rays, wvln)
Sample a 2D grid of field positions across the full field of view.
sample_radial_rays(num_field, depth, num_rays, wvln, direction)
Sample along the y-axis, x-axis, or diagonal.
sample_from_points(points, num_rays, wvln, scale_pupil)
Generate rays from specific point sources in object space.
sample_sensor(spp, wvln, sub_pixel)
Backward rays from the sensor plane (for image simulation).
Lens Properties
calc_foclen(test_fov_deg)
Compute effective focal length via ray tracing.
calc_fov()
Compute field of view angles (half-diagonal, horizontal, vertical).
calc_pupil()
Compute entrance and exit pupil positions and radii.
calc_numerical_aperture(n)
Compute numerical aperture in medium with refractive index n.
set_fnum(fnum)
Scale the aperture stop to achieve target f-number.
set_target_fov_fnum(rfov_eff, fnum)
Set both field of view and f-number targets.
PSF Computation
src.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 src/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 src/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 src/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 src/geolens_pkg/psf_compute.py
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 | |
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 src/geolens_pkg/psf_compute.py
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | |
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 src/geolens_pkg/psf_compute.py
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 | |
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 src/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 src/geolens_pkg/psf_compute.py
psf(point, ks, wvln)
Compute the point spread function. Dispatches to geometric or coherent methods.
psf_geometric(point, ks, wvln)
Geometric PSF via spot diagram binning.
psf_coherent(point, ks, wvln)
Coherent PSF via pupil wavefront propagation.
psf_huygens(point, ks, wvln)
Huygens PSF via Rayleigh-Sommerfeld diffraction.
psf_map(ks)
Compute PSF across a grid of field positions.
psf_center(point, ks, wvln)
Compute PSF center position for a given point source.
Evaluation
src.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_eff, …) 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_eff (float): Effective half field-of-view in radians (pinhole model).
rfov (float): Half field-of-view in radians (ray-traced).
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 src/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 src/geolens_pkg/eval.py
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 | |
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 src/geolens_pkg/eval.py
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 | |
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 src/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 src/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_eff
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_eff(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 src/geolens_pkg/eval.py
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 | |
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 src/geolens_pkg/eval.py
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 | |
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 src/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 src/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 src/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 src/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 src/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 src/geolens_pkg/eval.py
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 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 | |
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 src/geolens_pkg/eval.py
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 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 | |
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 src/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 src/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 src/geolens_pkg/eval.py
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 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 | |
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 src/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 src/geolens_pkg/eval.py
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 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 | |
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 src/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 src/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 src/geolens_pkg/eval.py
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 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 | |
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 src/geolens_pkg/eval.py
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 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 | |
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 src/geolens_pkg/eval.py
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 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 | |
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 src/geolens_pkg/eval.py
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 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 | |
Spot Diagrams
lens.draw_spot_map() # Spot diagram grid across the field
lens.draw_spot_radial() # Spot diagram along radial direction
lens.rms_map() # RMS spot size map
MTF
Distortion
lens.draw_distortion_radial() # Radial distortion curve
lens.draw_distortion_map() # 2D distortion map
Wavefront Error
Full Analysis
Seidel Aberrations
src.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 src/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 327 328 | |
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 src/geolens_pkg/eval_seidel.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 | |
Third-order (Seidel) aberration analysis via paraxial ray tracing. Computes per-surface coefficients: \(W_{040}\) (spherical), \(W_{131}\) (coma), \(W_{222}\) (astigmatism), \(W_{220}\) (field curvature), \(W_{311}\) (distortion), and chromatic terms.
Optimization
src.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 src/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 src/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
|
wvln
|
float
|
Wavelength in um. Defaults to WAVE_RGB[1]. |
None
|
Source code in src/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 src/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 src/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 src/geolens_pkg/optim.py
loss_ray_angle
Penalize rays that violate chief ray angle or obliquity constraints.
Uses softplus on the violation amount (cos_ref - cos_cra) so the loss is always non-negative, smooth at the boundary, and proportional to violation severity. Minimising the loss pushes cos(CRA) upward (i.e. reduces the chief ray angle).
Returns:
| Name | Type | Description |
|---|---|---|
Tensor |
Scalar ray-angle penalty loss (always >= 0). |
Source code in src/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 src/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 src/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 src/geolens_pkg/optim.py
optimize
optimize(lrs=[0.001, 0.001, 0.01, 0.0001], iterations=5000, test_per_iter=100, centroid=False, optim_mat=False, shape_control=True, momentum_decay=0.1, 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-3, 1e-2, 1e-4]. |
[0.001, 0.001, 0.01, 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
|
momentum_decay
|
float
|
Factor to scale Adam's first moment (exp_avg) at each evaluation step. Prevents stale momentum from the previous ray batch from corrupting gradients after resampling. The second moment (exp_avg_sq) is left untouched to preserve adaptive lr scaling. Set to 0.0 for a full reset, 1.0 to disable. Defaults to 0.1. |
0.1
|
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 src/geolens_pkg/optim.py
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 | |
curriculum_design
curriculum_design(lrs=[0.001, 0.001, 0.01, 0.0001], iterations=5000, test_per_iter=100, optim_mat=False, match_mat=False, shape_control=True, result_dir='./results')
Optimise the lens from scratch using curriculum aperture growth.
Gradually increases the aperture from 25% to full size over the training schedule, transforming a hard global optimisation into a sequence of easier subproblems.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lrs
|
list
|
Learning rates for [d, c, k, ai]. |
[0.001, 0.001, 0.01, 0.0001]
|
iterations
|
int
|
Total training iterations. |
5000
|
test_per_iter
|
int
|
Evaluate and save every N iterations. |
100
|
optim_mat
|
bool
|
Optimise material parameters. |
False
|
match_mat
|
bool
|
Match materials at each evaluation. |
False
|
shape_control
|
bool
|
Correct surface shapes at each evaluation. |
True
|
result_dir
|
str
|
Directory to save results. |
'./results'
|
Source code in src/geolens_pkg/optim.py
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 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 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 | |
optimize_lbfgs
optimize_lbfgs(lr=0.01, iterations=500, test_per_iter=50, centroid=False, optim_mat=False, shape_control=True, max_iter=5, history_size=10, line_search_fn='strong_wolfe', result_dir=None)
Optimise the lens using L-BFGS, a quasi-Newton method.
L-BFGS uses curvature information for faster convergence on smooth objectives, making it well-suited for fine-tuning pre-optimised lenses where the loss landscape is relatively smooth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lr
|
float
|
Learning rate (step size). Defaults to 0.01. |
0.01
|
iterations
|
int
|
Number of outer iterations. Defaults to 500. |
500
|
test_per_iter
|
int
|
Evaluate every N iterations. Defaults to 50. |
50
|
centroid
|
bool
|
Use chief-ray centroid as PSF centre. Defaults to False. |
False
|
optim_mat
|
bool
|
Optimise material parameters. Defaults to False. |
False
|
shape_control
|
bool
|
Apply |
True
|
max_iter
|
int
|
Max L-BFGS inner iterations per step. Defaults to 5. |
5
|
history_size
|
int
|
L-BFGS history size. Defaults to 10. |
10
|
line_search_fn
|
str
|
Line search strategy. Use
|
'strong_wolfe'
|
result_dir
|
str
|
Directory to save results. |
None
|
Source code in src/geolens_pkg/optim.py
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 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 | |
optimize_bfgs
optimize_bfgs(lrs=[0.001, 0.001, 0.01, 0.0001], lr=1.0, max_step_factor=10.0, iterations=500, test_per_iter=50, centroid=False, optim_mat=False, shape_control=True, reset_hessian_on_resample=False, result_dir=None, w_reg=0.1, w_focus=1.0)
Optimise the lens using full BFGS (no closure, Adam-like loop).
Maintains the complete N x N inverse Hessian approximation, giving
true second-order convergence for smooth objectives. Uses the same
zero_grad -> backward -> step loop as Adam, so ray re-sampling
at evaluation boundaries is straightforward.
The inverse Hessian is initialised as diag(per_param_lr) using the
learning rates from lrs, so the first BFGS step matches what Adam
would do. Per-element clamping ensures no parameter changes by more
than max_step_factor * its_lr per step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lrs
|
list
|
Per-type learning rates [d, c, k, ai], used to initialise the diagonal of the inverse Hessian and as per-element clamp bounds. Default: [1e-3, 1e-4, 1e-1, 1e-4]. |
[0.001, 0.001, 0.01, 0.0001]
|
lr
|
float
|
Global multiplier on the BFGS direction. Default: 1.0. |
1.0
|
max_step_factor
|
float
|
Per-element clamp — each scalar param
changes by at most |
10.0
|
iterations
|
int
|
Total outer iterations. Default: 500. |
500
|
test_per_iter
|
int
|
Evaluate / re-sample rays every N iters. Default: 50. |
50
|
centroid
|
bool
|
Use chief-ray centroid as PSF centre reference. |
False
|
optim_mat
|
bool
|
Include material parameters in optimisation. |
False
|
shape_control
|
bool
|
Call |
True
|
reset_hessian_on_resample
|
bool
|
Reset inverse Hessian to initial diagonal when rays are re-sampled. Default: False. |
False
|
result_dir
|
str | None
|
Directory for results. Auto-generated if None. |
None
|
w_reg
|
float
|
Weight for regularization losses (loss_surface, loss_intersec, loss_thickness). Default: 0.1. |
0.1
|
w_focus
|
float
|
Weight for focus loss (loss_infocus). Default: 1.0. |
1.0
|
Source code in src/geolens_pkg/optim.py
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 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 | |
get_optimizer_params
get_optimizer_params(lrs=[0.001, 0.001, 0.01, 0.0001], optim_mat=False, optim_surf_range=None, reparam=False)
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.001, 0.001, 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
|
reparam
|
bool
|
use normalized reparametrization for Aspheric surfaces. Set True for single-lr optimizers (BFGS). Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
optimizer parameters |
Source code in src/geolens_pkg/optim.py
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 | |
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 src/geolens_pkg/optim.py
optimize(lrs, iterations, test_per_iter, centroid, optim_mat, shape_control, result_dir)
Adam optimizer loop with cosine warmup scheduler and error-adaptive field weighting.
lens.optimize(
lrs=[1e-3, 1e-4, 1e-2, 1e-4],
iterations=2000,
test_per_iter=100,
centroid=False,
result_dir="results/finetune",
)
optimize_lbfgs(iterations, lr, reparam, result_dir)
L-BFGS optimizer with optional parameter reparametrization.
curriculum_design(iterations, test_per_iter, lrs, optim_mat, result_dir)
Curriculum learning with gradual aperture opening and material optimization.
Loss Functions
| Method | Returns |
|---|---|
loss_rms() |
RGB spot RMS error |
loss_infocus() |
On-axis focus penalty |
loss_reg() |
Composite regularization |
loss_surface() |
Surface shape penalty |
loss_intersec() |
Self-intersection penalty |
loss_thickness() |
Thickness / TTL penalty |
loss_ray_angle() |
Chief ray angle penalty |
loss_mat() |
Material bounds penalty |
Surface Operations
src.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 src/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 src/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 src/geolens_pkg/optim_ops.py
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 | |
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 src/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 src/geolens_pkg/optim_ops.py
add_aspheric()
Add aspheric polynomial terms to surfaces.
increase_aspheric_order()
Increase the order of existing aspheric polynomials.
prune_surf(expand_factor)
Resize surface clear apertures to actual ray footprint plus margin.
correct_shape()
Clip surfaces to valid geometry (positive edge thickness, valid sag).
match_materials()
Snap floating refractive indices to the nearest real glass in the catalog.
File I/O
src.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 src/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 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 | |
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 src/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 src/geolens_pkg/io.py
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 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 | |
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 src/geolens_pkg/io.py
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 | |
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 src/geolens_pkg/io.py
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 | |
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 src/geolens_pkg/io.py
read_lens_json(filename)
Load a lens from JSON format.
write_lens_json(filename)
Save a lens to JSON format.
read_lens_zmx(filename)
Load a lens from Zemax .zmx format.
write_lens_zmx(filename)
Save a lens to Zemax .zmx format.
read_lens_seq(filename)
Load a lens from Code V .seq format.
Visualization
src.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 src/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 src/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 src/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 src/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 src/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 src/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 | |
draw_layout()
Draw 2D lens cross-section with ray fans.
draw_lens_2d(ax)
Draw lens element outlines on a matplotlib axis.
draw_ray_2d(ax, ray)
Draw traced rays on a matplotlib axis.
Tolerancing
src.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 src/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 src/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 src/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 src/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 src/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 src/geolens_pkg/eval_tolerance.py
Manufacturing tolerance analysis following Jun Dai et al. (arXiv:2502.04719, 2025).
tolerancing_sensitivity()
Sensitivity-based tolerance analysis.
tolerancing_monte_carlo(num_samples)
Monte Carlo tolerance analysis with random perturbations.
Reparametrization
enable_reparam()
Enable parameter reparametrization on all Aspheric surfaces. Normalizes \(c\), \(k\), \(a_i\) to \(\sim\mathcal{O}(1)\) scale.
disable_reparam()
Disable reparametrization and restore physical parameter values.