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
Architectural Patterns implementation by using notification handler module prototype

This repository covers singleton, indirection, factory, adaptor, mediator patterns in python language by using university hypothetical notification module prototype. The code is just for demonstrating the pattern implementation not modules working

Muhammad Umair 2 Jan 8, 2022
A Python library to simulate a Zoom H6 recorder remote control

H6 A Python library to emulate a Zoom H6 recorder remote control Introduction This library allows you to control your Zoom H6 recorder from your compu

Matias Godoy 68 Nov 2, 2022
Probably the best way to simulate block scopes in Python

This is a package, as it says on the tin, to emulate block scoping in Python, the lack of which being a clever design choice yet sometimes a trouble.

null 88 Oct 26, 2022
This is a Python program I wrote to simulate the solar system with 79 lines of code.

Solar System With Python This is a Python program I wrote to simulate the solar system with 79 lines of code. Required modules tkinter, math, time Why

Mehmet Aydoğmuş 1 Oct 26, 2021
A redesign of our previous Python World Cup, aiming to simulate the 2022 World Cup all the way from the qualifiers

A redesign of our previous Python World Cup, aiming to simulate the 2022 World Cup all the way from the qualifiers. This new version is designed to be more compact and more efficient and will reflect the improvements in our programming ability.

Sam Counsell 1 Jan 7, 2022
Hook and simulate global keyboard events on Windows and Linux.

keyboard Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.

BoppreH 3.2k Jan 1, 2023
Manipulation OpenAI Gym environments to simulate robots at the STARS lab

liegroups Python implementation of SO2, SE2, SO3, and SE3 matrix Lie groups using numpy or PyTorch. [Documentation] Installation To install, cd into t

STARS Laboratory 259 Dec 11, 2022
MeerKAT radio telescope simulation package. Built to simulate multibeam antenna data.

MeerKATgen MeerKAT radio telescope simulation package. Designed with performance in mind and utilizes Just in time compile (JIT) and XLA backed vectro

Peter Ma 6 Jan 23, 2022
This is a library for simulate probability theory problems specialy conditional probability

This is a library for simulate probability theory problems specialy conditional probability. It is also useful to create custom single or joint distribution with specific PMF or PDF to get probability table and genearte data based on probability function.

Mohamadreza Kariminejad 6 Mar 30, 2022
A collection of design patterns and idioms in Python (With tests!).

Python Patterns Help the project financially: Donate: https://smartlegion.github.io/donate/ Yandex Money: https://yoomoney.ru/to/4100115206129186 PayP

null 5 Sep 12, 2021
What Do Deep Nets Learn? Class-wise Patterns Revealed in the Input Space

What Do Deep Nets Learn? Class-wise Patterns Revealed in the Input Space Introduction: Environment: Python3.6.5, PyTorch1.5.0 Dataset: CIFAR-10, Image

null 8 Mar 23, 2022
Analyzes crypto candles over a set time period and then trades based on winning patterns found

patternstrade Analyzes crypto candles over a set time period and then trades based on winning patterns found. Heavily customizable. Warning: This was

ConnorCreate 14 May 29, 2022
Discovering local read-level DNA methylation patterns and DNA methylation heterogeneity in intermediately methylated regions

Discovering local read-level DNA methylation patterns and DNA methylation heterogeneity in intermediately methylated regions

null 1 Jan 11, 2022
Python implementation of the ASFLIP advection method

This is a python implementation of the ASFLIP advection method . We would like to hear from you if you appreciate this work.

Raymond Yun Fei 133 Nov 13, 2022
Implementation of the MDMC method to search for magnetic ground state using VASP

Implementation of MDMC method ( by Olga Vekilova ) to search for magnetic ground state using VASP

Utkarsh Singh 1 Nov 27, 2021
Python meta class and abstract method library with restrictions.

abcmeta Python meta class and abstract method library with restrictions. This library provides a restricted way to validate abstract methods. The Pyth

Morteza NourelahiAlamdari 8 Dec 14, 2022
Lagrange Interpolation Method-Python

Lagrange Interpolation Method-Python The Lagrange interpolation formula is a way to find a polynomial, called Lagrange polynomial, that takes on certa

Motahare Soltani 2 Jul 5, 2022
A python package to adjust the bias of probabilistic forecasts/hindcasts using "Mean and Variance Adjustment" method.

Documentation A python package to adjust the bias of probabilistic forecasts/hindcasts using "Mean and Variance Adjustment" method. Read documentation

null 1 Feb 2, 2022
This is a method to build your own qgis configuration packages using osgeo4W.

This is a method to build your own qgis configuration packages using osgeo4W. Then you can automate deployment in your organization with a controled and trusted environnement.

Régis Haubourg 26 Dec 5, 2022