### Setup TorchOptics Defaults Source: https://torchoptics.readthedocs.io/en/stable/quickstart/index.html Import necessary libraries and set global defaults for grid spacing and wavelength. These defaults apply to all subsequent fields and elements. ```python import torch import torchoptics from torchoptics import Field, System from torchoptics.elements import AmplitudeModulator, Lens from torchoptics.profiles import checkerboard, circle, gaussian torchoptics.set_default_spacing(10e-6) # 10 µm grid spacing torchoptics.set_default_wavelength(700e-9) # 700 nm (red light) ``` -------------------------------- ### Install TorchOptics Source: https://torchoptics.readthedocs.io/en/stable/index.html Install the TorchOptics library using pip. This command installs the latest stable version. ```bash pip install torchoptics ``` -------------------------------- ### Import Libraries and Setup Source: https://torchoptics.readthedocs.io/en/stable/examples/optical_systems/lens_focusing.html Imports necessary libraries for optical system simulation and visualization. Sets default simulation parameters like grid spacing and wavelength. ```python import matplotlib.pyplot as plt import torch import torchoptics from torchoptics import Field, System, visualize_tensor from torchoptics.elements import Lens from torchoptics.profiles import gaussian ``` ```python shape = 512 # Grid size spacing = 10e-6 # Grid spacing (m) wavelength = 632.8e-9 # HeNe laser wavelength (m) focal_length = 100e-3 # Lens focal length (m) beam_waist = 1e-3 # Input beam waist (m) w_focus = wavelength * focal_length / (torch.pi * beam_waist) torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) device = "cuda" if torch.cuda.is_available() else "cpu" print(f"Focal length: {focal_length * 1e3:.0f} mm") print(f"Input beam waist: {beam_waist * 1e3:.1f} mm") print(f"Predicted spot size: {w_focus * 1e6:.1f} µm") ``` -------------------------------- ### Initialize Phase Modulator Source: https://torchoptics.readthedocs.io/en/stable/_downloads/c0654258368bca714c02af51f1bd0b47/training_multi_plane_focusing.ipynb Initializes a PhaseModulator with a zero-initialized phase pattern. This is the starting point for optimization. ```python phase_modulator = PhaseModulator(Parameter(torch.zeros(shape, shape)), z=0).to(device) ``` -------------------------------- ### Create a Lens Phase Profile Source: https://torchoptics.readthedocs.io/en/stable/user-guide/profiles.html Use `lens_phase()` to generate the quadratic phase profile of a thin lens. Wrap in `torch.exp(1j * phase)` to get the complex field. ```python field = torch.exp(1j * lens_phase(300, focal_length=300e-3, wavelength=700e-9)) visualize_tensor(field, title="Lens Phase") ``` -------------------------------- ### Import Libraries for Quantum State Discrimination Source: https://torchoptics.readthedocs.io/en/stable/_downloads/a5e21e778007342c988dc75ccded572b/quantum_state_discrimination.ipynb Imports necessary libraries including matplotlib, torch, and torchoptics modules for field operations and Hermite-Gaussian profiles. Ensure these libraries are installed before running. ```python import math import matplotlib.pyplot as plt import torch import torchoptics from torchoptics import Field from torchoptics.profiles import hermite_gaussian ``` -------------------------------- ### Simulate and Visualize Zernike Aberrations Source: https://torchoptics.readthedocs.io/en/stable/_downloads/c96987df88734d623c47f161047e78d8/zernike_aberrations.ipynb Iterates through a list of Zernike aberrations, applies them to a lens phase, and visualizes the resulting Point Spread Function (PSF). Requires prior setup of optical components and parameters. ```python aberrations_for_psf = [ (2, 0, "Defocus"), (2, 2, "Astigmatism"), (3, 1, "Coma"), (4, 0, "Spherical"), ] for n, m, name in aberrations_for_psf: # Add wavefront error to lens phase z_poly = zernike(shape, n, m, aperture_radius) aberrated_phase = phase + aberration_strength * z_poly lens = Modulator(pupil * torch.exp(1j * aberrated_phase), z=d_o).to(device) psf = System(lens).measure_at_z(point_source, z=d_o + d_i) visualize_tensor(psf.intensity(), title=rf"{name} ($Z_{{{n}}}^{{{m}}}$)") ``` -------------------------------- ### Example Output of Performance Metrics Source: https://torchoptics.readthedocs.io/en/stable/examples/optimization/training_multi_plane_focusing.html This is an example output showing the performance metrics for a bifocal lens, including overlap at specified focal planes and total efficiency. ```text Final Performance: Overlap at z = 50 mm: 0.347 Overlap at z = 100 mm: 0.671 Total efficiency: 0.509 ``` -------------------------------- ### Configure simulation parameters and defaults Source: https://torchoptics.readthedocs.io/en/stable/_downloads/4f85eaf72985ad118485913f6a3c9328/mach_zehnder_interferometer.ipynb Sets up simulation grid size, spacing, wavelength, and beam waist. It also configures default spacing and wavelength for torchoptics. ```python shape = 400 # Grid size (number of points per dimension) spacing = 10e-6 # Grid spacing (m) wavelength = 700e-9 # Wavelength (m) waist_radius = 800e-6 # Gaussian beam waist (m) # Configure torchoptics defaults torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) ``` -------------------------------- ### Configure Simulation Parameters Source: https://torchoptics.readthedocs.io/en/stable/examples/optical_phenomena/animate_propagation.html Sets up the grid size, spacing, wavelength, and aperture radius for the simulation. Default spacing and wavelength are configured using torchoptics functions. ```python shape = 500 # Grid size spacing = 10e-6 # Grid spacing (m) wavelength = 700e-9 # Red light (m) aperture_radius = 1.5e-3 # Octagon circumradius (m) # Configure torchoptics defaults torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) ``` -------------------------------- ### Retrieve Current Global Defaults Source: https://torchoptics.readthedocs.io/en/stable/user-guide/configuration.html Get the currently set global default spacing and wavelength. These values are returned as PyTorch Tensors. ```python torchoptics.get_default_spacing() # Returns Tensor torchoptics.get_default_wavelength() # Returns Tensor ``` -------------------------------- ### Apply Amplitude Mask Modulation Source: https://torchoptics.readthedocs.io/en/stable/user-guide/fields.html Modulate a Field using a real-valued profile, acting as an amplitude mask. This example uses a circular aperture profile. ```python # Real amplitude mask from torchoptics.profiles import circle apertured = field.modulate(circle(300, radius=1e-3)) ``` -------------------------------- ### Set up simulation parameters and print predictions Source: https://torchoptics.readthedocs.io/en/stable/_downloads/a262ed80a7d535a8333c44b2b97bce2b/lens_focusing.ipynb Defines grid size, wavelength, focal length, and beam waist. Calculates and prints the predicted focal spot size and sets default simulation parameters. ```python shape = 512 # Grid size spacing = 10e-6 # Grid spacing (m) wavelength = 632.8e-9 # HeNe laser wavelength (m) focal_length = 100e-3 # Lens focal length (m) beam_waist = 1e-3 # Input beam waist (m) w_focus = wavelength * focal_length / (torch.pi * beam_waist) torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) device = "cuda" if torch.cuda.is_available() else "cpu" print(f"Focal length: {focal_length * 1e3:.0f} mm") print(f"Input beam waist: {beam_waist * 1e3:.1f} mm") print(f"Predicted spot size: {w_focus * 1e6:.1f} µm") ``` -------------------------------- ### Define simulation parameters and defaults Source: https://torchoptics.readthedocs.io/en/stable/_downloads/c2898a92809c5997752dec643f23f776/polarized_field.ipynb Sets up the grid size, spacing, wavelength, and beam waist for the simulation. Configures default spacing and wavelength for torchoptics. ```python shape = 100 # Grid size (number of points per dimension) spacing = 10e-6 # Grid spacing (m) wavelength = 700e-9 # Wavelength (m) beam_waist = 250e-6 # Beam waist radius (m) extent_mm = (shape - 1) * spacing / 2 * 1e3 x_coords = torch.linspace(-extent_mm, extent_mm, shape) # Configure torchoptics defaults torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) ``` -------------------------------- ### Get Intensity and Power Source: https://torchoptics.readthedocs.io/en/stable/user-guide/spatial_coherence.html Extracts the time-averaged intensity profile and calculates the total power of a spatial coherence object. Intensity is returned as a tensor, and power as a scalar. ```python I = low_coh.intensity() # shape (H, W) P = low_coh.power() # scalar ``` -------------------------------- ### Define simulation parameters Source: https://torchoptics.readthedocs.io/en/stable/_downloads/390d20ff2921546a8e1e4f121c4b9e5a/4f_system.ipynb Sets up simulation parameters including grid size, spacing, wavelength, focal length, checkerboard tile size, and device selection (CPU/GPU). ```python shape = 500 # Grid size (number of points per dimension) spacing = 10e-6 # Grid spacing (m) wavelength = 700e-9 # Wavelength (m) focal_length = 50e-3 # Lens focal length (m) tile_length = 200e-6 # Checkerboard tile size (m) num_tiles = 15 # Number of tiles in each dimension device = "cuda" if torch.cuda.is_available() else "cpu" torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) ``` -------------------------------- ### Define Simulation Parameters Source: https://torchoptics.readthedocs.io/en/stable/_downloads/a8691a27817e3d2b42391a0a9e44f889/spatial_coherence.ipynb Sets up simulation parameters such as grid size, spacing, wavelength, beam waist, and coherence widths. It also configures torchoptics defaults and prints a summary of the parameters. ```python shape = 30 # Grid size (number of points per dimension) spacing = 10e-6 # Grid spacing (m) wavelength = 700e-9 # Wavelength (m) waist_radius = 40e-6 # Waist radius of the Gaussian beam (m) # Define coherence widths low_coherence_width = 10e-6 # Low spatial coherence (m) high_coherence_width = 1e-3 # High spatial coherence (m) # Determine computation device device = "cuda" if torch.cuda.is_available() else "cpu" # Configure torchoptics defaults torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) print(f"Beam waist: {waist_radius * 1e6:.0f} m") low_ratio = low_coherence_width / waist_radius print(f"Low coherence width: {low_coherence_width * 1e6:.0f} m (́c/w₀ = {low_ratio:.2f})") high_ratio = high_coherence_width / waist_radius print(f"High coherence width: {high_coherence_width * 1e3:.1f} mm (́c/w₀ = {high_ratio:.0f})") ``` -------------------------------- ### Create a System with Lenses Source: https://torchoptics.readthedocs.io/en/stable/user-guide/systems.html Instantiate a System by passing optical elements to its constructor. Element positions are determined by their 'z' attribute. Default spacing and wavelength can be set globally. ```python import torch import torchoptics from torchoptics import Field, System from torchoptics.elements import AmplitudeModulator, Lens from torchoptics.profiles import circle, gaussian torchoptics.set_default_spacing(10e-6) torchoptics.set_default_wavelength(700e-9) shape = 1000 f = 200e-3 system = System( Lens(shape, f, z=1 * f), Lens(shape, f, z=3 * f), ) ``` -------------------------------- ### Create a Spherical Wave Phase Profile Source: https://torchoptics.readthedocs.io/en/stable/user-guide/profiles.html Use `spherical_wave_phase()` to generate the phase profile for a diverging spherical wave. Wrap in `torch.exp(1j * phase)` to get the complex field. ```python field = torch.exp(1j * spherical_wave_phase(300, z=0.5, wavelength=700e-9)) visualize_tensor(field, title="Spherical Wave Phase") ``` -------------------------------- ### Create a Plane Wave Phase Profile Source: https://torchoptics.readthedocs.io/en/stable/user-guide/profiles.html Use `plane_wave_phase()` to generate the phase profile for a tilted plane wave. Wrap in `torch.exp(1j * phase)` to get the complex field. ```python field = torch.exp(1j * plane_wave_phase(300, theta=0.001, wavelength=700e-9)) visualize_tensor(field, title="Plane Wave Phase") ``` -------------------------------- ### Import Libraries and Configure Defaults Source: https://torchoptics.readthedocs.io/en/stable/examples/optimization/training_petal_beam.html Imports necessary libraries for simulation, visualization, and optimization. Configures default spacing and wavelength for TorchOptics. ```python import matplotlib.animation as animation import matplotlib.pyplot as plt import torch from torch.nn import Parameter import torchoptics from torchoptics import Field, System, visualize_tensor from torchoptics.elements import PhaseModulator from torchoptics.profiles import gaussian, laguerre_gaussian ``` ```python shape = 250 # Grid size (number of points per dimension) waist_radius = 300e-6 # Waist radius of the Gaussian beam (m) # Select computation device device = "cuda" if torch.cuda.is_available() else "cpu" # Configure torchoptics defaults torchoptics.set_default_spacing(10e-6) torchoptics.set_default_wavelength(700e-9) ``` -------------------------------- ### Initialize Trainable Diffractive System Source: https://torchoptics.readthedocs.io/en/stable/quickstart/index.html Initializes a diffractive system with three phase modulators. These elements are trainable parameters, allowing for gradient-based optimization. ```python # Trainable diffractive system: three phase planes initialized to zero system = System( PhaseModulator(Parameter(torch.zeros(shape, shape)), z=0.2), PhaseModulator(Parameter(torch.zeros(shape, shape)), z=0.4), PhaseModulator(Parameter(torch.zeros(shape, shape)), z=0.6), ) optimizer = torch.optim.Adam(system.parameters(), lr=0.05) for iteration in range(200): optimizer.zero_grad() output = system.measure_at_z(input_field, z=0.8) loss = 1 - output.inner(target_field).abs().square() # 1 - |η|² loss.backward() optimizer.step() ``` -------------------------------- ### Create and Visualize Checkerboard Input Field Source: https://torchoptics.readthedocs.io/en/stable/quickstart/index.html Create a Field object representing a checkerboard pattern. This is used as input for a 4f system example. The `tile_length` and `num_tiles` parameters define the pattern's characteristics. ```python input_field = Field(checkerboard(shape, tile_length=200e-6, num_tiles=15)) input_field.visualize(title="Input Field", vmax=1) ``` -------------------------------- ### Create a 4f system with two lenses Source: https://torchoptics.readthedocs.io/en/stable/autoapi/torchoptics/index.html Demonstrates the creation of a 4f optical system using the System class and Lens elements. The system is configured with lenses placed at specific z-positions and moved to a specified device. ```python system = System( Lens(shape, focal_length, z=1 * focal_length), Lens(shape, focal_length, z=3 * focal_length), ).to(device) ``` -------------------------------- ### Import Libraries and Configure Defaults Source: https://torchoptics.readthedocs.io/en/stable/examples/aberrations/zernike_aberrations.html Imports necessary libraries like matplotlib and torchoptics. Configures default simulation parameters such as grid spacing and wavelength. Selects the computation device (CUDA or CPU). ```python import matplotlib.pyplot as plt import torch import torchoptics from torchoptics import Field, System, visualize_tensor from torchoptics.elements import Modulator from torchoptics.profiles import circle, lens_phase, zernike ``` ```python shape = 500 # Grid size (number of points per dimension) spacing = 10e-6 # Grid spacing (m) wavelength = 500e-9 # Wavelength (m) focal_length = 0.5 # Lens focal length (m) aperture_radius = 1.5e-3 # Lens aperture radius (m) d_o = 1.0 # Object distance (m) d_i = 1.0 # Image distance (m), satisfies 1/f = 1/d_o + 1/d_i aberration_strength = 4 * torch.pi # Peak-to-valley wavefront error (~2 waves) # Configure torchoptics defaults torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) # Select computation device device = "cuda" if torch.cuda.is_available() else "cpu" ``` -------------------------------- ### Create a Cylindrical Lens Phase Profile Source: https://torchoptics.readthedocs.io/en/stable/user-guide/profiles.html Use `cylindrical_lens_phase()` to generate a quadratic phase profile in one direction, simulating a cylindrical lens. Wrap in `torch.exp(1j * phase)` to get the complex field. ```python field = torch.exp(1j * cylindrical_lens_phase(300, focal_length=300e-3, wavelength=700e-9)) visualize_tensor(field, title="Cylindrical Lens Phase") ``` -------------------------------- ### Import Libraries and Define Constants Source: https://torchoptics.readthedocs.io/en/stable/examples/aberrations/chromatic_aberration.html Imports necessary libraries and defines simulation parameters including material properties, spectral lines, and lens geometry. Sets up the default spacing and device for PyTorchOptics. ```python import matplotlib.pyplot as plt import torch import torchoptics from torchoptics import Field, System from torchoptics.elements import PolychromaticPhaseModulator from torchoptics.profiles import gaussian from torchoptics.profiles._profile_meshgrid import profile_meshgrid ``` ```python shape = 512 spacing = 10e-6 # 10 µm grid spacing — large enough that the 1 mm beam # decays to < 0.2 % amplitude at the boundary waist_radius = 1e-3 # 1 mm Gaussian beam waist # BK7 glass Cauchy coefficients A_cauchy = 1.5044 B_cauchy = 4.24e-15 # m² def n_bk7(wavelength): """Two-term Cauchy dispersion model for BK7 glass.""" return A_cauchy + B_cauchy / wavelength**2 # Fraunhofer spectral lines wavelengths = [486.1e-9, 589.3e-9, 656.3e-9] # F, d, C lines (m) colors = ["royalblue", "goldenrod", "firebrick"] labels = ["F-line 486 nm", "d-line 589 nm", "C-line 656 nm"] # Lens geometry: plano-convex, designed for f_d = 150 mm at the d-line n_d = n_bk7(589.3e-9) focal_d = 150e-3 # design focal length at d-line (m) R = focal_d * (n_d - 1) # radius of curvature (m) # Abbe number and theoretical focal lengths n_F, n_C = n_bk7(486.1e-9), n_bk7(656.3e-9) V_abbe = (n_d - 1) / (n_F - n_C) focal_theory = [R / (n_bk7(wl) - 1) for wl in wavelengths] lca_theory = focal_theory[2] - focal_theory[0] torchoptics.set_default_spacing(spacing) device = "cuda" if torch.cuda.is_available() else "cpu" print(f"BK7 refractive indices: nF = {n_F:.4f}, nd = {n_d:.4f}, nC = {n_C:.4f}") print(f"Abbe number: Vd = {V_abbe:.1f}") print(f"Radius of curvature: R = {R * 1e3:.2f} mm") print(f"Theoretical LCA: Δf = f_d / Vd = {lca_theory * 1e3:.2f} mm") ``` -------------------------------- ### Configure simulation parameters and device Source: https://torchoptics.readthedocs.io/en/stable/_downloads/13efaad8b0089b497a876083d6446158/fresnel_zone_plate.ipynb Sets up simulation parameters such as grid size, spacing, wavelength, and focal length. It also configures TorchOptics defaults and selects the computation device (CUDA or CPU). ```python shape = 600 # Grid size (number of points per dimension) spacing = 5e-6 # Grid spacing (m) wavelength = 500e-9 # Wavelength (m) focal_length = 0.3 # Desired focal length (m) # Configure torchoptics defaults torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) # Select computation device device = "cuda" if torch.cuda.is_available() else "cpu" ``` -------------------------------- ### Import Libraries and Configure Defaults Source: https://torchoptics.readthedocs.io/en/stable/examples/coherence_and_polarization/laser_speckle_patterns.html Imports necessary libraries for plotting, tensor operations, and torchoptics. Sets default spacing and wavelength for torchoptics simulations. ```python import matplotlib.pyplot as plt import torch import torchoptics from torchoptics import Field, visualize_tensor from torchoptics.profiles import circle, gaussian ``` ```python # Configure torchoptics defaults torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) device = "cuda" if torch.cuda.is_available() else "cpu" ``` -------------------------------- ### Define Simulation Parameters and Calculate Theoretical Angles Source: https://torchoptics.readthedocs.io/en/stable/_downloads/c1f92605fa06ef38297a1129ed425027/polychromatic_light_with_grating.ipynb Sets up simulation parameters such as grid size, spacing, beam waist, wavelengths for RGB light, and grating properties. It also calculates and prints the theoretical first-order diffraction angles for each wavelength. ```python shape = 500 # Grid size (number of points per dimension) spacing = 10e-6 # Grid spacing (m) waist_radius = 300e-6 # Input Gaussian beam waist (m) wavelengths = [450e-9, 550e-9, 700e-9] # Blue, green, red (m) colors = ["blue", "green", "red"] labels = ["Blue (450 nm)", "Green (550 nm)", "Red (700 nm)"] grating_period = 100e-6 # Grating period d (m) blaze_wavelength = wavelengths[0] # Blaze condition optimized for blue # Configure torchoptics defaults (spacing only; wavelength set per-field) torchoptics.set_default_spacing(spacing) device = "cuda" if torch.cuda.is_available() else "cpu" # Theoretical first-order deflection angles (radians) theta_theory = [wl / grating_period for wl in wavelengths] print("Theoretical first-order diffraction angles:") for lbl, theta in zip(labels, theta_theory): print(f" {lbl}: {theta * 1e3:.2f} mrad") ``` -------------------------------- ### Configure Simulation Parameters Source: https://torchoptics.readthedocs.io/en/stable/_downloads/b7e205eaab4bdb61763a0c7f7b81755a/laser_speckle_patterns.ipynb Sets up the simulation grid size, spacing, wavelength, and illumination beam radius. It also configures torchoptics defaults for spacing and wavelength and determines the computation device (CUDA or CPU). ```python shape = 512 # Grid size spacing = 5e-6 # Grid spacing (m) wavelength = 632.8e-9 # HeNe laser (m) beam_radius = 1e-3 # Illumination beam radius (m) # Configure torchoptics defaults torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) device = "cuda" if torch.cuda.is_available() else "cpu" ``` -------------------------------- ### Configure Simulation Parameters and Device Source: https://torchoptics.readthedocs.io/en/stable/_downloads/424f19c8cf6e3c2ef21198f68d83155d/talbot_effect.ipynb Sets up simulation grid size, physical parameters like spacing and wavelength, grating period, and calculates the Talbot distance. It also configures torchoptics defaults and selects the computation device (CUDA or CPU). ```python shape = 300 # Grid size (number of points per dimension) spacing = 5e-6 # Grid spacing (m) wavelength = 500e-9 # Wavelength (m), green light grating_period = 50e-6 # Grating period (m) # Talbot distance z_talbot = 2 * grating_period**2 / wavelength print(f"Talbot distance: z_T = {z_talbot * 1e3:.1f} mm") # Configure torchoptics defaults torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) # Select computation device device = "cuda" if torch.cuda.is_available() else "cpu" ``` -------------------------------- ### Create Gaussian Schell Model Sources Source: https://torchoptics.readthedocs.io/en/stable/user-guide/spatial_coherence.html Constructs low and high coherence light sources using the gaussian_schell_model function. Ensure default spacing and wavelength are set before use. ```python import torchoptics from torchoptics import SpatialCoherence, visualize_tensor from torchoptics.profiles import gaussian_schell_model torchoptics.set_default_spacing(10e-6) torchoptics.set_default_wavelength(700e-9) low_coh = SpatialCoherence( gaussian_schell_model(30, waist_radius=40e-6, coherence_width=10e-6) ) high_coh = SpatialCoherence( gaussian_schell_model(30, waist_radius=40e-6, coherence_width=1e-3) ) low_coh.visualize(title="Low Coherence (σ_c = 10 µm)") ``` ```python high_coh.visualize(title="High Coherence (σ_c = 1 mm)") ``` -------------------------------- ### System Indexing, Slicing, and Iteration Source: https://torchoptics.readthedocs.io/en/stable/user-guide/systems.html Systems support standard Python sequence operations like indexing to retrieve a single element, slicing to create a new System from a subset of elements, and iteration to loop through elements. ```python first = system[0] # Single element sub = system[0:2] # New System from slice n = len(system) # Element count for element in system: print(element) ``` -------------------------------- ### System Measurement with Phase Modulator Source: https://torchoptics.readthedocs.io/en/stable/_downloads/5d503a871a061d2c5bab6d90fe2b43ae/phase_only_modulators.ipynb Sets up a system with a phase modulator and a lens, then measures the output field at 2f for a uniform plane wave input. ```python system = System(phase_modulator, Lens(shape, focal_length, z=focal_length)).to(device) # Input is a uniform plane wave input_field = Field(torch.ones(shape, shape)).to(device) # Measure the output field at z = 2f output_field = system.measure_at_z(input_field, z=2 * focal_length) visualize_tensor(output_field.intensity(), title="Output Field at 2f", vmax=1) ``` -------------------------------- ### Define simulation parameters Source: https://torchoptics.readthedocs.io/en/stable/_downloads/c96987df88734d623c47f161047e78d8/zernike_aberrations.ipynb Sets up simulation parameters such as grid size, spacing, wavelength, lens properties, and aberration strength. Configures torchoptics defaults and selects the computation device. ```python shape = 500 # Grid size (number of points per dimension) spacing = 10e-6 # Grid spacing (m) wavelength = 500e-9 # Wavelength (m) focal_length = 0.5 # Lens focal length (m) aperture_radius = 1.5e-3 # Lens aperture radius (m) d_o = 1.0 # Object distance (m) d_i = 1.0 # Image distance (m), satisfies 1/f = 1/d_o + 1/d_i aberration_strength = 4 * torch.pi # Peak-to-valley wavefront error (~2 waves) # Configure torchoptics defaults torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) # Select computation device device = "cuda" if torch.cuda.is_available() else "cpu" ``` -------------------------------- ### Configure simulation parameters Source: https://torchoptics.readthedocs.io/en/stable/_downloads/18d5a120189995289163cf9a80b3a5bc/gaussian_beam_propagation.ipynb Sets up simulation parameters such as grid size, spacing, wavelength, and beam waist radius. It calculates the Rayleigh range and configures torchoptics defaults for spacing and wavelength. The device (CPU or CUDA) is also determined. ```python shape = 256 # Grid size spacing = 10e-6 # Grid spacing (m) wavelength = 632.8e-9 # HeNe laser wavelength (m) waist_radius = 200e-6 # Beam waist radius w_0 (m) rayleigh_range = torch.pi * waist_radius**2 / wavelength # z_R (m) # Configure torchoptics defaults torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) device = "cuda" if torch.cuda.is_available() else "cpu" print(f"Waist radius: {waist_radius * 1e6:.0f} µm") print(f"Rayleigh range: {rayleigh_range * 1e3:.1f} mm") ``` -------------------------------- ### Simulate 4f System with High-Pass Filter Source: https://torchoptics.readthedocs.io/en/stable/quickstart/index.html Sets up and simulates a 4f optical system that includes a high-pass filter at the Fourier plane. This demonstrates how to chain optical elements and measure the output field. ```python system = System( Lens(shape, f, z=1 * f), aperture, Lens(shape, f, z=3 * f), ) output = system.measure_at_z(input_field, z=4 * f) output.visualize(title="Output: Edges", vmax=1) ``` -------------------------------- ### Create and use Waveplate elements Source: https://torchoptics.readthedocs.io/en/stable/user-guide/elements.html Instantiate Waveplate, QuarterWaveplate, or HalfWaveplate to introduce phase delays between polarization axes without attenuation. These elements modify the polarization state. ```python from torchoptics.elements import HalfWaveplate, QuarterWaveplate, Waveplate # General waveplate wp = Waveplate(shape, phi=math.pi/3, theta=math.pi/4, z=0) # Quarter waveplate at 45°: converts x-linear to circular qwp = QuarterWaveplate(shape, theta=math.pi/4, z=0) # Half waveplate at 22.5°: rotates polarization by 45° hwp = HalfWaveplate(shape, theta=math.pi/8, z=0) ``` -------------------------------- ### Initialize Input Gaussian Field Source: https://torchoptics.readthedocs.io/en/stable/quickstart/index.html Sets up the default spacing and wavelength, then defines and visualizes an input Gaussian beam field for inverse design. ```python import torch from torch.nn import Parameter import torchoptics from torchoptics import Field, System from torchoptics.elements import PhaseModulator from torchoptics.profiles import gaussian, laguerre_gaussian torchoptics.set_default_spacing(10e-6) torchoptics.set_default_wavelength(700e-9) shape = 250 waist_radius = 300e-6 # Input: Gaussian beam input_field = Field(gaussian(shape, waist_radius=waist_radius), z=0) input_field.visualize(title="Input: Gaussian") ``` -------------------------------- ### Create a Field with Default Configuration Source: https://torchoptics.readthedocs.io/en/stable/user-guide/fields.html Construct a Field from a profile, using default spacing and wavelength if not specified. The print statement shows the resulting Field object's properties. ```python import torch import torchoptics from torchoptics import Field from torchoptics.profiles import gaussian, circle torchoptics.set_default_spacing(10e-6) torchoptics.set_default_wavelength(700e-9) field = Field(circle(300, radius=1e-3)) field.visualize(title="Circular Aperture") print(field) ``` ```python Field(shape=(300, 300), z=0.00e+00, spacing=(1.00e-05, 1.00e-05), offset=(0.00e+00, 0.00e+00), wavelength=7.00e-07) ``` -------------------------------- ### Initialize interferometer components and input field Source: https://torchoptics.readthedocs.io/en/stable/_downloads/4f85eaf72985ad118485913f6a3c9328/mach_zehnder_interferometer.ipynb Creates two BeamSplitter elements for the interferometer and defines the input field as a Gaussian beam. Visualizes the input beam's intensity. ```python bs1 = BeamSplitter(shape, theta=torch.pi / 4, phi_0=0, phi_r=0, phi_t=0) bs2 = BeamSplitter(shape, theta=torch.pi / 4, phi_0=0, phi_r=0, phi_t=0) # Input: Gaussian beam input_field = Field(gaussian(shape, waist_radius)) visualize_tensor(input_field.intensity(), title="Input Gaussian Beam") ``` -------------------------------- ### Define Target Patterns and Visualize Source: https://torchoptics.readthedocs.io/en/stable/_downloads/c0654258368bca714c02af51f1bd0b47/training_multi_plane_focusing.ipynb Generates target Gaussian spot patterns at two different focal planes and visualizes them. ```python # Target: Gaussian spots at each focal plane target_waist = 30e-6 # Target spot size (m) target_1 = Field(gaussian(shape, waist_radius=target_waist), z=focal_plane_1).to(device) target_2 = Field(gaussian(shape, waist_radius=target_waist), z=focal_plane_2).to(device) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), constrained_layout=True) ax1.imshow(target_1.intensity().cpu(), cmap="inferno") ax1.set_title(f"Target at z = {focal_plane_1 * 1e3:.0f} mm") ax1.axis("off") ax2.imshow(target_2.intensity().cpu(), cmap="inferno") ax2.set_title(f"Target at z = {focal_plane_2 * 1e3:.0f} mm") ax2.axis("off") plt.suptitle("Target Intensity Patterns", fontsize=12) plt.show() ``` -------------------------------- ### Import Necessary Libraries Source: https://torchoptics.readthedocs.io/en/stable/_downloads/5d503a871a061d2c5bab6d90fe2b43ae/phase_only_modulators.ipynb Imports the required modules from torchoptics and torch for optical field manipulation and simulation. ```python import torch import torchoptics from torchoptics import Field, System, visualize_tensor from torchoptics.elements import AmplitudeModulator, Lens, PhaseModulator from torchoptics.profiles import circle, hermite_gaussian ``` -------------------------------- ### Import necessary libraries for TorchOptics Source: https://torchoptics.readthedocs.io/en/stable/_downloads/3dcbeb94f5127f913ee859586069e3c5/aperture_limited_psf.ipynb Imports the required libraries for setting up and running optical simulations with TorchOptics, including plotting utilities. ```python import matplotlib.pyplot as plt import torch import torchoptics from torchoptics import Field, System from torchoptics.elements import Modulator from torchoptics.profiles import circle, lens_phase ``` -------------------------------- ### Create and use a Detector Source: https://torchoptics.readthedocs.io/en/stable/user-guide/elements.html Instantiate a Detector to convert a field into an intensity measurement. Gradients can flow back through the detector. ```python from torchoptics.elements import Detector detector = Detector(shape, z=0.5) power_map = detector(field) # Tensor of shape (H, W) ``` -------------------------------- ### Import necessary libraries Source: https://torchoptics.readthedocs.io/en/stable/_downloads/a8691a27817e3d2b42391a0a9e44f889/spatial_coherence.ipynb Imports the required libraries for spatial coherence simulation, including torch, torchoptics, and the Gaussian-Schell model profile. ```python import torch import torchoptics from torchoptics import SpatialCoherence from torchoptics.profiles import gaussian_schell_model as gsm ``` -------------------------------- ### Set Simulation Parameters Source: https://torchoptics.readthedocs.io/en/stable/_downloads/a5e21e778007342c988dc75ccded572b/quantum_state_discrimination.ipynb Configures simulation parameters such as grid size, beam waist radius, grid spacing, and wavelength. These values are crucial for accurate optical field calculations. ```python shape = 300 # Grid size (number of points per dimension) waist_radius = 300e-6 # Beam waist radius (m) spacing = 10e-6 # Grid spacing (m) wavelength = 700e-9 # Wavelength (m) torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) ``` -------------------------------- ### Initialize Polychromatic Phase Modulator Source: https://torchoptics.readthedocs.io/en/stable/_downloads/19d7e956cba886cfe6ecf959fca0e850/chromatic_aberration.ipynb Initializes a PolychromaticPhaseModulator with specified thickness and refractive index. The system is then converted to the appropriate device (e.g., GPU). ```python lens = PolychromaticPhaseModulator(thickness, n=n_bk7) system = System(lens).to(device) ``` -------------------------------- ### Create a Checkerboard Pattern Profile Source: https://torchoptics.readthedocs.io/en/stable/user-guide/profiles.html Use `checkerboard()` to create a tiled checkerboard pattern. Specify the number of pixels, tile length, and number of tiles. ```python profile = checkerboard(300, tile_length=200e-6, num_tiles=10) visualize_tensor(profile, title="Checkerboard") ``` -------------------------------- ### Set Simulation Parameters Source: https://torchoptics.readthedocs.io/en/stable/_downloads/c0654258368bca714c02af51f1bd0b47/training_multi_plane_focusing.ipynb Configures simulation parameters including grid size, spacing, wavelength, beam waist, and target focal planes. It also sets up the computation device and default TorchOptics settings. ```python shape = 256 # Grid size (smaller for faster training) spacing = 10e-6 # Grid spacing (m) wavelength = 632.8e-9 # HeNe laser (m) waist_radius = 500e-6 # Input beam waist (m) # Target focal distances focal_plane_1 = 50e-3 # First focus (m) focal_plane_2 = 100e-3 # Second focus (m) # Select computation device device = "cuda" if torch.cuda.is_available() else "cpu" # Configure torchoptics defaults torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) print(f"Target focal planes: {focal_plane_1 * 1e3:.0f} mm and {focal_plane_2 * 1e3:.0f} mm") ``` -------------------------------- ### Demonstrate sequential polarizer effects Source: https://torchoptics.readthedocs.io/en/stable/examples/coherence_and_polarization/polarized_field.html Illustrates how sequential polarizers affect light polarization. It shows that an intermediate polarizer can enable transmission through a subsequent polarizer that would otherwise block the light. ```python polarizer_0 = LinearPolarizer(shape, theta=0) polarizer_45 = LinearPolarizer(shape, theta=torch.pi / 4) polarizer_90 = LinearPolarizer(shape, theta=torch.pi / 2) after_0 = polarizer_0(field) after_45 = polarizer_45(field) after_90 = polarizer_90(field) after_45_90 = polarizer_90(after_45) stage_labels = ["Input", "0°", "45°", "90°", "45° → 90°"] stage_powers = [ field.power().sum().item(), after_0.power().sum().item(), after_45.power().sum().item(), after_90.power().sum().item(), after_45_90.power().sum().item(), ] print("Sequential Polarizer Experiment") for label, power in zip(stage_labels, stage_powers): print(f" {label:<10}: {power:.3f}") ``` ```text Sequential Polarizer Experiment Input : 1.000 0° : 1.000 45° : 0.500 90° : 0.000 45° → 90° : 0.250 ``` -------------------------------- ### Define simulation parameters and BK7 dispersion model Source: https://torchoptics.readthedocs.io/en/stable/_downloads/19d7e956cba886cfe6ecf959fca0e850/chromatic_aberration.ipynb Sets up simulation parameters like grid shape, spacing, beam waist, and BK7 glass Cauchy coefficients. Defines a function for the refractive index of BK7 based on wavelength and specifies the Fraunhofer spectral lines to be simulated. ```python shape = 512 spacing = 10e-6 # 10 µm grid spacing — large enough that the 1 mm beam # decays to < 0.2 % amplitude at the boundary waist_radius = 1e-3 # 1 mm Gaussian beam waist # BK7 glass Cauchy coefficients A_cauchy = 1.5044 B_cauchy = 4.24e-15 # m² def n_bk7(wavelength): """Two-term Cauchy dispersion model for BK7 glass.""" return A_cauchy + B_cauchy / wavelength**2 # Fraunhofer spectral lines wavelengths = [486.1e-9, 589.3e-9, 656.3e-9] # F, d, C lines (m) colors = ["royalblue", "goldenrod", "firebrick"] labels = ["F-line 486 nm", "d-line 589 nm", "C-line 656 nm"] # Lens geometry: plano-convex, designed for f_d = 150 mm at the d-line n_d = n_bk7(589.3e-9) focal_d = 150e-3 # design focal length at d-line (m) R = focal_d * (n_d - 1) # radius of curvature (m) # Abbe number and theoretical focal lengths n_F, n_C = n_bk7(486.1e-9), n_bk7(656.3e-9) V_abbe = (n_d - 1) / (n_F - n_C) focal_theory = [R / (n_bk7(wl) - 1) for wl in wavelengths] lca_theory = focal_theory[2] - focal_theory[0] torchoptics.set_default_spacing(spacing) device = "cuda" if torch.cuda.is_available() else "cpu" print(f"BK7 refractive indices: nF = {n_F:.4f}, nd = {n_d:.4f}, nC = {n_C:.4f}") print(f"Abbe number: Vd = {V_abbe:.1f}") print(f"Radius of curvature: R = {R * 1e3:.2f} mm") print(f"Theoretical LCA: Δf = f_d / Vd = {lca_theory * 1e3:.2f} mm") ``` -------------------------------- ### Registering Optics Properties with OpticsModule Source: https://torchoptics.readthedocs.io/en/stable/autoapi/torchoptics/index.html Demonstrates how to subclass OpticsModule and register trainable and non-trainable properties using register_optics_property. This is useful for creating custom optical components that manage their own parameters. ```python from torchoptics import OpticsModule from torch.nn import Parameter class MyOpticsModule(OpticsModule): def __init__(self, trainable_property, non_trainable_property): super().__init__() self.register_optics_property("trainable_property", Parameter(trainable_property), shape=()) self.register_optics_property("non_trainable_property", non_trainable_property, shape=()) ``` -------------------------------- ### Set default simulation parameters Source: https://torchoptics.readthedocs.io/en/stable/_downloads/3dcbeb94f5127f913ee859586069e3c5/aperture_limited_psf.ipynb Configures the default spacing and wavelength for the TorchOptics simulation. This sets up the environment for subsequent optical element and field definitions. ```python torchoptics.set_default_spacing(10e-6) torchoptics.set_default_wavelength(700e-9) shape = 500 wavelength = 700e-9 # m spacing = 10e-6 # m focal_length = 0.5 # m d_o = 1.0 # Object distance (m) d_i = 1.0 # Image distance (m), satisfies 1/f = 1/d_o + 1/d_i lens_z = d_o image_z = d_o + d_i device = "cuda" if torch.cuda.is_available() else "cpu" print(f"Focal length: {focal_length} m") print(f"Object distance: {d_o} m, Image distance: {d_i} m") print(f"Wavelength: {wavelength * 1e9:.0f} nm") ``` -------------------------------- ### Create Random Phase Screen and Input Field Source: https://torchoptics.readthedocs.io/en/stable/_downloads/b7e205eaab4bdb61763a0c7f7b81755a/laser_speckle_patterns.ipynb Generates a random phase screen with uniformly distributed phases to simulate surface roughness. It then creates a Gaussian beam amplitude and combines it with the phase to form the input Field object, visualizing the initial field. ```python # Create random phase screen (fully developed speckle) random_phase = 2 * torch.pi * torch.rand(shape, shape) # Illumination: Gaussian beam amplitude = gaussian(shape, waist_radius=beam_radius) # Create Field object input_field = Field(amplitude * torch.exp(1j * random_phase)).to(device) input_field.visualize(title="Input Field") ``` -------------------------------- ### Import necessary libraries Source: https://torchoptics.readthedocs.io/en/stable/examples/optical_phenomena/animate_propagation.html Imports the required libraries for the simulation, including torch and torchoptics modules. ```python import torch import torchoptics from torchoptics import Field, animate_tensor from torchoptics.profiles import octagon ``` -------------------------------- ### Define Simulation Parameters Source: https://torchoptics.readthedocs.io/en/stable/_downloads/9e7c9ae99ba5cb1b1663c1e074cbf4ad/youngs_double_slit.ipynb Sets up the physical and computational parameters for the simulation, including grid dimensions, spacing, wavelength, slit dimensions, and separation. It also configures torchoptics defaults and selects the computation device (CUDA or CPU). ```python shape = 500 # Grid size (number of points per dimension) spacing = 5e-6 # Grid spacing (m) wavelength = 500e-9 # Wavelength (m), green light slit_width = 40e-6 # Width of each slit (m) slit_height = 1.5e-3 # Height of each slit (m) slit_separation = 250e-6 # Center-to-center separation (m) # Configure torchoptics defaults torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) # Select computation device device = "cuda" if torch.cuda.is_available() else "cpu" ``` -------------------------------- ### Import necessary libraries Source: https://torchoptics.readthedocs.io/en/stable/_downloads/a262ed80a7d535a8333c44b2b97bce2b/lens_focusing.ipynb Imports required modules from matplotlib, torch, and torchoptics for optical simulations and visualizations. ```python import matplotlib.pyplot as plt import torch import torchoptics from torchoptics import Field, System, visualize_tensor from torchoptics.elements import Lens from torchoptics.profiles import gaussian ``` -------------------------------- ### Import necessary libraries for simulation Source: https://torchoptics.readthedocs.io/en/stable/_downloads/4f85eaf72985ad118485913f6a3c9328/mach_zehnder_interferometer.ipynb Imports required modules from matplotlib, torch, and torchoptics for setting up and visualizing the simulation. ```python import matplotlib.pyplot as plt import torch import torchoptics from torchoptics import Field, visualize_tensor from torchoptics.elements import BeamSplitter from torchoptics.profiles import gaussian ``` -------------------------------- ### Set Simulation Parameters Source: https://torchoptics.readthedocs.io/en/stable/_downloads/5d503a871a061d2c5bab6d90fe2b43ae/phase_only_modulators.ipynb Configures the simulation parameters including grid size, spacing, wavelength, focal length, and computation device. It also sets default values for spacing and wavelength in torchoptics. ```python shape = 1000 # Grid size (number of points per dimension) spacing = 10e-6 # Grid spacing (m) wavelength = 700e-9 # Wavelength (m) focal_length = 200e-3 # Lens focal length (m) waist_radius = 0.3e-3 # Select computation device device = "cuda" if torch.cuda.is_available() else "cpu" # Configure torchoptics defaults torchoptics.set_default_spacing(spacing) torchoptics.set_default_wavelength(wavelength) ```