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
ALSPAC data analysis studying links between screen-usage and mental health issues in children. Provided data has been synthesised.

ADSMH - Mental Health and Screen Time Group coursework for Applied Data Science at the University of Bristol. Overview The data set that you have was

Kai 1 Jan 13, 2022
Powerful Assistant

Delta-Assistant Hi I'm Phoenix This project is a smart assistant This is the 1.0 version of this project I am currently working on the third version o

1 Nov 17, 2021
Howell County, Missouri, COVID-19 data and (unofficial) estimates

COVID-19 in Howell County, Missouri This repository contains the daily data files used to generate my COVID-19 dashboard for Howell County, Missouri,

Jonathan Thornton 0 Jun 18, 2022
Provides guideline on how to configure pre-commit hooks in your own python project

Pre-commit Configuration Guide The main aim of this repository is to act as a guide on how to configure the pre-commit hooks in your existing python p

Faraz Ahmed Khan 2 Mar 31, 2022
Tool to audit and fix Python project requirements.

Requirement Auditor Utility to revise and updated python requirement files.

Luis Carlos Berrocal 1 Nov 07, 2021
Web3 Solidity Connector

With this project, you can compile your sol files and create new transactions including creating contract and calling the state changer functions. You can integrate integrate your sol files with Pyth

Fethi Tekyaygil 3 Oct 09, 2022
A python script made for personal use to monitor for sports card restocks on target.com since they are sold out often

TargetProductMonitor A python script made for personal use to monitor for sports card resocks on target.com since they are sold out often. When a rest

Bryan Lorden 2 Jul 31, 2022
CMPE 204 Modelling Project

CISC/CMPE 204 Modelling Project Welcome to the major project for CISC/CMPE 204 (Fall 2021)! Change this README.md file to summarize your project (few

totallyrin 2 May 16, 2022
addon for blender to import mocap data from tools like easymocap, frankmocap and Vibe

b3d_mocap_import addon for blender to import mocap data from tools like easymocap, frankmocap and Vibe ==================VIBE================== To use

Carlos Barreto 97 Dec 07, 2022
A code base for python programs the goal is to integrate all the useful and essential functions

Base Dev EN This GitHub will be available in French and English FR Ce GitHub sera disponible en français et en anglais Author License Screen EN 🇬🇧 D

Pikatsuto 1 Mar 07, 2022
Graphsignal Logger

Graphsignal Logger Overview Graphsignal is an observability platform for monitoring and troubleshooting production machine learning applications. It h

Graphsignal 143 Dec 05, 2022
Camera track the tip of a pen to use as a drawing tablet

cablet Camera track the tip of a pen to use as a drawing tablet Setup You will need: Writing utensil with a colored tip (preferably blue or green) Bac

14 Feb 20, 2022
Python-Roadmap - Дорожная карта по изучению Python

Python Roadmap Я решил сделать что-то вроде дорожной карты (Roadmap) для изучения языка Python. Возможно, если найдутся желающие дополнять ее, модифиц

Ruslan Prokhorov 1.2k Dec 28, 2022
Includes Chapters for Python Crash Course session.

python-crash-course Includes Chapters for Python Crash Course session. What will you learn: Python Essentials Creating Server Writing REST API Writing

Vineet Rao 3 Feb 17, 2021
The mock Pokemon Environment I built in 2019 to study Reinforcement Learning + Pokemon

ghetto-pokemon-rl-environment ##NOT MAINTAINED! Fork and maintain yourself. Environment I made back in 2019 to use Pokemon to practice reinforcement l

2 Dec 09, 2021
pgvector support for Python

pgvector-python pgvector support for Python Great for online recommendations 🎉 Supports Django, SQLAlchemy, Psycopg 2, Psycopg 3, and asyncpg Install

Andrew Kane 37 Dec 20, 2022
Estimating the potential photovoltaic production of buildings (in Berlin)

The following people contributed equally to this repository (in alphabetical order): Daniel Bumke JJX Corstiaen Versteegh This repository is forked on

Daniel Bumke 6 Feb 18, 2022
Flask html response minifier

Flask-HTMLmin Minify flask text/html mime type responses. Just add MINIFY_HTML = True to your deployment config to minify HTML and text responses of y

Hamid Feizabadi 85 Dec 07, 2022
Reload all Blender add-on modules

Reload-Addon This add-on creates a list of the modules that the add-on selected in the drop-down menu contains and reloads them with the keyboard shor

2 Dec 02, 2021
Free components that wrap up Python into Delphi and Lazarus (FPC)

Python for Delphi (P4D) is a set of free components that wrap up the Python DLL into Delphi and Lazarus (FPC). They let you easily execute Python scri

747 Jan 02, 2023