### Install LightPipes with pyFFTW support Source: https://opticspy.github.io/lightpipes/_sources/install.rst.txt Install LightPipes with pyFFTW support for potentially faster FFT calculations. This is the recommended way to install if pyFFTW is available and desired. ```bash sudo pip(3) install LightPipes[pyfftw] ``` -------------------------------- ### Compile and Install FFTW Source: https://opticspy.github.io/lightpipes/_sources/install.rst.txt Commands to configure, compile, and install the FFTW library from source. This is necessary for pyFFTW installation on systems like Raspberry Pi. ```bash cd fftw-3.3.9 ./configure --enable-threads --enable-shared make sudo make install ``` -------------------------------- ### Install LightPipes Source: https://opticspy.github.io/lightpipes/_sources/install.rst.txt Perform a normal installation of LightPipes. If pyFFTW is not installed, LightPipes will fall back to using numpy FFT. ```bash sudo pip(3) install LightPipes ``` -------------------------------- ### Install matplotlib Source: https://opticspy.github.io/lightpipes/manual.html Install the matplotlib package for plotting. This is a prerequisite for visualizing simulation results. ```bash >>> pip install matplotlib ``` -------------------------------- ### Install python3-gi-cairo Source: https://opticspy.github.io/lightpipes/_sources/install.rst.txt Install the python3-gi-cairo package, which may be a prerequisite for certain LightPipes functionalities. ```bash sudo apt install python3-gi-cairo ``` -------------------------------- ### Michelson Interferometer Setup and Simulation Source: https://opticspy.github.io/lightpipes/_sources/MichelsonInterferometer.rst.txt This code sets up and simulates a basic Michelson interferometer. It defines parameters like wavelength, beam size, grid resolution, arm lengths, and distances, then propagates a Gaussian beam through the setup to observe the intensity pattern on a screen. Use this for a fundamental understanding of the interferometer simulation. ```python #! /usr/bin/env python from LightPipes import * import matplotlib.pyplot as plt wavelength=632.8*nm #wavelength of HeNe laser size=15*mm # size of the grid N=500 # number (NxN) of grid pixels R=9*mm # laser beam radius z1=8*cm # length of arm 1 z2=7*cm # length of arm 2 z3=3*cm # distance laser to beamsplitter z4=5*cm # distance beamsplitter to screen Rbs=0.5 # reflection beam splitter tx=0.0*mrad; ty=0.0*mrad # tilt of mirror 1 #Generate a laser beam: F=Begin(size,wavelength,N) F=GaussBeam(F, R) #Propagate to the beamsplitter: F=Forvard(z3,F) #Split the beam and propagate to mirror #2: F2=IntAttenuator(1-Rbs,F) F2=Forvard(z2,F2) #Propagate back to the beamsplitter: F2=Tilt(tx,ty,F2) F2=Forvard(z2,F2) F2=IntAttenuator(Rbs,F2) #Split off the second beam and propagate to- and back from the mirror #1: F10=IntAttenuator(Rbs,F) F1=Forvard(z1*2,F10) F1=IntAttenuator(1-Rbs,F1) #Recombine the two beams and propagate to the screen: F=BeamMix(F1,F2) F=Forvard(z4,F) I=Intensity(1,F) s1 = r'LightPipes for Python ' + LPversion + '\n\n'+ r'Michelson interferometer'+ '\n' s2 = r'Michelson.py'+ '\n\n'+ f'size = {size/mm:4.2f} mm' + '\n'+ f'$\lambda$ = {wavelength/um:4.2f} $\mu$m' + '\n'+ f'N = {N:d}' + '\n'+ f'R = {R/mm:4.2f} mm beam radius of the laser' + '\n'+ f'z1 = {z1/mm:4.2f} mm length of arm 1' + '\n'+ f'z2 = {z2/mm:4.2f} mm length of arm 2' + '\n'+ f'z3 = {z3/mm:4.2f} mm distance from the laser to the beam splitter' + '\n'+ f'z4 = {z4/mm:4.2f} mm distance from the beam splitter to the screen' + '\n'+ f'tx, ty = {tx/mrad:4.2f}, {ty/mrad:4.2f} mrad tilt of mirror 2' + '\n' r'${\copyright}$ Fred van Goor, June 2020' fig=plt.figure(figsize=(6,9)); ax1 = fig.add_subplot(311);ax1.axis('off') ax2 = fig.add_subplot(312);ax2.axis('off') ax3 = fig.add_subplot(313);ax3.axis('off') ax1.imshow(I,cmap='jet');ax1.set_title('intensity pattern') ax2.text(0.0,0.6,s1,fontsize=12, fontweight='bold') ax3.text(0.0,0.50,s2) plt.show() ``` -------------------------------- ### Install pyFFTW package Source: https://opticspy.github.io/lightpipes/_sources/install.rst.txt Install the pyFFTW package separately. This can be done before or after installing LightPipes. ```bash sudo pip(3) install pyFFTW ``` -------------------------------- ### Install LightPipes for Python Source: https://opticspy.github.io/lightpipes/_sources/introduction.rst.txt Install the latest version of LightPipes for Python using pip. This command is used to get started with the library. ```bash pip install LightPipes ``` -------------------------------- ### Simulate Multi-Hole Diffraction Source: https://opticspy.github.io/lightpipes/_sources/MultiHoleAndSlit.rst.txt This example simulates the diffraction pattern produced by light passing through multiple circular holes. Ensure the lightpipes library is installed. ```python import numpy as np import lightpipes as lp from lightpipes. অপটিক্স import * # Import all optics functions # Define simulation parameters n = 512 # Number of grid points size = 10e-3 # Physical size of the grid (meters) wavelength = 632.8e-9 # Wavelength of light (meters) # Create a Wavefront object wave = lp.Wavefront(n, size, wavelength) # Define the multi-hole aperture # Example: 3 holes in a line # hole_radius = 0.5e-3 # hole_spacing = 2e-3 # wave.aperture = lp.MultiHole(wave, hole_radius, hole_spacing, n_holes=3, orientation='horizontal') # Example: 5 holes in a cross pattern wave.aperture = lp.MultiHole(wave, radius=0.3e-3, spacing=1.5e-3, n_holes=5, orientation='cross') # Propagate the wavefront to a distance # For example, to the far field (using Fraunhofer approximation) distance = 1.0 # meters propagated_wave = wave.propagate(distance) # Visualize the intensity pattern propagated_wave.intensity().plot(title='Multi-Hole Diffraction Pattern') # You can also access the intensity data as a numpy array: # intensity_data = propagated_wave.intensity().data ``` -------------------------------- ### Comparing Propagation Methods Source: https://opticspy.github.io/lightpipes/_sources/manual.rst.txt This example demonstrates the difference in results between using a small aperture (waveguide-like) and a larger grid for far-field propagation. ```python from LightPipes import * size = 100e-3 wavelength = 632.8e-9 # Initialize the field field = Begin(size, wavelength, 1000) # Propagate 1m forward field = Forvard(field, 1.0) # Filter with an aperture equal to grid size field = RectAperture(field, size, size) # Propagate 1m forward again field = Forvard(field, 1.0) # Initialize the field with a larger grid field2 = Begin(size*4, wavelength, 1000) # Propagate 1m forward field2 = Forvard(field2, 1.0) # Filter with an aperture smaller than the grid field2 = RectAperture(field2, 10e-3, 10e-3) # Propagate 1m forward again field2 = Forvard(field2, 1.0) ``` -------------------------------- ### Install LightPipes Python Package Source: https://opticspy.github.io/lightpipes/_sources/install.rst.txt Use this command to install the LightPipes package from PyPi. If you have both Python 2.7 and 3.+ installed, use pip3 instead of pip. ```bash pip(3) install LightPipes ``` -------------------------------- ### CylindricalLens Example Source: https://opticspy.github.io/lightpipes/command-reference.html Demonstrates the application of CylindricalLens with different parameters for focal length, shift, and angle. ```python >>> F=Begin(size,wavelength,N) >>> F=CylindricalLens(F,f) #Cylindrical lens in the center >>> F=CylindricalLens(F,f, x_shift=2*mm) #idem, shifted 2 mm in x direction >>> F=CylindricalLens(F,f, x_shift=2*mm, angle=30.0*deg) #idem, rotated 30 degrees ``` -------------------------------- ### Initialize LightPipes Field Source: https://opticspy.github.io/lightpipes/manual.html Starts LightPipes calculations by defining grid size, dimension, and wavelength. Requires importing the LightPipes package and optionally units. ```python from LightPipes import * GridSize = 30*mm GridDimension = 5 lambda_ = 500*nm #lambda_ is used because lambda is a Python build-in function. Field = Begin(GridSize, lambda_, GridDimension) print(Field.field) ``` -------------------------------- ### Install LightPipes for Python 3 Source: https://opticspy.github.io/lightpipes/install.html Installs LightPipes for Python 3, typically used on systems like Raspberry Pi. ```bash sudo pip3 install lightpipes ``` -------------------------------- ### Install Cython and ATLAS Source: https://opticspy.github.io/lightpipes/_sources/install.rst.txt Install necessary build tools like Cython and the ATLAS library, which are often required for compiling Python packages with C extensions. ```bash sudo pip3 install cython sudo apt-get install libatlas-base-dev ``` -------------------------------- ### Test LightPipes Installation Source: https://opticspy.github.io/lightpipes/_sources/install.rst.txt After installation, run these Python commands to test if LightPipes is working correctly. A successful test will output 'LightPipes for Python: test passed.' ```python >>> from LightPipes import * >>> LPtest() LightPipes for Python: test passed. >>> ``` -------------------------------- ### Install LightPipes for Python 3 Source: https://opticspy.github.io/lightpipes/_sources/install.rst.txt Final installation command for LightPipes using pip, typically for Python 3. This command should be run after all dependencies are met. ```bash sudo pip(3) install lightpipes ``` -------------------------------- ### Get Help for a Specific Command in LightPipes Source: https://opticspy.github.io/lightpipes/_sources/support.rst.txt Use the `help()` function at the Python prompt to get detailed information about specific LightPipes commands. This is useful for understanding command arguments and return values. ```python from LightPipes import * help(Begin) ``` -------------------------------- ### Far-field Propagation with Rectangular Aperture Source: https://opticspy.github.io/lightpipes/manual.html Demonstrates far-field propagation of a rectangular aperture using LightPipes. This example sets up a larger propagation distance and a different initial field size compared to near-field examples. Requires LightPipes and Matplotlib. ```python from LightPipes import * import matplotlib.pyplot as plt Field=Begin(400*mm, 1*um, 512) Field = RectAperture(20*mm,20*mm,0, 0,0, Field) Field = Forvard(500*m, Field) I = Intensity(0,Field) x=[] for i in range(512): x.append((-20*mm/2+i*20*mm/512)/mm) fig=plt.figure(figsize=(10,6)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) ax1.imshow(I,cmap='rainbow'); ax1.axis('off') ax2.plot(x,I[256]);ax2.set_xlabel('x [mm]');ax2.set_ylabel('Intensity [a.u.]') ax2.grid('on') plt.show() ``` -------------------------------- ### Simulate Interference from Multiple Holes Source: https://opticspy.github.io/lightpipes/_sources/MultiHoleAndSlit.rst.txt Demonstrates creating a row of holes and analyzing the interference pattern. This example is useful for understanding diffraction from multiple apertures. ```python #! python3 import numpy as np import matplotlib.pyplot as plt from LightPipes import * """ MultiHole.py Demonstrates the MultiHole command. Two wavelengths are used to show the principles of a grating. cc Fred van Goor, June 2020. """ wavelength=1000*nm size=30*mm N=800 N2=int(N/2) HoleSeparation=2*mm z=300*cm Nholes=6 size_hole=1*mm HoleDiameter=0.5*mm Ndiameter=int(HoleDiameter/size*N) Nhole=int(size_hole/size*N) Fhole=Begin(size_hole,wavelength,Nhole) Fhole=CircAperture(Fhole,HoleDiameter/2) F=Begin(size,wavelength,N) F=RowOfFields(F,Fhole,Nholes,HoleSeparation) Iholes=Intensity(F) X=np.arange(N) X=(X/N-1/2)*size/mm F=Lens(F,z) F=Fresnel(F,z) Iscreen=Intensity(F) s= r'LightPipes for Python,' + '\n' + r'MultiHole.py'+ '\n\n' r'size = {:4.2f} mm'.format(size/mm) + '\n' + r'$\\lambda$ = {:4.2f} nm'.format(wavelength/nm) + '\n' + r'N = {:d}'.format(N) + '\n' + r'diameter holes: {:4.2f} mm'.format(HoleDiameter/mm) + '\n' + r'separation of the holes: {:4.2f} mm'.format(HoleSeparation/mm) + '\n' + r'number of holes: {:d}'.format(Nholes) + '\n' + r'focal length lens: {:4.2f} cm'.format(z/cm) + '\n\n' + r'${\\copyright}$ Fred van Goor, May 2020' fig=plt.figure(figsize=(10,6)) ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222);# ax2.set_ylim(bottom=130,top=170) ax3 = fig.add_subplot(223) ax4 = fig.add_subplot(224) ax1.imshow(Iholes,cmap='gray',aspect='equal');ax1.axis('off'); ax1.set_title('Screen with holes') ax2.imshow(Iscreen,cmap='jet',aspect='equal');ax2.axis('off'); ax2.set_title('Intensity distribution at the focus of the lens') ax3.plot(X,Iscreen[N2]); ax3.set_xlabel('x [mm]'); ax3.set_ylabel('Intensity [a.u.]'); ax3.set_title('Cross section of intensity at the focus') ax4.text(0,0,s); ax4.axis('off') plt.show() ``` -------------------------------- ### Begin Source: https://opticspy.github.io/lightpipes/command-reference.html Initializes a new optical field with specified grid size, wavelength, and dimension. Allows for memory optimization by setting the data type. ```APIDOC ## Begin(_size_ , _labda_ , _N_ , _dtype =None_) ### Description Initiates a field with a grid size, a wavelength and a grid dimension. By setting dtype to numpy.complex64 memory can be saved. If dtype is not set (default = None), complex (equivalent to numpy.complex128) will be used for the field array. ### Parameters * **size** (_int_, _float_) – size of the square grid * **labda** (_int_, _float_) – the wavelength of the output field * **N** (_int_) – the grid dimension * **dtype** (_complex_, _numpy.complex64_, _numpy.complex128_ (default = None) – type of the field array ### Returns output field (N x N square array of complex numbers). ### Return type LightPipes.field.Field ### Example ```python >>> from LightPipes import * >>> size = 20*mm >>> wavelength = 500*nm >>> N = 5 >>> F = Begin(size, wavelength, N) ``` ``` -------------------------------- ### Simulate Multi-Slit Diffraction Source: https://opticspy.github.io/lightpipes/_sources/MultiHoleAndSlit.rst.txt This example simulates the diffraction pattern produced by light passing through multiple parallel slits. Ensure the lightpipes library is installed. ```python import numpy as np import lightpipes as lp from lightpipes. অপটিক্স import * # Import all optics functions # Define simulation parameters n = 512 # Number of grid points size = 10e-3 # Physical size of the grid (meters) wavelength = 632.8e-9 # Wavelength of light (meters) # Create a Wavefront object wave = lp.Wavefront(n, size, wavelength) # Define the multi-slit aperture # Example: 3 slits # slit_width = 0.2e-3 # slit_spacing = 1.0e-3 # wave.aperture = lp.MultiSlit(wave, slit_width, slit_spacing, n_slits=3, orientation='horizontal') # Example: 5 slits wave.aperture = lp.MultiSlit(wave, width=0.1e-3, spacing=0.5e-3, n_slits=5, orientation='vertical') # Propagate the wavefront to a distance distance = 1.0 # meters propagated_wave = wave.propagate(distance) # Visualize the intensity pattern propagated_wave.intensity().plot(title='Multi-Slit Diffraction Pattern') # You can also access the intensity data as a numpy array: # intensity_data = propagated_wave.intensity().data ``` -------------------------------- ### Arbitrary Intensity and Phase Distribution (Python) Source: https://opticspy.github.io/lightpipes/_sources/manual.rst.txt This example demonstrates how to create and apply arbitrary intensity and phase distributions to a light beam. It's useful for simulating complex optical elements or wavefront shaping. ```python import numpy as np import matplotlib.pyplot as plt from LightPipes import * # Parameters wavelength = 633*nm size = 10*mm N = 256 # Grid size # Initialize Field F = Begin(size, wavelength, N) # Create an arbitrary phase distribution (e.g., a simple phase ramp) # phase_map = np.zeros((N, N)) # for i in range(N): # for j in range(N): # phase_map[i, j] = (i / N) * 2 * np.pi # Example phase ramp # Create an arbitrary intensity distribution (e.g., a Gaussian beam) # intensity_map = np.zeros((N, N)) # center_x, center_y = N // 2, N // 2 # sigma = N / 8 # for i in range(N): # for j in range(N): # intensity_map[i, j] = np.exp(-((i - center_x)**2 + (j - center_y)**2) / (2 * sigma**2)) # Apply custom phase and intensity filters # F = Phase(phase_map, F) # Apply custom phase # F = Intensity(intensity_map, F) # Apply custom intensity # For demonstration, let's create a simple phase and intensity filter # Example: A circular aperture for intensity and a quadratic phase for focus radius = size / 4 phase_center_x, phase_center_y = 0, 0 phase_coeff = 1e-3 # Controls the curvature of the phase intensity_map = np.zeros((N, N)) phase_map = np.zeros((N, N)) for i in range(N): for j in range(N): x = (i - N/2) * size / N y = (j - N/2) * size / N # Circular aperture for intensity if x**2 + y**2 < radius**2: intensity_map[i, j] = 1.0 else: intensity_map[i, j] = 0.0 # Quadratic phase for focusing phase_map[i, j] = phase_coeff * (x**2 + y**2) F = Intensity(intensity_map, F) F = Phase(phase_map, F) # Calculate and plot the resulting intensity and phase I = Intensity(0, F) Phi = Phase(0, F) plt.figure(figsize=(12, 5)) plt.subplot(1, 2, 1) plt.imshow(I, cmap='jet') plt.title('Intensity Distribution') plt.xlabel('x index') plt.ylabel('y index') plt.colorbar() plt.subplot(1, 2, 2) plt.imshow(Phi, cmap='hsv') plt.title('Phase Distribution') plt.xlabel('x index') plt.ylabel('y index') plt.colorbar() plt.tight_layout() plt.show() ``` -------------------------------- ### Far-Field Propagation with Forvard Source: https://opticspy.github.io/lightpipes/_sources/manual.rst.txt For far-field propagation, the grid size must be significantly larger than the beam to avoid interference from wave guide walls. This example uses a larger grid. ```python from LightPipes import * size = 100e-3 wavelength = 632.8e-9 # Initialize the field with a larger grid field = Begin(size*4, wavelength, 1000) # Propagate 1m forward field = Forvard(field, 1.0) # Filter with an aperture smaller than the grid field = RectAperture(field, 10e-3, 10e-3) # Propagate 1m forward again field = Forvard(field, 1.0) ``` -------------------------------- ### Focusing a Lens with Steps Command Source: https://opticspy.github.io/lightpipes/manual.html Demonstrates calculating the intensity distribution in the focus of a lens using the `Steps` command for propagation. This example models diffraction, absorption, and refraction effects. ```python from LightPipes import* import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt wavelength=632.8*nm; size=4*mm; N=100; N2=50; R=1.5*mm; dz=10*mm; f=50*cm; n=(1.0 + 0.1j)*np.ones((N,N)) Icross=np.zeros((100,N)) X=range(N) Z=range(100) X, Z=np.meshgrid(X,Z) F=Begin(size,wavelength,N); F=CircAperture(R,0,0,F); F=Lens(f,0,0,F); for i in range(0,100): F=Steps(dz,1,n,F); I=Intensity(0,F); Icross[i][:N]=I[N2][:N] ax = plt.axes(projection='3d') ax.plot_surface(X, Z, Icross, rstride=1, cstride=1, cmap='rainbow', linewidth=0.0, ) plt.axis('off') plt.show() ``` -------------------------------- ### Initialize Field with Begin Command Source: https://opticspy.github.io/lightpipes/_sources/manual.rst.txt Initializes the optical field. Requires importing LightPipes and defining grid parameters. The Begin command creates a uniform field with intensity 1 and phase 0. ```bash >>> from LightPipes import * >>> GridSize = 30*mm >>> GridDimension = 5 >>> lambda_ = 500*nm #lambda_ is used because lambda is a Python build-in function. >>> Field = Begin(GridSize, lambda_, GridDimension) >>> print(Field.field) [[1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j] [1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j] [1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j] [1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j] [1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j]] ``` -------------------------------- ### Import Bitmap as Filter (Python) Source: https://opticspy.github.io/lightpipes/_sources/manual.rst.txt This example shows how to import a bitmap image (like an arrow created in Paint) and use it as a filter to shape the light beam's intensity and phase. ```python import numpy as np import matplotlib.pyplot as plt from PIL import Image from LightPipes import * # Parameters wavelength = 633*nm size = 10*mm N = 200 # Grid size should match the bitmap dimensions if possible # Initialize Field F = Begin(size, wavelength, N) # Load the bitmap image (ensure 'arrow.png' is in the same directory or provide the full path) # The image should be a monochrome bitmap (black and white) try: img = Image.open('arrow.png').convert('L') # Convert to grayscale # Resize image if necessary to match N, or adjust N to match image size if img.size != (N, N): img = img.resize((N, N)) bitmap_data = np.array(img) # Normalize the bitmap data to be between 0 and 1 # Assuming black is 0 and white is 255 bitmap_filter = 1.0 - (bitmap_data / 255.0) # Invert: white areas let light through (1), black areas block (0) # Apply the bitmap as an intensity filter F = Intensity(bitmap_filter, F) # Calculate and plot the resulting intensity I = Intensity(0, F) plt.figure(figsize=(8, 6)) plt.imshow(I, cmap='jet') plt.title('Intensity after applying Bitmap Filter (Arrow)') plt.xlabel('x index') plt.ylabel('y index') plt.colorbar() plt.show() except FileNotFoundError: print("Error: 'arrow.png' not found. Please ensure the bitmap file is in the correct directory.") except Exception as e: print(f"An error occurred: {e}") ``` -------------------------------- ### Install numpy Source: https://opticspy.github.io/lightpipes/manual.html Install the numpy package for numerical operations, which is used for array manipulation in plotting. ```bash >>> pip install numpy ``` -------------------------------- ### Find Python installation directory (Windows) Source: https://opticspy.github.io/lightpipes/_sources/install.rst.txt Command to locate the Python installation directory on Windows systems. ```bash where python ``` -------------------------------- ### Install Matplotlib for Plotting Source: https://opticspy.github.io/lightpipes/_sources/install.rst.txt Matplotlib is a required plotting library for most LightPipes applications. Install it using pip. ```bash pip(3) install matplotlib ``` -------------------------------- ### LPhelp Source: https://opticspy.github.io/lightpipes/command-reference.html Navigates to the LightPipes documentation website. ```APIDOC ## LPhelp() ### Description Goes to the LightPipes documentation website. ### Endpoint https://opticspy.github.io/lightpipes/ ``` -------------------------------- ### Find Python installation directory (Linux/Mac) Source: https://opticspy.github.io/lightpipes/_sources/install.rst.txt Command to locate the Python installation directory on Linux or Mac systems. ```bash which python ``` -------------------------------- ### Spatial Filtering with PipFFT (Python) Source: https://opticspy.github.io/lightpipes/_sources/manual.rst.txt This example demonstrates spatial filtering using the PipFFT command, which performs a Fourier transform on the light field. It allows for filtering in the frequency domain before transforming back. ```python import numpy as np import matplotlib.pyplot as plt from LightPipes import * # Parameters wavelength = 633*nm size = 10*mm N = 256 # Initialize Field with a Gaussian beam F = Begin(size, wavelength, N) F = GaussianBeam(F) # Calculate initial intensity I_initial = Intensity(0, F) # Apply a spatial filter in the Fourier domain (e.g., a circular aperture) # First, perform FFT F_fft = PipFFT(F) # Define filter parameters in the frequency domain # The frequency domain grid size corresponds to 2*pi*lambda/delta_x # One step in frequency domain corresponds to 2*pi*lambda/grid_size # Let's apply a circular aperture in the frequency domain freq_domain_size = size # The size parameter of PipFFT is the physical size of the grid freq_aperture_radius = 1 / (5 * mm) # Example: filter out high frequencies # Create a circular mask in the frequency domain freq_x = np.fft.fftfreq(N, d=freq_domain_size/N) freq_y = np.fft.fftfreq(N, d=freq_domain_size/N) X_freq, Y_freq = np.meshgrid(freq_x, freq_y) freq_mask = np.zeros((N, N)) for i in range(N): for j in range(N): if X_freq[i, j]**2 + Y_freq[i, j]**2 < freq_aperture_radius**2: freq_mask[i, j] = 1.0 else: freq_mask[i, j] = 0.0 # Apply the frequency mask F_fft_filtered = F_fft * freq_mask # Perform inverse FFT to get the filtered field F_filtered = PipFFT(F_fft_filtered) # PipFFT performs both forward and inverse FFT # Calculate final intensity I_filtered = Intensity(0, F_filtered) # Plotting plt.figure(figsize=(12, 5)) plt.subplot(1, 2, 1) plt.imshow(I_initial, cmap='jet') plt.title('Initial Intensity') plt.xlabel('x index') plt.ylabel('y index') plt.colorbar() plt.subplot(1, 2, 2) plt.imshow(I_filtered, cmap='jet') plt.title('Filtered Intensity (Spatial Filter)') plt.xlabel('x index') plt.ylabel('y index') plt.colorbar() plt.tight_layout() plt.show() ``` -------------------------------- ### Install Numpy Source: https://opticspy.github.io/lightpipes/_sources/manual.rst.txt Installs the numpy package, which is used for numerical operations and array manipulation in LightPipes, particularly for plotting results. ```bash >>> pip install numpy ``` -------------------------------- ### LPdemo Source: https://opticspy.github.io/lightpipes/command-reference.html Demonstrates the simulation of a two-holes interferometer. Returns a plot of the interference pattern and a listing of the Python script. ```APIDOC ## LPdemo() ### Description Demonstrates the simulation of a two-holes interferometer. ### Returns A plot of the interference pattern and a listing of the Python script. ### Return type matplotlib.image.AxesImage ``` -------------------------------- ### Install LightPipes C++ version Source: https://opticspy.github.io/lightpipes/_sources/install.rst.txt Install the C++ version 1.2.0 of LightPipes, suitable for environments like Raspberry Pi with Python 3.7. ```bash sudo pip(3) install LightPipes==1.2.0 ``` -------------------------------- ### LightPipes Begin Command Signature Source: https://opticspy.github.io/lightpipes/_sources/support.rst.txt This is the signature for the `Begin` command, which creates a plane wave. It requires GridSize, Wavelength, and N (grid points). ```bash Help on built-in function Begin: Begin(...) method of LightPipes._LightPipes.Init instance F = Begin(GridSize, Wavelength, N) :ref:`Creates a plane wave (phase = 0.0, amplitude = 1.0). ` Args:: GridSize: size of the grid Wavelength: wavelength of the field N: N x N grid points (N must be even) Returns:: F: N x N square array of complex numbers (1+0j). Example: :ref:`Diffraction from a circular aperture ` >>> ``` -------------------------------- ### Find Python installation directory Source: https://opticspy.github.io/lightpipes/install.html Commands to locate the Python installation directory on different operating systems, necessary for finding and editing configuration files. ```bash where python ``` ```bash which python ``` -------------------------------- ### Simulate Poisson's Spot with LightPipes Source: https://opticspy.github.io/lightpipes/PoissonSpot.html This script simulates Poisson's spot by creating a uniform plane wave, introducing a circular opaque disk as an obstacle, and performing Fresnel propagation. It then calculates and visualizes the intensity pattern, showing the characteristic bright central spot and diffraction rings. Requires numpy, LightPipes, and matplotlib. ```python import numpy as np from LightPipes import * import matplotlib.pyplot as plt # Parameters wavelength=5*um size=25.0*mm N=2000 N2=int(N/2) z=20*cm # Begin with a plane wave F = Begin(size, wavelength, N) # Gaussian laser beam w0=size/3 F=GaussBeam(F, w0) # Circular opaque disk (obstacle) disk_diameter = 6.0 * mm F = CircScreen(F,disk_diameter/2) # Fresnel propagation F = Fresnel(F, z) # Intensity at the screen I = Intensity(0, F) # Coordinates for plotting x = np.linspace(-size/2, size/2, N) / mm s1 = r'LightPipes for Python' + '\n' s2 = r'Poisson.py'+ '\n\n'\ f'size = {size/mm:4.2f} mm' + '\n' f'$\lambda$ = {wavelength/um:4.2f} $\mu$m' + '\n' f'N = {N:d}' + '\n' + f'd = {disk_diameter/mm:4.2f} mm disk diameter' + '\n' f'w0 = {w0/mm:4.2f} mm radius Gauss beam' + '\n' f'z = {z/cm:4.2f} cm distance from disk' + '\n' r'${\copyright}$ Fred van Goor, February 2026' fig=plt.figure(figsize=(11,6)) fig.suptitle("The spot of Poisson") ax1 = fig.add_subplot(221);ax1.axis('off') ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223);ax3.axis('off') ax1.set_xlim(N2-300,N2+300) ax1.set_ylim(N2-300,N2+300) ax1.imshow(I,cmap='jet') ax1.set_title(f'Intensity pattern after {z/cm:4.1f} cm propagation') X=np.linspace(-size/2,size/2,N) ax2.plot(X/mm,I[N2]); ax2.set_xlabel('x[mm]'); ax2.set_ylabel('Intensity [a.u.]') ax2.set_xlim(-1,1); ax2.set_title('The intensity cross-section of the spot') ax3.text(0.0,1.0,s1,fontsize=12, fontweight='bold') ax3.text(0.0,0.3,s2) plt.show() ``` -------------------------------- ### Simulate Lens and Fresnel Propagation with Spherical Coordinates Source: https://opticspy.github.io/lightpipes/manual.html This example demonstrates simulating optical propagation through a lens and using Fresnel diffraction, comparing results obtained with and without spherical coordinates. It visualizes phase and intensity distributions. Requires LightPipes and Matplotlib. ```python from LightPipes import * import matplotlib.pyplot as plt def TheExample(N): fig=plt.figure(figsize=(15,9.5)) ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) ax4 = fig.add_subplot(224) labda=1000*nm; size=10*mm; f=10*cm f1=10*m f2=f1*f/(f1-f) frac=f/f1 newsize=frac*size w=5*mm; F=Begin(size,labda,N); F=RectAperture(w,w,0,0,0,F); #1) Using Lens and Fresnel: F1=Lens(f,0,0,F) F1=Fresnel(f,F1) phi1=Phase(F1);phi1=PhaseUnwrap(phi1) I1=Intensity(0,F1); x1=[] for i in range(N): x1.append((-size/2+i*size/N)/mm) #2) Using Lens + LensFresnel and Convert: F2=Lens(f1,0,0,F); F2=LensFresnel(f2,f,F2); F2=Convert(F2); phi2=Phase(F2);phi2=PhaseUnwrap(phi2) I2=Intensity(0,F2); x2=[] for i in range(N): x2.append((-newsize/2+i*newsize/N)/mm) ax1.plot(x1,phi1[int(N/2)],'k--',label='Without spherical coordinates') ax1.plot(x2,phi2[int(N/2)],'k',label='With spherical coordinates'); ax1.set_xlim(-newsize/2/mm,newsize/2/mm) ax1.set_ylim(-2,4) ax1.set_xlabel('x [mm]'); ax1.set_ylabel('phase [rad]'); ax1.set_title('phase, N = %d' %N) legend = ax1.legend(loc='upper center', shadow=True) ax2.plot(x1,I1[int(N/2)],'k--',label='Without spherical coordinates') ax2.plot(x2,I2[int(N/2)], 'k',label='With spherical coordinates'); ax2.set_xlim(-newsize/2/mm,newsize/2/mm) ax2.set_ylim(0,100000) ax2.set_xlabel('x [mm]'); ax2.set_ylabel('Intensity [a.u.]'); ax2.set_title('intensity, N = %d' %N) legend = ax2.legend(loc='upper center', shadow=True) ax3.imshow(I1);ax3.axis('off');ax3.set_title('Without spherical coordinates') ax3.set_xlim(int(N/2)-N*frac/2,int(N/2)+N*frac/2) ax3.set_ylim(int(N/2)-N*frac/2,int(N/2)+N*frac/2) ax4.imshow(I2);ax4.axis('off');ax4.set_title('With spherical coordinates') plt.figtext(0.3,0.95,'Spherical Coordinates, f = 10cm lens\nGrid dimension is: %d x %d pixels' %(N, N), fontsize = 18, color='red') TheExample(100) #100 x 100 grid TheExample(1000) #1000 x 1000 grid plt.show() ``` -------------------------------- ### Locate LightPipes Site-Packages Directory Source: https://opticspy.github.io/lightpipes/_sources/UserDefinedFunctions.rst.txt Provides Python code to find the 'site-packages' directory where LightPipes is installed. This is necessary for adding custom functions directly to the installation. ```python import site print(site.getsitepackages()) ``` -------------------------------- ### Plot Bessel Annular Slit Example Source: https://opticspy.github.io/lightpipes/_sources/PoissonSpottoBesselBeam.rst.txt Generates a plot illustrating the Bessel beam created by an annular slit. This example is useful for visualizing non-diffractive beam properties. ```python import numpy as np import matplotlib.pyplot as plt from lightpipes.beam import CircularAperture, Beam from lightpipes.propagation import FresnelPropagation # Parameters wavelength = 633e-9 # meters radius = 1e-3 # meters N = 1024 # grid size length = 0.1 # meters # Create a beam wavelength = 633e-9 # meters radius = 1e-3 # meters N = 1024 # grid size length = 0.1 # meters # Create a beam field = Beam(radius=radius, wavelength=wavelength, N=N) # Create an annular aperture # Inner radius is 0.5 * outer radius annular_aperture = CircularAperture(field, radius=radius, inner_radius=radius/2) # Propagate the beam propagator = FresnelPropagation(length=length, field=field) field = propagator.propagate(annular_aperture) # Plot the intensity plt.figure(figsize=(8, 6)) plt.imshow(np.abs(field.field)**2, extent=[field.x.min(), field.x.max(), field.y.min(), field.y.max()]) plt.title('Bessel Beam Intensity') plt.xlabel('x (m)') plt.ylabel('y (m)') plt.colorbar(label='Intensity') plt.show() ```