DiffOptics is a scientific differentiable ray tracing and computational lens optimization engine implemented in pure Python. It combines 3D vector geometric optics, exact Newton-Raphson aspheric surface intersection, 3D Snell's law refraction, and gradient-based automatic differentiation to eliminate geometric aberrations and optimize optical designs towards diffraction limits.
The sag
Where:
-
$c = \frac{1}{R}$ is the base vertex curvature (reciprocal of radius of curvature$R$ ). -
$k$ is the conic constant:-
$k = 0$ : Spherical surface -
$k = -1$ : Parabolic surface -
$k < -1$ : Hyperbolic surface -
$-1 < k < 0$ : Elliptic surface
-
-
$\alpha_4, \alpha_6$ are higher-order even aspheric deformation coefficients.
The inward surface normal unit vector
Let
The refracted ray direction
Total Internal Reflection (TIR) occurs when
Optical aberrations are quantified via the Root-Mean-Square (RMS) spot radius on the detector plane:
Where parameter vector
flowchart TD
A["Generate Collimated / Point Ray Bundle (\mathbf{p}_0, \mathbf{d}_0)"] --> B["Iterate Sequential Optical Surfaces"]
B --> C["Newton-Raphson Line-Surface Intersection F(\mathbf{p} + t \mathbf{d}) = 0"]
C --> D["Compute Surface Normal \mathbf{n} and Aperture Mask"]
D --> E["Vector Snell Refraction: \mathbf{d} \to \mathbf{d}'"]
E --> F["Accumulate Optical Path Length (OPL)"]
F --> G["Advance to Next Surface or Detector Plane"]
G --> H["Compute Spot Coordinates (x, y) & RMS Radius \sigma_{\text{RMS}}"]
H --> I["Compute Autodiff Parameter Gradients \nabla_\theta \mathcal{L}"]
I --> J["Adam Optimization Update: \theta \leftarrow \theta - \Delta\theta"]
# Clone the repository
git clone https://github.com/ZengLLQ/diff-optics.git
cd diff-optics
# Install package
pip install -e .diffoptics trace --curvature 0.02 --thickness 5.0 --focal-dist 100.0diffoptics optimize --iterations 30 --lr 0.05import numpy as np
from diffoptics import RayBundle, OpticalSurface, OpticalSystem, LensOptimizer
# 1. Assemble optical system
s1 = OpticalSurface(z_position=0.0, curvature=0.025, conic=0.0, refractive_index=1.5168)
s2 = OpticalSurface(z_position=5.0, curvature=0.0, refractive_index=1.0)
system = OpticalSystem(surfaces=[s1, s2], z_image=85.0)
# 2. Trace collimated beam
rays = RayBundle.create_collimated_bundle(radius=8.0, num_rings=4)
system.trace(rays)
rms_init = system.compute_rms_spot_radius(rays)
print(f"Initial RMS Spot: {rms_init:.4f} mm")
# 3. Optimize conic constant using Adam gradient descent
opt = LensOptimizer(system, lambda: RayBundle.create_collimated_bundle(8.0, 4), [(0, "conic")])
opt_params, _ = opt.optimize_adam(learning_rate=0.05, iterations=20)
print(f"Optimized Conic: {opt_params[0]:.4f}")Run the full pytest suite:
pytest -vThis software is released under the MIT License.