Implementation of the Angular Spectrum method in Python to simulate Diffraction Patterns

Overview

Diffraction Simulations - Angular Spectrum Method

Implementation of the Angular Spectrum method in Python to simulate Diffraction Patterns with arbitrary apertures. You can use it for simulating both monochromatic and polychromatic light also with arbitrary spectrums.

How the method and the simulator work is described in this Article. Take a look to the Youtube video to see the animated simulations!

animation

Installation

  1. Clone repository
  2. Install requirements via pip install -r requirements.txt

Examples

To perform the simulations, just run from the folder proyect in the command prompt the corresponding Python scripts:

python hexagon_monochromatic.py

N|Solid

python hexagon_polychromatic.py

N|Solid

python rectangular_grating_small.py

N|Solid

python rectangular_grating.py

N|Solid

python circular_rings.py

N|Solid

python text.py

N|Solid

Comments
  • Possibility of Phase-Object Diffraction Simulation

    Possibility of Phase-Object Diffraction Simulation

    Hi! Thanks for your really amazing work! I am a newbie in optics and I am wondering whether it's possible to produce diffraction like image And here is the light field with the description from the paper

    A laser beam emitted from a He–Ne laser at a wavelength of 632.8 nm (NEC Electronics Inc. GLG5002) was first spatially filtered by a pinhole with an aperture of 10 µm and then collimated by a lens with a focal length of f= 200mm. The plane wave was guided to illuminate a phase object, producing intensity images as shown in Fig. 5b. To acquire the diffraction pattern, we placed the camera (SensiCam EM, pixel pitch: 8 µm) at a distance d= 22.3mm from the phase object.

    image

    Appreciate it a lot if you could help me about this:) Wish you a good day!

    opened by FishWoWater 8
  • Is it possible to modulate the initial MonochromaticField?

    Is it possible to modulate the initial MonochromaticField?

    Thank you for creating such a useful tool. In my recent research, I need a plane wave only whose intensity is modulated, but I can't achieve this effect with MonochromaticField and Could you tell me how to implement this function?

    opened by Windaway 5
  • plot_intensity() and plot_colors() show different results

    plot_intensity() and plot_colors() show different results

    Hi,

    firstly I would like to thank you for this nice package. However, I am experiencing some trouble with the visualisation functions. Below, you can find the example "circular_aperture_lens.py" with two added lines of code. It seems to me that the functions plot_intensity() and plot_colors() show different results, which is somehow confusing. Is this a bug or did I use the functions not as intended?

    import diffractsim
    diffractsim.set_backend("CPU") #Change the string to "CUDA" to use GPU acceleration
    
    from diffractsim import MonochromaticField, nm, mm, cm, CircularAperture, Lens
    
    F = MonochromaticField(
        wavelength = 543 * nm, extent_x=13. * mm, extent_y=13. * mm, Nx=2000, Ny=2000, intensity =0.01
    )
    
    F.add(CircularAperture(radius = 0.7*mm))
    F.propagate(100*cm)
    F.add(Lens(f = 100*cm)) # Just remove this command to see the pattern without lens
    F.propagate(100*cm)
    
    rgb = F.get_colors()
    F.plot_colors(rgb, xlim=[-3*mm,3*mm], ylim=[-3*mm,3*mm])
    F.plot_intensity(F.get_intensity(), xlim=[-3*mm,3*mm], ylim=[-3*mm,3*mm])
    
    opened by CakeUser321 3
  • NX and NY definition?

    NX and NY definition?

    Hi! Could you explain me what are NX and NY in MonochromaticField and PolychromaticField? What are they correlation with extent_x and extent_y visually? I would like to simulate diffraction pattern of a grating 20 cm in front of a telescope (F=11 m, D=60 cm) at its focal plane. Do you have some suggestions? Thank you in advance.

    opened by irfanimaduddin 3
  • How should handle the circular convolution and the linear convolution in the angular spectrum method?

    How should handle the circular convolution and the linear convolution in the angular spectrum method?

    Hi, there. Firstly, thank you for your great job for the fresh men like me! It's really helpful! So here is the thing, I read the angular spectrum method part to implement the wave propagation, and I noticed you just used two fft2s and ifft. So this is a circular convolution, right? I am wondering what should we choose between circular convolution and linear convolution? Thanks in advance!

    opened by nophy 2
  • Running rectangular slit with CPU

    Running rectangular slit with CPU

    Running rectangular slit with CPU gives me the following error- AttributeError: 'RectangularSlit' object has no attribute 'xx'

    rectangular_slit.zip

    [I have attached the code I'm running] complete traceback-

    Traceback (most recent call last):

    File "", line 1, in runfile('C:/Users/acer/Desktop/python-sonu/programms/rectangular_slit.py', wdir='C:/Users/acer/Desktop/python-sonu/programms')

    File "C:\Users\acer\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace)

    File "C:\Users\acer\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace)

    File "C:/Users/acer/Desktop/python-sonu/programms/rectangular_slit.py", line 15, in F.add(RectangularSlit(width= 1mm, height=5cm,x0=0,y0=0))

    File "C:\Users\acer\Anaconda3\lib\site-packages\diffractsim\monochromatic_simulator.py", line 51, in add self.E = optical_element.get_E(self.E, self.xx, self.yy, self.λ)

    File "C:\Users\acer\Anaconda3\lib\site-packages\diffractsim\diffractive_elements\diffractive_element.py", line 18, in get_E return E*self.get_transmittance(xx, yy, λ)

    File "C:\Users\acer\Anaconda3\lib\site-packages\diffractsim\diffractive_elements\rectangular_slit.py", line 25, in get_transmittance bd.ones_like(self.xx), bd.zeros_like(self.xx))

    AttributeError: 'RectangularSlit' object has no attribute 'xx rectangular_slit.zip '

    opened by Abhisek1300 2
  • How to simulate Fourier Transform at the Focal Plane (when input_distance = f)

    How to simulate Fourier Transform at the Focal Plane (when input_distance = f)

    Hi, Thank you for your fantastic work.

    I have implemented the lens system as given in this script. I also followed your article as well.

    When I set up input_distance = output_distance = focal_length= 25cm, Ideally I should get the Fourier Transform at the output. But the implementation does not give that. Could you please guide me on how I can get that?

    Input field (intensity) image

    What I got from the simulation (I checked for multiple scale factors in scale_propagation function (in this script). Below are images for scale_factor= 30) image

    What should I get (Fourier Transform) image image

    opened by udithhaputhanthri 1
  • Two visualization questions

    Two visualization questions

    I have two questions about visualization which are:

    1. I would like to get full longitudinal profile plot for a big lens (in 60 cm wide) but the plot_longitudinal_profile_colors function trimmed it on y axis. How could I deal with this kind of issue?
    2. Is there any code available to create an animation of intensity plots?

    Thanks, Irfan

    opened by irfanimaduddin 1
  • Rectangular Slit with CUDA

    Rectangular Slit with CUDA

    Running a rectungular slit with CUDA backend gives me the following error:

    Traceback (most recent call last): File "C:/Users/ethan/Documents/PycharmProjects/diffraction/examples/circular_aperture_lens.py", line 27, in F.add_rectangular_slit(x0=0, y0=0, width=1.5 * mm, height=1.5 * mm) File "C:\Users\ethan\Documents\PycharmProjects\diffraction\venv\lib\site-packages\diffractsim\monochromatic_simulator.py", line 68, in add_rectangular_slit [bd.ones(self.E.shape), bd.zeros(self.E.shape)], File "C:\Users\ethan\Documents\PycharmProjects\diffraction\venv\lib\site-packages\cupy_indexing\indexing.py", line 199, in select if cond.dtype.type is not cupy.bool_: AttributeError: 'bool' object has no attribute 'dtype'

    Can be fixed by modifying assignment if the 't' variable in the 'add_rectangular_slit' function.

    t = bd.select(
                [
                    ((self.xx > (x0 - width / 2)) & (self.xx < (x0 + width / 2)))
                    & ((self.yy > (y0 - height / 2)) & (self.yy < (y0 + height / 2))),
                    bd.full(self.E.shape, True, dtype=bool)
                ],
                [bd.ones(self.E.shape), bd.zeros(self.E.shape)],
            )
    
    opened by ethan-becker-fathom 1
  • Corrected errors in input+output plane coordinate systems and added lens example

    Corrected errors in input+output plane coordinate systems and added lens example

    There is a mistake in the coordinate system definitions of the current version which means that for example a lens does not focus exactly on the optical axis. If you try and run the supplied example in an old version of the code you would get:

    old_image old_PSF

    And with the new version you would instead get the following on-axis responses:

    new_image new_PSF

    P.S. I have also updated the calculation of kz in order to include non-propagating modes. If not, the supplied example will fail

    P.P.S. Changes only made to the monochromatic simulator

    opened by villadsegede 1
  • Refactor user and developer experience

    Refactor user and developer experience

    Hello @rafael-fuente, I really enjoyed your simulations! I am creating a pull request with features that will allow for easier user and developer experience when working with your project.

    opened by irahorecka 1
  • Code documentation

    Code documentation

    The description of the functions are clear but I had a hard time understanding how they worked. If you want, I can help you create even better documentation in code.

    opened by GuilhermeMonteiroPeixoto 0
  • Lens aberration function

    Lens aberration function

    I noticed that the lens aberration attribute was not being referenced correctly (missing self.). I also added the missing wavelength dependence and a simple example showing how it can be used.

    opened by danielbrown2 0
  • ApertureFromImage() seems to always assume the image is in linear sRGB

    ApertureFromImage() seems to always assume the image is in linear sRGB

    Hi,

    I think this tool you made is awesome, and I really enjoy playing with it. My only "complaint" is that when using a grayscale image as an aperture, the result at a dstance of 0 look different from the original image. I'm guessing that it's because F.get_colors() correctly converts the output image to sRGB, but when loading the aperture image with ApertureFromImage(), the image isn't correctly converted to linear.

    Editing the grayscale conversion in aperture_from_image.py this way seems to fix it: t = 0.2990 * np.power(imgRGB[:, :, 0],2.2) + 0.5870 * np.power(imgRGB[:, :, 1],2.2) + 0.1140 * np.power(imgRGB[:, :, 2],2.2)

    opened by stduhpf 0
  • Request for CPU multi core processing support

    Request for CPU multi core processing support

    First, like your work, and I would like to make it better.

    I would be nice to have support for multi-core processing. I know that numpy runs fast on the cpu but cannot use more then one core. Also not all computers can use well the gpu and installing and using cupy is not straight foreword and easy as numpy.

    On the side, there are module that able to use multi core for mathematical operation like numba. In addition, its installation is simple and it is easy to use.

    I would like to help with that and it seems that the change for the code would not be so big. Thanks

    opened by eitan-davis 0
Releases(v2.2.3)
  • v2.2.3(Feb 18, 2022)

    Diffractsim is a flexible and easy-to-use Python diffraction simulator that focuses on visualizing physical optics phenomena.

    The simulator provides scalar diffraction techniques for full-optical path propagation, an interface for simulation setup, and several plotting options, counting with CIE Color matching functions for accurate color reproduction.

    It supports lenses, phase hologram generation, and GPU acceleration.

    Source code(tar.gz)
    Source code(zip)
    diffractsim-2.2.3.zip(1.90 MB)
Owner
Rafael de la Fuente
Rafael de la Fuente
Exploiting Linksys WRT54G using a vulnerability I found.

Exploiting Linksys WRT54G Exploit # Install the requirements. pip install -r requirements.txt ROUTER_HOST=192.169.1.1 ROUTER_USERNAME=admin ROUTER_P

Elon Gliksberg 31 May 29, 2022
To effectively detect the faulty wafers

wafer_fault_detection Aim of the project: In electronics, a wafer (also called a slice or substrate) is a thin slice of semiconductor, such as crystal

Arun Singh Babal 1 Nov 06, 2021
Official repository for the BPF Performance Tools book

BPF Performance Tools This is the official repository of BPF (eBPF) tools from the book BPF Performance Tools: Linux and Application Observability. Th

Brendan Gregg 1.2k Dec 28, 2022
VacationCycleLogicBackEnd - Vacation Cycle Logic BackEnd With Python

Vacation Cycle Logic BackEnd Getting Started Existing virtualenv If your project

Mohamed Gamal 0 Jan 03, 2022
dotfiles - Cristian Valero Abundio

In this repository you can find various configurations to configure your Linux operating system, preferably ArchLinux and its derivatives.

Cristian Valero Abundio 1 Jan 09, 2022
Script to work around some quirks of the blender obj importer

ObjFix 1.0 (WIP) Script to work around some quirks of the blender obj importer Installation Download this repo In Blender, press "Edit" on the top-bar

Red_3D 4 Nov 20, 2021
A command-line utility that creates projects from cookiecutters (project templates), e.g. Python package projects, VueJS projects.

Cookiecutter A command-line utility that creates projects from cookiecutters (project templates), e.g. creating a Python package project from a Python

18.6k Jan 02, 2023
Dump Data from FTDI Serial Port to Binary File on MacOS

Dump Data from FTDI Serial Port to Binary File on MacOS

pandy song 1 Nov 24, 2021
Better firefox bookmarks script for rofi

rofi-bookmarks Small python script to open firefox bookmarks with rofi. Features Icons! Only show bookmarks in a specified bookmark folder Show entire

32 Nov 10, 2022
A simple interface to help lazy people like me to shutdown/reboot/sleep their computer remotely.

🦥 Lazy Helper ! A simple interface to help lazy people like me to shut down/reboot/sleep/lock/etc. their computer remotely. - USAGE If you're a lazy

MeHDI Rh 117 Nov 30, 2022
An integrated library for checking email if it is registered on social media

An integrated library for checking email if it is registered on social media

Sidra ELEzz 13 Dec 08, 2022
Plock : A stack based programming language

Plock : A stack based programming language

1 Oct 25, 2021
Python MapReduce library written in Cython.

Python MapReduce library written in Cython. Visit us in #hadoopy on freenode. See the link below for documentation and tutorials.

Brandyn White 243 Sep 16, 2022
Adversarial Robustness with Non-uniform Perturbations

Adversarial Robustness with Non-uniform Perturbations This repository hosts the code to replicate experiments of the paper Adversarial Robustness with

5 May 20, 2022
a sketch of what a zkvm could look like

We want to build a ZKP that validates an entire EVM block or as much of it as we can efficiently. Its okay to adjust the gas costs for every EVM opcode. Its also to exclude some opcodes for now if th

25 Dec 30, 2022
PIP Manager written in python Tkinter

PIP Manager About PIP Manager is designed to make Python Package handling easier by just a click of a button!! Available Features Installing packages

Will Payne 9 Dec 09, 2022
Ssma is a tool that helps you collect your badges in a satr platform

satr-statistics-maker ssma is a tool that helps you collect your badges in a satr platform 🎖️ Requirements python = 3.7 Installation first clone the

TheAwiteb 3 Jan 04, 2022
System Design Assignments as part of Arpit's System Design Masterclass

System Design Assignments The repository contains a set of problem statements around Software Architecture and System Design as conducted by Arpit's S

Relog 1.1k Jan 09, 2023
All kinds of programs are accepted here, raise a genuine PR, and claim a PR, Make 4 successful PR's and get the Stickers and T-Shirt from hacktoberfest 2021

this repository is excluded from hacktoberfest Hacktoberfest-2021 This repository aims to help code beginners with their first successful pull request

34 Sep 11, 2022
Remote execution of a simple function on the server

FunFetch Remote execution of a simple function on the server All types of Python support objects.

Decave 4 Jun 30, 2022