import numpy as np import matplotlib.pyplot as plt import copy from scipy.special import hermite from scipy.special import genlaguerre import os from scipy.io import savemat class BeamQ: """ Class for Gaussian beam q-parameter and derived beam properties. Attributes ---------- q : complex Complex beam parameter (real: relative z from waist, imag: Rayleigh range). wavelength : float Wavelength in meters (must be positive). """ def __init__(self, q: complex, wavelength: float = 1064e-9): self._lambda = None self._q = None # Use setters for validation self.wavelength = wavelength self.q = q @property def wavelength(self) -> float: """Wavelength (m).""" return self._lambda @wavelength.setter def wavelength(self, value: float): if value <= 0: raise ValueError("Wavelength must be positive") self._lambda = float(value) @property def q(self) -> complex: """Complex q-parameter.""" return self._q @q.setter def q(self, value: complex): if np.imag(value) < 0: raise ValueError("Imaginary part of q parameter must be positive") self._q = complex(value) # --- Alternative constructors --- @classmethod def from_waist_and_z(cls, w0: float, z: float, wavelength: float = 1064e-9): """ Create BeamQ with waist w0 at relative position z (m). """ zr = np.pi * w0**2 / wavelength q = z + 1j * zr return cls(q, wavelength) @classmethod def from_waist_and_r(cls, w0: float, R: float, wavelength: float = 1064e-9): """ Create BeamQ with waist w0 (m) and curvature R (m) at z=0. """ zr = np.pi * w0**2 / wavelength q = 1.0 / (1.0 / R - 1j / zr) return cls(q, wavelength) @classmethod def from_width_and_r(cls, w: float, R: float, wavelength: float = 1064e-9): """ Create BeamQ with beam radius w (m) and curvature R (m) at z=0. """ # Solve for measurement plane Z and Rayleigh range Z = R / (1.0 + (R * wavelength / (np.pi * w**2))**2) ZR = np.sqrt(Z * (R - Z)) q = Z + 1j * ZR return cls(q, wavelength) # --- Core transformations --- @staticmethod def transform_value(q_val: complex, M) -> complex: """ Transform q via ABCD matrix M (2x2 array-like). """ M = np.asarray(M, dtype=complex) return (M[0, 0] * q_val + M[0, 1]) / (M[1, 0] * q_val + M[1, 1]) def transform(self, M) -> 'BeamQ': """ Return a new BeamQ after ABCD matrix M transformation. """ q_new = self.transform_value(self.q, M) beam_new = copy.copy(self) beam_new.q = q_new return beam_new def duplicate(self) -> 'BeamQ': """Return a copy of this BeamQ object.""" return copy.copy(self) # --- Dependent properties --- @property def waist_size(self) -> float: """Beam waist radius w0 (m).""" return np.sqrt(np.imag(self.q) * self.wavelength / np.pi) @property def rayleigh_range(self) -> float: """Rayleigh range zR (m).""" w0 = self.waist_size return np.pi * w0**2 / self.wavelength @property def divergence_angle(self) -> float: """Half-angle divergence theta (rad).""" w0 = self.waist_size zR = self.rayleigh_range return w0 / zR @property def waist_z(self) -> float: """Relative axial distance from waist (m).""" return float(np.real(self.q)) @property def beam_width(self) -> float: """Beam radius w(z) at measurement plane (m).""" z = self.waist_z zR = self.rayleigh_range w0 = self.waist_size return w0 * np.sqrt(1.0 + (z / zR)**2) @property def radius_of_curvature(self) -> float: """Wavefront radius of curvature R(z) (m).""" z = self.waist_z zR = self.rayleigh_range if z != 0: return z * (1.0 + (zR / z)**2) return np.inf # --- Beam overlap --- def overlap(self, other: 'BeamQ') -> float: """ Compute power overlap between two coaxial Gaussian beams. """ if self.wavelength != other.wavelength: raise ValueError("Cannot overlap beams of different wavelengths") w1 = self.waist_size w2 = other.waist_size q1 = self.q q2 = other.q lam = self.wavelength return (2 * np.pi / lam * w1 * w2 / abs(np.conj(q2) - q1))**2 # --- Plotting --- @staticmethod def plot_beam_width(beams, z_domain, **kwargs): """ Plot beam radius vs. z for an array of BeamQ objects. """ widths = [b.beam_width for b in beams] plt.plot(z_domain, widths, **kwargs) plt.plot(z_domain, [-w for w in widths], **kwargs) plt.xlabel('z (m)') plt.ylabel('Beam radius (m)') plt.grid(True) plt.show() def cart2pol(x, y): """Convert Cartesian coordinates to polar coordinates.""" r = np.sqrt(x**2 + y**2) th = np.arctan2(y, x) return th, r def pol2cart(th, r): """Convert polar coordinates to Cartesian coordinates.""" x = r * np.cos(th) y = r * np.sin(th) return x, y class HGMode: """ Hermite-Gaussian mode representation and utilities. """ def __init__(self, m: int, n: int, mfd: float, X: np.ndarray, Y: np.ndarray): """ Initialize a single Hermite-Gaussian mode. Parameters ---------- m, n : int Mode indices (order) along x and y. mfd : float Mode field diameter (m). X, Y : ndarray 2D meshgrid arrays (m). """ self.m = m self.n = n self.mfd = mfd self.X = X self.Y = Y # Precompute normalized coordinates W = mfd / 2.0 u_x = np.sqrt(2) * X / W u_y = np.sqrt(2) * Y / W # Compute mode field Hx = HGMode.hermite_poly(m, u_x) * np.exp(-u_x**2 / 2) Hy = HGMode.hermite_poly(n, u_y) * np.exp(-u_y**2 / 2) field = Hx * Hy # Normalize to unit total intensity norm = np.sqrt(np.sum(np.abs(field)**2)) self.field = field / norm if norm > 0 else field @staticmethod def hermite_poly(order: int, x: np.ndarray) -> np.ndarray: """Compute physicists' Hermite polynomial H_order(x).""" return hermite(order)(x) class LGMode: """ Laguerre-Gaussian mode representation and utilities. """ def __init__(self, p: int, l: int, mfd: float, X: np.ndarray, Y: np.ndarray): """ Initialize a single Laguerre-Gaussian mode LG_p^l. Parameters ---------- p : int Radial index (>=0). l : int Azimuthal index (can be positive, negative or zero). mfd : float Mode field diameter (m). X, Y : ndarray 2D meshgrid arrays (m). """ self.p = p self.l = l self.mfd = mfd self.X = X self.Y = Y # Beam waist radius W = mfd / 2.0 # Polar coordinates r = np.sqrt(X**2 + Y**2) phi = np.arctan2(Y, X) # Normalized radial coordinate rho = np.sqrt(2) * r / W # Generalized Laguerre polynomial L_p^{|l|}(rho^2) poly = genlaguerre(p, abs(l))(rho**2) # Radial envelope radial = rho**abs(l) * poly * np.exp(-rho**2 / 2) # Azimuthal phase factor phase = np.exp(1j * l * phi) self.phase = phase field = radial * phase # Normalize to unit total intensity norm = np.sqrt(np.sum(np.abs(field)**2)) self.field = field / norm if norm > 0 else field @staticmethod def generate_basis(p_max: int, l_max: int, X: np.ndarray, Y: np.ndarray, mfd: float): """ Generate all LG modes for 0<=p<=p_max and -l_max<=l<=l_max. Returns ------- modes : ndarray Array of shape (N, Nx, Ny) of complex fields, where N = (p_max+1)*(2*l_max+1). P, L : ndarray Arrays of mode indices of shape (N,) for p and l. total_intensity : ndarray Sum of intensities of all generated modes. """ Nx, Ny = X.shape p_list = range(p_max + 1) l_list = range(-l_max, l_max + 1) N = (p_max + 1) * (2 * l_max + 1) modes = np.zeros((N, Nx, Ny), dtype=np.complex64) P = np.zeros(N, dtype=int) L = np.zeros(N, dtype=int) total_intensity = np.zeros((Nx, Ny), dtype=np.float32) idx = 0 for p in p_list: for l in l_list: mode = LGMode(p, l, mfd, X, Y).field modes[idx] = mode P[idx] = p L[idx] = l total_intensity += np.abs(mode)**2 idx += 1 return modes, P, L, total_intensity def propagate(f, H0): # Convert real-space field to k-space field F = np.fft.fftshift(np.fft.fft2(np.fft.fftshift(f))) # Apply the transfer function of free-space F = F * H0 # Convert k-space field back to real-space f = np.fft.fftshift(np.fft.ifft2(np.fft.fftshift(F))) return f def cart2pol(x, y): """Convert Cartesian coordinates to polar coordinates.""" r = np.sqrt(x**2 + y**2) th = np.arctan2(y, x) return th, r def pol2cart(th, r): """Convert polar coordinates to Cartesian coordinates.""" x = r * np.cos(th) y = r * np.sin(th) return x, y def fibreArrayXYZ(dx, dy, z, X, Y, MFD, wavelength): """ Calculate the fields for all the spots in a fibre array. dx, dy: arrays of x and y positions for each spot (length = modeCount) z: z offset (can be scalar or array matching X/Y) X, Y: meshgrid arrays MFD: mode field diameter wavelength: wavelength of light Returns: SPOTS (modeCount, Nx, Ny), TOTAL (Nx, Ny) """ w0 = MFD / 2.0 Nx, Ny = X.shape modeCount = len(np.atleast_1d(dx)) SPOTS = np.zeros((modeCount, Nx, Ny), dtype=np.complex64) TOTAL = np.zeros((Nx, Ny), dtype=np.float32) for modeIdx in range(modeCount): x_shift = X - dx[modeIdx] y_shift = Y - dy[modeIdx] zr = np.pi * w0 ** 2 / wavelength k = 2 * np.pi / wavelength Wz = w0 * np.sqrt(1 + (z / zr) ** 2) phi = np.arctan(z / zr) Rz = z * (1 + (zr / z) ** 2) with np.errstate(divide='ignore', invalid='ignore'): Rz_ = np.where(Rz != 0, 1.0 / Rz, 0.0) R2 = x_shift ** 2 + y_shift ** 2 Rzterm = R2 * Rz_ / 2.0 spot = (w0 / Wz) * np.exp(-R2 / Wz ** 2) * np.exp(-1j * (k * z + k * Rzterm - phi)) norm = np.sqrt(np.sum(np.abs(spot) ** 2)) if norm > 0: spot = spot / norm TOTAL += np.abs(spot) ** 2 SPOTS[modeIdx, :, :] = spot return SPOTS, TOTAL def transferFunctionOfFreeSpace(x, y, dz, wavelength): """ Calculate the transfer function of free space for propagation distance dz. x, y: meshgrid arrays (2D) dz: propagation distance wavelength: wavelength of light Returns: H0 (2D array) """ Nx = x.shape[1] Ny = x.shape[0] # Setup your k-space coordinate system fs_x = Nx / (np.max(x) - np.min(x)) v_x = fs_x * (np.arange(-Nx/2, Nx/2) / Nx) fs_y = Ny / (np.max(y) - np.min(y)) v_y = fs_y * (np.arange(-Ny/2, Ny/2) / Ny) V_x, V_y = np.meshgrid(v_x, v_y) # Exponent for the transfer function of free-space tfCoef1 = -1j * 2 * np.pi * np.sqrt(wavelength**-2 - V_x**2 - V_y**2) # Transfer function of free-space for propagation distance dz H0 = np.exp(tfCoef1 * dz) return H0 def updateMask(FIELDS, MASKS, modeCount, planeIdx, symmetricMasks): """ Update the mask based on the fields in each plane. """ MASK = np.exp(1j*np.angle(np.squeeze(MASKS[planeIdx]))) MSK = np.zeros_like(MASK, dtype=np.complex64) for modeIdx in range(modeCount): fwd = np.squeeze(FIELDS[0, planeIdx, modeIdx]) bwd = np.conj(np.squeeze(FIELDS[1, planeIdx, modeIdx])) pF = np.sum(np.abs(fwd)**2) pB = np.sum(np.abs(bwd)**2) dM = (fwd*bwd)/np.sqrt(pF*pB) dphi = np.sum(dM*np.conj(MASK)) MSK = MSK + dM * np.exp(-1j*np.angle(dphi)) overlap = np.sum(np.abs(dM)**2) if symmetricMasks: MSK = (MSK + np.flipud(MSK))/2 MASKS[planeIdx] = MSK return MASKS def graphfields(fields: np.ndarray, masks: np.ndarray, plane_count: int, mode_count: int = 1, fig_number: int = 2): """ Plot summed mode intensities (forward/backward) and mask angles. Parameters ---------- fields : ndarray Complex array of shape (2, plane_count, mode_count, Ny, Nx), where fields[0,:,:,:,:] is the “forward” field and fields[1,:,:,:,:] is the “backward” field. masks : ndarray Complex mask array of shape (plane_count, Ny, Nx). plane_count : int Number of planes to plot. mode_count : int, optional Number of modes to sum over (default is 1). fig_number : int, optional Matplotlib figure number to use (default is 2). """ # Create (or activate) the figure plt.figure(fig_number, figsize=(plane_count * 2, 6)) plt.clf() # Loop over each plane for p in range(plane_count): # Sum |E|^2 over modes for forward fields total_forward = np.zeros_like(fields[0, p, 0]) for m in range(mode_count): total_forward += np.abs(fields[0, p, m])**2 # Sum |E|^2 over modes for backward fields total_backward = np.zeros_like(fields[1, p, 0]) for m in range(mode_count): total_backward += np.abs(fields[1, p, m])**2 # 1) Forward intensity ax1 = plt.subplot(3, plane_count, p + 1) im1 = ax1.imshow(np.abs(total_forward), origin='lower', aspect='equal') ax1.axis('off') ax1.set_title(f'Plane {p+1} Fwd') # 2) Backward intensity ax2 = plt.subplot(3, plane_count, plane_count + p + 1) im2 = ax2.imshow(np.abs(total_backward), origin='lower', aspect='equal') ax2.axis('off') ax2.set_title(f'Plane {p+1} Bwd') # 3) Mask angle ax3 = plt.subplot(3, plane_count, 2*plane_count + p + 1) angle_mask = np.angle(masks[p]) im3 = ax3.imshow(angle_mask, origin='lower', aspect='equal') ax3.axis('off') ax3.set_title(f'Plane {p+1} Mask') im3.set_clim(-np.pi, np.pi) plt.colorbar(im3, ax=ax3, fraction=0.046, pad=0.04) plt.tight_layout() def overlap(field1: np.ndarray, field2: np.ndarray) -> float: """ Compute |∬ conj(field1)*field2 dx dy|^2, without any internal normalization. """ return np.abs(np.sum(np.conj(field1) * field2))**2 def normalize(field: np.ndarray) -> np.ndarray: """ Scale field so that ∬ |field|^2 dx dy = 1 (on the discrete grid). """ norm = np.sqrt(np.sum(np.abs(field)**2)) return field / norm if norm > 0 else field def evaluate_masks_eta(H0: np.ndarray, GAUSS: np.ndarray, MASKS: np.ndarray, TARGET: np.ndarray): """ Parameters ---------- H0 : 2D transfer function (k-space) for one plane spacing GAUSS : input field on plane 1 MASKS : array of shape (2, Ny, Nx) of complex masks TARGET : target field on plane 2 Returns ------- FORWARD_OUT : field after two‐plane forward propagation BACKWARD_OUT : field after two‐plane backward propagation eta : overlap(FORWARD_OUT, TARGET) """ plane_count = MASKS.shape[0] # ——— forward chain ——— forward = GAUSS.copy() # plane 1 → plane 2 # apply mask on plane 1, propagate to plane 2 m0 = np.exp(-1j * np.angle(MASKS[0])) forward = forward * m0 forward = propagate(forward, H0) # now apply mask on plane 2 (no further propagation) m1 = np.exp(-1j * np.angle(MASKS[1])) forward = forward * m1 # ——— backward chain ——— # start from TARGET on plane 2 backward = TARGET.copy() # apply mask on plane 2, propagate *back* to plane 1 mb1 = np.exp(1j * np.angle(MASKS[1])) backward = backward * mb1 backward = propagate(backward, np.conj(H0)) # apply mask on plane 1 (no further backward propagation) mb0 = np.exp(1j * np.angle(MASKS[0])) backward = backward * mb0 # ——— compute overlap ——— forward = normalize(forward) eta = overlap(forward, normalize(TARGET.copy())) return forward, backward, eta def save_slm_masks(run_name: str, masks: np.ndarray, *, wavelength: float = None, pixel_size: float = None, plane_spacing: float = None, output_dir: str = ".", w0: float = None, LG_mfd: float = None): """ Save one or more phase‐only masks for your SLM. Parameters ---------- run_name : str Base name for all saved files (no extension). masks : ndarray Complex array of shape (P, Ny, Nx), where P=number of planes. wavelength : float, optional Laser wavelength [m] (will be recorded in .mat). pixel_size : float, optional SLM pixel pitch [m] (will be recorded in .mat). plane_spacing : float, optional Distance between masks [m] (will be recorded in .mat). output_dir : str, optional Directory to write files into (will be created if missing). Output ------ {output_dir}/{run_name}.mat Contains variables: - MASKS : your complex mask array - wavelength, pixel_size, plane_spacing (if provided) {output_dir}/{run_name}.npy NumPy dump of the same array. {output_dir}/{run_name}_plane{n+1}.png HSV-phase image for each mask plane. """ # ensure output directory exists os.makedirs(output_dir, exist_ok=True) # 1) save .mat mat_dict = {"MASKS": masks} if wavelength is not None: mat_dict["wavelength"] = wavelength if pixel_size is not None: mat_dict["pixel_size"] = pixel_size if plane_spacing is not None: mat_dict["plane_spacing"] = plane_spacing if w0 is not None: mat_dict["w0"] = w0 if LG_mfd is not None: mat_dict["LG_mfd"] = LG_mfd mat_path = os.path.join(output_dir, f"{run_name}.mat") savemat(mat_path, mat_dict) print(f"Saved MATLAB file → {mat_path}") # 2) save .npy npy_path = os.path.join(output_dir, f"{run_name}.npy") np.save(npy_path, masks) print(f"Saved NumPy file → {npy_path}") # 3) save phase images for i, mask in enumerate(masks): # extract phase in [−π,π] phase = np.angle(mask) png_path = os.path.join(output_dir, f"{run_name}_plane{i+1}.png") plt.imsave(png_path, phase, cmap="hsv", vmin=-np.pi, vmax=np.pi) print(f"Saved phase image → {png_path}") def pad_field(field, Nx_p, Ny_p): """Center field of shape (Ny,Nx) in a zero array of shape (Ny_p,Nx_p).""" Ny, Nx = field.shape pad_x = (Nx_p - Nx)//2 pad_y = (Ny_p - Ny)//2 Fp = np.zeros((Ny_p, Nx_p), dtype=field.dtype) Fp[pad_y:pad_y+Ny, pad_x:pad_x+Nx] = field return Fp, pad_x, pad_y def crop_field(Fp, pad_x, pad_y, Nx, Ny): """Extract the central (Ny,Nx) from the padded array.""" return Fp[pad_y:pad_y+Ny, pad_x:pad_x+Nx]