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
PREFS is a Python library to store and manage preferences and settings.

PREFS PREFS is a Python library to store and manage preferences and settings. PREFS stores a Python dictionary in a total human-readable file, the PRE

Pat 13 May 26, 2022
Calibre Libgen Non-fiction / Sci-tech store plugin

CalibreLibgenSci A Libgen Non-Fiction/Sci-tech store plugin for Calibre Installation Download the latest zip file release from here Open Calibre Navig

IDDQD 9 Dec 27, 2022
Programming in Bioinformatics, Block 3

Programming in Bioinformatics - Block 3 I. Setting up Environment and Running the Code Create the environment using the pibi_block3.yml file with the

2 Dec 10, 2021
Do you need a screensaver for CircuitPython? Of course you do

circuitpython_screensaver Do you need a screensaver for CircuitPython? Of course you do Demo video of dvdlogo screensaver: screensaver_dvdlogo.mp4 Dem

Tod E. Kurt 8 Sep 02, 2021
Web App for University Project

University Project About I made this web app to finish a project assigned by my teacher. It is written entirely in Python, thanks to streamlit to make

15 Nov 27, 2022
libvcs - abstraction layer for vcs, powers vcspull.

libvcs - abstraction layer for vcs, powers vcspull. Setup $ pip install libvcs Open up python: $ python # or for nice autocomplete and syntax highlig

python utilities for version control 46 Dec 14, 2022
An educational platform for students

Watch N Learn About Watch N Learn is an educational platform for students. Watch N Learn incentivizes students to learn with fun activities and reward

Brian Law 3 May 04, 2022
A simple PID tuner and simulator.

PIDtuner-V0.1 PlantPy PID tuner version 0.1 Features Supports first order and ramp process models. Supports Proportional action on PV or error or a sp

3 Jun 23, 2022
Attempt at a Windows version of the plotman Chia Plot Manager system

windows plotman: an attempt to get plotman to work on windows THIS IS A BETA. Not ready for production use just yet. Almost, but not quite there yet.

59 May 11, 2022
This repository can help you made a PocketMine-MP Server with Termux apps!

Hello This GitHub repository can made you a Server PocketMine-MP On development! How to Install Open Termux Type "pkg install git && python" If python

1 Mar 04, 2022
A python package template that can be adapted for RAP projects

Warning - this repository is a snapshot of a repository internal to NHS Digital. This means that links to videos and some URLs may not work. Repositor

NHS Digital 3 Nov 08, 2022
Projeto de análise de dados com SQL

Project-Analizyng-International-Debt-Statistics- Projeto de análise de dados com SQL - Plataforma Data Camp Descrição do Projeto : Não é que nós human

Lorrayne Silva 1 Feb 01, 2022
ASVspoof 2021 Baseline Systems

ASVspoof 2021 Baseline Systems Baseline systems are grouped by task: Speech Deepfake (DF) Logical Access (LA) Physical Access (PA) Please find more de

91 Dec 28, 2022
Nicotine+: A graphical client for the SoulSeek peer-to-peer system

Nicotine+ Nicotine+ is a graphical client for the Soulseek peer-to-peer file sharing network. Nicotine+ aims to be a pleasant, Free and Open Source (F

940 Jan 03, 2023
This code extracts line width of phonons from specular energy density (SED) calculated with LAMMPS.

This code extracts line width of phonons from specular energy density (SED) calculated with LAMMPS.

Masato Ohnishi 3 Jun 15, 2022
Display your data in an attractive way in your notebook!

Bloxs Bloxs is a simple python package that helps you display information in an attractive way (formed in blocks). Perfect for building dashboards, re

MLJAR 192 Dec 28, 2022
Hoopoe - Get notified of important stuff, right away.

Hoopoe - Get notified of important stuff, right away. Report a Bug · Request a Feature . Ask a Question Table of Contents About Getting Started Prereq

Vahid Al 8 Nov 12, 2022
Tomador de ramos UC automatico para Windows, Linux y macOS

auto-ramos v2.0 Tomador de ramos UC automatico para Windows, Linux y macOS Funcion Este script de Python tiene como principal objetivo hacer que la to

Open Source eUC 13 Jun 29, 2022
Example teacher bot for deployment to Chai app.

Create and share your own chatbot Here is the code for uploading the popular "Ms Harris (Teacher)" chatbot to the Chai app. You can tweak the config t

Chai 1 Jan 10, 2022
This is collection of Managementsystem programs: Hospital Management, Student Managemen, etc

Contribute in this repository and help other students with their assignment by adding python scripts for various management system programs.

GDSC BVP DET - Navi Mumbai 3 Mar 20, 2022