4.1. diffractio package
4.1.1. Submodules
4.1.2. diffractio.config module
Configuration file. Standard diffractio units are um: um = 1.
4.1.3. diffractio.scalar_fields_X module
This module generates Scalar_field_X class and several functions for multiprocessing. It is required also for generating masks and fields.
- The main atributes are:
self.x (numpy.array): linear array with equidistant positions. The number of data is preferibly \(2^n\) .
self.wavelength (float): wavelength of the incident field.
self.u (numpy.array): equal size than x. complex field
- There are also some secondary atributes:
self.quality (float): quality of RS algorithm
self.info (str): description of data
self.type (str): Class of the field
self.date (str): date
Class for unidimensional scalar fields
- Definition of a scalar field
instantiation, duplicate, clear_field, print
add, substract sources
multiply masks and sources
save and load data
- Functions for generation of masks
insert masks, insert_array_masks - insert other masks inside the mask
filter -
- Propagation
fft, ifft - fourier transform
RS - Rayleigh Sommerfeld. It allows amplification of the field
BPM - Beam propagation method
- Drawing functions
draw
- Parameters:
intensity, average intensity
get_edges_transitions (mainly for pylithography)
- Functions
kernelRS, kernelRSinverse
- Multiprocessing
polychromatic_multiprocessing
extended_source_multiprocessing
extended_polychromatic_source
- class diffractio.scalar_fields_X.Scalar_field_X(x=None, wavelength=None, n_background=1, info='')[source]
Bases:
object
Class for unidimensional scalar fields.
- Parameters:
x (numpy.array) – linear array with equidistant positions. The number of data is preferibly \(2^n\) .
wavelength (float) – wavelength of the incident field
n_background (float) – refraction index of background
info (str) – String with info about the simulation
- self.x
Linear array with equidistant positions. The number of data is preferibly \(2^n\).
- Type:
numpy.array
- self.wavelength
Wavelength of the incident field.
- Type:
float
- self.u
Complex field. The size is equal to self.x.
- Type:
numpy.array
- self.quality
Quality of RS algorithm.
- Type:
float
- self.info
Description of data.
- Type:
str
- self.type
Class of the field.
- Type:
str
- self.date
Date when performed.
- Type:
str
- duplicate(clear=False)[source]
Duplicates the instance
- Parameters:
clear (bool) – If True, clears the self.u argument, else it keeps the same than in self.
- Returns
new_instance (scalar_field_X): duplicated instance.
- reduce_to_1()[source]
All the values greater than 1 pass to 1. This is used for Scalar_masks when we add two masks.
- save_data(filename, add_name='', description='', verbose=False)[source]
Common save data function to be used in all the modules. The methods included are: npz, matlab
- Parameters:
filename (str) – filename
add_name= (str) – sufix to the name, if ‘date’ includes a date
description (str) – text to be stored in the dictionary to save.
verbose (bool) – If verbose prints filename.
- Returns:
filename. If False, file could not be saved.
- Return type:
(str)
- load_data(filename, verbose=False)[source]
- Load data from a file to a Scalar_field_X.
The methods included are: npz, matlab
- Parameters:
filename (str) – filename
verbose (bool) – shows data process by screen
- cut_resample(x_limits='', num_points=[], new_field=False, interp_kind='linear')[source]
Cuts the field to the range (x0,x1). If one of this x0,x1 positions is out of the self.x range it does nothing. It is also valid for resampling the field, just write x0,x1 as the limits of self.x
- Parameters:
x_limits (numpy.array) – (x0,x1) - starting and final points to cut, if ‘’ - takes the current limit x[0] and x[-1]
num_points (int) – it resamples x, and u [],’’,0,None -> it leave the points as it is
new_field (bool) – if True it returns a new Scalar_field_X
interp_kind (str) – ‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’
- Returns:
if new_field is True
- Return type:
- incident_field(u0)[source]
Incident field for the experiment. It takes a Scalar_source_X field.
- Parameters:
u0 (Scalar_source_X) – field produced by Scalar_source_X (or a X field)
- inverse_amplitude(new_field=False)[source]
Inverts the amplitude of the mask, phase is equal as initial
- Parameters:
new_field (bool) – If True it returns a Scalar_mask_X object, else, it modifies the existing object.
- Returns:
If new_field is True, it returns a Scalar_mask_X object.
- Return type:
- inverse_phase(new_field=False)[source]
Inverts the phase of the mask, amplitude is equal as initial
- Parameters:
new_field (bool) – If True it returns a Scalar_mask_X object, else, it modifies the existing object.
- Returns:
If new_field is True, it returns a Scalar_mask_X object.
- Return type:
- insert_mask(t1, x0_mask1, clean=True, kind_position='left')[source]
Insert mask t1 in mask self. It is performed using interpolation.
- Parameters:
t1 (Scalar_field_X) – field X (shorter)
x0_mask1 (float) – location of starting point at t0 of init point of t1.
clean (bool) – if True remove previous fields, else substitute
kind_position (str) – ‘left’ ‘center’
- pupil(x0, radius)[source]
Place a pupil in the field.
- Parameters:
x0 (float) – center of pupil.
radius (float) – radius of pupil.
- insert_array_masks(t1, x_pos, clean=True, kind_position='left')[source]
Insert several identical masks t1 in self.u according to positions x_pos
- Parameters:
t1 (Scalar_field_X) – mask to insert.
x_pos (numpy.array) – array with locations.
clean (bool) – elliminate preview fields in self.
kind_position (str) – ‘left’, ‘center’: positions are at left or center.
- repeat_structure(num_repetitions, position='center', new_field=True)[source]
Repeat the structure n times.
- Parameters:
num_repetitions (int) – Number of repetitions of the mask
position (string or number) – ‘center’, ‘previous’ or initial position. Initial x
new_field (bool) – If True, a new mask is produced, else, the mask is modified.
- fft(z=None, shift=True, remove0=False, matrix=False, new_field=False, verbose=False)[source]
Far field diffraction pattern using Fast Fourier Transform (FFT).
- Parameters:
z (float) – distance to the observation plane or focal of lens. If None the exit is in radians
shift (bool) – if True, fftshift is performed
remove0 (bool) – if True, central point is removed
matrix (bool) – if True only matrix is returned. If False, returns Scalar_field_X
new_field (bool) – if True returns Scalar_field_X, else it puts in self
verbose (bool) – if True, prints info
- Returns:
FFT of the input field
- Return type:
(array or Scalar_field_X or None)
- ifft(z=None, shift=True, remove0=True, matrix=False, new_field=False, verbose=False)[source]
Inverse Fast Fourier Transform (ifft) of the field.
- Parameters:
z (float) – distance to the observation plane or focal of lens
shift (bool) – if True, fftshift is performed
remove0 (bool) – if True, central point is removed
matrix (bool) – if True only matrix is returned. If False, returns Scalar_field_X
new_field (bool) – if True returns Scalar_field_X, else it puts in self
verbose (bool) – if True, prints info
- Returns:
FFT of the input field
- Return type:
(array or Scalar_field_X or None)
- RS(z, amplification=1, n=1, new_field=True, matrix=False, xout=None, fast=False, kind='z', verbose=True)[source]
Fast-Fourier-Transform method for numerical integration of diffraction Rayleigh-Sommerfeld formula. Is we have a field of size N*M, the result of propagation is also a field N*M. Nevertheless, there is a parameter amplification which allows us to determine the field in greater observation planes (jN)x(jM).
- Parameters:
z (float) – Distance to observation plane. if z<0 inverse propagation is executed
n (float) – Refraction index
new_field (bool) – if False the computation goes to self.u, if True a new instance is produced
matrix (bool) – If True, the result of the function is a numpy.array
fast (bool) – Instead of using Hankle function for RS kernel uses expotential
amplification (int) – number of frames in x direction
kind (str) – ‘z’. In some circunstamces the function is used for other integrals
verbose (bool) – if True it writes to shell
- Returns:
Scalar_field_X, If matrix is True: numpy.array() Else: None
- Return type:
If New_field is True
- Info:
This approach a quality parameter: If self.quality>1, propagation is right.
- CZT(z, xout, verbose=False)[source]
Chirped z-transform.
- Parameters:
z (float or np.array) – diffraction distance
xout (float or np.array) – x array with positions of the output plane
verbose (bool) – If True it prints information.
- Returns:
Complex amplitude of the outgoing light beam
- Return type:
u_out
References
[Light: Science and Applications, 9(1), (2020)]
- WPM(fn, zs, num_sampling=None, ROI=None, x_pos=None, z_pos=None, get_u_max=False, has_edges=True, pow_edge=80, verbose=False)[source]
- WPM method used for very dense sampling. It does not storages the intensity distribution at propagation, but only selected areas. The areas to be stored are:
global view with a desired sampling given by num_sampling.
intensity at the last plane.
Intensity at plane with maximum intensity (focus of a lens, for example)
Region of interest given by ROI.
- Parameters:
fn (function) – Function that returns the refraction index at a plane in a numpy.array
zs (np.array) – linspace with positions z where to evaluate the field.
num_sampling (int, int) – If None, it does not storage intermediate data. Otherwise, it stores a small XZ matrix which size in num_sampling.
ROI (np.array, np.array) – x and z arrays with positions and sampling to store. It is used when we need to store with a high density a small area of the total field.
x_pos (float or None) – If not None, a high density longitudinal array with the field at x_pos position is stored.
z_pos (float or None) – If not None, a high density transversal array with the field at z_pos is stored.
get_u_max (bool) – If True, returns field at z position with maximum intensity.
has_edges (bool) – If True absorbing edges are used.
pow_edge (float) – If has_edges, power of the supergaussian.
verbose (bool) – If True prints information.
- Returns:
final field u_out_gv (Scalar_field_XZ): global view u_out_roi (Scalar_field_XZ): field at ROI positions u_axis_x (Scalar_field_X): field at position z_pos u_axis_z (Scalar_field_Z): field at position x_pos u_max (Scalar_field_X): field at position with maximum intensity z_max (float): position with maximum intensity
- Return type:
u_iter (Scalar_field_X)
References
Fertig and K.-H. Brenner, “Vector wave propagation method,” J. Opt. Soc. Am. A, vol. 27, no. 4, p. 709, 2010.
Schmidt et al., “Wave-optical modeling beyond the thin-element-approximation,” Opt. Express, vol. 24, no. 26, p. 30188, 2016.
- normalize(new_field=False)[source]
Normalizes the field so that intensity.max()=1.
- Parameters:
new_field (bool) – If False the computation goes to self.u. If True a new instance is produced.
- Returns
u (numpy.array): normalized optical field
- MTF(kind='mm', has_draw=True)[source]
Computes the MTF of a field,.
- Parameters:
kind (str) – ‘mm’, ‘degrees’
has_draw (bool) – If True draws the MTF
- Returns:
frequencies in lines/mm (numpy.array) mtf_norm: normalizd MTF
- Return type:
(numpy.array) fx
- average_intensity(verbose=False)[source]
Returns the average intensity as: (np.abs(self.u)**2).sum() / num_data
- Parameters:
verbose (bool) – If True it prints the value of the average intensity.
- Returns:
average intensity.
- Return type:
(float)
- get_edges(kind_transition='amplitude', min_step=0, verbose=False, filename='')[source]
Determine locations of edges for a binary mask.
- Parameters:
kind_transition – ‘amplitude’ ‘phase’ if we see the amplitude or phase of the field
min_step – minimum step for consider a transition
- Returns:
array with +1, -1 with rasing or falling edges pos_transition: positions x of transitions raising: positions of raising falling: positions of falling
- Return type:
type_transition
- get_RS_minimum_z(n=1, quality=1, verbose=True)[source]
Determines the minimum available distance for RS algorithm. If higher or lower quality parameters is required you can add as a parameter
- Parameters:
n (float) – refraction index of the surrounding medium.
quality (int, optional) – quality. Defaults to 1.
verbose (bool, optional) – prints info. Defaults to True.
- Returns:
z_min for quality_factor>quality
- Return type:
z_min (float)
- draw(kind='intensity', logarithm=False, normalize=False, cut_value=None, filename='', scale='')[source]
Draws X field. There are several data from the field that are extracted, depending of ‘kind’ parameter.
- Parameters:
kind (str) – type of drawing: ‘amplitude’, ‘intensity’, ‘field’, ‘phase’, ‘fill’, ‘fft’
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (bool) – If True, max(intensity)=1
cut_value (float) – If not None, cuts the maximum intensity to this value
filename (str) – if not ‘’ stores drawing in file,
scale (str) – ‘’, ‘scaled’, ‘equal’, scales the XY drawing
- diffractio.scalar_fields_X.kernelRS(x, wavelength, z, n=1, kind='z', fast=False)[source]
Kernel for RS propagation. It uses the hankel tansform.
There is a ‘fast’ version based on \(hk_1 = \sqrt{2/(\pi \, k \, R)} e^{i (k \, R - 3 \pi / 4)}\) which approximates the result.
- Parameters:
x (numpy.array) – positions x
wavelength (float) – wavelength of incident fields
z (float) – distance for propagation
n (float) – refraction index of background
kind (str) – ‘z’, ‘x’, ‘0’: for simplifying vector propagation
fast (bool) – If True The approximation is much faster. According to https://dlmf.nist.gov/10.2#E5
- Returns:
kernel
- Return type:
(complex array)
References
Shen and A. Wang, “Fast-Fourier-transform based numerical integration method for the Rayleigh-Sommerfeld diffraction formula,” Appl. Opt., vol. 45, no. 6, pp. 1102–1110, 2006.
- diffractio.scalar_fields_X.kernelRSinverse(x, wavelength, z, n=1, kind='z', fast=False)[source]
Kernel for inverse RS propagation. See also kernelRS
- Parameters:
x (numpy.array) – positions x
wavelength (float) – wavelength of incident fields
z (float) – distance for propagation
n (float) – refraction index of background
kind (str) – ‘z’, ‘x’, ‘0’: for simplifying vector propagation
fast (bool) – If True The approximation is much faster. According to https://dlmf.nist.gov/10.2#E5
- Returns:
kernel
- Return type:
complex array
- diffractio.scalar_fields_X.PWD_kernel(u, n, k0, k_perp2, dz)[source]
Step for scalar (TE) Plane wave decomposition (PWD) algorithm.
- Parameters:
u (np.array) – fields
n (np.array) – refraction index
k0 (float) – wavenumber
k_perp2 (np.array) – transversal k**2
dz (float) – increment in distances
- Returns:
Field at at distance dz from the incident field
- Return type:
numpy.array()
References
Schmidt, S. et al. “Wave-optical modeling beyond the thin-element-approximation”. ‘Opt. Express’ 24, 30188 (2016).
- diffractio.scalar_fields_X.WPM_schmidt_kernel(u, n, k0, k_perp2, dz)[source]
Kernel for fast propagation of WPM method
- Parameters:
u (np.array) – fields
n (np.array) – refraction index
k0 (float) – wavenumber
k_perp2 (np.array) – transversal k**2
dz (float) – increment in distances
References
Fertig and K.-H. Brenner, “Vector wave propagation method,” J. Opt. Soc. Am. A, vol. 27, no. 4, p. 709, 2010.
Schmidt et al., “Wave-optical modeling beyond the thin-element-approximation,” Opt. Express, vol. 24, no. 26, p. 30188, 2016.
- diffractio.scalar_fields_X.polychromatic_multiprocessing(function_process, wavelengths, spectrum, num_processors=2, verbose=False)[source]
It performs an analysis of polychromatic light. It needs a function with only one input parameter: wavelength. It determines the intensity for each wavelength and the final results is the summation of the intensities.
- Parameters:
function_process (function) – function with accepts params as input parameters:
wavelengths (array) – wavelengths in the spectrum
spectrum (array) – weights for the spectrum. if None: uniform spectrum, else array with the same dimension as wavelengths
num_processors (int) – number of processors for the computation
verbose (bool) – if True send information to shell
- Returns:
intensity = intensity + spectrum[i] * np.abs(u_s[i].u)**2 u_s (Scalar_field_X): fields for each wavelength time_proc (float): time interval in the processing
- Return type:
intensity (array, complex)
- diffractio.scalar_fields_X.extended_source_multiprocessing(function_process, x0s, num_processors=2, verbose=False)[source]
It performs an analysis of extendes source light. It needs a function with only an input parameter, that is x0s positions of sources. It determines the intensity for each wavelength and it is added.
- Parameters:
function_process (function) – function with accepts params as input Parameters:
x0s (array) – positions of sources
num_processors (int) – number of processors for the computation
verbose (bool) – if True send information to shell
- Returns:
intensity = intensity + spectrum[i] * np.abs(u_s[i].u)**2 - u_s (Scalar_field_X): fields for each wavelength - time_proc (float): time interval in the processing
- Return type:
intensity (array, complex)
- diffractio.scalar_fields_X.extended_polychromatic_source(function_process, x0s, wavelengths, spectrum, num_processors=2, verbose=False)[source]
It performs an analysis of extendes source light. It needs a function with only an input parameter, that is x0s positions of sources. It determines the intensity for each wavelength and it is added.
- Parameters:
function_process (function) – function with accepts params as input Parameters:
x0s (array) – positions of sources
wavelengths (array) – wavelengths in the spectrum
spectrum (array) – weights for the spectrum. If None: uniform spectrum, else array with the same dimension as wavelengths
num_processors (int) – number of processors for the computation
verbose – if True send information to shell
- diffractio.scalar_fields_X.quality_factor(range_x, num_x, z, wavelength, n=1, verbose=False)[source]
Determine the quality factor for RS algorithm
- Parameters:
x (np.array) – x array with positions
z (float) – observation distance
wavelength (float) – wavelength)
n (float) – refraction index
- Returns:
_description_
- Return type:
_type_
- diffractio.scalar_fields_X.get_RS_minimum_z(range_x, num_x, wavelength, n=1, quality=1, verbose=True)[source]
_summary_
- Parameters:
range_x (float) – range_x
num_x (int) – num_x
z (float) – z
wavelength (float) – wavelength
quality (int, optional) – quality. Defaults to 1.
verbose (bool, optional) – prints info. Defaults to True.
- Returns:
_description_
- Return type:
_type_
4.1.4. diffractio.scalar_fields_XY module
This module generates Scalar_field_XY class.
It can be considered an extension of Scalar_field_X for visualizing XY fields
For the case of Rayleigh sommefeld it is not necessary to compute all z positions but the final.
Nevertheless, for BPM method, intermediate computations are required. In this class, intermediate results are stored.
X,Y fields are defined using ndgrid (not with meshgrid, it is different).
It is required also for generating masks and fields.
- The main atributes are:
self.x - x positions of the field
self.y - y positions of the field
self.wavelength - wavdelength of the incident field. The field is monochromatic
self.u (numpy.array): equal size to x * y. complex field
self.X (numpy.array): equal size to x * y. complex field
self.Y (numpy.array): equal size to x * y. complex field
self.quality (float): quality of RS algorithm
self.info (str): description of data
self.type (str): Class of the field
self.date (str): date of execution
The magnitude is related to microns: micron = 1.
Class for XY scalar fields
- Definition of a scalar field
instatiation, duplicate
save, load data
cut_resample, binarize, discretize
get_phase, get_amplitude, remove_amplitude, remove_phase, amplitude2phase, phase2amplitude
- Propagation
fft, ifft, RS, RS_simple, RS_amplificacion
- Drawing functions
draw, draw_profile,
video, progresion
- Parameters
profile
- Functions outside the class
draw_several_fields
draw2D
several_propagations
kernelRS, kernelRSinverse, kernelFresnel, WPM_schmidt_kernel
- class diffractio.scalar_fields_XY.Scalar_field_XY(x=None, y=None, wavelength=None, info='')[source]
Bases:
object
Class for working with XY scalar fields.
- Parameters:
x (numpy.array) – linear array with equidistant positions. The number of data is preferibly \(2^n\) .
y (numpy.array) – linear array wit equidistant positions for y values
wavelength (float) – wavelength of the incident field
info (str) – String with info about the simulation
- self.x
linear array with equidistant positions. The number of data is preferibly \(2^n\) .
- Type:
numpy.array
- self.y
linear array wit equidistant positions for y values
- Type:
numpy.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.u
(x,z) complex field
- Type:
numpy.array
- self.info
String with info about the simulation
- Type:
str
- reduce_to_1()[source]
All the values greater than 1 pass to 1. This is used for Scalar_masks when we add two masks.
- add(other, kind='standard')[source]
adds two Scalar_field_x. For example two light sources or two masks
- Parameters:
other (Scalar_field_X) – 2 field to add
kind (str) – instruction how to add the fields: - ‘maximum1’: mainly for masks. If t3=t1+t2>1 then t3= 1. - ‘standard’: add fields u3=u1+u2 and does nothing.
- Returns:
u3 = u1 + u2
- Return type:
- rotate(angle, position=None, new_field=False)[source]
Rotation of X,Y with respect to position. If position is not given, rotation is with respect to the center of the image
- Parameters:
angle (float) – angle to rotate, in radians
position (float, float) – position of center of rotation
- apodization(power=10)[source]
Multiply field by an apodizer. The apodizer is a super_gauss function.
- Parameters:
power (int, optional) – size of apodization. Defaults to 10.
- save_data(filename, add_name='', description='', verbose=False)[source]
Common save data function to be used in all the modules. The methods included are: npz, matlab
- Parameters:
filename (str) – filename
add_name= (str) – sufix to the name, if ‘date’ includes a date
description (str) – text to be stored in the dictionary to save.
verbose (bool) – If verbose prints filename.
- Returns:
filename. If False, file could not be saved.
- Return type:
(str)
- load_data(filename, verbose=False)[source]
- Load data from a file to a Scalar_field_X.
The methods included are: npz, matlab
- Parameters:
filename (str) – filename
verbose (bool) – shows data process by screen
- save_mask(filename='', kind='amplitude', binarize=False, cmap='gray', info='')[source]
Create a mask in a file, for example, ablation or litography engraver
- Parameters:
filename (str) – file name
kind (str) – save amplitude, phase or intensity. If intensity it is normalized to (0,1)
binarize (bool) – If True convert the mask in (0,1) levels
cmap (str) – colormap. (gray)
info (str) – info of the mask
- Returns:
area (in um**2)
- Return type:
float
- cut_resample(x_limits='', y_limits='', num_points=[], new_field=False, interp_kind=(3, 1))[source]
it cut the field to the range (x0,x1). If one of this x0,x1 positions is out of the self.x range it do nothing. It is also valid for resampling the field, just write x0,x1 as the limits of self.x
- Parameters:
x_limits (float,float) – (x0,x1) starting and final points to cut. if ‘’ - takes the current limit x[0] and x[-1]
y_limits (float,float) – (y0,y1) - starting and final points to cut. if ‘’ - takes the current limit y[0] and y[-1]
num_points (int) – it resamples x, y and u. [],’’,,None -> it leave the points as it is
new_field (bool) – it returns a new Scalar_field_XY
interp_kind – numbers between 1 and 5
- incident_field(u0)[source]
Incident field for the experiment. It takes a Scalar_source_X field.
- Parameters:
u0 (Scalar_source_X) – field produced by Scalar_source_X (or a X field)
- pupil(r0=None, radius=None, angle=0.0)[source]
place a pupil in the field. If r0 or radius are None, they are computed using the x,y parameters.
- Parameters:
r0 (float, float) – center of circle/ellipse
radius (float, float) or (float) – radius of circle/ellipse
angle (float) – angle of rotation in radians
Example
pupil(r0=(0 * um, 0 * um), radius=(250 * um, 125 * um), angle=0 * degrees)
- fft(z=0, shift=True, remove0=True, matrix=False, new_field=False)[source]
Fast Fourier Transform (FFT) of the field.
- Parameters:
z (float) – distance to the observation plane or focal of lens if z==0, no x,y scaled is produced
shift (bool) – if True, fftshift is performed
remove0 (bool) – if True, central point is removed
matrix (bool) – if True only matrix is returned. if False, returns Scalar_field_X
new_field (bool) – if True returns Scalar_field_X, else it puts in self
- Returns:
FFT of the input field
- Return type:
(np.array or Scalar_field_X or None)
- ifft_proposal(z=0.0, shift=True, remove0=True, matrix=False, new_field=False)[source]
Fast Fourier Transform (fft) of the field.
- Parameters:
z (float) – distance to the observation plane or focal of lens
shift (bool) – if True, fftshift is performed
remove0 (bool) – if True, central point is removed
matrix (bool) – if True only matrix is returned. If False, returns Scalar_field_X
new_field (bool) – if True returns Scalar_field_X, else puts in self
- Returns:
FFT of the input field
- Return type:
(np.array or Scalar_field_X or None)
- ifft(z=0.0, shift=True, remove0=True, matrix=False, new_field=False)[source]
Fast Fourier Transform (fft) of the field.
- Parameters:
z (float) – distance to the observation plane or focal of lens
shift (bool) – if True, fftshift is performed
remove0 (bool) – if True, central point is removed
matrix (bool) – if True only matrix is returned. If False, returns Scalar_field_X
new_field (bool) – if True returns Scalar_field_X, else puts in self
- Returns:
FFT of the input field
- Return type:
(np.array or Scalar_field_X or None)
- RS(z, amplification=(1, 1), n=1, new_field=True, matrix=False, xout=None, yout=None, kind='z', verbose=False)[source]
Fast-Fourier-Transform method for numerical integration of diffraction Rayleigh-Sommerfeld formula. Is we have a field of size N*M, the result of propagation is also a field N*M. Nevertheless, there is a parameter amplification which allows us to determine the field in greater observation planes (jN)x(jM).
- Parameters:
amplification (int, int) – number of frames in x and y direction
z (float) – distance to observation plane. if z<0 inverse propagation is executed
n (float) – refraction index
new_field (bool) – if False the computation goes to self.u, if True a new instance is produced.
matrix (Bool) – if True returns a matrix, else a Scalar_field_XY
xout (float) – If not None, the sampling area is moved. This is the left position
yout (float) – If not None, the sampling area y moved. This is the lower position.
kind (str) –
verbose (bool) – if True it writes to shell
- Returns:
Scalar_field_X, else None.
- Return type:
if New_field is True
Note
One advantage of this approach is that it returns a quality parameter: if self.quality>1, propagation is right.
References
Shen and A. Wang, “Fast-Fourier-transform based numerical integration method for the Rayleigh-Sommerfeld diffraction formula,” Appl. Opt., vol. 45, no. 6, pp. 1102–1110, 2006.
- WPM(fn, zs, num_sampling=(512, 512), ROI=(None, None), r_pos=None, z_pos=None, get_u_max=False, has_edges=True, pow_edge=80, matrix=False, verbose=False)[source]
- WPM method used for very dense sampling. It does not storages the intensity distribution at propagation, but only selected areas. The areas to be stored are:
global view with a desired sampling given by num_sampling.
intensity at the last plane.
Intensity at plane with maximum intensity (focus of a lens, for example)
Region of interest given by ROI.
- Parameters:
fn (function) – Function that returns the refraction index at a plane in a numpy.array
zs (np.array) – linspace with positions z where to evaluate the field.
num_sampling (int, int) – If None, it does not storage intermediate data. Otherwise, it stores a small XZ matrix which size in num_sampling.
ROI (np.array, np.array) – x and z arrays with positions and sampling to store. It is used when we need to store with a high density a small area of the total field.
r_pos (float or None) – If not None, a high density longitudinal array with the field at x_pos position is stored.
z_pos (float or None) – If not None, a high density transversal array with the field at z_pos is stored.
get_u_max (bool) – If True, returns field at z position with maximum intensity.
has_edges (bool) – If True absorbing edges are used.
pow_edge (float) – If has_edges, power of the supergaussian.
verbose (bool) – If True prints information.
References
Fertig and K.-H. Brenner, “Vector wave propagation method,” J. Opt. Soc. Am. A, vol. 27, no. 4, p. 709, 2010.
Schmidt et al., “Wave-optical modeling beyond the thin-element-approximation,” Opt. Express, vol. 24, no. 26, p. 30188, 2016.
- CZT_backup(z, xout=None, yout=None, verbose=False)[source]
Chirped Z Transform algorithm for XY Scheme. z, xout, and yout parameters can be numbers or arrays. The output Scheme depends on this input parameters.
- Parameters:
z (float) – diffraction distance
xout (np.array) – x array with positions of the output plane
yout (np.array) – y array with positions of the output plane
verbose (bool) – If True, it prints some information
- Returns:
Scalar_field_** depending of the input scheme. When all the parameters are numbers, it returns the complex field at that point.
- Return type:
u_out
References
[Light: Science and Applications, 9(1), (2020)]
- CZT(z, xout=None, yout=None, verbose=False)[source]
Chirped Z Transform algorithm for XY Scheme. z, xout, and yout parameters can be numbers or arrays. The output Scheme depends on this input parameters.
- Parameters:
z (float) – diffraction distance
xout (np.array) – x array with positions of the output plane
yout (np.array) – y array with positions of the output plane
verbose (bool) – If True, it prints some information
- Returns:
Scalar_field_** depending of the input scheme. When all the parameters are numbers, it returns the complex field at that point.
- Return type:
u_out
References
[Light: Science and Applications, 9(1), (2020)]
- profile(point1='', point2='', npixels=None, kind='intensity', order=2)[source]
Determine profile in image. If points are not given, then image is shown and points are obtained clicking.
- Parameters:
point1 (float) – initial point. if ‘’ get from click
point2 (float) – final point. if ‘’ get from click
npixels (int) – number of pixels for interpolation
kind (str) – type of drawing: ‘amplitude’, ‘intensity’, ‘phase’
order (int) – order for interpolation
- Returns:
profile numpy.array: z values for profile (float, float): point1 (float, float): point2
- Return type:
numpy.array
- draw_profile(point1='', point2='', npixels=None, kind='intensity', order=2)[source]
Draws profile in image. If points are not given, then image is shown and points are obtained clicking.
- Parameters:
point1 (float) – initial point. if ‘’ get from click
point2 (float) – final point. if ‘’ get from click
npixels (int) – number of pixels for interpolation
kind (str) – type of drawing: ‘amplitude’, ‘intensity’, ‘phase’
order (int) – order for interpolation
- Returns:
profile numpy.array: z values for profile (float, float): point1 (float, float): point2
- Return type:
numpy.array
- get_edges(kind_transition='amplitude', min_step=0, verbose=False, filename='')[source]
Determine locations of edges for a binary mask. Valid for litography engraving of gratings.
- Parameters:
kind_transition – ‘amplitude’ ‘phase’.
min_step – minimum step for consider a transition
- Returns:
array with +1, -1 with rasing or falling edges pos_transition: positions x of transitions raising: positions of raising falling: positions of falling
- Return type:
type_transition
- search_focus(kind='moments', verbose=True)[source]
Search for location of .
- Parameters:
kind (str) – ‘moments’ or ‘maximum’
verbose (bool) – If True prints information.
- Returns:
positions of focus
- Return type:
(x,y)
- MTF(kind='mm', has_draw=True, is_matrix=True)[source]
Computes the MTF of a field, If this field is near to focal point, the MTF will be wide
- Parameters:
kind (str) – ‘mm’, ‘degrees’
has_draw (bool) – If True draws the MTF
- Returns:
frequencies in lines/mm (numpy.array) mtf_norm: normalizd MTF
- Return type:
(numpy.array) fx
- beam_width_4s(has_draw=True)[source]
Returns the beam width parameters according to ISO11146.
- Parameters:
has_draw (bool) – If True, it draws
- Returns:
dx width x (float): dy width y (float): principal_axis, angle (str): (x_mean, y_mean, x2_mean, y2_mean, xy_mean), Moments
- Return type:
(float)
References
- average_intensity(verbose=False)[source]
Returns average intensity as: (np.abs(self.u)**2).sum() / num_data.
- Parameters:
verbose (bool) – If True prints data.
- send_image_screen(id_screen, kind='amplitude')[source]
Takes the images and sends the images to a screen in full size.
- Parameters:
id_screen (hdl) – handle to screen
kind ('str') – ‘amplitude’, ‘intensity’, ‘phase’
- get_amplitude(matrix=False, new_field=False)[source]
Gets the amplitude of the field.
- Parameters:
matrix (bool) – if True numpy.matrix is returned
new_field (bool) – if True it returns a new Scalar_field_XY
- Returns:
Scalar_field_X if matrix is True: numpy.array
- Return type:
if New_field is True
- get_phase(matrix=False, new_field=False)[source]
Gets the phase of the field.
- Parameters:
matrix (bool) – if True numpy.matrix is returned
new_field (bool) – if True it returns a new Scalar_field_XY
- Returns:
Scalar_field_X. if Matrix is True: numpy.array.
- Return type:
if New_field is True
- remove_phase(sign=False, matrix=False, new_field=False)[source]
Removes the phase of the field. Amplitude is kept.
- Parameters:
sign (bool) – If True, sign is kept, else, it is removed
matrix (bool) – if True numpy.matrix is returned
new_field (bool) – if True it returns a new Scalar_field_XY
- Returns:
Scalar_field_X. if Matrix is True: numpy.array.
- Return type:
if New_field is True
- binarize(kind='amplitude', bin_level=None, level0=None, level1=None, new_field=False, matrix=False)[source]
Changes the number of points in field, mantaining the area.
- Parameters:
kind (str) – ‘amplitude’ or ‘phase’
bin_level (float) – value of cut. If None, the cut is in the mean value
level0 (float) – minimum value. If None, minimum value of field
level1 (float) – maximum value. If None, maximum value of field
new_field (bool) – if True returns new field
matrix (bool) – if True it returs a matrix
- Returns:
if new_field is True returns Scalar_field_XY
- Return type:
TODO: Check and pass to utils
- discretize(kind='amplitude', num_levels=2, factor=1, phaseInicial=0, new_field=True, matrix=False)[source]
Discretize in a number of levels equal to num_levels.
- Parameters:
kind (str) – “amplitude” o “phase”
num_levels (int) – number of levels for the discretization
factor (float) – from the level, how area is binarized. if 1 everything is binarized,
phaseInicial (float) –
new_field (bool) – if True returns new field
matrix (bool) – if True it returs a matrix
- Returns:
if new_field is True returns Scalar_field_XY
- Return type:
TODO: Check and pass to utils
- normalize(new_field=False)[source]
Normalizes the field so that intensity.max()=1.
- Parameters:
new_field (bool) – If False the computation goes to self.u. If True a new instance is produced
- Returns
u (numpy.array): normalized optical field
- get_RS_minimum_z(n=1, quality=1, verbose=True)[source]
Determines the minimum available distance for RS algorithm. If higher or lower quality parameters is required you can add as a parameter
- Parameters:
n (float) – refraction index of the surrounding medium.
quality (int, optional) – quality. Defaults to 1.
verbose (bool, optional) – prints info. Defaults to True.
- Returns:
z_min for quality_factor>quality
- Return type:
z_min (float)
- draw(kind='intensity', logarithm=False, normalize=False, title='', filename='', cut_value=None, has_colorbar='', colormap_kind='', reduce_matrix='standard', percentage_intensity=None, **kwargs)[source]
Draws XY field.
- Parameters:
kind (str) – type of drawing: ‘amplitude’, ‘intensity’, ‘phase’, ‘ ‘field’, ‘real_field’, ‘contour’
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (str) – False, ‘maximum’, ‘area’, ‘intensity’
title (str) – title for the drawing
filename (str) – if not ‘’ stores drawing in file,
cut_value (float) – if provided, maximum value to show
has_colorbar (bool) – if True draws the colorbar
percentage_intensity (None or number) – If None it takes from CONF_DRAWING[‘percentage_intensity’], else uses this value
reduce_matrix (str) – ‘standard’
- diffractio.scalar_fields_XY.kernelRS(X, Y, wavelength, z, n=1, kind='z')[source]
Kernel for RS propagation.
- Parameters:
X (numpy.array) – positions x
Y (numpy.array) – positions y
wavelength (float) – wavelength of incident fields
z (float) – distance for propagation
n (float) – refraction index of background
kind (str) – ‘z’, ‘x’, ‘0’: for simplifying vector propagation
- Returns:
kernel
- Return type:
complex np.array
- diffractio.scalar_fields_XY.kernelRSinverse(X, Y, wavelength=0.6328, z=-10000.0, n=1, kind='z')[source]
Kernel for inverse RS propagation
- Parameters:
X (numpy.array) – positions x
Y (numpy.array) – positions y
wavelength (float) – wavelength of incident fields
z (float) – distance for propagation
n (float) – refraction index of background
kind (str) – ‘z’, ‘x’, ‘0’: for simplifying vector propagation
- Returns:
kernel
- Return type:
complex np.array
- diffractio.scalar_fields_XY.kernelFresnel(X, Y, wavelength=0.6328, z=10000.0, n=1)[source]
Kernel for Fesnel propagation.
- Parameters:
X (numpy.array) – positions x
Y (numpy.array) – positions y
wavelength (float) – wavelength of incident fields
z (float) – distance for propagation
n (float) – refraction index of background
- Returns:
kernel
- Return type:
complex np.array
- diffractio.scalar_fields_XY.PWD_kernel(u, n, k0, k_perp2, dz)[source]
Step for scalar(TE) Plane wave decomposition(PWD) algorithm.
- Parameters:
u (np.array) – field
n (np.array) – refraction index
k0 (float) – wavenumber
k_perp (np.array) – transversal k
dz (float) – increment in distances
- Returns:
Field at at distance dz from the incident field
- Return type:
(numpy.array)
References
Schmidt, S. et al. Wave - optical modeling beyond the thin - element - approximation. Opt. Express 24, 30188 (2016).
- diffractio.scalar_fields_XY.WPM_schmidt_kernel(u, n, k0, k_perp2, dz)[source]
Kernel for fast propagation of WPM method
- Parameters:
u (np.array) – fields
n (np.array) – refraction index
k0 (float) – wavenumber
k_perp2 (np.array) – transversal k**2
dz (float) – increment in distances
References
Fertig and K.-H. Brenner, “Vector wave propagation method,” J. Opt. Soc. Am. A, vol. 27, no. 4, p. 709, 2010.
Schmidt et al., “Wave-optical modeling beyond the thin-element-approximation,” Opt. Express, vol. 24, no. 26, p. 30188, 2016.
- diffractio.scalar_fields_XY.get_RS_minimum_z(range_x, range_y, num_x, num_y, wavelength, n=1, quality=1, verbose=True)[source]
_summary_
- Parameters:
range_x (float) – range_x
range_y (float) – range_y
num_x (int) – num_x
num_y (int) – num_y
z (float) – z
wavelength (float) – wavelength
quality (int, optional) – quality. Defaults to 1.
verbose (bool, optional) – prints info. Defaults to True.
- Returns:
z_min for quality_factor>quality
- Return type:
z_min (float)
- diffractio.scalar_fields_XY.quality_factor(range_x, range_y, num_x, num_y, z, wavelength, n=1, verbose=False)[source]
Determine the quality factor for RS algorithm
- Parameters:
x (np.array) – x array with positions
y (np.array) – y array with positions
z (float) – observation distance
wavelength (float) – wavelength)
n (float) – refraction index
- Returns:
_description_
- Return type:
_type_
4.1.5. diffractio.scalar_fields_XYZ module
This module generates Scalar_field_XYZ class and several functions for multiprocessing. It is required also for generating masks and fields. The main atributes are:
self.u - field XYZ
self.x - x positions of the field
self.y - y positions of the fieldalgorithm
self.z - z positions of the field
self.wavelength - wavelength of the incident field. The field is monochromatic
self.u0 - initial field at z=z0
self.n_background - background refraction index
self.n - refraction index
The magnitude is related to microns: micron = 1.
Class for unidimensional scalar fields
- Definition of a scalar field
instantiation, duplicate
load and save data
to_Scalar_field_XY
xy_2_xyz
cut_function
__rotate__
__rotate_axis__
- Propagation
RS - Rayleigh Sommerfeld
RS_amplification
BPM - Beam Propagation method
- Drawing functions
draw_XYZ
draw_XY
draw_XZ
draw_volume
draw_refractive_index
video
- class diffractio.scalar_fields_XYZ.Scalar_field_XYZ(x=None, y=None, z=None, wavelength=None, n_background=1.0, info='')[source]
Bases:
object
Class for 3D scalar fields.
- Parameters:
u0 (Scalar_field_XY) – Initial scalar field. wavelength, and x, y arrays are obtained from this field.
z (numpy.array) – linear array with equidistant positions.
n_background (float) – refraction index of background
info (str) – String with info about the simulation
- self.x
linear array with equidistant positions. The number of data is preferibly \(2^n\) .
- Type:
numpy.array
- self.y
linear array with equidistant positions. The number of data is preferibly \(2^n\) .
- Type:
numpy.array
- self.z
linear array with equidistant positions. The number of data is preferibly \(2^n\) .
- Type:
numpy.array
- self.u
equal size than X. complex field
- Type:
numpy.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.u0
Initial XY field
- Type:
- self.n_background
background refraction index.
- Type:
float
- self.n
refraction index. Same dimensions than self.u.
- Type:
numpy.array
- xy_2_xyz(u0_XY, z)[source]
Similar to Init. send a Scalarfield_XY and passes to XYZ.
- Parameters:
u0_XY (Scalar_field_XY) – init field
z (numpy.array) – array with z positions
- normalize(new_field=False)[source]
Normalizes the field so that intensity.max()=1.
- Parameters:
new_field (bool) – If False the computation goes to self.u. If True a new instance is produced
- Returns
u (numpy.array): normalized optical field
- reduce_to_1()[source]
All the values greater than 1 pass to 1. This is used for Scalar_masks when we add two masks.
- save_data(filename, add_name='', description='', verbose=False)[source]
Common save data function to be used in all the modules. The methods included are: npz, matlab
- Parameters:
filename (str) – filename
add_name= (str) – sufix to the name, if ‘date’ includes a date
description (str) – text to be stored in the dictionary to save.
verbose (bool) – If verbose prints filename.
- Returns:
filename. If False, file could not be saved.
- Return type:
(str)
- load_data(filename, verbose=False)[source]
- Load data from a file to a Scalar_field_XZ.
The methods included are: npz, matlab
- Parameters:
filename (str) – filename
verbose (bool) – shows data process by screen
- cut_resample(x_limits='', y_limits='', z_limits='', num_points=[], new_field=False, interp_kind=(3, 1))[source]
it cut the field to the range (x0,x1). If one of this x0,x1 positions is out of the self.x range it do nothing. It is also valid for resampling the field, just write x0,x1 as the limits of self.x
- Parameters:
x_limits (float,float) – (x0,x1) starting and final points to cut, if ‘’ - takes the current limit x[0] and x[-1]
y_limits (float,float) – (y0,y1) - starting and final points to cut, if ‘’ - takes the current limit y[0] and z[-1]
num_points (int) – it resamples x, y and u, where [],’’,0,None -> it leave the points as it is new_field (bool): it returns a new Scalar_field_XY
interp_kind – numbers between 1 and 5
- incident_field(u0, z0=None)[source]
Incident field for the experiment. It takes a Scalar_source_XYZ field.
- Parameters:
u0 (Scalar_source_X) – field produced by Scalar_source_XYZ (or a XYZ field)
z0 (float) – position of the incident field. if None, ‘’, [], is at the beginning
- RS(verbose=False, num_processors=0)[source]
Rayleigh Sommerfeld propagation algorithm
- Parameters:
verbose (bool) – shows the quality of algorithm (>1 good)
num_processors (int) – number of processors for multiprocessing
- Returns:
time in the processing
- RS_amplification(amplification=(1, 1))[source]
Rayleigh Sommerfeld propagation algorithm. it performs amplification
- Parameters:
amplification (int,int) – number of fields
- Return type:
- BPM(has_edges=True, pow_edge=80, verbose=False)[source]
3D Beam propagation method (BPM).
- Parameters:
has_edges (bool) – If True absorbing edges are used.
pow_edge (float) – If has_edges, power of the supergaussian
verbose (bool) – shows data process by screen
References
Algorithm in “Engineering optics with matlab” pag 119
- PWD(n=None, matrix=False, verbose=False)[source]
Plane wave decompostion algorithm.
- Parameters:
n (np. array) – refraction index, If None, it is n_background
verbose (bool) – If True prints state of algorithm
- Returns:
Field at at distance dz from the incident field
- Return type:
numpy.array()
References
Schmidt, S. et al. Wave-optical modeling beyond the thin-element-approximation. Opt. Express 24, 30188 (2016).
- WPM(has_edges=True, pow_edge=80, verbose=False)[source]
WPM Methods. ‘schmidt method is very fast, only needs discrete number of refraction indexes’
- Parameters:
has_edges (bool) – If True absorbing edges are used.
pow_edge (float) – If has_edges, power of the supergaussian
verbose (bool) – If True prints information
References
Fertig and K.-H. Brenner, “Vector wave propagation method,” J. Opt. Soc. Am. A, vol. 27, no. 4, p. 709, 2010.
Schmidt et al., “Wave-optical modeling beyond the thin-element-approximation,” Opt. Express, vol. 24, no. 26, p. 30188, 2016.
- to_Scalar_field_XY(iz0=None, z0=None, is_class=True, matrix=False)[source]
pass results to Scalar_field_XY. Only one of the first two variables (iz0,z0) should be used
- Parameters:
iz0 (int) – position i of z data in array
z0 (float) – position z to extract
is_class (bool) – If True it returns a class
matrix (bool) – If True it returns a matrix
- to_Scalar_field_XZ(iy0=None, y0=None, is_class=True, matrix=False)[source]
pass results to Scalar_field_XZ. Only one of the first two variables (iy0,y0) should be used
- Parameters:
iy0 (int) – position i of y data in array
y0 (float) – position y to extract
class (bool) – If True it returns a class
matrix (bool) – If True it returns a matrix
- to_Scalar_field_YZ(ix0=None, x0=None, is_class=True, matrix=False)[source]
pass results to Scalar_field_XZ. Only one of the first two variables (iy0,y0) should be used
- Parameters:
ix0 (int) – position i of x data in array
x0 (float) – position x to extract
class (bool) – If True it returns a class
matrix (bool) – If True it returns a matrix
- to_Z(kind='amplitude', x0=None, y0=None, has_draw=True, z_scale='mm')[source]
pass results to u(z). Only one of the first two variables (iy0,y0) and (ix0,x0) should be used.
- Parameters:
kind (str) – ‘amplitude’, ‘intensity’, ‘phase’
x0 (float) – position x to extract
y0 (float) – position y to extract
has_draw (bool) – draw the field
z_scale (str) – ‘mm’, ‘um’
- Returns:
array with z field (numpy.array): amplitude, intensity or phase of the field
- Return type:
z (numpy.array)
- average_intensity(has_draw=False)[source]
Returns average intensity as: (np.abs(self.u)**2).mean()
- Parameters:
verbose (bool) – If True prints data.
- Returns:
z array with average intensity at each plane z.
- Return type:
intensity_mean (np.array)
- beam_widths(kind='FWHM2D', has_draw=[True, False], percentage=0.5, remove_background=None, verbose=False)[source]
Determines the widths of the beam
- Parameters:
kind (str) – kind of algorithm: ‘sigma4’, ‘FWHM2D’
has_draw (bool, bool) – First for complete analysis, second for all FWHM2D computations
verbose (bool) – prints info
- Returns:
beam_width_x (np.array) beam_width_y (np.array) principal_axis_z (np.array)
- surface_detection(mode=1, min_incr=0.01, has_draw=False)[source]
detect edges of variation in refraction index
- Parameters:
min_incr (float) – minimum incremental variation to detect.
has_draw (bool) – if True, it draws the surface.
- draw_proposal(kind='intensity', logarithm=0, normalize='maximum', draw_borders=False, filename='', scale='', min_incr=0.0005, reduce_matrix='standard', colorbar_kind=False, colormap_kind='gist_heat')[source]
Draws XYZ field.
- Parameters:
kind (str) – type of drawing: ‘amplitude’, ‘intensity’, ‘phase’, ‘real’
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (bool) – If True, max(intensity)=1
draw_borders (bool) – If True draw edges of objects
filename (str) – if not ‘’ stores drawing in file,
scale (str) – ‘’, ‘scaled’, ‘equal’, scales the XY drawing
min_incr – incrimum increment in refraction index for detecting edges
reduce_matrix (int, int) – when matrix is enormous, we can reduce it only for drawing purposes. If True, reduction factor
- draw_XY(z0=5000.0, kind='intensity', logarithm=0, normalize='maximum', title='', filename='', cut_value='', has_colorbar='False', reduce_matrix='')[source]
longitudinal profile XY at a given z value
- Parameters:
z0 (float) – value of z for interpolation
kind (str) – type of drawing: ‘amplitude’, ‘intensity’, ‘phase’, ‘ ‘field’, ‘real_field’, ‘contour’
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (str) – False, ‘maximum’, ‘area’, ‘intensity’
title (str) – title for the drawing
filename (str) – if not ‘’ stores drawing in file,
cut_value (float) – if provided, maximum value to show
has_colorbar (bool) – if True draws the colorbar
() (reduce_matrix) –
- draw_XZ(kind='intensity', y0=0.0, logarithm=0, normalize='', draw_borders=False, filename='', **kwargs)[source]
Longitudinal profile XZ at a given x0 value.
- Parameters:
y0 (float) – value of y for interpolation
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (str) – False, ‘maximum’, ‘intensity’, ‘area’
draw_borders (bool) – check
filename (str) – filename to save
- draw_YZ(x0=0.0, logarithm=0, normalize='', draw_borders=False, filename='')[source]
Longitudinal profile YZ at a given x0 value.
- Parameters:
x0 (float) – value of x for interpolation
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (str) – False, ‘maximum’, ‘intensity’, ‘area’
draw_borders (bool) – check
filename (str) – filename to save
- draw_XYZ_deprecated(kind='intensity', logarithm=False, normalize='', pixel_size=(128, 128, 128))[source]
Draws XZ field.
- Parameters:
kind (str) – type of drawing: ‘intensity’, ‘phase’, ‘real_field’
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (bool) – If True, max(intensity)=1
pixel_size (float, float, float) – pixels for drawing
- draw_volume_deprecated(logarithm=0, normalize='', maxintensity=None)[source]
Draws XYZ field with mlab
- Parameters:
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (bool) – If True, max(intensity)=1
maxintensity (float) – maximum value of intensity
- TODO: Simplify, drawing
include kind and other parameters of draw
- draw_refractive_index_deprecated(kind='real')[source]
Draws XYZ refraction index with slicer
- Parameters:
kind (str) – ‘real’, ‘imag’, ‘abs’
- video(filename='', kind='intensity', fps=15, frame=True, axis='auto', verbose=False, directory_name='new_video')[source]
Makes a video in the range given by self.z.
- Parameters:
filename (str) – filename (.avi, .mp4)
kind (str) – type of drawing: ‘intensity’, ‘phase’.
fps (int) – frames per second
frame (bool) – figure with or without axis.
verbose (bool) – If True prints
TODO: include logarithm and normalize
4.1.6. diffractio.scalar_fields_XZ module
This module generates Scalar_field_XZ class.
It includes multiprocessing for RS and BPM polychromatic
It can be considered an extension of Scalar_field_X for visualizing XZ fields
For the case of Rayleigh sommefeld it is not necessary to compute all z positions but the final.
Nevertheless, for BPM method, intermediate computations are required. In this class, intermediate results are stored.
X,Z fields are defined using ndgrid (not with meshgrid, it is different).
It is required also for generating masks and fields. The main atributes are:
self.x - x positions of the field
self.z - z positions of the field
self.u - field XZ
self.n - refraction index XZ
self.wavelength - wavelength of the incident field. The field is monochromatic
The magnitude is related to microns: micron = 1.
Class for XZ scalar fields
- Definition of a scalar field
instatiation, duplicate, clean_refractive_index
save, load data
rotate_field, cut_resample,
- Illumination
incident_field
- Operations
surface_detection
search focus
- Propagation
RS, RS_polychormatic,
BPM, BPM_poychromatic, BPM_inverse, BPM_back_propagation
- Drawing functions
draw
draw_refractive_index
draw_incident_field
draw_profiles_interactive
video
- Parameters
final_field
profile_longitudinal
profile_transversal
- class diffractio.scalar_fields_XZ.Scalar_field_XZ(x=None, z=None, wavelength=None, n_background=1, info='')[source]
Bases:
object
Class for working with XZ scalar fields.
- Parameters:
x (numpy.array) – linear array with equidistant positions. The number of data is preferibly \(2^n\) .
z (numpy.array) – linear array wit equidistant positions for z values
wavelength (float) – wavelength of the incident field
n_background (float) – refraction index of background
info (str) – String with info about the simulation
- self.x
linear array with equidistant positions. The number of data is preferibly \(2^n\) .
- Type:
numpy.array
- self.z
linear array wit equidistant positions for z values
- Type:
numpy.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.u0
size x - field at the last z position
- Type:
numpy.array
- self.u
(x,z) complex field
- Type:
numpy.array
- self.n_background
(x,z) refraction index
- Type:
numpy.array
- self.fast
if True fast algoritm (approx. Hankle function)
- Type:
bool
- self.info
String with info about the simulation
- Type:
str
- reduce_to_1()[source]
All the values greater than 1 pass to 1. This is used for Scalar_masks when we add two masks.
- refractive_index_from_scalar_mask_XY(mask_XY, refractive_index_max)[source]
- Transforms XY mask into XZ mask.
Areas with value 0 pass to n_background.
When transmittance of mask_XY is 1, pass to refractive_index_max.
- Parameters:
mask_XY (diffractio.Scalar_mask_XY) – mask
refractive_index_max (float) – real and imaginary part of maximum refraction index.
- Returns:
_description_
- Return type:
_type_
- rotate_field(angle, center_rotation, kind='all', n_background=1)[source]
Rotate all the image a certain angle
- Parameters:
angle (float) – angle to rotate, in radians
n_background (float) – refraction index of zone incoming
kind (str) – ‘all’, ‘n’, ‘field’
center_rotation (float, float) – (z,x) position for rotation
- normalize(new_field=False)[source]
Normalizes the field so that intensity.max()=1.
- Parameters:
new_field (bool) – If False the computation goes to self.u. If True a new instance is produced
- Returns
u (numpy.array): normalized optical field
- mask_field(size_edge=0)[source]
mask the incident field at the edges, each edge is masked size_edge
- Parameters:
size_edge (float) – size of edges
- smooth_refractive_index(type_filter=2, pixels_filtering=10, max_diff_filter=0.1, draw_check=False)[source]
Technique to remove artifacts in BPM propagation.
- Parameters:
type_filter (int) – 1 - 2D, 2 - 1D z (selective), 3 - 1D x (selective)
pixels_filtering (int) – num_pixels used for filtering
max_diff_filter (float) – maximum difference of n in profile between two adjancted pixels to use selective filtering
draw_check (bool) – draw the differences.
- Returns:
percentage_filtered (np.array): lineas_filtradas
- Return type:
(float)
References
Robert McLeod “Numerical Methods in Photonics Lecture Notes” University of Colorado at Boulder, pag 204 (15/54)
- save_data(filename, add_name='', description='', verbose=False)[source]
Common save data function to be used in all the modules. The methods included are: npz, matlab
- Parameters:
filename (str) – filename
add_name= (str) – sufix to the name, if ‘date’ includes a date
description (str) – text to be stored in the dictionary to save.
verbose (bool) – If verbose prints filename.
- Returns:
filename. If False, file could not be saved.
- Return type:
(str)
- load_data(filename, verbose=False)[source]
- Load data from a file to a Scalar_field_XZ.
The methods included are: npz, matlab
- Parameters:
filename (str) – filename
verbose (bool) – shows data process by screen
- cut_resample(x_limits='', z_limits='', num_points=[], new_field=False, interp_kind=(3, 1))[source]
it cut the field to the range (x0,x1). if one of this x0,x1 positions is out of the self.x range it do nothing. It is also valid for resampling the field, just write x0,x1 as the limits of self.x
- Parameters:
x_limits (float,float) – (x0,x1) starting and final points to cut. if ‘’ - takes the current limit x[0] and x[-1]
z_limits (float,float) – (z0,z1) - starting and final points to cut. if ‘’ - takes the current limit z[0] and z[-1]
num_points (int) – it resamples x, z and u. ([],’’,0,None) -> it leave the points as it is
new_field (bool) – it returns a new Scalar_field_XZ
interp_kind – numbers between 1 and 5
- incident_field(u0, z0=None)[source]
Incident field for the experiment. It takes a Scalar_source_X field
- Parameters:
u0 (Scalar_source_X) – field produced by Scalar_source_X (or a X field)
z0 (float) – position of the incident field. if None, ‘’, [], is at the beginning
- BPM(has_edges=True, pow_edge=80, division=False, matrix=False, verbose=False)[source]
Beam propagation method (BPM).
- Parameters:
has_edges (bool or np.array) – If True absorbing edges are used. If np.array, they are 0 or 1 depending if at this z position filtering is performed.
pow_edge (float) – If has_edges, power of the supergaussian
division (False, int) – If False nothing, else divides the BPM algorithm in several different executions. To avoid RAM problems
matrix (bool) – if True returns a matrix else
verbose (bool) – shows data process by screen
References: Algorithm in “Engineering optics with matlab” pag 119.
- BPM_inverse(verbose=False)[source]
Beam propagation method (BPM) in inverse mode.
- Parameters:
verbose (bool) – shows data process by screen
References
Algorithm in “Engineering optics with matlab” pag 119
- BPM_back_propagation(verbose=False)[source]
Beam propagation method (BPM). The field that generates the final field is obtained.
- Parameters:
verbose (bool) – shows data process by screen
References
Algorithm in “Engineering optics with matlab” pag 119
- RS(xout=None, verbose=False, num_processors=2)[source]
Rayleigh Sommerfeld propagation algorithm
- Parameters:
xout (float) – init position of output position
verbose (bool) – shows the quality of algorithm (>1 good)
num_processors (int) – number of processors for multiprocessing
- Returns:
time in the processing
- PWD(n=None, matrix=False, verbose=False)[source]
Plane wave decomposition algorithm (PWD).
- Parameters:
n (np. array) – refraction index, If None, it is n_background
matrix (bool) – if True returns a matrix else
verbose (bool) – If True prints state of algorithm
- Returns:
Field at at distance dz from the incident field
- Return type:
numpy.array()
References
Schmidt, S. et al. Wave-optical modeling beyond the thin-element-approximation. Opt. Express 24, 30188 (2016).
- WPM(kind='schmidt', has_edges=True, pow_edge=80, matrix=False, verbose=False)[source]
WPM Method. ‘schmidt method is very fast, only needs discrete number of refraction indexes’
- Parameters:
kind (str) – ‘schmidt’, ‘scalar’
has_edges (bool) – If True absorbing edges are used.
pow_edge (float) – If has_edges, power of the supergaussian
matrix (bool) – if True returns a matrix else
verbose (bool) – If True prints information
References
Fertig and K.-H. Brenner, “Vector wave propagation method,” J. Opt. Soc. Am. A, vol. 27, no. 4, p. 709, 2010.
Schmidt et al., “Wave-optical modeling beyond the thin-element-approximation,” Opt. Express, vol. 24, no. 26, p. 30188, 2016.
- RS_polychromatic(initial_field, wavelengths, spectrum='', verbose=False, num_processors=2)[source]
Rayleigh Sommerfeld propagation algorithm for polychromatic light.
- Parameters:
initial_field (Scalar_field_X) – function with only input variable wavelength
wavelengths (numpy.array) – array with wavelengths
spectrum (numpy.array) – array with spectrum. if ‘’ then uniform_spectrum
verbose (bool) – shows the quality of algorithm (>1 good)
num_processors (int) – number of processors for multiprocessing
- Returns:
self.u=sqrt(Intensities) - no phase is stored, only intensity
- Return type:
- BPM_polychromatic(initial_field, wavelengths, spectrum, verbose=False, num_processors=4)[source]
Rayleigh Sommerfeld propagation algorithm for polychromatic light
- Parameters:
initial_field (Scalar_field_X) – function with only input variable wavelength
wavelengths (numpy.array) – array with wavelengths
spectrum (numpy.array) – array with spectrum. if ‘’ then uniform_spectrum
verbose (bool) – shows the quality of algorithm (>1 good)
num_processors (int) – number of processors for multiprocessing
- Returns:
self.u=sqrt(Intensities) - no phase is stored, only intensity
- Return type:
- fast_propagation(mask_xz, num_pixels_slice=1024, verbose=False)[source]
combines RS and BPM”” to generate the final field
- Parameters:
mask_xz (Scalar_mask_XZ) – function that returns Scalar_mask_XZ
num_pixels_slice (int) – num of slices for each BPM propagation
verbose (bool) – If True prints info.
- Returns:
u_current, fields_BPM, transitions
- intensity()[source]
Returns the intensity of the field
- Returns:
intensity of the field.
- Return type:
(np.array)
- average_intensity(has_draw=False)[source]
Returns average intensity as: (np.abs(self.u)**2).mean()
- Parameters:
has_draw (bool) – If True draws data.
- Returns:
z array with average intensity at each plane z.
- Return type:
intensity_mean (np.array)
- check_intensity(draw=True, normalized=True)[source]
Checks that intensity distribution is not lost by edges. It can be executed after a RS or BPM propagation.
- Parameters:
draw (bool) – Draws the intensity
normalized (bool) – Draws it normalized
- Returns:
array with intensity I(z)
- Return type:
(np.array)
- detect_index_variations(n_edge, incr_n=0.1)[source]
In a XZ masks, detects refraction index variations.
- Parameteres:
n_edge (float): incr_n (float): refraction index variation to detect
- Returns:
x for left edge. h_lens_l (np.array): h for left edge. x_lens_r (np.array): x for right edge. h_lens_r (np.array): h for right edge.
- Return type:
x_lens_l (np.array)
- surface_detection(mode=1, min_incr=0.1, reduce_matrix='standard', has_draw=False)[source]
detect edges of variation in refraction index.
- Parameters:
mode (int) – 1 or 2, algorithms for surface detection: 1-gradient, 2-diff
min_incr (float) – minimum incremental variation to detect
reduce_matrix (int, int) – when matrix is enormous, we can reduce it only for drawing purposes. If True, reduction factor
has_draw (bool) – If True draw.
- draw(kind='intensity', logarithm=0, normalize='', draw_borders=False, filename='', scale='', min_incr=0.0005, reduce_matrix='standard', colorbar_kind=False, colormap_kind='', z_scale='um', edge_matrix=None, interpolation='spline36', percentage_intensity=None, **kwargs)[source]
Draws XZ field.
- Parameters:
kind (str) – type of drawing: ‘amplitude’, ‘intensity’, ‘phase’, ‘real’
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (bool) – If True, max(intensity)=1
draw_borders (bool) – If True draw edges of objects
filename (str) – if not ‘’ stores drawing in file,
scale (str) – ‘’, ‘scaled’, ‘equal’, scales the XY drawing
min_incr – incrimum increment in refraction index for detecting edges
reduce_matrix (int, int) – when matrix is enormous, we can reduce it only for drawing purposes. If True, reduction factor
z_scale (str) – ‘mm’, ‘um’
edge_matrix (numpy.array) – positions of borders
interpolation (str) – methods = [None, ‘none’, ‘nearest’, ‘bilinear’, ‘bicubic’, ‘spline16’, ‘spline36’, ‘hanning’, ‘hamming’, ‘hermite’, ‘kaiser’, ‘quadric’, ‘catrom’, ‘gaussian’, ‘bessel’, ‘mitchell’, ‘sinc’, ‘lanczos’]
percentage_intensity (None or number) – If None it takes from CONF_DRAWING[‘percentage_intensity’], else uses this value
- draw_refractive_index(kind='all', draw_borders=True, title='', filename='', scale='', min_incr=0.01, reduce_matrix='standard', colorbar_kind=None, colormap_kind=<matplotlib.colors.LinearSegmentedColormap object>, edge_matrix=None)[source]
Draws refraction index.
- Parameters:
kind (str) – ‘all’, ‘real’, ‘imag’
draw_borders (bool) – If True draw edges of objects
filename (str) – if not ‘’ stores drawing in file,
title (str) – title of drawing
scale (str) – ‘’, ‘scaled’, ‘equal’, scales the XY drawing
min_incr – minimum increment in refraction index for detecting edges
reduce_matrix (int, int) – when matrix is enormous, we can reduce it only for drawing purposes. If True, reduction factor
edge_matrix (numpy.array) – positions of borders
- draw_incident_field(kind='intensity', logarithm=False, normalize=False, filename='')[source]
Draws incident field self.u0
- Parameters:
kind (str) – type of drawing: ‘amplitude’, ‘intensity’, ‘field’, ‘phase’, ‘fill’, ‘fft’
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (bool) – If True, max(intensity)=1
filename (str) – if not ‘’ stores drawing in file,
- profile_longitudinal(kind='intensity', x0=0.0, logarithm=False, normalize=False, z_scale='um', draw=True, filename='')[source]
Determine and draws longitudinal profile
- Parameters:
kind (str) – type of drawing: ‘amplitude’, ‘intensity’, ‘phase’, ‘refractive_index’
x0 (float) – profile that passes through x=x0
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (str) – False, ‘maximum’, ‘intensity’, ‘area’
draw (bool) – If True, draws, False only returns profile
filename (str) – if not ‘’ stores drawing in file
- Returns:
profile
- Return type:
numpy.array
- profile_transversal(kind='intensity', z0=0.0, logarithm=False, normalize=False, draw=True, filename='')[source]
Determine and draws transversal profile.
- Parameters:
kind (str) – type of drawing: ‘amplitude’, ‘intensity’, ‘phase’, ‘refractive_index’
z0 (float) – profile that passes through z=z0
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (str) – False, ‘maximum’, ‘intensity’, ‘area’
draw (bool) – If True, draws, False only returns profile
filename (str) – if not ‘’ stores drawing in file,
- Returns:
profile
- Return type:
numpy.array
TODO: Include interpolation
- search_focus(verbose=True)[source]
Search for location of maximum.
- Parameters:
kind (str) – type of drawing: ‘amplitude’, ‘intensity’, ‘phase’, ‘refractive_index’
x0 (float) – profile that passes through x=x0
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (str) – False, ‘maximum’, ‘intensity’, ‘area’
draw (bool) – If True, draws, False only returns profile
filename (str) – if not ‘’ stores drawing in file,
- Returns:
positions of focus
- Return type:
(x,z)
- beam_widths(kind='FWHM1D', has_draw=[True, False], z_scale='um', percentage=0.5, remove_background=None, verbose=False)[source]
Computes the beam width for all the distances z. :param kind: kind of algorithm: ‘sigma4’, ‘FWHM1D’ :type kind: str :param has_draw: First for complete analysis, second for all FWHM2D computations :type has_draw: bool, bool :param percentage: (0-1) percentage for the beam detection :type percentage: float :param remove_background=None: :param : :param verbose: prints info :type verbose: bool
- Returns:
for each distance z (numpy.array) positions_center: positions of centers for each z
- Return type:
(numpy.array) widths
- video(kind='intensity', z_min=None, z_max=None, logarithm=False, normalize=False, time_video=10.0, frames_reduction=5, filename='video.avi', dpi=100)[source]
Generates a video in the z dimension.
- Parameters:
kind (str) –
z_min (float) –
z_max (float) –
logarithm (bool) –
normalize (bool) –
time_video (float) –
frames_reduction (int) –
filename (str) –
dpi (int) –
4.1.7. diffractio.scalar_fields_Z module
This module generates Scalar_field_Z class
- The main atributes are:
self.z (numpy.array): linear array with equidistant positions. The number of data is preferibly \(2^n\) .
self.wavelength (float): wavelength of the incident field.
self.u (numpy.array): equal size than x. complex field
- There are also some secondary atributes:
self.quality (float): quality of RS algorithm
self.info (str): description of data
self.type (str): Class of the field
self.date (str): date
Class for unidimensional scalar fields
- Definition of a scalar field
instantiation, duplicate, clear_field, print
save and load data
- Drawing functions
draw
- Parameters:
intensity, average intensity
get_edges_transitions (mainly for pylithography)
- class diffractio.scalar_fields_Z.Scalar_field_Z(z=None, wavelength=None, n_background=1, info='')[source]
Bases:
object
Class for unidimensional scalar fields in z axis.
- Parameters:
z (numpy.array) – linear array with equidistant positions.
wavelength (float) – wavelength of the incident field
n_background (float) – refraction index of background
info (str) – String with info about the simulation
- self.z
Linear array with equidistant positions. The number of data is preferibly \(2^n\).
- Type:
numpy.array
- self.wavelength
Wavelength of the incident field.
- Type:
float
- self.u
Complex field. The size is equal to self.z.
- Type:
numpy.array
- self.quality
Quality of RS algorithm.
- Type:
float
- self.info
Description of data.
- Type:
str
- self.type
Class of the field.
- Type:
str
- self.date
Date when performed.
- Type:
str
- save_data(filename, add_name='', description='', verbose=False)[source]
Common save data function to be used in all the modules. The methods included are: npz, matlab
- Parameters:
filename (str) – filename
add_name= (str) – sufix to the name, if ‘date’ includes a date
description (str) – text to be stored in the dictionary to save.
verbose (bool) – If verbose prints filename.
- Returns:
filename. If False, file could not be saved.
- Return type:
(str)
- load_data(filename, verbose=False)[source]
- Load data from a file to a Scalar_field_X.
The methods included are: npz, matlab
- Parameters:
filename (str) – filename
verbose (bool) – shows data process by screen
- cut_resample(z_limits='', num_points=[], new_field=False, interp_kind='linear')[source]
Cuts the field to the range (z0,z1). If one of this z0,z1 positions is out of the self.z range it does nothing. It is also valid for resampling the field, just write z0,z1 as the limits of self.z
- Parameters:
z_limits (numpy.array) – (z0,z1) - starting and final points to cut, if ‘’ - takes the current limit z[0] and z[-1]
num_points (int) – it resamples z, and u [],’’,0,None -> it leave the points as it is
new_field (bool) – if True it returns a new Scalar_field_z
interp_kind (str) – ‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’
- Returns:
if new_field is True
- Return type:
- normalize(new_field=False)[source]
Normalizes the field so that intensity.max()=1.
- Parameters:
new_field (bool) – If False the computation goes to self.u. If True a new instance is produced
- Returns
u (numpy.array): normalized optical field
- average_intensity(verbose=False)[source]
Returns the average intensity as: (np.abs(self.u)**2).sum() / num_data
- Parameters:
verbose (bool) – If True it prints the value of the average intensity.
- Returns:
average intensity.
- Return type:
(float)
- FWHM1D(percentage=0.5, remove_background=None, has_draw=False)[source]
- Parameters:
percentage (float) – value between 0 and 1. 0.5 means that the width is computed at half maximum.
remove_background (str) – ‘min’, ‘mean’, None
has_draw (bool) – If true it draws
- Returns:
width, in this z case: DOF
- Return type:
width (float)
- DOF(percentage=0.5, remove_background=None, has_draw=False)[source]
Determines Depth-of_focus (DOF) in terms of the width at different distances
- Parameters:
percentage (float) – value between 0 and 1. 0.5 means that the width is computed at half maximum.
remove_background (str) – ‘min’, ‘mean’, None
has_draw (bool) – If true it draws
- Returns:
width, in this z case: D
- Return type:
width (float)
References
Saleh and M. C. Teich, Fundamentals of photonics. john Wiley & sons, 2nd ed. 2007. Eqs (3.1-18) (3.1-22) page 79
- Returns:
Depth of focus (float): beam waist (float, float, float): postions (z_min, z_0, z_max) of the depth of focus
- Return type:
(float)
- draw(kind='intensity', logarithm=False, normalize=False, cut_value=None, z_scale='um', unwrap=False, filename='')[source]
Draws z field. There are several data from the field that are extracted, depending of ‘kind’ parameter.
- Parameters:
kind (str) – type of drawing: ‘amplitude’, ‘intensity’, ‘field’, ‘phase’
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (bool) – If True, max(intensity)=1
cut_value (float) – If not None, cuts the maximum intensity to this value
unwrap (bool) – If True, unwraps the phase.
filename (str) – if not ‘’ stores drawing in file,
4.1.8. diffractio.scalar_masks_X module
This module generates Scalar_mask_X class for definingn masks. Its parent is Scalar_field_X.
- The main atributes are:
self.u - field
self.x - x positions of the field
self.wavelength - wavelength of the incident field. The field is monocromatic
Class for unidimensional scalar masks
- Functions
mask_from_function, mask_from_array
slit, double slit
two_levels, gray_scale
prism, biprism_fresnel, biprism_fresnel_nh
lens, lens_spherical, aspheric, fresnel_lens
roughness, dust, dust_different_sizes
sine_grating, ronchi_grating, binary_grating, blazed_grating
chriped_grating, chirped_grating_p, chirped_grating_q
I0s
- class diffractio.scalar_masks_X.Scalar_mask_X(x=None, wavelength=None, n_background=1, info='')[source]
Bases:
Scalar_field_X
Class for unidimensional scalar masks.
- Parameters:
x (numpy.array) – linear array with equidistant positions. The number of data is preferibly \(2^n\) .
wavelength (float) – wavelength of the incident field
n_background (float) – refraction index of background
info (str) – String with info about the simulation
- self.x
linear array with equidistant positions. The number of data is preferibly \(2^n\) .
- Type:
numpy.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.u
equal size than x. complex field
- Type:
numpy.array
- self.quality
quality of RS algorithm
- Type:
float
- self.info
description of data
- Type:
str
- self.type
Class of the field
- Type:
str
- self.date
date when performed
- Type:
str
- filter(mask, new_field=True, binarize=False, normalize=False)[source]
Widens a field using a mask.
- Parameters:
mask (diffractio.Scalar_mask_X) – filter
new_field (bool) – If True, develope new Field
binarize (bool, float) – If False nothing, else binarize in level
normalize (bool) – If True divides the mask by sum:
- mask_from_function(index=1.5, f1=0, f2=0, v_globals={}, x0=0.0, radius=0.0)[source]
Phase mask defined between two surfaces \(f_1\) and \(f_2\): \(h(x,y)=f_2(x,y)-f_1(x,y)\), \(t(x)=mask(x)e^{i\,k\,(n-1)(f_{2}-f_{1})}\)
- Parameters:
index (float) – refraction index of the mask
f1 (str) – first surface
f2 (str) – second surface
v_globals (dict) – variable definitions
mask (bool) – True if a mask is defined to block areas
x0 (float) – center of mask
radius (float) – radius of the mask
- mask_from_array(index=1.5, array1=None, array2=None, interp_kind='quadratic', radius=0.0, x0=0.0)[source]
Phase mask defined between two surfaces defined by arrays: array1 and array2, \(t(x)=mask(x)e^{i\,k\,(n-1)(array2(x,z)-array1(x,z))}\)
- Parameters:
index (float) – refraction index of the mask
array1 (numpy.array) – array of data (x,z) for the first surface
array2 (numpy.array) – array of data (x,z) for the second surface
interp_kind (str) – ‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’
mask (bool) – True if a mask is defined to block areas
x0 (float) – center of mask
radius (float) – radius of the mask
- dots(x0)[source]
Generates 1 or several point masks at positions x0
- Parameters:
np.array (x0 float or) – x point or points where mask is 1.
- slit(x0, size)[source]
Slit: 1 inside, 0 outside
- Parameters:
x0 (float) – center of slit
size (float) – size of slit
- double_slit(x0, size, separation)[source]
double slit: 1 inside, 0 outside
- Parameters:
x0 (float) – center of slit
size (float) – size of slit
separation (float) – separation between slit centers
- two_levels(level1=0, level2=1, x_edge=0)[source]
Divides the image in two levels.
- Parameters:
level1 (float) – value of level1
level2 (float) – value of level2
x_edge (float) – position of separation of levels
- gray_scale(num_levels, levelMin=0, levelMax=1)[source]
Divides the mask in n, vertical levels.
- Parameters:
num_levels (int) – number of levels
levelMin (float) – minimum value of levels
levelMax (float) – maximum value of levels
- prism(x0, n, angle)[source]
Prism.
- Parameters:
x0 (float) – vertex of prism
n (float) – refractive_index
angle (float) – angle of prism
- biprism_fresnel(angle, x0, radius=0)[source]
Fresnel biprism.
- Parameters:
angle (float) – angle of the fresnel biprism
x0 (float) – central position of fresnel biprism
radius (float) – radius of the fresnel biprism, if mask is True
mask (bool) – if True radius is applied
- biprism_fresnel_nh(x0, width, height, n)[source]
Fresnel biprism, uses height and refraction index.
- Parameters:
x0 (float) – vertex of biprism
width (float) – size of biprism
height (float) – height of biprism
n (float) – refractive_index
- lens(x0, focal, radius=0)[source]
Paraxial lens.
- Parameters:
x0 (float) – center of lens
focal (float) – focal length of lens
- lens_spherical(x0, radius, focal, refractive_index=1.5)[source]
Spherical lens, without paraxial approximation. The focal distance and the refraction index are used for the definition. When the refraction index decreases, the radius of curvature decrases and less paraxial.
- Parameters:
r0 (float, float) – (x0,y0) - center of lens
radius (float, float) or (float) – radius of lens mask
focal (float, float) or (float) – focal length of lens
index (refraction) – refraction index of the lens
- aspheric(x0, c, k, a, n0, n1, radius)[source]
Asferic surface. $z = rac{c r^2}{1+sqrt{1-(1+k) c^2 r^2 }}+sum{a_i r^{2i}}$
- Parameters:
x0 (float): position of center c (float): base curvature at vertex, inverse of radius k (float): conic constant a (list): order aspheric coefficients: A4, A6, A8, … n0 (float): refraction index of first medium n1 (float): refraction index of second medium radius (float): radius of aspheric surface
Conic Constant Surface Type k = 0 spherical k = -1 Paraboloid k < -1 Hyperboloid -1 < k < 0 Ellipsoid k > 0 Oblate eliposid
- References:
https://www.edmundoptics.com/knowledge-center/application-notes/optics/all-about-aspheric-lenses/
- fresnel_lens(x0, focal, kind='phase', binary=False, phase=3.141592653589793, radius=0.0)[source]
Fresnel lens. Amplitude phase, continuous or binary.
- Parameters:
x0 (float) – center of lens
focal (float) – focal length of lens
kind (str) – ‘amplitude’ or phase
binary (bool) – binary or profile
phase (float) – if kind==’phase’ -> maximum phase
mask (bool) – if True, mask with size radius
radius (float) – radius of lens mask
- Returns:
heights [0,1] of lens.
- Return type:
h (np.array)
- roughness(t=50.0, s=1.0)[source]
Rough surface, phase
According to movile average (Ogilvy p.224). very good in time for long arrays
- Parameters:
t (float) – correlation lens
s (float) – std of roughness
- Returns:
topography maps in microns
- Return type:
numpy.array
- dust_different_sizes(percentage, size, std=0)[source]
Mask with dust particles of different sizes.
- Parameters:
percentage (float) – percentage of area afected by noise
size (float) – mean size of dust
std (float) – std for size of dust
- Returns:
positions - positions of dust numpy.array: sizes - size of dust float: percentage_real - real percentage of dust
- Return type:
numpy.array
- dust(percentage, size=0)[source]
Mask with dust particles of equal sizes.
- Parameters:
percentage (float) – percentage of area afected by noise
size (float) – size of dust
value (float) – value included when there is noise
- Returns:
positions - positions of dust numpy.array: sizes - size of dust float: percentage_real - real percentage of dust
- Return type:
numpy.array
- sine_grating(x0, period, amp_min=0, amp_max=1)[source]
Sinusoidal grating
- Parameters:
x0 (float) – shift of grating
period (float) – period of the grating
amp_min (float) – minimum amplitude
amp_max (float) – maximum amplitude
- ronchi_grating(x0, period, fill_factor=0.5)[source]
Amplitude binary grating, fill-factor can be defined. It is obtained as a sine_grating that after is binarized. Fill factor is determined as y0=cos(pi*fill_factor)
- Parameters:
x0 (float) – shift of the grating
period (float) – period of the grating
fill_factor (float) – (0,1) - fill factor of grating
- binary_grating(x0, period, fill_factor, amin, amax, phase)[source]
binary grating amplitude and/or phase
- Parameters:
x0 (float) – shift of the grating
period (float) – period of the grating
fill_factor (float) – (0,1) - fill factor of grating
amin (float) – minimum amplitude
amax (float) – maximum amplitude
phase (float) – phase shift (radians)
- blazed_grating(x0, period, phase_max)[source]
Phase, blazed grating. The phase shift is determined by heigth and refraction index.
- Parameters:
x0 (float) – shift of the grating
period (float) – period of the grating
phase_max (float) – maximum_phase_differences
- Returns:
phase for each position
- Return type:
phase (np.array)
- chirped_grating_p(kind, p0, p1, amp_min, amp_max, phase_max, delta_x=0, x0=None, length=0, x_center=0)[source]
Chirped grating with linear p(x) variation.
- Parameters:
kind (str) – ‘amplitude’, ‘phase’, ‘amplitude_binary’, ‘phase_binary’
p0 (float) – initial period of the grating
p1 (float) – final period of the grating
amp_min (float) – minimum transmittance
amp_max (float) – maximum transmittance
phase_max (float) – maximum modulation for phase gratings
delta_x (float) – x shifting for movement of grating
x0 (float) –
length (float) – length of the grating. 0: length is equal to size of x l=(x[-1]-x[0]), <l: it can be shorter than l
x_center (float) – x-position of center of grating
- Returns:
px
- Return type:
numpy.array
- chirped_grating_q(kind, p0, p1, amp_min, amp_max, phase_max, delta_x=0, length=0, x_center=0)[source]
Chirped grating with linear q(x) variation. The transmitance is: t = np.cos(np.pi*q*(x-x0) + np.pi*q0*(x-x0))
- Parameters:
kind (str) – ‘amplitude’, ‘phase’, ‘amplitude_binary’, ‘phase_binary’
p0 (float) – initial period of the grating
p1 (float) – final period of the grating
amp_min (float) – minimum transmittance
amp_max (float) – maximum transmittance
phase_max (float) – maximum modulation for phase gratings
delta_x (float) – x shifting for movement of grating
length (float) – length of the grating, 0: length is equal to size of x l=(x[-1]-x[0]). <l: it can be shorter than l
x_center (float) – x-position of center of grating
- Returns:
qx
- Return type:
numpy.array
- chirped_grating(kind, p_x, x0, amp_min, amp_max, phase_max, delta_x, length=0)[source]
General chirped grating with variation given by function p(x).
- Parameters:
kind (str) – ‘amplitude’, ‘phase’, ‘amplitude_binary’, ‘phase_binary’
p_x (str) – function with variation of periods
amp_min (float) – minimum transmittance
amp_max (float) – maximum transmittance
phase_max (float) – maximum modulation for phase gratings
delta_x (float) – x shifting for movement of grating
length (float) – length of the grating. 0: length is equal to size of x l=(x[-1]-x[0]). <l: it can be shorter than l
- Returns:
p(x)
- Return type:
numpy.array
- binary_code_positions(x_transitions, start='down', has_draw=True)[source]
Genenerates a binary code, using the positions given in x_transitions
- Parameters:
x_transitions (numpy.array) – positions where transitions are placed
start (str) – How the binary code starts:’down’ (starts in 0) or ‘up’ (starts in 1)
has_draw (bool) – If True, draws the code
- binary_code(x0=0.0, kind='standard', code=[1, 1, 0, 0, 1, 0, 1], bit_width=20.0)[source]
Binary code in form of 1’s and 0’s.
- Parameters:
kind (str) – there are serveral types of codes ‘standard’ - normal ‘abs_fag’ - used in some abs encoders
code (numpy.array) – array with values of code
bit_width (float) – size of each data of code
x0 (float) – Initial position
4.1.9. diffractio.scalar_masks_XY module
This module generates Scalar_mask_XY class for definingn masks. Its parent is Scalar_field_X.
- The main atributes are:
self.x - x positions of the field
self.z - z positions of the field
self.u - field XZ
self.n - refraction index XZ
self.wavelength - wavelength of the incident field. The field is monochromatic
The magnitude is related to microns: micron = 1.
Class for unidimensional scalar masks
- Functions
set_amplitude, set_phase
binarize, two_levels, gray_scale
a_dataMatrix
area
save_mask
inverse_amplitude, inverse_phase
widen
image
point_maks, slit, double_slit, square, circle, super_gauss, square_circle, ring, cross
mask_from_function
prism, lens, lens_spherical, aspheric, fresnel_lens
sine_grating, sine_edge_grating ronchi_grating, binary_grating, blazed_grating, forked_grating, grating2D, grating_2D_chess
axicon, axicon_binary, biprism_fresnel,
radial_grating, angular_grating, hyperbolic_grating, archimedes_spiral, laguerre_gauss_spiral
hammer
roughness, circle_rough, ring_rough, fresnel_lens_rough,
- class diffractio.scalar_masks_XY.Scalar_mask_XY(x=None, y=None, wavelength=None, info='')[source]
Bases:
Scalar_field_XY
Class for working with XY scalar masks.
- Parameters:
x (numpy.array) – linear array with equidistant positions. The number of data is preferibly \(2^n\)
y (numpy.array) – linear array with equidistant positions for y values
wavelength (float) – wavelength of the incident field
info (str) – String with info about the simulation
- self.x
linear array with equidistant positions. The number of data is preferibly \(2^n\) .
- Type:
numpy.array
- self.y
linear array wit equidistant positions for y values
- Type:
numpy.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.u
(x,z) complex field
- Type:
numpy.array
- self.info
String with info about the simulation
- Type:
str
- set_amplitude(q=1, positive=0, amp_min=0, amp_max=1)[source]
makes that the mask has only amplitude.
- Parameters:
q (int) – 0 - amplitude as it is and phase is removed. 1 - take phase and convert to amplitude
positive (int) – 0 - value may be positive or negative. 1 - value is only positive
- set_phase(q=1, phase_min=0, phase_max=3.141592653589793)[source]
Makes the mask as phase, q=0: Pass amplitude to 1. q=1: amplitude pass to phase
- area(percentage)[source]
Computes area where mask is not 0
- Parameters:
percentage_maximum (float) – percentage from maximum intensity to compute
- Returns:
area (in um**2)
- Return type:
float
Example
area(percentage=0.001)
- inverse_amplitude(new_field=False)[source]
Inverts the amplitude of the mask, phase is equal as initial
- Parameters:
new_field (bool) – If True it returns a Scalar_mask_XY object, else, it modifies the existing object
- Returns:
If new_field is True, it returns a Scalar_mask_XY object.
- Return type:
- inverse_phase(new_field=False)[source]
Inverts the phase of the mask, amplitude is equal as initial
- Parameters:
new_field (bool) – If True it returns a Scalar_mask_XY object, else, it modifies the existing object
- Returns:
If new_field is True, it returns a Scalar_mask_XY object.
- Return type:
- filter(mask, new_field=True, binarize=False, normalize=False)[source]
Widens a field using a mask
- Parameters:
mask (diffractio.Scalar_mask_XY) – filter
new_field (bool) – If True, develope new Field
binarize (bool, float) – If False nothing, else binarize in level
normalize (bool) – If True divides the mask by sum.
- widen(radius, new_field=True, binarize=True)[source]
Widens a mask using a convolution of a certain radius
- Parameters:
radius (float) – radius of convolution
new_field (bool) – returns a new XY field
binarize (bool) – binarizes result.
- extrude_mask_x(mask_X, y0=None, y1=None, kind='unique', normalize=None)[source]
Converts a Scalar_mask_X in volumetric between z0 and z1 by growing between these two planes :param mask_X: an amplitude mask of type Scalar_mask_X. :type mask_X: Scalar_mask_X :param y0: initial position of mask :type y0: float :param y1: final position of mask :type y1: float :param kind: ‘superpose’, ‘unique’ :type kind: str :param normalize: if ‘cut’ (>1 -> 1), ‘normalize’, None :type normalize: str
- mask_from_function(r0, index, f1, f2, radius=0, v_globals={})[source]
phase mask defined between 2 surfaces $f_1$ and $f_2$: $h(x,y)=f_2(x,y)-f_1(x,y)$
- Parameters:
r0 (float, float) – center of cross
index (float) – refraction index
f1 (str) – function for first surface
f2 (str) – function for second surface
radius (float, float) or (float) – size of mask
v_globals (dict) – dictionary with globals
mask (bool) – If True applies mask
- image(filename='', canal=0, normalize=True, lengthImage=False, invert=False, angle=0)[source]
Converts an image file XY mask. If the image is color, we get the first Red frame
- Parameters:
filename (str) – filename of the image
canal (int) – number of channel RGB to get the image
normalize (bool) – if True normalizes the image
lengthImage (bool, int) – If False does nothing, if number resize image
invert (bool) – if True the image is inverted
angle (float) – rotates image a certain angle
- Returns
str: filename
- repeat_structure(num_repetitions, position='center', new_field=True)[source]
Repeat the structure (n x m) times.
- Parameters:
num_repetitions (int, int) – Number of repetitions of the mask
position (string or number,number) – ‘center’, ‘previous’ or initial position. Initial x
new_field (bool) – If True, a new mask is produced, else, the mask is modified.
- masks_to_positions(pos, new_field=True, binarize=False, normalize=False)[source]
Place a certain mask on several positions.
Parameters: pos (float, float) or (np.array, np.array): (x,y) point or points where mask is placed. new_field (bool): If True, a new mask is produced, else, the mask is modified. Default: True. binarize (bool, float): If False nothing, else binarize in level. Default: False. normalize (bool): If True divides the mask by sum. Default: False.
Example
masks_to_positions(np.array([[0,100,100],[0,-100,100]]),new_field=True)
- polygon(vertices)[source]
Draws a polygon with the vertices given in a Nx2 numpy array.
- Parameters:
vertices (np.array) – Nx2 array with the x,y positions of the vertices.
Example
x0 = np.linspace(-3 * mm, 3 * mm, 512) y0 = np.linspace(-3 * mm, 3 * mm, 512) wavelength = 0.6328 *um vertices = np.array([(0 * mm, 0 * mm), (2 * mm, 0 * mm), (2 * mm, 1 * mm),(0 * mm, 1 * mm)]) t = Scalar_mask_XY(x0, y0, wavelength) t.polygon(vertices) t.draw()
- regular_polygon(num_vertices, radius, angle=0)[source]
Generates a regular polygon.
- Parameters:
num_vertices (int) – num_vertices
radius (float) – external radius
angle (float) – angle of rotation
- Returns:
position of vertices
- Return type:
vertices (np.array)
- star(num_peaks, radii, angle=0)[source]
Generates a regular polygon
- Parameters:
num_peaks (int) – number of peaks.
radii (float, float) – external radius
angle (float) – angle of rotation
- Returns:
position of vertices
- Return type:
vertices (np.array)
Example
x0 = np.linspace(-3 * mm, 3 * mm, 512) y0 = np.linspace(-3 * mm, 3 * mm, 512) wavelength = 0.6328 *um t = Scalar_mask_XY(x0, y0, wavelength) vertices = t.stars(5, (2*mm,1*mm), 0*degrees) t.draw()
- triangle(r0=None, slope=2.0, height=50.0, angle=0.0)[source]
Create a triangle mask. It uses the equation of a straight line: y = -slope * (x - x0) + y0
- Parameters:
r0 (float, float) – Coordinates of the top corner of the triangle
slope (float) – Slope if the equation above
height (float) – Distance between the top corner of the triangle and the basis of the triangle
angle (float) – Angle of rotation of the triangle
- photon_sieve(t1, r0, top_one=True)[source]
Generates a matrix of shapes given in t1.
- Parameters:
t1 (Scalar_mask_XY) – Mask of the desired figure to be drawn
r0 (float, float) or (np.array, np.array) – (x,y) point or points where mask is 1
top_one (bool) – If True, max(mask) = 1
- Returns:
number of points in the mask
- Return type:
(int)
- insert_array_masks(t1, space, margin=0, angle=0.0)[source]
Generates a matrix of shapes given in t1.
- Parameters:
t1 (Scalar_mask_XY) – Mask of the desired figure to be drawn
space (float, float) or (float) – spaces between figures.
margin (float, float) or (float) – extra space outside the mask
angle (float) – Angle to rotate the matrix of circles
- Returns:
number of points in the mask
- Return type:
(int)
Example
A = Scalar_mask_XY(x, y, wavelength)
A.ring(r0, radius1, radius2, angle)
insert_array_masks(t1 = A, space = 50 * um, angle = 0 * degrees)
- dots(r0)[source]
Generates 1 or several point masks at positions r0
- Parameters:
r0 (float, float) or (np.array, np.array) – (x,y) point or points where mask is 1
- dots_regular(xlim, ylim, num_data, verbose=False)[source]
Generates n x m or several point masks.
- Parameters:
xlim (float, float) – (xmin, xmax) positions
ylim (float, float) – (ymin, ymax) positions
num_data (int, int) – (x, y) number of points
- two_levels(level1=0, level2=1, x_edge=0, angle=0)[source]
Divides the field in two levels
- Parameters:
level1 (float) – value of first level
level2 (float) – value of second level
x_edge (float) – position of division
angle (float) – angle of rotation in radians
- edge_series(r0, period, a_coef, b_coef=None, angle=0.0, invert=True)[source]
Creates a linear aperture using the Fourier coefficients.
- Parameters:
x0 (float) – x-axis displacement (for ‘fslit’ function)
period (float) – Function period
a_coef (np.array, 2 rows and x columns) – coefficients that multiply the cosine function.
b_coef (np.array, 2 rows and x columns) – coefficients that multiply the sine function.
angle (float) – angle of rotation in radians
invert (bool) – inverts transmittance values (for ‘fslit’ function)
arrays (For both) –
row (Second) – coefficient orders
row – coefficient values
Example
- t1.edge_series(x0=0, period=50, a_coef=np.array(
[[0,1],[100,50]]), angle = 0 * degrees, invert=False)
- slit(x0, size, angle=0.0)[source]
Slit: 1 inside, 0 outside
- Parameters:
x0 (float) – center of slit
size (float) – size of slit
angle (float) – angle of rotation in radians
- slit_series(x0, width, period1, period2, Dy, a_coef1, a_coef2, b_coef1=None, b_coef2=None, angle=None)[source]
Creates a lineal function using the Fourier coefficients.
- Parameters:
x0 (float) – position of the center of the slit
width (float) – slit width
period1 (float) – Period of the first function
period2 (float) – Period of the second function
Dy (float, float) – Shifts of the edges
a_coef1 (np.array, 2 rows and x columns) – coefficients that multiply the cosine in the first function.
a_coef2 (np.array, 2 rows and x columns) – coefficients that multiply the cosine in the second function.
b_coef1 (np.array, 2 rows and x columns) – coefficients that multiply the sine in the first function.
b_coef2 (np.array, 2 rows and x columns) – coefficients that multiply the sine in the second function.
arrays (For the) – First row - coefficient orders, Second row - coefficient values
angle (float) – angle of rotation in radians
Example
- t1.slit_series(x0=0, width=10, period1=50,
period2=20, a_coef1=np.array([[0,1],[100,50]]) )
- double_slit(x0, size, separation, angle=0.0)[source]
double slit: 1 inside, 0 outside
- Parameters:
x0 (float) – center of double slit
size (float) – size of slit
separation (float) – separation between slit centers
angle (float) – angle of rotation in radians
- square(r0, size, angle=0)[source]
Square: 1 inside, 0 outside
- Parameters:
r0 (float, float) – center of square
size (float, float) or (float) – size of slit
angle (float) – angle of rotation in radians
Example
m.square(r0=(0 * um, 0 * um), size=(250 * um, 120 * um), angle=0 * degrees)
- gray_scale(num_levels, levelMin=0, levelMax=1)[source]
Generates a number of strips with different amplitude
- Parameters:
num_levels (int) – number of levels
levelMin (float) – value of minimum level
levelMax (float) – value of maximum level
- circle(r0, radius, angle=0.0)[source]
Creates a circle or an ellipse.
- Parameters:
r0 (float, float) – center of circle/ellipse
radius (float, float) or (float) – radius of circle/ellipse
angle (float) – angle of rotation in radians
Example
circle(r0=(0 * um, 0 * um), radius=(250 * um, 125 * um), angle=0 * degrees)
- circular_sector(r0, radii, angles)[source]
Generates a circular sector.
- Parameters:
r0 (int, int) – position of center
radii (float) or (float, float) – radius
angles (float, float) – initial and final angle in radians.
- super_gauss(r0, radius, power=2, angle=0.0)[source]
Supergauss mask.
- Parameters:
r0 (float, float) – center of circle
radius (float, float) or (float) – radius of circle
power (float) – value of exponential
angle (float) – angle of rotation in radians
Example
- super_gauss(r0=(0 * um, 0 * um), radius=(250 * um,
125 * um), angle=0 * degrees, potencia=2)
- square_circle(r0, R1, R2, s, angle=0.0)[source]
Between circle and square, depending on fill factor s
s=0 circle, s=1 square
- Parameters:
r0 (float, float) – center of square_circle
R1 (float) – radius of first axis
R2 (float) – radius of first axis
s (float) – [0-1] shape parameter: s=0 circle, s=1 square
angle (float) – angle of rotation in radians
- Reference:
Fernandez Guasti, M. De la Cruz Heredia “diffraction pattern of a circle/square aperture” J.Mod.Opt. 40(6) 1073-1080 (1993)
- angular_aperture(a_coef, b_coef=None, angle=0.0)[source]
Creates a radial function using the Fourier coefficients.
- Parameters:
a_coef (np.array, 2 rows and x columns) – coefficients that multiply the cosine function.
b_coef (For a_coef and) – coefficients that multiply the sine function.
angle (float) – angle of rotation in radians
b_coef –
values. (the first row are the coefficient orders and the second row are coefficient) –
Example
- angular_aperture(t, a_coef=np.array(
[[0,1],[20,10]]), angle= 0 * degrees)
- ring(r0, radius1, radius2, angle=0.0)[source]
Ring.
- Parameters:
r0 (float, float) – center of ring
radius1 (float, float) or (float) – inner radius
radius2 (float, float) or (float) – outer radius
angle (float) – angle of rotation in radians
- rings(r0, inner_radius, outer_radius)[source]
Structure based on several rings, with radius given by inner_radius and outer_radius.
- Parameters:
r0 (float, float) – (x0,y0) - center of lens
inner_radius (np.array) – inner radius
outer_radius (np.array) – inner radius
mask (bool) – if True, mask with size radius of maximum outer radius
- cross(r0, size, angle=0.0)[source]
Cross
- Parameters:
r0 (float, float) – center of cross
size (float, float) or (float) – length, width of cross
angle (float) – angle of rotation in radians
- prism(r0, angle_wedge, angle=0.0)[source]
prism which produces a certain angle
- Parameters:
r0 (float, float) – center wedge
angle_wedge (float) – angle of wedge in x direction
angle (float) – angle of rotation in radians
- lens(r0, focal, radius=0, angle=0.0)[source]
Transparent lens
- Parameters:
r0 (float, float) – (x0,y0) - center of lens
focal (float, float) or (float) – focal length of lens
radius (float, float) or (float) – radius of lens mask. If radius = 0, no mask is applied
angle (float) – angle of axis in radians
Example
lens(r0=(0 * um, 0 * um),focal=(5 * mm, 10 * mm), radius=100*um, angle=0 * degrees)
- lens_spherical(r0, focal, refractive_index=1.5, radius=0)[source]
Spherical lens, without paraxial approximation. The focal distance and the refraction index are used for the definition. When the refraction index decreases, the radius of curvature decrases and less paraxial. Now, only one focal.
- Parameters:
r0 (float, float) – (x0,y0) - center of lens
focal (float) – focal length of lens
refractive_index (float) – refraction index
radius (float) – radius of lens mask
- lens_spherical:
lens(r0=(0 * um, 0 * um), radius= 200 * um, focal= 10 * mm, refractive_index=1.5)
- aspheric(r0, c, k, a, n0, n1, radius=0)[source]
asferic surface.
$z =
rac{c r^2}{1+sqrt{1-(1+k) c^2 r^2 }}+sum{a_i r^{2i}}$
- Parameters:
x0 (float): position of center c (float): base curvature at vertex, inverse of radius k (float): conic constant a (list): order aspheric coefficients: A4, A6, A8, … n0 (float): refraction index of first medium n1 (float): refraction index of second medium radius (float): radius of aspheric surface
Conic Constant Surface Type k = 0 spherical k = -1 Paraboloid k < -1 Hyperboloid -1 < k < 0 Ellipsoid k > 0 Oblate eliposid
- References:
https://www.edmundoptics.com/knowledge-center/application-notes/optics/all-about-aspheric-lenses/
- lens_cylindrical(x0, focal, refractive_index=1.5, radius=0, angle=0.0)[source]
Cylindrical lens, without paraxial approximation. The focal distance and the refraction index are used for the definition. When the refraction index decreases, the radius of curvature decrases and less paraxial. When refractive_index is None or 0, then the paraxial approximation is used
- Parameters:
x0 (float) – center of lens
focal (float) – focal length of lens
refractive_index (float) – refraction index
radius (float) – radius of lens mask
- lens_spherical:
lens(r0=0, radius= 200 * um, focal= 10 * mm, refractive_index=1.5)
- fresnel_lens(r0, focal, levels=(1, 0), kind='amplitude', phase=0, radius=0, angle=0)[source]
Fresnel lens, amplitude (0,1) or phase (0-phase)
- Parameters:
r0 (float, float) – (x0,y0) - center of lens
focal (float, float) or (float) – focal length of lens
radius (float, float) or (float) – radius of lens mask
levels (float, float) – levels (1,0) or other of the lens
kind (str) – ‘amplitude’ or ‘phase’
phase (float) – phase shift for phase lens
angle (float) – angle of axis in radians
Example
fresnel_lens( r0=(0 * um, 0 * um), focal=(5 * mm, 10 * mm), radius=200*um, angle=0 * degrees, kind=’amplitude’,phase=pi)
- axicon(r0, refractive_index, angle, radius=0, off_axis_angle=0.0, reflective=False)[source]
Axicon,
- Parameters:
r0 (float, float) – (x0,y0) - center of lens
refractive_index (float) – refraction index
angle (float) – angle of the axicon
radius (float) – radius of lens mask
off_axis_angle (float) –
reflective (bool) – True if the axicon works in reflective mode.
- axicon_binary(r0, period, radius=0)[source]
axicon_binary. Rings with equal period
- Parameters:
r0 (float, float) – (x0,y0) - center of lens
radius (float) – radius of lens mask
period (float) – distance of rings
Example
axicon_binary(r0=(0 * um, 0 * um), period=20 * um, radius=200 * um)
- biprism_fresnel(r0, width, height, n)[source]
Fresnel biprism.
- Parameters:
r0 (float, float) – (x0,y0) - center of lens
width (float) – width
height (float) – height of axicon
n (float) – refraction index
Example
biprism_fresnel(r0=(0 * um, 0 * um), width=100 * um, height=5 * um, n=1.5)
- radial_grating(r0, period, phase, radius, is_binary=True)[source]
Radial grating.
- Parameters:
r0 (float, float) – (x0,y0) - center of lens
period (float) – period of the grating
phase (float) – initial phase
radius (float) – radius of the grating (masked)
is_binary (bool) – if True binary else, scaled
Example
- radial_grating(r0=(0 * um, 0 * um), period=20 * um,
phase=0 * um, radius=400 * um, is_binary=True)
- angular_grating(r0, num_petals, phase, radius, is_binary=True)[source]
Angular grating.
- Parameters:
r0 (float, float) – (x0,y0) - center of lens
period (float) – period of the grating
phase (float) – initial phase
radius (float) – radius of the grating (masked)
is_binary (bool) – if True binary else, scaled
Example
- angular_grating(r0=(0 * um, 0 * um), num_petals =20,
phase=0 * um, radius=400 * um, is_binary=True)
- hyperbolic_grating(r0, period, radius, is_binary, angle=0.0)[source]
Hyperbolic grating.
- Parameters:
r0 (float, float) – (x0,y0) - center of lens
period (float) – period of the grating
radius (float) – radius of the grating (masked)
is_binary (bool) – if True binary else, scaled
angle (float) – angle of the grating in radians
Example
hyperbolic_grating(r0=(0 * um, 0 * um), period=20 * um, radius=400 * um, is_binary=True)
- hammer(r0, size, hammer_width, angle=0.0)[source]
Square with hammer (like in lithography). Not very useful, an example
- Parameters:
r0 (float, float) – (x0,y0) - center of square
size (float, float) – size of the square
hammer_width (float) – width of hammer
angle (float) – angle of the grating in radians
Example
- hammer(r0=(0 * um, 0 * um), size=(250 * um, 120 * um),
hammer_width=5 * um, angle=0 * degrees)
- archimedes_spiral(r0, period, phase, p, radius, is_binary)[source]
Archimedes spiral
- Parameters:
r0 (float, float) – (x0,y0) - center of archimedes_spiral
period (float) – period of spiral
phase (float) – initial phase of spiral
p (int) – power of spiral
radius (float) – radius of the mask
is_binary (bool) – if True binary mask
Example
- archimedes_spiral(r0=(0 * um, 0 * um), period=20 * degrees,
phase=0 * degrees, p=1, radius=200 * um, is_binary=True)
- laguerre_gauss_spiral(r0, kind, n, l, w0, z)[source]
laguerre_gauss spiral
- Parameters:
r0 (float, float) – (x0,y0) - center of laguerre_gauss_spiral
kind (str) – ‘amplitude’ or ‘phase’
n (int) – of spiral
l (int) – power of spiral
w0 (float) – width of spiral
z (float) – propagation distance
Example
- laguerre_gauss_spiral(
r0=(0 * um, 0 * um), kind=’amplitude’, l=1, w0=625 * um, z=0.01 * um)
- forked_grating(r0, period, l, alpha, kind, angle=0.0)[source]
Forked grating: exp(1.j * alpha * cos(l * THETA - 2 * pi / period * (Xrot - r0[0])))
- Parameters:
r0 (float, float) – (x0,y0) - center of forked grating
period (float) – basic period of teh grating
l (int) –
alpha (int) –
kind (str) – ‘amplitude’ or ‘phase’
angle (float) – angle of the grating in radians
Example
forked_grating(r0=(0 * um, 0 * um), period=20 * um, l=2, alpha=1, angle=0 * degrees)
- sine_grating(x0, period, amp_min=0, amp_max=1, angle=0.0)[source]
Sinusoidal grating: self.u = amp_min + (amp_max - amp_min) * (1 + cos(2 * pi * (Xrot - phase) / period)) / 2
- Parameters:
x0 (float) – phase shift
period (float) – period of the grating
amp_min (float) – minimum amplitude
amp_max (float) – maximum amplitud
angle (float) – angle of the grating in radians
Example
- sine_grating(period=40 * um, amp_min=0, amp_max=1,
x0=0 * um, angle=0 * degrees)
- ronchi_grating(x0, period, fill_factor=0.5, angle=0)[source]
Amplitude binary grating with fill factor: self.u = amp_min + (amp_max - amp_min) * (1 + cos(2 * pi * (Xrot - phase) / period)) / 2
- Parameters:
x0 (float) – phase shift
period (float) – period of the grating
fill_factor (float) – fill_factor
angle (float) – angle of the grating in radians
Notes
Ronchi grating when fill_factor = 0.5.
It is obtained from a sinusoidal, instead as a sum of slits, for speed.
The equation to determine the position y0 is: y0=cos(pi*fill_factor)
Example
ronchi_grating(x0=0 * um, period=40*um, fill_factor=0.5, angle=0)
- binary_grating(x0, period, fill_factor=0.5, amin=0, amax=1, phase=0.0, angle=0.0)[source]
Binary grating (amplitude and/or phase). The minimum and maximum value of amplitude and phase can be controlled.
- Parameters:
x0 (float): phase shift period (float): period of the grating fill_factor (float): fill_factor amin (float): minimum amplitude amax (float): maximum amplitude phase (float): max phase shift in phase gratings angle (float): angle of the grating in radians
Example
- binary_grating( x0=0, period=40 * um, fill_factor=0.5,
amin=0, amax=1, phase=0 * degrees, angle=0 * degrees)
- blazed_grating(period, phase_max, x0, angle=0.0)[source]
Blazed grating.
- Parameters:
period (float): period of the grating phase_max (float): maximum phase of the blazed grating x0 (float): initial displacement of the grating angle (float): angle of the grating in radians
Example
blazed_grating(period=40 * um, phase_max=2*np.pi, x0, angle=0 * degrees)
- grating_2D(r0, period, fill_factor, amin=0, amax=1.0, phase=0, angle=0.0)[source]
2D binary grating
- Parameters:
r0 (float, r0): initial position period (float, float): period of the grating fill_factor (float): fill_factor amin (float): minimum amplitude amax (float): maximum amplitude phase (float): max phase shift in phase gratings angle (float): angle of the grating in radians
Example
grating_2D(period=40. * um, amin=0, amax=1., phase=0. * pi / 2, x0=0, fill_factor=0.75, angle=0.0 * degrees)
- grating_2D_chess(r0, period, fill_factor, amin=0, amax=1, phase=0.0, angle=0.0)[source]
2D binary grating as chess
- Parameters:
r0 (float, r0): initial position period (float): period of the grating fill_factor (float): fill_factor amin (float): minimum amplitude amax (float): maximum amplitude phase (float): max phase shift in phase gratings angle (float): angle of the grating in radians
Example
grating_2D_chess(r0=(0,0), period=40. * um, fill_factor=0.75, amin=0, amax=1., phase=0. * pi / 2, angle=0.0 * degrees)
- roughness(t, s, refractive_index=-1)[source]
Generation of a rough surface. According to Ogilvy p.224
- Parameters:
t (float, float) – (tx, ty), correlation length of roughness
s (float) – std of heights
refractive_index (float) – refraction index, if -1 it is reflexion
Example
roughness(t=(50 * um, 25 * um), s=1 * um)
- circle_rough(r0, radius, angle, sigma)[source]
Circle with a rough edge.
- Parameters:
r0 (float,float) – location of center
radius (float) – radius of circle
angle (float) – when radius are not equal, axis of ellipse
sigma (float) – std of roughness
- ring_rough(r0, radius1, radius2, angle, sigma)[source]
Ring with a rough edge
- Parameters:
r0 (float,float) – location of center
radius1 (float) – inner radius
radius2 (float) – outer radius
angle (float) – when radius are not equal, axis of ellipse
sigma (float) – std of roughness
- fresnel_lens_rough(r0, radius, focal, angle, sigma)[source]
Ring with a rough edge
- Parameters:
r0 (float,float) – location of center
radius (float) – maximum radius of mask
focal (float) – outer radius
angle (float) – when radius are not equal, axis of ellipse
sigma (float) – std of roughness
- super_ellipse(r0, radius, n=(2, 2), angle=0.0)[source]
Super_ellipse. Abs((Xrot - x0) / radiusx)^n1 + Abs()(Yrot - y0) / radiusy)=n2
- Parameters:
r0 (float, float) – center of super_ellipse
radius (float, float) – radius of the super_ellipse
n (float, float) = degrees of freedom of the next equation, n = (n1, n2) –
angle (float) – angle of rotation in radians
Note
n1 = n2 = 1: for a square n1 = n2 = 2: for a circle n1 = n2 = 0.5: for a superellipse
References
https://en.wikipedia.org/wiki/Superellipse
Example
super_ellipse(r0=(0 * um, 0 * um), radius=(250 * um, 125 * um), angle=0 * degrees)
- superformula(r0, radius, n, m, angle=0.0)[source]
superformula. Abs((Xrot - x0) / radiusx)^n1 + Abs()(Yrot - y0) / radiusy)=n2
- Parameters:
r0 (float, float) – center of super_ellipse
radius (float, float) – radius of the super_ellipse
n (float, float, float) – n1, n2, n3 parameters
m (float) – num of petals
angle (float) – angle of rotation in radians
Note
n1 = n2 = 1: for a square n1 = n2 = 2: for a circle n1 = n2 = 0.5: for a superellipse
References
Gielis, J. “A Generic Geometric Transformation that Unifies a Wide Range of Natural and Abstract Shapes.” Amer. J. Botany 90, 333-338, 2003. https://mathworld.wolfram.com/Superellipse.html
Example
superformula(r0=(0, 0), radius=(1.5 * mm, 1.5 * mm), n=(1, 1, 1), m=8, angle=0 * degrees)
- elliptical_phase(f1, f2, angle)[source]
Elliptical phase
- Parameters:
f1 (float) – focal f1
f2 (float) – focal f2
angle (float) – angle
- sinusoidal_slit(size, x0, amplitude, phase, period, angle=0.0)[source]
This function will create a sinusoidal wave-like slit.
- Parameters:
x0 (float) – center of slit
size (float) – size of slit
amplitude (float, float) – Phase between the wave-like borders of the slit.
phase (float) – Phase between the wave-like borders of the slit
period (float) – wavelength of the wave-like border of the slit
angle (float) – Angle to be rotated the sinusoidal slit
Example
- sinusoidal_slit(y0=(10 * um, -10 * um), amplitude=(10 * um, 20 * um),
phase=0 * degrees, angle=0 * degrees, period=(50 * um, 35 * um))
- crossed_slits(r0, slope, angle=0.0)[source]
This function will create a crossed slit mask.
- Parameters:
r0 (float, float) – center of the crossed slit
slope (float, float) – slope of the slit
angle (float) – Angle of rotation of the slit
Example
crossed_slits(r0 = (-10 * um, 20 * um), slope = 2.5, angle = 30 * degrees)
- hermite_gauss_binary(r0, w0, n, m)[source]
Binary phase mask to generate an Hermite Gauss beam.
- Parameters:
r0 (float, float) – (x,y) position of source.
w0 (float, float) – width of the beam.
n (int) – order in x.
m (int) – order in y.
Example
hermite_gauss_binary(r0=(0,0), w0=(100*um, 50*um), n=2, m=3)
- laguerre_gauss_binary(r0, w0, n, l)[source]
Binary phase mask to generate an Hermite Gauss beam.
- Parameters:
r0 (float, float) – (x,y) position of source.
w0 (float, float) – width of the beam.
n (int) – radial order.
l (int) – angular order.
Example
laguerre_gauss_binary(r0=(0,0), w0=1*um, n=0, l=0)
4.1.10. diffractio.scalar_masks_XYZ module
This module generates Scalar_mask_XYZ class for definingn masks. Its parent is scalar_fields_XYZ.
- The main atributes are:
self.x - x positions of the field
self.y - y positions of the field
self.z - z positions of the field
self.u - field XYZ
self.n - refraction index XYZ
self.wavelength - wavelength of the incident field. The field is monochromatic
The magnitude is related to microns: micron = 1.
Class for unidimensional scalar masks
- Functions
object_by_surfaces
sphere
square
cylinder
- class diffractio.scalar_masks_XYZ.Scalar_mask_XYZ(x, y, z, wavelength, n_background=1.0, info='')[source]
Bases:
Scalar_field_XYZ
- object_by_surfaces(r0, refractive_index, Fs, angles, v_globals={})[source]
Mask defined by n surfaces given in array Fs={f1, f2, h(x,y,z)=f1(x,y,z)*f2(x,y,z)*….*fn(x,y,z)
- Parameters:
rotation_point (float, float, float) – location of the mask
refractive_index (float, str) – can be a number or a function n(x, y,z)
Fs (list) – condtions as str that will be computed using eval
array1 (numpy.array) – array (x,y,z) that delimits the second surface
angle (float) – angle of rotation (radians)
v_globals (dict) – dict with global variables
verbose (bool) – shows data if true
- sphere(r0, radius, refractive_index, angles)[source]
Insert a sphere in background. If it is something else previous, it is removed.
- Parameters:
r0 – (x0, y0, z0) Location of sphere, for example (0 * um, 0*um, 0 * um)
radius – (rx, ry, rz) Radius of sphere. It can be a ellipsoid. If radius is a number, then it is a sphere refractive_index (float, str): refraction index , for example: 1.5 + 1.0j
- square(r0, length, refractive_index, angles=None, rotation_point=None)[source]
Insert a rectangle in background. If something previous, is removed.
- Parameters:
r0 (float, float, float) – (x0, y0,z0) Location of the rectangle, for example (0*um, 0*um, 0*um)
size (float, float, float) – x,y,z size of the rectangle
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
rotation_point (float, float, float) –
- cylinder(r0, radius, length, refractive_index, axis, angle)[source]
Insert a cylinder in background. If something previous, is removed.
- Parameters:
r0 (float, float, float) – (x0, y0,z0) Location of the rectangle, for example (0*um, 0*um, 0*um)
radius (float,float) – x,y, size of the circular part of cylinder
length (float) – length of cylidner
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
axis (float float, float) – axis direction
angle (float) – angle of rotation of the semi-plane, in radians
4.1.11. diffractio.scalar_masks_XZ module
Generates Scalar_mask_XZ class for definingn masks. Its parent is Scalar_field_XZ.
- The main atributes are:
self.x - x positions of the field
self.z - z positions of the field
self.u - field XZ
self.n - refraction index XZ
self.wavelength - wavelength of the incident field. The field is monochromatic
The magnitude is related to microns: micron = 1.
Class for unidimensional scalar masks
- Functions
extrude_mask, mask_from_function, mask_from_array, object_by_surfaces
image
semi_plane, layer, rectangle, slit, sphere, semi_sphere
wedge, prism, biprism
ronchi_grating, sine_grating
probe
lens_plane_convergent, lens_convergent, lens_plane_divergent, lens_divergent
roughness
- class diffractio.scalar_masks_XZ.Scalar_mask_XZ(x=None, z=None, wavelength=None, n_background=1, info='')[source]
Bases:
Scalar_field_XZ
Class for working with XZ scalar masks.
- Parameters:
x (numpy.array) – linear array with equidistant positions. The number of data is preferibly \(2^n\) .
z (numpy.array) – linear array wit equidistant positions for z values
wavelength (float) – wavelength of the incident field
n_background (float) – refraction index of background
info (str) – String with info about the simulation
- self.x
linear array with equidistant positions. The number of data is preferibly \(2^n\).
- Type:
numpy.array
- self.z
linear array wit equidistant positions for z values
- Type:
numpy.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.u0
size x - field at the last z position
- Type:
numpy.array
- self.u
(x,z) complex field
- Type:
numpy.array
- self.n_background
(x,z) refraction index
- Type:
numpy.array
- self.info
String with info about the simulation
- Type:
str
- extrude_mask(t, z0, z1, refractive_index, v_globals={}, angle=0)[source]
Converts a Scalar_mask_X in volumetric between z0 and z1 by growing between these two planes :param t: an amplitude mask of type Scalar_mask_X. :type t: Scalar_mask_X :param z0: initial position of mask :type z0: float :param z1: final position of mask :type z1: float :param refractive_index: can be a number or a function n(x,z) :type refractive_index: float, str
- mask_from_function(r0, refractive_index, f1, f2, z_sides, angle, v_globals={})[source]
Phase mask defined between two surfaces f1 and f1: h(x,z)=f2(x,z)-f1(x,z)
- Parameters:
r0 (float, float) – location of the mask
refractive_index (float, str) – can be a number or a function n(x,z)
f1 (str) – function that delimits the first surface
f2 (str) – function that delimits the second surface
z_sides (float, float) – limiting upper and lower values in z,
angle (float) – angle of rotation (radians)
v_globals (dict) – dict with global variables
- mask_from_array(r0=(0.0, 0.0), refractive_index=1.5, array1=None, array2=None, x_sides=None, angle=0.0, v_globals={}, interp_kind='quadratic', has_draw=False)[source]
Mask defined between two surfaces given by arrays (x,z): h(x,z)=f2(x,z)-f1(x,z). For the definion of f1 and f2 from arrays is performed an interpolation
- Parameters:
r0 (float, float) – location of the mask
refractive_index (float, str) – can be a number or a function n(x,z)
array1 (numpy.array) – array (x,z) that delimits the first surface
array2 (numpy.array) – array (x,z) that delimits the second surface
x_sides (float, float) – limiting upper and lower values in x,
angle (float) – angle of rotation (radians): TODO -> not working
v_globals (dict) – dict with global variables -> TODO perphaps it is not necessary
interp_kind – ‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’
- mask_from_array_proposal(r0=(0.0, 0.0), refractive_index_substrate=1.5, refractive_index_mask=None, array1=None, array2=None, x_sides=None, angle=0.0, v_globals={}, interp_kind='quadratic', has_draw=False)[source]
Mask defined between two surfaces given by arrays (x,z): h(x,z)=f2(x,z)-f1(x,z). For the definion of f1 and f2 from arrays is performed an interpolation
- Parameters:
r0 (float, float) – location of the mask
refractive_index_mask (float, str) – can be a number or a function n(x,z)
refractive_index_substrate (float, str) – can be a number or a function n(x,z)
array1 (numpy.array) – array (x,z) that delimits the first surface
array2 (numpy.array) – array (x,z) that delimits the second surface
x_sides (float, float) – limiting upper and lower values in x,
angle (float) – angle of rotation (radians): TODO -> not working
v_globals (dict) – dict with global variables -> TODO perphaps it is not necessary
interp_kind – ‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’
- object_by_surfaces(rotation_point, refractive_index, Fs, angle, v_globals={}, verbose=False)[source]
Mask defined by n surfaces given in array Fs={f1, f2, ….}. h(x,z)=f1(x,z)*f2(x,z)*….*fn(x,z)
- Parameters:
rotation_point (float, float) – location of the mask
refractive_index (float, str) – can be a number or a function n(x,z)
Fs (list) – condtions as str that will be computed using eval
array1 (numpy.array) – array (x,z) that delimits the second surface
angle (float) – angle of rotation (radians)
v_globals (dict) – dict with global variables -> TODO perphaps it is not necessary
verbose (bool) – shows data if true
- add_surfaces(fx, x_sides, refractive_index, min_incr=0.1, angle=0.0)[source]
A topography fx is added to one of the faces of object u (self.n).
- Parameters:
u (Scalar_mask_XZ) – topography
fx (numpy.array, numpy.array) – [x1, fx1], [x2, fx2] array with topography to add
x_sides (float, float) – positions of edges
refractive_index (float, str) – refraction index: number of string
min_incr (float) – minimum variation of refraction index to detect edge.
angle (float (float, float)) – angle and optative rotation angle.
- discretize_refractive_index(num_layers=None, n_layers=None, new_field=False)[source]
Takes a refraction index an discretize it according refraction indexes.
- Parameters:
num_layers ((int,int), optional) – number of layers (for real and imaginary parts), without counting background. Defaults to None. By default, both parameters are None, but one of then must be filled. If both are present, num_layers is considered
n_layers (np.array, optional) – array with refraction indexes to discretize. Defaults to None.
new_field (bool) – If True, it generates a new field.
- Returns:
refraction indexes selected.
- Return type:
(np.array)
- image(filename, n_max, n_min, angle=0, invert=False)[source]
Converts an image file in an xz-refraction index matrix. If the image is gray-scale the refraction index is gradual betwee n_min and n_max. If the image is color, we get the first Red frame
- Parameters:
filename (str) – filename of the image
n_max (float) – maximum refraction index
n_min (float) – minimum refraction index
angle (float) – angle to rotate the image in radians
invert (bool) – if True the image is inverted
- TODO: Now it is only possible that image size is equal to XZ, change using interpolation
Rotation position
- dots(positions, refractive_index=1)[source]
Generates 1 or several point masks at positions r0
- Parameters:
positions (float, float) or (np.array, np.array) – (x,z) point or points where mask is 1
refractive_index (float) – refraction index
- semi_plane(r0, refractive_index, angle=0, rotation_point=None)[source]
Inserts a semi-sphere in background (x>x0). If something else previous, it is removed.
- Parameters:
r0= (x0,z0) (float,float) – Location of the same plane.
refractive_index (float, str) – refraction index.
angle (float) – angle of rotation of the semi-plane, in radians
rotation_point (float, float) –
- layer(r0, depth, refractive_index, angle, rotation_point=None)[source]
Insert a layer. If it is something else previous, it is removed.
Parameters: r0 (float, float): (x0,z0) Location of the same plane, for example (0 * um, 20 * um) depth (float): depth of the layer refractive_index (float, str): refraction index , for example: 1.5 + 1.0j angle (float): angle of rotation of the semi-plane, in radians rotation_point (float, float). Rotation point
- rectangle(r0, size, refractive_index, angle=0.0, rotation_point=None)[source]
Insert a rectangle in background. Something previous, is removed.
- Parameters:
r0 (float, float) – (x0,z0) Location of the rectangle, for example (0 * um, 20 * um)
size (float, float) – x,z size of the rectangle
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
rotation_point (float, float) –
- slit(r0, aperture, depth, refractive_index, refractive_index_center='', angle=0, rotation_point=None)[source]
Insert a slit in background.
- Parameters:
r0 (float, float) – (x0,z0) Location of the rectangle, for example (0 * um, 20 * um)
aperture (float) – length of the opened part of the slit
depth (float) – depth of the slit
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
refractive_index_center (float, str?) – refraction index of center if refractive_index_center=’’, [], 0 then we copy what it was previously at aperture
angle (float) – angle of rotation of the semi-plane, in radians
rotation_point (float, float) –
- sphere(r0, radius, refractive_index, angle=0, rotation_point=None)[source]
Insert a sphere in background.
- Parameters:
r0 (float, float) – (x0,z0) Location of the rectangle, for example (0 * um, 20 * um)
radius (float, float) – radius x,y of the sphere (ellipsoid)
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
rotation_point (float, float) –
- semi_sphere(r0, radius, refractive_index, angle=0, rotation_point=None)[source]
Insert a semi_sphere in background.
- Parameters:
r0 (float, float) – (x0,z0) Location of the rectangle, for example (0 * um, 20 * um)
radius (float, float) – radius x,y of the sphere (ellipsoid)
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
rotation_point (float, float) –
- lens_plane_convergent(r0, aperture, radius, thickness, refractive_index, angle=0, rotation_point=None, mask=0)[source]
Insert a plane-convergent lens in background-
- Parameters:
r0 (float, float) – (x0,z0) position of the center of lens, for example (0 * um, 20 * um) for plane-convergent z0 is the location of the plane for convergent-plane (angle =180*degrees) the thickness has to be added to z0
aperture (float) – aperture of the lens. If it is 0, then it is not applied
radius (float) – radius of the curved surface
thickness (float) – thickness at the center of the lens
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
mask (array, str) – (mask_depth, refractive_index) or False. It masks the field outer the lens using a slit with depth = mask_depth
rotation_point (float, float) –
- Returns:
geometrical focal distance (numpy.array): ipasa, indexes [iz,ix] of lens
- Return type:
(float)
- lens_convergent(r0, aperture, radius, thickness, refractive_index, angle=0, rotation_point=None, mask=0)[source]
Inserts a convergent lens in background.
- Parameters:
r0 (float, float) – (x0,z0) position of the center of lens, for example (0 * um, 20 * um) for plane-convergent z0 is the location of the plane for convergent-plane (angle =180*degrees) the thickness has to be added to z0
aperture (float) – aperture of the lens. If it is 0, then it is not applied
radius (float, float) – (radius1,radius2) radius of curvature (with sign)
thickness (float) – thickness at the center of the lens
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
rotation_point (float, float) – rotation point.
mask (array, str) – (mask_depth, refractive_index) or False. It masks the field outer the lens using a slit with depth = mask_depth
- Returns:
geometrical focal distance (numpy.array): ipasa, indexes [iz,ix] of lens
- Return type:
(float)
- lens_plane_divergent(r0, aperture, radius, thickness, refractive_index, angle=0, rotation_point=None, mask=False)[source]
Insert a plane-divergent lens in background.
- Parameters:
r0 (float, float) – (x0,z0) position of the center of lens, for example (0 * um, 20 * um) for plane-convergent z0 is the location of the plane for convergent-plane (angle =180*degrees) the thickness has to be added to z0
aperture (float) – aperture of the lens. If it is 0, then it is not applied
radius (float) – radius of curvature (with sign)
thickness (float) – thickness at the center of the lens
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
mask (array, str) – (mask_depth, refractive_index) or False. It masks the field outer the lens using a slit with depth = mask_depth
- Returns:
geometrical focal distance (numpy.array): ipasa, indexes [iz,ix] of lens
- Return type:
(float)
- lens_divergent(r0, aperture, radius, thickness, refractive_index, angle=0, rotation_point=None, mask=0)[source]
Insert a divergent lens in background.
- Parameters:
r0 (float, float) – (x0,z0) position of the center of lens, for example (0 * um, 20 * um) for plane-convergent z0 is the location of the plane for convergent-plane (angle =180*degrees) the thickness has to be added to z0
aperture (float) – aperture of the lens. If it is 0, then it is not applied
radius (float, float) – (radius1, radius2) radius of curvature (with sign)
thickness (float) – thickness at the center of the lens
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
rotation_point (float, float) – rotation point
mask (array, str) – (mask_depth, refractive_index) or False. It masks the field outer the lens using a slit with depth = mask_depth
- Returns:
geometrical focal distance (numpy.array): ipasa, indexes [iz,ix] of lens
- Return type:
(float)
- aspheric_surface_z(r0, refractive_index, cx, Qx, a2, a3, a4, side, angle)[source]
Define an aspheric surface
- Parameters:
r0 (float, float) – (x0,z0) position of apex
refractive_index (float, str) – refraction index
cx (float) – curvature
Qx (float) – Conic constant
side (str) – ‘left’, ‘right’
- Returns:
Bool array with positions inside the surface
- Return type:
numpy.array
- aspheric_lens(r0, angle, refractive_index, cx, Qx, depth, size, a2=(0, 0), a3=(0, 0), a4=(0, 0))[source]
Define an aspheric surface as defined in Gomez-Pedrero.
- Parameters:
r0 (float, float) – position x,z of lens
angle (float) – rotation angle of lens + r0_rot
cx (float, float) – curvature
Qx (float, float) – Conic constant
depth (float, float) – distance of the apex
size (float) – diameter of lens
- Returns:
Bool array with positions inside the surface
- Return type:
numpy.array
- wedge(r0, length, refractive_index, angle_wedge, angle=0, rotation_point=None)[source]
Insert a wedge pointing towards the light beam
- Parameters:
r0 (float, float) – (x0,z0) Location of the rectangle, for example (0 * um, 20 * um)
length (float) – length of the long part (z direction)
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
angle_wedge (float) –
angle (float) – angle of rotation of the semi-plane, in radians
rotation_point (float, float) –
- prism(r0, length, refractive_index, angle_prism, angle=0, rotation_point=None)[source]
Similar to wedge but the use is different. Also the angle is usually different. One of the sides is paralel to x=x0
- Parameters:
r0 (float, float) – (x0,z0) Location of the rectangle, for example (0 * um, 20 * um)
length (float) – length of the long part (z direction)
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
angle_prism (float) –
angle (float) – angle of rotation of the semi-plane, in radians
rotation_point (float, float) –
- biprism(r0, length, height, refractive_index, angle=0)[source]
Fresnel biprism.
- Parameters:
r0 (float, float) – (x0,z0) Location of the rectangle, for example (0 * um, 20 * um)
length (float) – length of the long part (z direction)
height (float) – height of biprism
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
- ronchi_grating(r0, period, fill_factor, length, height, Dx, refractive_index, heigth_substrate, refractive_index_substrate, angle)[source]
Insert a ronchi grating in background.
- Parameters:
r0 (float, float) – (x0,z0) Location of the rectangle, for example (0 * um, 20 * um)
period (float) – period of the grating
fill_factor (float) – [0,1], fill factor of the grating
length (float) – length of the grating
height (float) – height of the grating
Dx (float) – displacement of grating with respect x=0
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
heigth_substrate (float) – height of the substrate
refractive_index_substrate (float, str) – refraction index of substrate, 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
- sine_grating(period, heigth_sine, heigth_substrate, r0, length, Dx, refractive_index, angle=0)[source]
Insert a sine grating in background.
- Parameters:
period (float) – period of the grating
fill_factor (float) – [0,1], fill factor of the grating
heigth_sine (float) – height of the grating
heigth_substrate (float) – height of the substrate
r0 (float, float) – (x0,z0) Location of the rectangle, for example (0 * um, 20 * um)
length (float) – length of the grating
Dx (float) – displacement of grating with respect x=0
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
- probe(r0, base, length, refractive_index, angle)[source]
Probe with a sinusoidal shape.
- Parameters:
r0 (float, float) – (x0,z0) position of the center of base, for example (0 * um, 20 * um)
base (float) – base of the probe
length (float) – length of the graprobeing
Dx (float) – displacement of grating with respect x=0
refractive_index (float, str) – refraction index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
- rough_sheet(r0, size, t, s, refractive_index, angle, rotation_point=None)[source]
Sheet with one of the surface rough.
- Parameters:
r0 (float, float) – (x0,z0) Location of sphere, for example (0 * um, 20 * um)
size (float, float) – (sizex, sizez) size of the sheet
s (float) – std roughness
t (float) – correlation length of roughness
refractive_index (float, str) – refraction index
angle (float) – angle
rotation_point (float, float) – rotation point
- Returns:
ipasa, indexes [iz,ix] of lens
- Return type:
(numpy.array)
References
According to Ogilvy p.224
4.1.12. diffractio.scalar_sources_X module
This module generates Scalar_field_X class for defining sources. Its parent is Scalar_field_X.
- The main atributes are:
self.u - field
self.x - x positions of the field
self.wavelength - wavelength of the incident field. The field is monocromatic
The magnitude is related to microns: mifcron = 1.
Class for unidimensional scalar masks
- Functions
plane_wave
gauss_beam
spherical_wave
plane_waves_dict
plane_waves_several_inclined
gauss_beams_several_parallel
gauss_beams_several_inclined
- Also
Polychromatic and extendes sources are defined in scalar_fields_X.py for multiprocessing purposes.
- class diffractio.scalar_sources_X.Scalar_source_X(x, wavelength, n_background=1, info='')[source]
Bases:
Scalar_field_X
Class for unidimensional scalar sources.
- Parameters:
x (numpy.array) – linear array with equidistant positions. The number of data is preferibly \(2^n\) .
wavelength (float) – wavelength of the incident field
n_background (float) – refraction index of background
info (str) – String with info about the simulation
- self.x
linear array with equidistant positions. The number of data is preferibly \(2^n\) .
- Type:
numpy.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.u
equal size than x. complex field
- Type:
numpy.array
- self.quality
quality of RS algorithm
- Type:
float
- self.info
description of data
- Type:
str
- self.type
Class of the field
- Type:
str
- self.date
date when performed
- Type:
str
- plane_wave(A=1, theta=0.0, z0=0.0)[source]
Plane wave.
- Parameters:
A (float) – maximum amplitude
theta (float) – angle in radians
z0 (float) – constant value for phase shift
- gauss_beam(x0, w0, z0, A=1, theta=0.0)[source]
Gauss Beam.
- Parameters:
x0 (float) – x position of center
w0 (float) – minimum beam width
z0 (float) – position of beam width
A (float) – maximum amplitude
theta (float) – angle in radians
- spherical_wave(A, x0, z0, normalize=False)[source]
Spherical wave. self.u = amplitude * A * exp(-1.j * sign(z0) * k * Rz) / Rz
- Parameters:
A (float) – maximum amplitude
x0 (float) – x position of source
z0 (float) – z position of source
mask (bool) – If true, masks the spherical wave with radius
normalize (bool) – If True, maximum of field is 1
- plane_waves_dict(params)[source]
Several plane waves with parameters defined in dictionary
- Parameters:
params – list with a dictionary: A (float): maximum amplitude theta (float): angle in radians z0 (float): constant value for phase shift
- plane_waves_several_inclined(A, num_beams, max_angle)[source]
Several paralel plane waves.
- Parameters:
A (float) – maximum amplitude
num_beams (int) – number of ints
max_angle (float) – maximum angle for beams
- gauss_beams_several_parallel(A, num_beams, w0, z0, x_central, x_range, theta=0.0)[source]
Several parallel gauss beams
- Parameters:
A (float) – maximum amplitude
num_beams (int) – number of gaussian beams (equidistintan)
w0 (float) – beam width of the bemas
z0 (float) – constant value for phase shift
x_central (float) – central position of rays
x_range (float) – range of rays
theta (float) – angle of the parallel beams
- gauss_beams_several_inclined(A, num_beams, w0, x0, z0, max_angle)[source]
Several inclined gauss beams
- Parameters:
A (float) – maximum amplitude
num_beams (int) – number of gaussian beams (equidistintan)
w0 (float) – beam width of the bemas
x0 (fl(float) – maximum amplitude
num_beams – number of ints
maoat) – initial position of gauss beam at x
z0 (float) – constant value for phase shift
max_angle (float) – maximum angle for beams
4.1.13. diffractio.scalar_sources_XY module
This module generates Scalar_source_XY class for defining sources. Its parent is Scalar_field_XY.
- The main atributes are:
self.x - x positions of the field
self.y - y positions of the field
self.u - field XY
self.wavelength - wavelength of the incident field. The field is monocromatic
The magnitude is related to microns: micron = 1.
Class for unidimensional scalar masks
- Functions
plane_wave
gauss_beam
spherical_wave
vortex_beam
laguerre_beam
hermite_gauss_beam
zernike_beam
bessel_beam
plane_waves_dict
plane_waves_several_inclined
gauss_beams_several_parallel
gauss_beams_several_inclined
- Also
laguerre_polynomial_nk
fZernike
delta_kronecker
- class diffractio.scalar_sources_XY.Scalar_source_XY(x=None, y=None, wavelength=None, info='')[source]
Bases:
Scalar_field_XY
Class for XY scalar sources.
- Parameters:
x (numpy.array) – linear array with equidistant positions. The number of data is preferibly \(2^n\) .
y (numpy.array) – linear array wit equidistant positions for y values
wavelength (float) – wavelength of the incident field
info (str) – String with info about the simulation
- self.x
linear array with equidistant positions. The number of data is preferibly \(2^n\) .
- Type:
numpy.array
- self.y
linear array wit equidistant positions for y values
- Type:
numpy.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.u
(x,z) complex field
- Type:
numpy.array
- self.info
String with info about the simulation
- Type:
str
- plane_wave(A=1, theta=0.0, phi=0.0, z0=0.0)[source]
- Plane wave. self.u = A * exp(1.j * k *
- (self.X * sin(theta) * cos(phi) +
self.Y * sin(theta) * sin(phi) + z0 * cos(theta)))
According to https://en.wikipedia.org/wiki/Spherical_coordinate_system: physics (ISO 80000-2:2019 convention)
- Parameters:
A (float) – maximum amplitude
theta (float) – angle in radians
phi (float) – angle in radians
z0 (float) – constant value for phase shift
- gauss_beam(r0, w0, z0, alpha=0.0, beta=0.0, A=1, theta=0.0, phi=0.0)[source]
Gauss Beam.
- Parameters:
r0 (float, float) – (x,y) position of center
w0 (float, float) – (wx,wy) minimum beam width
z0 (float) – (z0x, z0y) position of beam width for each axis (could be different)
alpha (float) – rotation angle of the axis of the elliptical gaussian amplitude
beta (float) – rotation angle of the axis of the main directions of the wavefront (it can be different from alpha)
A (float) – maximum amplitude
theta (float) – angle in radians (angle of k with respect to z))
References:
- spherical_wave(r0, z0, A=1, radius=0, normalize=False)[source]
Spherical wave.
- Parameters:
A (float) – maximum amplitude
r0 (float, float) – (x,y) position of source
z0 (float) or (float, float) – z0 or (zx0, zy0) position of source. When two parameters, the source is stigmatic
radius (float) – radius for mask
normalize (bool) – If True, maximum of field is 1
- vortex_beam(A, r0, w0, m)[source]
Vortex beam.
- Parameters:
A (float) – Amplitude
r0 (float, float) – (x,y) position of source
w0 (float) – width of the vortex beam
m (int) – order of the vortex beam
Example
vortex_beam(r0=(0 * um, 0 * um), w0=100 * um, m=1)
- hermite_gauss_beam(r0, A, w0, n, m, z, z0)[source]
Hermite Gauss beam.
- Parameters:
A (float) – amplitude of the Hermite Gauss beam.
r0 (float, float) – (x,y) position of the beam center.
w0 (float, float) – Gaussian waist.
n (int) – order in x.
m (int) – order in y.
z (float) – Propagation distance.
z0 (float, float) – Beam waist position at each dimension
Example
hermite_gauss_beam(A=1, r0=(0,0), w0=(100*um, 50*um), n=2, m=3, z=0)
- laguerre_beam(r0, A, w0, n, l, z, z0)[source]
Laguerre beam.
- Parameters:
A (float) – amplitude of the Hermite Gauss beam.
r0 (float, float) – (x,y) position of the beam center.
w0 (float) – Gaussian waist.
n (int) – radial order.
l (int) – angular order.
z (float) – Propagation distance.
z0 (float) – Beam waist position.
Example
laguerre_beam(A=1, r0=(0 * um, 0 * um), w0=1 * um, p=0, l=0, z=0)
- zernike_beam(A, r0, radius, n, m, c_nm)[source]
Zernike beam.
- Parameters:
A (float) – amplitude of the Zernike beam beam
r0 (float, float) – (x,y) position of source
radius (float) – width of the beam
n (list) – list of integers with orders
m (list) – list of integers with orders
c_nm (list) – list of coefficients, in radians
Example
zernike_beam(A=1, r0=(0,0), radius=5 * mm, n=[1, 3, 3, 5, 5, 5], m=[1, 1, 3, 1, 3, 5], c_nm=[.25, 1, 1, 1, 1, 1])
- bessel_beam(A, r0, alpha, n, theta=0.0, phi=0.0, z0=0)[source]
Bessel beam produced by an axicon. Bessel-beams are generated using 2D axicons.
- Parameters:
A (float) – amplitude of the Bessel beam
r0 (float, float) – (x,y) position of source
alpha (float) – angle of the beam generator
n (int) – order of the beam
theta (float) – angle in radians
phi (float) – angle in radians
z0 (float) – constant value for phase shift
References
J. Durnin, J. Miceli, and J. H. Eberly, Phys. Rev. Lett. 58, 1499 (1987). F. Courvoisier, et al. “Surface nanoprocessing with nondiffracting femtosecond Bessel beams” Optics Letters Vol. 34, No. 20 3163 (2009)
- plane_waves_dict(params)[source]
Several plane waves with parameters defined in dictionary
- Parameters:
params – list with a dictionary: A (float): maximum amplitude theta (float): angle in radians phi (float): angle in radians z0 (float): constant value for phase shift
- plane_waves_several_inclined(A, num_beams, max_angle, z0=0)[source]
Several paralel plane waves
- Parameters:
A (float) – maximum amplitude
num_beams (int, int) – number of beams in the x and y directions
max_angle (float, float) – maximum angle of the beams
z0 (float) – position of the beams
- gauss_beams_several_parallel(r0, A, num_beams, w0, z0, r_range, theta=0.0, phi=0.0)[source]
Several parallel gauss beams
- Parameters:
A (float) – maximum amplitude
num_beams (int, int) – number of gaussian beams (equidistintan) in x and y direction.
w0 (float) – beam width of the bemas
z0 (float) – constant value for phase shift
r0 (float, float) – central position of rays (x_c, y_c)
r_range (float, float) – range of rays x, y
theta (float) – angle
phi (float) – angle
- gauss_beams_several_inclined(A, num_beams, w0, r0, z0, max_angle)[source]
Several inclined gauss beams
- Parameters:
A (float) – maximum amplitude
num_beams (int, int) – number of gaussian beams (equidistintan) in x and y direction.
w0 (float) – beam width
r0 (float, float) – central position of rays (x_c, y_c)
z0 (float) – constant value for phase shift
max_angle (float, float) – maximum angles
4.1.14. diffractio.utils_common module
Common functions to classes
- diffractio.utils_common.computer_parameters(verbose=False)[source]
- Determine several computer parameters:
number of processors
available memory
total memory
max frequency
- Parameters:
verbose (bool) – If True prints data
- Returns:
number of processors info_memory (int) : Gbytes memory_available (int): % available memory freq_max (int): Maximum frequency (GHz)
- Return type:
num_max_processors (int)
- diffractio.utils_common.several_propagations(iluminacion, masks, distances)[source]
performs RS propagation through several masks
- Parameters:
iluminacion (Scalar_source_XY) – illumination
masks (list) – list with several (Scalar_masks_XY)
distances (list) – list with seera distances
- Returns:
u0 field at the last plane given by distances Scalar_field_XY: u1 field just at the plane of the last mask
- Return type:
- diffractio.utils_common.get_date()[source]
gets current date and hour.
- Returns:
date in text
- Return type:
(str)
- diffractio.utils_common.save_data_common(cls, filename, add_name='', description='', verbose=False)[source]
Common save data function to be used in all the modules. The methods included are: npz, matlab
- Parameters:
filename (str) – filename
= (add_name) – sufix to the name, if ‘date’ includes a date
description (str) – text to be stored in the dictionary to save.
verbose (bool) – If verbose prints filename.
- Returns:
filename. If False, file could not be saved.
- Return type:
(str)
- diffractio.utils_common.load_data_common(cls, filename, verbose=False)[source]
- Common load data function to be used in all the modules.
The methods included are: npz, matlab
- Parameters:
cls (class) – class X, XY, XZ, XYZ, etc..
filename (str) – filename
verbose (bool) – If True prints data
4.1.15. diffractio.utils_drawing module
Functions for drawing
- diffractio.utils_drawing.view_image(filename)[source]
reproduces image
- Parameters:
filename (str) – filename
- diffractio.utils_drawing.concatenate_drawings(kind1='png', kind2='png', nx=5, ny=3, geometria_x=256, geometria_y=256, raiz='fig4_nsensors_1', nombreFigura='figura2.png', directorio='')[source]
- diffractio.utils_drawing.draw2D(image, x, y, xlabel='$x (\\mu m)$', ylabel='$y (\\mu m)$', title='', color='YlGnBu', interpolation='nearest', scale='scaled', reduce_matrix='standard', range_scale='um', verbose=False)[source]
makes a drawing of XY
- Parameters:
image (numpy.array) – image to draw
x (numpy.array) – positions x
y (numpy.array) – positions y
xlabel (str) – label for x
ytlabel (str) – label for y
title (str) – title
color (str) – color
interpolation (str) – ‘bilinear’, ‘nearest’
scale (str) – kind of axis (None, ‘equal’, ‘scaled’, etc.)
range_scale (str) – ‘um’ o ‘mm’
verbose (bool) – if True prints information
- Returns:
handle of figure IDax: handle of axis IDimage: handle of image
- Return type:
id_fig
- diffractio.utils_drawing.draw_several_fields(fields, titles='', title='', figsize='', kinds='', logarithm=False, normalize=False)[source]
Draws several fields in subplots
- Parameters:
fields (list) – list with several scalar_fields_XY
titles (list) – list with titles
title (str) – suptitle
kinds (list) – list with kinds of figures (amplitude’, ‘intensity’, ‘phase’, ‘real_field’, ‘contour’)
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (bool) – If True, max(intensity)=1
- diffractio.utils_drawing.change_image_size(image_name, length='800x600', final_filename='prueba.png', dpi=100)[source]
change the size with imageMagick
- Parameters:
image_name (str) – name of file
length (str) – size of image
final_filename (str) – final filename
dpi (int) – dpi
Examples:
- convert image_name -resize ‘1000’ -units 300 final_filename.png
anchura 1000 - mantiene forma
- convert image_name -resize ‘x200’ final_filename.png
height 200 - mantiene forma
- convert image_name -resize ‘100x200>’ final_filename.png
mantiene forma, lo que sea mayor
- convert image_name -resize ‘100x200<’ final_filename.png
mantiene forma, lo que sea menor
- convert image_name -resize ‘@1000000’ final_filename.png
mantiene la forma, con 1Mpixel
- convert image_name -resize ‘100x200!’ final_filename.png
obliga a tener el tamaño, no mantiene escala
- diffractio.utils_drawing.extract_image_from_video(nombre_video=None, num_frame='[0, ]', final_filename='prueba.png')[source]
Extract images form a video using imageMagick.
convert ‘animacion.avi[15,]’ animacion_frame.png. Extracts frame 15 (ony 15) convert ‘animacion.avi[15]’ animacion_frame.png. Extracts the first 15 convert ‘animacion.avi[5,10]’ animacion_frame.png. Extracts frame 5 and 10
- diffractio.utils_drawing.normalize_draw(u, logarithm=0, normalize=False, cut_value=None)[source]
Gets a field and changes its caracteristics for drawing
- Parameters:
u (field) – field
logarithm (float) – logarithm to image: np.log(logarithm*u + 1)
normalize (str or bool) – False, ‘mean’, ‘intensity’
- diffractio.utils_drawing.prepare_drawing(u, kind='intensity', logarithm=False, normalize=False)[source]
It is necessary that figure is previously defined: plt.figure()
- Parameters:
field (u -) –
'intensity' (kind -) –
'amplitude' –
'phase' –
False (logarithm - True or) –
normalize – False, ‘maximum’, ‘intensity’, ‘area’
- Returns:
I_drawing for direct plotting
- Return type:
returns (numpy.array)
- diffractio.utils_drawing.reduce_matrix_size(reduce_matrix, x, y, image, verbose=False)[source]
Reduces the size of matrix for drawing purposes. If the matrix is very big, the drawing process is slow.
- Parameters:
reduce_matrix (str or (int, int)) – if str: ‘standard’, if (int, int) reduction_factor.
x (np.array) – array with x.
y (np.array) – array with y or z
image (np.array) – image to reduce the size.
verbose (bool) – if True, prints info
- Returns:
reduced image
- Return type:
(np.array)
4.1.16. diffractio.utils_math module
Common functions to classes
- diffractio.utils_math.nextpow2(x)[source]
Exponent of next higher power of 2. It returns the exponents for the smallest powers of two that satisfy $2^p≥A$ for each element in A. By convention, nextpow2(0) returns zero.
- Parameters:
x (float) – value
- Returns:
Exponent of next higher power of 2
- Return type:
integer
- diffractio.utils_math.Bluestein_dft_x(x, f1, f2, fs, mout)[source]
Bluestein dft
- Parameters:
x (_type_) – _description_
f1 (_type_) – _description_
f2 (_type_) – _description_
fs (_type_) – _description_
mout (_type_) – _description_
- Reference:
Hu, Y., Wang, Z., Wang, X., Ji, S., Zhang, C., Li, J., Zhu, W., Wu, D., Chu, J. (2020). “Efficient full-path optical calculation of scalar and vector diffraction using the Bluestein method”. Light: Science and Applications, 9(1). https://doi.org/10.1038/s41377-020-00362-z
- diffractio.utils_math.Bluestein_dft_xy(x, f1, f2, fs, mout)[source]
Bluestein dft
- Parameters:
x (_type_) – _description_
f1 (_type_) – _description_
f2 (_type_) – _description_
fs (_type_) – _description_
mout (_type_) – _description_
- diffractio.utils_math.find_local_extrema(kind, y, x, pixels_interpolation=0, pixels_filter=0)[source]
Determine local minima in a numpy array.
- Parameters:
kind (str) – ‘maxima’, ‘minima’
y (numpy.ndarray) – variable with local minima.
x (numpy.ndarray) – x position
- Returns:
i positions of local minima.
- Return type:
(numpy.ndarray)
- diffractio.utils_math.reduce_to_1(class_diffractio)[source]
All the values greater than 1 pass to 1. This is used for Scalar_masks when we add two masks. :param class: Scalar_field_X, XY ,…. :type class: class
- diffractio.utils_math.distance(x1, x2)[source]
Compute distance between two vectors.
- Parameters:
x1 (numpy.array) – vector 1
x2 (numpy.array) – vector 2
- Returns:
distance between vectors.
- Return type:
(float)
- diffractio.utils_math.nearest(vector, number)[source]
Computes the nearest element in vector to number.
- Parameters:
vector (numpy.array) – array with numbers
number (float) – number to determine position
- Returns:
index - index of vector which is closest to number. (float): value - value of vector[index]. (float): distance - difference between number and chosen element.
- Return type:
(int)
- diffractio.utils_math.nearest2(vector, numbers)[source]
Computes the nearest element in vector to numbers.
- Parameters:
vector (numpy.array) – array with numbers
number (numpy.array) – numbers to determine position
- Returns:
index - indexes of vector which is closest to number. (numpy.array): value - values of vector[indexes]. (numpy.array): distance - difference between numbers and chosen elements.
- Return type:
(numpy.array)
- diffractio.utils_math.find_extrema(array2D, x, y, kind='max', verbose=False)[source]
In a 2D-array, formed by vectors x, and y, the maxima or minima are found
- Parameters:
array2D (np. array 2D) – 2D array with variable
x (np.array 1D) – 1D array with x axis
y (np.array 1D) – 1D array with y axis
kind (str) – ‘min’ or ‘max’: detects minima or maxima
verbose (bool) – If True prints data.
- Returns:
indexes of the position xy_ext (float, float): position of maximum extrema (float): value of maximum
- Return type:
indexes (int,int)
- diffractio.utils_math.ndgrid(*args, **kwargs)[source]
n-dimensional gridding like Matlab’s NDGRID.
- Parameters:
sequences (The input *args are an arbitrary number of numerical) –
lists (e.g.) –
arrays –
tuples. (or) –
argument (The i-th dimension of the i-th output) –
argument. (has copies of the i-th input) –
Example
>>> x, y, z = [0, 1], [2, 3, 4], [5, 6, 7, 8]
>>> X, Y, Z = ndgrid(x, y, z) # unpacking the returned ndarray into X, Y, Z
Each of X, Y, Z has shape [len(v) for v in x, y, z].
>>> X.shape == Y.shape == Z.shape == (2, 3, 4) True
>>> X array([[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]) >>> Y array([[[2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]], [[2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]]) >>> Z array([[[5, 6, 7, 8], [5, 6, 7, 8], [5, 6, 7, 8]], [[5, 6, 7, 8], [5, 6, 7, 8], [5, 6, 7, 8]]])
With an unpacked argument list:
>>> V = [[0, 1], [2, 3, 4]]
>>> ndgrid(*V) # an array of two arrays with shape (2, 3) array([[[0, 0, 0], [1, 1, 1]], [[2, 3, 4], [2, 3, 4]]])
For input vectors of different data kinds, same_dtype=False makes ndgrid() return a list of arrays with the respective dtype. >>> ndgrid([0, 1], [1.0, 1.1, 1.2], same_dtype=False) [array([[0, 0, 0], [1, 1, 1]]), array([[ 1. , 1.1, 1.2], [ 1. , 1.1, 1.2]])]
Default is to return a single array.
>>> ndgrid([0, 1], [1.0, 1.1, 1.2]) array([[[ 0. , 0. , 0. ], [ 1. , 1. , 1. ]], [[ 1. , 1.1, 1.2], [ 1. , 1.1, 1.2]]])
- diffractio.utils_math.get_amplitude(u, sign=False)[source]
Gets the amplitude of the field.
- Parameters:
u (numpy.array) – Field.
sign (bool) – If True, sign is kept, else, it is removed
- Returns:
numpy.array
- Return type:
(numpy.array)
- diffractio.utils_math.get_phase(u)[source]
Gets the phase of the field.
- Parameters:
u (numpy.array) – Field.
- Returns:
numpy.array
- Return type:
(numpy.array)
- diffractio.utils_math.amplitude2phase(u)[source]
Passes the amplitude of a complex field to phase. Previous phase is removed. \(u = A e^{i \phi} -> e^(i abs(A))\)
- Parameters:
u (numpy.array, dtype=complex) – complex field
- Returns:
only-phase complex vector.
- Return type:
(numpy.array)
- diffractio.utils_math.phase2amplitude(u)[source]
Passes the phase of a complex field to amplitude.
- Parameters:
u (numpy.array, dtype=complex) – complex field
- Returns:
amplitude without phase complex vector.
- Return type:
(numpy.array)
- diffractio.utils_math.normalize(v, order=2)[source]
Normalize vectors with different L norm (standard is 2).
- Parameters:
v (numpy.array) – vector to normalize
order (int) – order for norm
- Returns:
normalized vector.
- Return type:
(numpy.array)
- diffractio.utils_math.binarize(vector, min_value=0, max_value=1)[source]
Binarizes vector between two levels, min and max. The central value is (min_value+max_value)/2
- Parameters:
vector – (numpy.array) array with values to binarize
min_value (float) – minimum value for binarization
max_value (float) – maximum value for binarization
- Returns:
binarized vector.
- Return type:
(numpy.array)
- diffractio.utils_math.discretize(u, kind='amplitude', num_levels=2, factor=1, phase0=0, new_field=True, matrix=False)[source]
Discretize in a number of levels equal to num_levels.
- Parameters:
kind (str) – “amplitude” o “phase”
num_levels (int) – number of levels for the discretization
factor (float) – from the level, how area is binarized. if 1 everything is binarized,
phase0 (float) –
new_field (bool) – if True returns new field
matrix (bool) – if True it returs a matrix
- Returns:
if new_field is True returns scalar_fields_XY
- Return type:
scalar_fields_XY
- diffractio.utils_math.delta_kronecker(a, b)[source]
Delta kronecker
- Parameters:
a (np.float) – number
b (np.float) – number
- Returns:
1 if a==b and 0 if a<>b
- diffractio.utils_math.vector_product(A, B)[source]
Returns the vector product between two vectors.
- Parameters:
A (numpy.array) – 3x1 vector array.
B (numpy.array) – 3x1 vector array.
- Returns:
3x1 vector product array
- Return type:
(numpy.array)
- diffractio.utils_math.dot_product(A, B)[source]
Returns the dot product between two vectors.
- Parameters:
A (numpy.array) – 3x1 vector array.
B (numpy.array) – 3x1 vector array.
- Returns:
3x1 dot product
- Return type:
(complex)
- diffractio.utils_math.divergence(E, r)[source]
Returns the divergence of a field a given point (x0,y0,z0).
- Parameters:
E (numpy.array) – complex field
r (numpy.array) – 3x1 array with position r=(x,y,z).
- Returns:
Divergence of the field at (x0,y0,z0)
- Return type:
(float)
- diffractio.utils_math.curl(E, r)[source]
Returns the Curl of a field a given point (x0,y0,z0)
- Parameters:
E (numpy.array) – complex field
r (numpy.array) – 3x1 array with position r=(x,y,z).
- Returns:
Curl of the field at (x0,y0,z0)
- Return type:
(numpy.array)
- diffractio.utils_math.get_edges(x, f, kind_transition='amplitude', min_step=0, verbose=False, filename='')[source]
We have a binary mask and we obtain locations of edges. valid for litography engraving of gratings
- Parameters:
x (float) – position x
f (numpy.array) – Field. If real function, use ‘amplitude’ in kind_transition.
kind_transition (str) – ‘amplitude’ ‘phase’ of the field where to get the transitions.
min_step (float) – minimum step for consider a transition
verbose (bool) – If True prints information about the process.
filename (str) – If not ‘’, saves the data on files. filename is the file name.
- Returns:
array with +1, -1 with rasing or falling edges pos_transition (numpy.array): positions x of transitions raising (numpy.array): positions of raising falling (numpy.array): positions of falling
- Return type:
type_transition (numpy.array)
- diffractio.utils_math.cut_function(x, y, length, x_center='')[source]
takes values of function inside (x_center+length/2: x_center+length/2)
- diffractio.utils_math.fft_convolution2d(x, y)[source]
2D convolution, using FFT
- Parameters:
x (numpy.array) – array 1 to convolve
y (numpy.array) – array 2 to convolve
- Returns:
convolved function
- diffractio.utils_math.fft_convolution1d(x, y)[source]
1D convolution, using FFT
- Parameters:
x (numpy.array) – array 1 to convolve
y (numpy.array) – array 2 to convolve
- Returns:
convolved function
- diffractio.utils_math.fft_filter(x, y, normalize=False)[source]
1D convolution, using FFT
- Parameters:
x (numpy.array) – array 1 to convolve
y (numpy.array) – array 2 to convolve
- Returns:
convolved function
- diffractio.utils_math.fft_correlation1d(x, y)[source]
1D correlation, using FFT (fftconvolve)
- Parameters:
x (numpy.array) – array 1 to convolve
y (numpy.array) – array 2 to convolve
- Returns:
correlation function
- Return type:
numpy.array
- diffractio.utils_math.fft_correlation2d(x, y)[source]
- Parameters:
x (numpy.array) – array 1 to convolve
y (numpy.array) – array 2 to convolve
- Returns:
2d correlation function
- Return type:
numpy.array
- diffractio.utils_math.rotate_image(x, z, img, angle, pivot_point)[source]
similar to rotate image, but not from the center but from the given
- Parameters:
img (np.array) – image to rotate
angle (float) – angle to rotate
pivot_point (float, float) – (z,x) position for rotation
- Returns:
rotated image
- diffractio.utils_math.cart2pol(x, y)[source]
cartesian to polar coordinate transformation.
- Parameters:
x (np.array) – x coordinate
y (np.aray) – y coordinate
- Returns:
rho numpy.array: phi
- Return type:
numpy.array
- diffractio.utils_math.pol2cart(rho, phi)[source]
polar to cartesian coordinate transformation
- Parameters:
rho (np.aray) – rho coordinate
rho – rho coordinate
- Returns:
x numpy.array: y
- Return type:
numpy.array
- diffractio.utils_math.fZernike(X, Y, n, m, radius=5000.0)[source]
Zernike function for aberration computation.
Note
k>=l
if k is even then l is even. if k is odd then l is odd.
The first polinomial is the real part ant the second de imaginary part.
n m aberración
0 0 piston
1 -1 vertical tilt
1 1 horizontal tilt
2 -2 astigmatismo oblicuo
2 0 desenfoque miopía si c>0 o desenfoque hipermetropía si c<0
2 2 astigmatismo anormal si c>0 o astigmatismo normal si c<0
3 -3 trebol oblicuo
3 -1 coma vertical, c>0 empinamiento superior, c<0 emp. inferior
3 1 como horizontal
3 3 trebol horizontal
4 -4 trebol de cuatro hojas oblicuo
4 -2 astigmatismo secundario oblicuo
4 0 esférica c>0 periferia más miópica que centro, c<0 periferia más hipertrópica que el centro
4 2 astigmatismo secundario a favor o en contra de la regla
4 4 trebol de cuatro hojas horizontal
Reference:
Navarro, J. Arines, R. Rivera “Direct and inverse discrete Zernike transform” Opt. Express 17(26) 24269
- diffractio.utils_math.laguerre_polynomial_nk(x, n=4, k=5)[source]
Auxiliar laguerre polinomial of orders n and k function y = LaguerreGen(varargin) LaguerreGen calculates the utilsized Laguerre polynomial L{n, alpha} This function computes the utilsized Laguerre polynomial L{n,alpha}. If no alpha is supplied, alpha is set to zero and this function calculates the “normal” Laguerre polynomial.
Parameters: - n = nonnegative integer as degree level - alpha >= -1 real number (input is optional)
The output is formated as a polynomial vector of degree (n+1) corresponding to MatLab norms (that is the highest coefficient is the first element).
Example: - polyval(LaguerreGen(n, alpha), x) evaluates L{n, alpha}(x) - roots(LaguerreGen(n, alpha)) calculates roots of L{n, alpha}
Calculation is done recursively using matrix operations for very fast execution time.
Author: Matthias.Trampisch@rub.de Date: 16.08.2007 Version 1.2
References
Szeg: “Orthogonal Polynomials” 1958, formula (5.1.10)
- diffractio.utils_math.get_k(x, flavour='-')[source]
- provides k vector from x vector. With flavour set to “-”, the axis will be inverse-fftshifted,
thus its DC part being the first index.
- Parameters:
x (np.array) – x array
flavour (str) – ‘-’ (for ifftshifted axis)
- Returns:
k vector
- Return type:
kx (np.array)
Fixed by Bob-Swinkels
- diffractio.utils_math.get_k_deprecated(x, flavour='-')[source]
provides k vector from x vector. Two flavours are provided (ordered + or disordered - )
- Parameters:
x (np.array) – x array
flavour (str) – ‘+’ or ‘-’
- Returns:
k vector
- Return type:
kx (np.array)
- diffractio.utils_math.filter_edge_1D(x, size=1.1, exponent=32)[source]
function 1 at center and reduced at borders. For propagation algorithms
- Parameters:
x (np.array) – position
size (float) – related to relative position of x
exponent (integer) – related to shape of edges
- Returns:
function for filtering
- Return type:
np.array
- diffractio.utils_math.filter_edge_2D(x, y, size=1.1, exponent=32)[source]
function 1 at center and reduced at borders. For propagation algorithms
- Parameters:
x (np.array) – x position
y (np.array) – y position
size (float) – related to relative position of x and y
exponent (integer) – related to shape of edges
- Returns:
function for filtering
- Return type:
np.array
4.1.17. diffractio.utils_multiprocessing module
- diffractio.utils_multiprocessing.separate_from_iterable(iterable, shape=0)[source]
This function does somehow the opposite of the previous one, it takes an iterable made of lists and separates each one in a different variable, reshaped with the desired shape
- diffractio.utils_multiprocessing.execute_multiprocessing(__function_process__, dict_Parameters, num_processors, verbose=False)[source]
Executes multiprocessing reading a dictionary.
- Parameters:
process (__function_process__ function tu) –
dictionary (it only accepts a) –
dict_Parameters –
Parameters (dictionary / array with) –
num_processors –
used (if 1 no multiprocessing is) –
verbose –
time (prints processing) –
- Returns:
reults of multiprocessing processing time
- Return type:
data
Examples
- def __function_process__(xd):
x = xd[‘x’] y = xd[‘y’] # grt = copy.deepcopy(grating) suma = x + y return dict(sumas=suma, ij=xd[‘ij’])
- def creation_dictionary_multiprocessing():
# create Parameters: for multiprocessing t1 = time.time() X = np.linspace(1, 2, 10) Y = np.linspace(1, 2, 1000) dict_Parameters = [] ij = 0 for i, x in enumerate(X):
- for j, y in enumerate(Y):
dict_Parameters.append(dict(x=x, y=y, ij=[ij])) ij += 1
t2 = time.time() print(“time creation dictionary = {}”.format(t2 - t1)) return dict_Parameters
4.1.18. diffractio.utils_optics module
General purpose optics functions
- diffractio.utils_optics.roughness_1D(x, t, s, kind='normal')[source]
Rough surface, 1D
- Parameters:
x (numpy.array) – array with x positions
t (float) – correlation lens
s (float) – std of roughness
kind (str) – ‘normal’, ‘uniform’
- Returns:
(numpy.array) Topography of roughnness in microns.
References
JA Oglivy “Theory of wave scattering from random surfaces” Adam Hilger p.224.
- diffractio.utils_optics.roughness_2D(x, y, t, s)[source]
Rough surface, 2D
- Parameters:
x (numpy.array) – x positions
y (numpy.array) – y positions
t (float, float) – (tx, ty), correlation length of roughness
s (float) – std of heights
- Returns:
(numpy.array) Topography of roughnness in microns.
Example
roughness(t=(50 * um, 25 * um), s=1 * um)
References
JA Oglivy “Theory of wave scattering from random surfaces” Adam Hilger p.224.
- diffractio.utils_optics.beam_width_1D(u, x, remove_background=None)[source]
One dimensional beam width, according to D4σ or second moment width.
- Parameters:
u (np.array) – field (not intensity).
x (np.array) – x
- Returns:
width (float): x_mean
- Return type:
(float)
References
- diffractio.utils_optics.width_percentage(x, y, percentage=0.5, verbose=False)[source]
beam width (2*sigma) given at a certain height from maximum
- Parameters:
x (np.array) – x
y (np.array) – y
percentage (float) – percentage of height. For example: 0.5
- Returns:
width, width of at given % (list): x_list: (x[i_left], x[i_max], x[i_right]) (list): x_list: (i_left, i_max, i_right)
- Return type:
(float)
Notes
y=np.exp(-x**2/(s**2)) percentage=1/e -> width = 2*s y=np.exp(-x**2/(s**2)) percentage=1/e**4 -> width = 4*s y=np.exp(-x**2/(2*s**2)) percentage=1/e**2 = -> width = 4*s
- diffractio.utils_optics.beam_width_2D(x, y, intensity, remove_background=False, has_draw=False)[source]
2D beam width, ISO11146 width
- Parameters:
x (np.array) – 1d x
y (np.array) – 1d y
intensity (np.array) – intensity
- Returns:
dx width x (float): dy width y (float): principal_axis, angle (str): (x_mean, y_mean, x2_mean, y2_mean, xy_mean), Moments
- Return type:
(float)
References
- diffractio.utils_optics.refractive_index(filename, wavelength, raw=False, has_draw=True)[source]
gets refraction index from https://refractiveindex.info .
Files has to be converted to xlsx format.
n and k checks has to be activated.
- Parameters:
filename (str) – xlsx file
wavelength (float) – wavelength in microns, example, 0.6328.
raw (bool) – if True returns all the data in file.
has_draw (bool) – draw the data from the file
- Returns:
n, k from each wavelength if raw is True (np.array, np.array): n,k for wavelengths in file
- Return type:
if raw is False (float, float)
- diffractio.utils_optics.FWHM1D(x, intensity, percentage=0.5, remove_background=None, has_draw=False)[source]
remove_background = ‘min’, ‘mean’, None
- diffractio.utils_optics.FWHM2D(x, y, intensity, percentage=0.5, remove_background='None', has_draw=False, xlim=None)[source]
TODO: perform profiles at several angles and fit to a ellipse. Get dx, dy, angle, x_center, y_center
- diffractio.utils_optics.DOF(z, widths, w_factor=1.4142135623730951, w_fixed=0, has_draw=False, verbose=False)[source]
Determines Depth-of_focus (DOF) in terms of the width at different distances
- Parameters:
z (np.array) – z positions
widths (np.array) – width at positions z
w_factor (float) – range to determine z where w = w_factor * w0, being w0 the beam waist
w_fixed (float) – If it is not 0, then it is used as w_min
has_draw (bool) – if True draws the depth of focus
verbose (bool) – if True, prints data
References
Saleh and M. C. Teich, Fundamentals of photonics. john Wiley & sons, 2nd ed. 2007. Eqs (3.1-18) (3.1-22) page 79
- Returns:
Depth of focus (float): beam waist (float, float, float): postions (z_min, z_0, z_max) of the depth of focus
- Return type:
(float)
- diffractio.utils_optics.detect_intensity_range(x, intensity, percentage=0.95, has_draw=True, logarithm=True)[source]
Determines positions x_min, x_max where intensity of the beam is percentage
- Parameters:
x (np.array) – x positions
intensity (np.array) – Intensity of the 1D beam
percentage (float) – value 0-1 representing the percentage of intensity between area
has_draw (bool) – if True draws the field an the range
logarithm (bool) – when has_draw, draws logarithm or normal intensity
- Returns:
positions (x_min, right) where intensity beam is enclosed at %.
- Return type:
(float, float)
- diffractio.utils_optics.MTF_ideal(frequencies, wavelength, diameter, focal, kind, verbose=False, has_draw=False)[source]
Determines the ideal MTF of a lens.
References
- Parameters:
frequencies (numpy.array) – array with frequencies in lines/mm
wavelength (float) – wavelength of incoming light beam
diameter (float) – diameter of lens
focal (float) – focal distance of lens
kind (float) – ‘1D’, ‘2D’
verbose (bool) – if True displays limit frequency of the lens
- Returns:
Normalized MTF of ideal lens (float) frequency_max: maximum frequency of the lens
- Return type:
(numpy.array) MTF
- diffractio.utils_optics.lines_mm_2_cycles_degree(lines_mm, focal)[source]
Pasa líneas por mm a cyclos/grado, más tipico de ojo Infor saca estos cálculos 181022 :param lines_mm: lines_per_mm :type lines_mm: numpy.array or float :param focal: focal of lens :type focal: float
- diffractio.utils_optics.MTF_parameters(MTF, MTF_ideal, lines_mm=50, verbose=False)[source]
MTF parameters: strehl_ratio, mtf_50_ratio, freq_50_real, freq_50_ideal
References
frequencies of mtf ar given since both MTF can have different steps MTF:
- Parameters:
MTF (N,2 numpy.array) – (freq, MTF) of system in lines/mm
MTF_ideal (M,2 numpy.array) – (freq, MTF) of ideal system in lines/mm
lines_mm (float) – (0-1) Height of MTF for ratios
- Returns:
strehl_ratio (float): MTF_ratio at freq_obs height (float): frequency at freq_obs of MTF (float): frequency at freq_obs of MTF_ideal
- Return type:
(float)
- diffractio.utils_optics.gauss_spectrum(wavelengths, w_central, Dw, normalize=True)[source]
returns weigths for a gaussian spectrum :param wavelengths: array with wavelengths :param w_central: central wavelength :param Dw: width of the spectrum :param normalize: if True sum of weights is 1
- diffractio.utils_optics.lorentz_spectrum(wavelengths, w_central, Dw, normalize=True)[source]
returns weigths for a gaussian spectrum :param wavelengths: array with wavelengths :param w_central: central wavelength :param Dw: width of the spectrum :param normalize: if True sum of weights is 1
- diffractio.utils_optics.uniform_spectrum(wavelengths, normalize=True)[source]
returns weigths for a gaussian spectrum :param wavelengths: array with wavelengths :param w_central: central wavelength :param Dw: width of the spectrum :param normalize: if True sum of weights is 1
- diffractio.utils_optics.normalize_field(self, new_field=False)[source]
Normalize the field to maximum intensity.
- Parameters:
(Scalar_field) – field_*
new_field (bool) – If True returns a field, else returns a matrix
- Returns:
normalized field.
- Return type:
(np.array)
- diffractio.utils_optics.field_parameters(u, has_amplitude_sign=False)[source]
Determines main parameters of field: amplitude intensity phase. All this parameters have the same dimension as u.
- Parameters:
u (numpy.array) – optical field (comes usually form field.u)
has_amplitude_sign (bool) – If True - amplitude = np.sign(u) * np.abs(u), Else: amplitude = np.abs(u)
- Returns:
np.abs(u) intensity (numpy.array): np.abs(u)**2 phase (numpy.array): np.angle(u)
- Return type:
amplitude (numpy.array)
- diffractio.utils_optics.convert_phase2heigths(phase, wavelength, n, n_background)[source]
We have a phase and it is converted to a depth. It is useful to convert Scalar_mask_X to Scalar_mask_XZ
phase(x,z)= k (n-n_0) h(x,z).
- Parameters:
phase (np.array) – Phases
wavelength (float) – wavelength
n (float or complex) – refraction index of material
n_background (float) – refraction index of background
- Returns:
depths related to phases
- Return type:
(np.array)
- diffractio.utils_optics.convert_amplitude2heigths(amplitude, wavelength, kappa, n_background)[source]
We have a phase and it is converted to a depth. It is useful to convert Scalar_mask_X to Scalar_mask_XZ.
- Parameters:
phase (np.array) – Phases
wavelength (float) – wavelength
kappa (float) – refraction index of material.
n_background (float) – refraction index of background
- Returns:
depths related to amplitudes
- Return type:
(np.array)
- diffractio.utils_optics.fresnel_equations_kx(kx, wavelength, n1, n2, outputs=[True, True, True, True], has_draw=True, kind='amplitude_phase')[source]
Fresnel_equations where input are kx part of wavevector.
- Parameters:
kx (np.array) – kx
wavelength (float) – wavelength
n1 (float) – refraction index of first materia
n2 (float) – refraction index of second materia
outputs (bool,bool,bool,bool) – Selects the outputs to compute
has_draw (bool, optional) – if True, it draw. Defaults to False.
kind (str) – It draw ‘amplitude_phase’ or ‘real_imag’
- Returns:
t_TM, t_TE, r_TM, r_TE (TM is parallel and TE is perpendicular)
- Return type:
_type_
- diffractio.utils_optics.transmitances_reflectances_kx(kx, wavelength, n1, n2, outputs=[True, True, True, True], has_draw=False)[source]
Transmitances and reflectances, where input are kx part of wavevector.
- Parameters:
kx (np.array) – kx
wavelength (float) – wavelength
n1 (float) – refraction index of first materia
n2 (float) – refraction index of second materia
has_draw (bool, optional) – if True, it draw. Defaults to False.
outputs (bool,bool,bool,bool) – Selects the outputs to compute
- Returns:
T_TM, T_TE, R_TM, R_TE (TM is parallel and TE is perpendicular)
- Return type:
_type_
- diffractio.utils_optics.fresnel_equations(theta, wavelength, n1, n2, outputs=[True, True, True, True], has_draw=False, kind='amplitude_phase')[source]
Fresnel equations and reflectances, where input are angles of incidence.
- Parameters:
kx (np.array) – kx
wavelength (float) – wavelength
n1 (float) – refraction index of first materia
n2 (float) – refraction index of second materia
kind (str) – It draw ‘amplitude_phase’ or ‘real_imag’
has_draw (bool, optional) – if True, it draw. Defaults to False.
kind – It draw ‘amplitude_phase’ or ‘real_imag’
- Returns:
T_TM, T_TE, R_TM, R_TE (TM is parallel and TE is perpendicular)
- Return type:
_type_
- diffractio.utils_optics.transmitances_reflectances(theta, wavelength, n1, n2, outputs=[True, True, True, True], has_draw=False)[source]
Transmitances and reflectances, where input are angles of incidence.
- Parameters:
kx (np.array) – kx
wavelength (float) – wavelength
n1 (float) – refraction index of first materia
n2 (float) – refraction index of second materia
has_draw (bool, optional) – if True, it draw. Defaults to False.
outputs (bool,bool,bool,bool) – Selects the outputs to compute
- Returns:
T_TM, T_TE, R_TM, R_TE (TM is parallel and TE is perpendicular)
- Return type:
_type_
4.1.19. diffractio.utils_slicer_deprecated module
4.1.20. diffractio.utils_tests module
Common functions to classes
- diffractio.utils_tests.comparison(proposal, solution, maximum_diff)[source]
This functions is mainly for testing. It compares compares proposal to solution.
- Parameters:
proposal (numpy.matrix) – proposal of result.
solution (numpy.matrix) – results of the test.
maximum_diff (float) – maximum difference allowed.
- Returns:
True if comparison is possitive, else False.
- Return type:
(bool)
- diffractio.utils_tests.benchmark_num_pixels(function, n_max=10)[source]
This function is for benchmarking using an increasing number of pixels 2**n.
- Parameters:
function (function) – Functions that has as argumetn the number of pixels 2**n.
4.1.21. diffractio.vector_fields_X module
This module generates Vector_field_X class. It is required also for generating masks and fields. The main atributes are:
self.x - x positions of the field
self.Ex - x component of electric field
self.Ey - y component of electric field
self.Ez - z component of electric field
self.wavelength - wavelength of the incident field. The field is monocromatic
self.info (str): description of data
self.type (str): Class of the field
self.date (str): date when performed
The magnitude is related to microns: micron = 1.
Class for X vector fields
- Definition of a scalar field
add, substract fields
save, load data, clean, get, normalize
cut_resample
- Vector parameters
polarization_states
- Drawing functions
draw: intensity, intensities, phases, fields, stokes, param_ellipse, ellipses
- class diffractio.vector_fields_X.Vector_field_X(x, wavelength, info='')[source]
Bases:
object
Class for vectorial fields.
- Parameters:
x (numpy.array) – linear array with equidistant positions. The number of data is preferibly 2**n.
wavelength (float) – wavelength of the incident field
info (str) – String with info about the simulation
- self.x
linear array with equidistant positions. The number of data is preferibly 2**n.
- Type:
numpy.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.Ex
Electric_x field
- Type:
numpy.array
- self.Ey
Electric_y field
- Type:
numpy.array
- self.Ez
Electric_z field
- Type:
numpy.array
- save_data(filename, add_name='', description='', verbose=False)[source]
Common save data function to be used in all the modules. The methods included are: npz, matlab
- Parameters:
filename (str) – filename
add_name= (str) – sufix to the name, if ‘date’ includes a date
description (str) – text to be stored in the dictionary to save.
verbose (bool) – If verbose prints filename.
- Returns:
filename. If False, file could not be saved.
- Return type:
(str)
- load_data(filename, verbose=False)[source]
- Load data from a file to a Vector_field_X.
The methods included are: npz, matlab
- Parameters:
filename (str) – filename
verbose (bool) – shows data process by screen
- get(kind='fields', is_matrix=True)[source]
Takes the vector field and divide in Scalar_field_X.
- Parameters:
kind (str) – ‘fields’, ‘intensity’, ‘intensities’, ‘phases’, ‘stokes’, ‘params_ellipse’
- Returns:
(Ex, Ey, Ez),
- Return type:
- apply_mask(u)[source]
Multiply field by binary scalar mask: self.Ex = self.Ex * u.u
- Parameters:
u (Scalar_mask_X) – mask
- polarization_states(matrix=False)[source]
returns the Stokes parameters
- Parameters:
Matrix (bool) – if True returns Matrix, else Scalar_field_X
- Returns:
S0,S1,S2,S3 images for Matrix=True S0,S1,S2,S3 for Matrix=False
- polarization_ellipse(pol_state=None, matrix=False)[source]
returns A, B, theta, h polarization parameter of elipses
- Parameters:
pol_state (None or (I, Q, U, V)) – Polarization state previously computed
Matrix (bool) – if True returns Matrix, else Scalar_field_X
- Returns:
A, B, theta, h for Matrix=True CA, CB, Ctheta, Ch for Matrix=False
- draw(kind='intensity', logarithm=0, normalize=False, cut_value=None, filename='', draw=True, **kwargs)[source]
Draws electromagnetic field
- Parameters:
kind (str) – ‘intensity’, ‘intensities’, intensities_rz, ‘phases’, fields’, ‘stokes’
logarithm (float) – If >0, intensity is scaled in logarithm
normalize (bool) – If True, max(intensity)=1
cut_value (float) – If not None, cuts the maximum intensity to this value
filename (str) – if not ‘’ stores drawing in file,
4.1.22. diffractio.vector_fields_XY module
This module generates Vector_field_XY class. It is required also for generating masks and fields. The main atributes are:
self.Ex - x component of electric field
self.Ey - y component of electric field
self.Ez - z component of electric field
self.wavelength - wavelength of the incident field. The field is monocromatic
self.x - x positions of the field
self.y - y positions of the field
self.X (numpy.array): equal size to x * y. complex field
self.Y (numpy.array): equal size to x * y. complex field
self.quality (float): quality of RS algorithm
self.info (str): description of data
self.type (str): Class of the field
self.date (str): date when performed
The magnitude is related to microns: micron = 1.
Class for XY vector fields
- Definition of a scalar field
add, substract fields
save, load data, clean, get, normalize
cut_resample
appy_mask
- Vector parameters
polarization_states
polarization_ellipse
- Propagation
RS - Rayleigh Sommerfeld
- Drawing functions
draw: intensity, intensities, phases, fields, stokes, param_ellipse, ellipses
- class diffractio.vector_fields_XY.Vector_field_XY(x, y, wavelength, info='')[source]
Bases:
object
Class for vectorial fields.
- Parameters:
x (numpy.array) – linear array with equidistant positions. The number of data is preferibly 2**n.
y (numpy.array) – linear array with equidistant positions. The number of data is preferibly 2**n.
wavelength (float) – wavelength of the incident field
info (str) – String with info about the simulation
- self.x
linear array with equidistant positions. The number of data is preferibly 2**n.
- Type:
numpy.array
- self.y
linear array with equidistant positions. The number of data is preferibly 2**n.
- Type:
numpy.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.Ex
Electric_x field
- Type:
numpy.array
- self.Ey
Electric_y field
- Type:
numpy.array
- save_data(filename, add_name='', description='', verbose=False)[source]
Common save data function to be used in all the modules. The methods included are: npz, matlab
- Parameters:
filename (str) – filename
add_name= (str) – sufix to the name, if ‘date’ includes a date
description (str) – text to be stored in the dictionary to save.
verbose (bool) – If verbose prints filename.
- Returns:
filename. If False, file could not be saved.
- Return type:
(str)
- load_data(filename, verbose=False)[source]
- Load data from a file to a Vector_field_XY.
The methods included are: npz, matlab
- Parameters:
filename (str) – filename
verbose (bool) – shows data process by screen
- get(kind='fields', is_matrix=True)[source]
Takes the vector field and divide in Scalar_field_XY
- Parameters:
kind (str) – ‘fields’, ‘intensity’, ‘intensities’, ‘phases’, ‘stokes’, ‘params_ellipse’
- Returns:
(Ex, Ey),
- Return type:
- pupil(r0=None, radius=None, angle=0.0)[source]
place a pupil in the field. If r0 or radius are None, they are computed using the x,y parameters.
- Parameters:
r0 (float, float) – center of circle/ellipse
radius (float, float) or (float) – radius of circle/ellipse
angle (float) – angle of rotation in radians
Example
pupil(r0=(0 * um, 0 * um), radius=(250 * um, 125 * um), angle=0 * degrees)
- apply_mask(u)[source]
Multiply field by binary scalar mask: self.Ex = self.Ex * u.u
- Parameters:
u (Scalar_mask_XY) – mask
- RS(z=10000.0, n=1, new_field=True, amplification=(1, 1), verbose=False)[source]
Fast-Fourier-Transform method for numerical integration of diffraction Rayleigh-Sommerfeld formula. Thin Element Approximation is considered for determining the field just after the mask: \(\mathbf{E}_{0}(\zeta,\eta)=t(\zeta,\eta)\mathbf{E}_{inc}(\zeta,\eta)\) Is we have a field of size N*M, the result of propagation is also a field N*M. Nevertheless, there is a parameter amplification which allows us to determine the field in greater observation planes (jN)x(jM).
- Parameters:
z (float) – distance to observation plane. if z<0 inverse propagation is executed
n (float) – refraction index
new_field (bool) – if False the computation goes to self.u if True a new instance is produced
amplification (int, int) – number of frames in x and y direction
verbose (bool) – if True it writes to shell. Not implemented yet
- Returns:
Scalar_field_X else None
- Return type:
if New_field is True
Note
One adventage of this approach is that it returns a quality parameter: if self.quality>1, propagation is right.
References
From Applied Optics vol 45 num 6 pp. 1102-1110 (2006)
- VFFT(radius, focal, n=1, new_field=False, shift=True, remove0=True, matrix=False, has_draw=False)[source]
Vector Fast Fourier Transform (FFT) of the field.
The focusing system, shown schematically in Fig. 1 is modelled by a high NA, aberration-free, aplanatic lens obeying the sine condition, having a focal length fand collecting light under a convergence angle theta_max. Denoting the refractive index of the medium in the focal region with n, the NA of the lens can be written as NA= n sin theta_max. The polarization changes on the lens surfaces described by the Fresnel formulae have been neglected.
Ei = (Eix, Eiy, Eiz) is the local electric field vector.
- Parameters:
radius (float) – radius of lens
focal (float) – focal
n (float) – refraction index
matrix (bool) – if True only matrix is returned. if False, returns Scalar_field_X.
new_field (bool) – if True returns Vector_field_XY, else it puts in self.
shift (bool) – if True, fftshift is performed.
remove0 (bool) – if True, central point is removed.
has_draw (bool) – if True draw the field.
- Returns:
FFT of the input field.
- Return type:
(np.array or vector_fields_XY or None)
- Reference:
Jahn, Kornél, and Nándor Bokor. 2010. “Intensity Control of the Focal Spot by Vectorial Beam Shaping.” Optics Communications 283 (24): 4859–65. https://doi.org/10.1016/j.optcom.2010.07.030.
TODO: Some inconsistency in the radius of the circle lower than the size of the field.
- IVFFT(radius, focal, n=1, new_field=False, matrix=False, has_draw=False)[source]
Inverse Vector Fast Fourier Transform (FFT) of the field.
The focusing system, shown schematically in Fig. 1 is modelled by a high NA, aberration-free, aplanatic lens obeying the sine condition, having a focal length fand collecting light under a convergence angle theta_max. Denoting the refractive index of the medium in the focal region with n, the NA of the lens can be written as NA= n sin theta_max. The polarization changes on the lens surfaces described by the Fresnel formulae have been neglected.
Ei = (Eix, Eiy, Eiz) is the local electric field vector.
- Parameters:
radius (float) – radius of lens
focal (float) – focal
n (float) – refraction index
matrix (bool) – if True only matrix is returned. if False, returns Scalar_field_X.
new_field (bool) – if True returns Vector_field_XY, else it puts in self.
has_draw (bool) – if True draw the field.
- Returns:
FFT of the input field.
- Return type:
(np.array or vector_fields_XY or None)
- Reference:
Jahn, Kornél, and Nándor Bokor. 2010. “Intensity Control of the Focal Spot by Vectorial Beam Shaping.” Optics Communications 283 (24): 4859–65. https://doi.org/10.1016/j.optcom.2010.07.030.
TODO: Radius of the circle lower than the size of the field.
- VRS(z, n=1, new_field=True, verbose=False, amplification=(1, 1))[source]
Fast-Fourier-Transform method for numerical integration of diffraction Vector Rayleigh-Sommerfeld formula.
- Parameters:
z (float) – distance to observation plane. if z<0 inverse propagation is executed
n (float) – refraction index
new_field (bool) – if False the computation goes to self.u. If True a new instance is produced
verbose (bool) – if True it writes to shell. Not implemented yet
- Returns:
Scalar_field_X, else None
- Return type:
if New_field is True
References
H. Ye, C.-W. Qiu, K. Huang, J. Teng, B. Luk’yanchuk, y S. P. Yeo, «Creation of a longitudinally polarized subwavelength hotspot with an ultra-thin planar lens: vectorial Rayleigh–Sommerfeld method», Laser Phys. Lett., vol. 10, n.º 6, p. 065004, jun. 2013. DOI: 10.1088/1612-2011/10/6/065004 http://stacks.iop.org/1612-202X/10/i=6/a=065004?key=crossref.890761f053b56d7a9eeb8fc6da4d9b4e
- CZT(z, xout=None, yout=None, verbose=False)[source]
Vector Z Chirped Transform algorithm (VCZT)
- Parameters:
z (float) – diffraction distance
xout (np.array) – x array with positions of the output plane
yout (np.array) – y array with positions of the output plane
verbose (bool) – If True prints some information
- Returns:
Output field. It depends on the size of xout, yout, and z.
- Return type:
E_out (variable)
References
[Light: Science and Applications, 9(1), (2020)]
- polarization_states(matrix=False)[source]
returns the Stokes parameters
- Parameters:
Matrix (bool) – if True returns Matrix, else Scalar_field_XY
- Returns:
S0,S1,S2,S3 images for Matrix=True S0,S1,S2,S3 for Matrix=False
- polarization_ellipse(pol_state=None, matrix=False)[source]
returns A, B, theta, h polarization parameter of elipses
- Parameters:
pol_state (None or (I, Q, U, V)) – Polarization state previously computed
Matrix (bool) – if True returns Matrix, else Scalar_field_XY
- Returns:
A, B, theta, h for Matrix=True CA, CB, Ctheta, Ch for Matrix=False
- cut_resample(x_limits='', y_limits='', num_points=[], new_field=False, interp_kind=(3, 1))[source]
Cuts the field to the range (x0,x1). (y0,y1). If one of this x0,x1 positions is out of the self.x range it do nothing. It is also valid for resampling the field, just write x0,x1 as the limits of self.x
- Parameters:
x_limits (float,float) – (x0,x1) starting and final points to cut. if ‘’ - takes the current limit x[0] and x[-1]
y_limits (float,float) – (y0,y1) - starting and final points to cut. if ‘’ - takes the current limit y[0] and y[-1]
num_points (int) – it resamples x, y and u. [],’’,0,None -> it leave the points as it is
new_field (bool) – it returns a new Scalar_field_XY
interp_kind (int) – numbers between 1 and 5
- draw(kind='intensity', logarithm=0, normalize=False, cut_value=None, num_ellipses=(11, 11), amplification=0.5, filename='', draw=True, only_image=False, **kwargs)[source]
Draws electromagnetic field
- Parameters:
kind (str) – ‘intensity’, ‘intensities’, intensities_rz, ‘phases’, fields’, ‘stokes’, ‘param_ellipse’, ‘ellipses’
logarithm (float) – If >0, intensity is scaled in logarithm
normalize (bool) – If True, max(intensity)=1
cut_value (float) – If not None, cuts the maximum intensity to this value
num_ellipses (int) – number of ellipses for parameters_ellipse
amplification (float) – amplification of ellipses
filename (str) – if not ‘’ stores drawing in file,
4.1.23. diffractio.vector_fields_XYZ module
This module generates Vector_field_XYZ class. It is required also for generating masks and fields. The main atributes are:
self.Ex - x component of electric field
self.Ey - y component of electric field
self.Ez - z component of electric field
self.wavelength - wavelength of the incident field. The field is monocromatic
self.x - x positions of the field
self.y - y positions of the field
self.z - z positions of the field
self.X (numpy.array): equal size to x * y * z. complex field
self.Y (numpy.array): equal size to x * y * z. complex field
self.Z (numpy.array): equal size to x * y * z. complex field
self.quality (float): quality of RS algorithm
self.info (str): description of data
self.type (str): Class of the field
self.date (str): date when performed
The magnitude is related to microns: micron = 1.
Class for XY vector fields
- Definition of a scalar field
add, substract fields
save, load data, clean, get, normalize
cut_resample
appy_mask
- Vector parameters
polarization_states
polarization_ellipse
- Propagation
RS - Rayleigh Sommerfeld
- Drawing functions
draw: intensity, intensities, phases, fields, stokes, param_ellipse, ellipses
- class diffractio.vector_fields_XYZ.Vector_field_XYZ(x, y, z, wavelength, info='')[source]
Bases:
object
Class for vectorial fields.
- Parameters:
x (numpy.array) – linear array with equidistant positions. The number of data is preferibly 2**n.
y (numpy.array) – linear array with equidistant positions. The number of data is preferibly 2**n.
z (numpy.array) – linear array with equidistant positions. The number of data is preferibly 2**n.
wavelength (float) – wavelength of the incident field
info (str) – String with info about the simulation
- self.x
linear array with equidistant positions. The number of data is preferibly 2**n.
- Type:
numpy.array
- self.y
linear array with equidistant positions. The number of data is preferibly 2**n.
- Type:
numpy.array
- self.z
linear array with equidistant positions. The number of data is preferibly 2**n.
- Type:
numpy.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.Ex
Electric_x field
- Type:
numpy.array
- self.Ey
Electric_y field
- Type:
numpy.array
- self.Ez
Electric_z field
- Type:
numpy.array
- save_data(filename, add_name='', description='', verbose=False)[source]
Common save data function to be used in all the modules. The methods included are: npz, matlab
- Parameters:
filename (str) – filename
add_name= (str) – sufix to the name, if ‘date’ includes a date
description (str) – text to be stored in the dictionary to save.
verbose (bool) – If verbose prints filename.
- Returns:
filename. If False, file could not be saved.
- Return type:
(str)
- load_data(filename, verbose=False)[source]
- Load data from a file to a Vector_field_XY.
The methods included are: npz, matlab
- Parameters:
filename (str) – filename
verbose (bool) – shows data process by screen
- get(kind='fields', is_matrix=True)[source]
Takes the vector field and divide in Scalar_field_XYZ
- Parameters:
kind (str) – ‘fields’, ‘intensity’, ‘intensities’, ‘phases’, ‘stokes’, ‘params_ellipse’
- Returns:
(Ex, Ey),
- Return type:
- polarization_states(matrix=False)[source]
returns the Stokes parameters
- Parameters:
Matrix (bool) – if True returns Matrix, else Scalar_field_XYZ
- Returns:
S0,S1,S2,S3 images for Matrix=True S0,S1,S2,S3 for Matrix=False
- polarization_ellipse(pol_state=None, matrix=False)[source]
returns A, B, theta, h polarization parameter of elipses
- Parameters:
pol_state (None or (I, Q, U, V)) – Polarization state previously computed
Matrix (bool) – if True returns Matrix, else Scalar_field_XYZ
- Returns:
A, B, theta, h for Matrix=True CA, CB, Ctheta, Ch for Matrix=False
- normalize(new_field=False)[source]
Normalizes the field so that intensity.max()=1.
- Parameters:
new_field (bool) – If False the computation goes to self.u. If True a new instance is produced
- Returns
u (numpy.array): normalized optical field
- to_Vector_field_XY(iz0=None, z0=None, is_class=True, matrix=False)[source]
pass results to Scalar_field_XY. Only one of the first two variables (iz0,z0) should be used
- Parameters:
iz0 (int) – position i of z data in array
z0 (float) – position z to extract
class (bool) – If True it returns a class
matrix (bool) – If True it returns a matrix
TODO: Simplify and change variable name clase
- to_Vector_field_XZ(iy0=None, y0=None, is_class=True, matrix=False)[source]
pass results to Vector_field_XZ. Only one of the first two variables (iy0,y0) should be used
- Parameters:
iy0 (int) – position i of y data in array
y0 (float) – position y to extract
class (bool) – If True it returns a class
matrix (bool) – If True it returns a matrix
- to_Vector_field_YZ(ix0=None, x0=None, is_class=True, matrix=False)[source]
pass results to Vector_field_XZ. Only one of the first two variables (iy0,y0) should be used
- Parameters:
ix0 (int) – position i of x data in array
x0 (float) – position x to extract
class (bool) – If True it returns a class
matrix (bool) – If True it returns a matrix
- to_Z(kind='amplitude', x0=None, y0=None, has_draw=True, z_scale='mm')[source]
pass results to u(z). Only one of the first two variables (iy0,y0) and (ix0,x0) should be used.
- Parameters:
kind (str) – ‘amplitude’, ‘intensity’, ‘phase’
x0 (float) – position x to extract
y0 (float) – position y to extract
has_draw (bool) – draw the field
z_scale (str) – ‘mm’, ‘um’
- Returns:
array with z field (numpy.array): amplitude, intensity or phase of the field
- Return type:
z (numpy.array)
- draw_XY(z0=5000.0, kind='intensity', logarithm=0, normalize='maximum', title='', filename='', cut_value='', has_colorbar='False', reduce_matrix='')[source]
longitudinal profile XY at a given z value
- Parameters:
z0 (float) – value of z for interpolation
kind (str) – type of drawing: ‘amplitude’, ‘intensity’, ‘phase’, ‘ ‘field’, ‘real_field’, ‘contour’
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (str) – False, ‘maximum’, ‘area’, ‘intensity’
title (str) – title for the drawing
filename (str) – if not ‘’ stores drawing in file,
cut_value (float) – if provided, maximum value to show
has_colorbar (bool) – if True draws the colorbar
() (reduce_matrix) –
- draw_XZ(kind='intensity', y0=0.0, logarithm=0, normalize='', draw_borders=False, filename='', **kwargs)[source]
Longitudinal profile XZ at a given x0 value.
- Parameters:
y0 (float) – value of y for interpolation
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (str) – False, ‘maximum’, ‘intensity’, ‘area’
draw_borders (bool) – check
filename (str) – filename to save
- draw_YZ(x0=0.0, logarithm=0, normalize='', draw_borders=False, filename='')[source]
Longitudinal profile YZ at a given x0 value.
- Parameters:
x0 (float) – value of x for interpolation
logarithm (bool) – If True, intensity is scaled in logarithm
normalize (str) – False, ‘maximum’, ‘intensity’, ‘area’
draw_borders (bool) – check
filename (str) – filename to save
4.1.24. diffractio.vector_fields_XZ module
This module generates Vector_field_X class. It is required also for generating masks and fields. The main atributes are:
self.x - x positions of the field
self.Ex - x component of electric field
self.Ey - y component of electric field
self.Ez - z component of electric field
self.wavelength - wavelength of the incident field. The field is monocromatic
self.info (str): description of data
self.type (str): Class of the field
self.date (str): date when performed
The magnitude is related to microns: micron = 1.
Class for X vector fields
- Definition of a scalar field
add, substract fields
save, load data, clean, get, normalize
cut_resample
- Vector parameters
polarization_states
- Drawing functions
draw: intensity, intensities, phases, fields, stokes, param_ellipse, ellipses
- class diffractio.vector_fields_XZ.Vector_field_XZ(x, z, wavelength, info='')[source]
Bases:
object
Class for vectorial fields.
- Parameters:
x (numpy.array) – linear array with equidistant positions. The number of data is preferibly 2**n.
wavelength (float) – wavelength of the incident field
info (str) – String with info about the simulation
- self.x
linear array with equidistant positions. The number of data is preferibly 2**n.
- Type:
numpy.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.Ex
Electric_x field
- Type:
numpy.array
- self.Ey
Electric_y field
- Type:
numpy.array
- self.Ez
Electric_z field
- Type:
numpy.array
- save_data(filename, add_name='', description='', verbose=False)[source]
Common save data function to be used in all the modules. The methods included are: npz, matlab
- Parameters:
filename (str) – filename
add_name= (str) – sufix to the name, if ‘date’ includes a date
description (str) – text to be stored in the dictionary to save.
verbose (bool) – If verbose prints filename.
- Returns:
filename. If False, file could not be saved.
- Return type:
(str)
- load_data(filename, verbose=False)[source]
- Load data from a file to a Vector_field_X.
The methods included are: npz, matlab
- Parameters:
filename (str) – filename
verbose (bool) – shows data process by screen
- get(kind='fields', is_matrix=True)[source]
Takes the vector field and divide in Scalar_field_X.
- Parameters:
kind (str) – ‘fields’, ‘intensity’, ‘intensities’, ‘phases’, ‘stokes’, ‘params_ellipse’
- Returns:
(Ex, Ey, Ez),
- Return type:
- apply_mask(u)[source]
Multiply field by binary scalar mask: self.Ex = self.Ex * u.u
- Parameters:
u (Scalar_mask_X) – mask
- polarization_states(matrix=False)[source]
returns the Stokes parameters
- Parameters:
Matrix (bool) – if True returns Matrix, else Scalar_field_X
- Returns:
S0,S1,S2,S3 images for Matrix=True S0,S1,S2,S3 for Matrix=False
- polarization_ellipse(pol_state=None, matrix=False)[source]
returns A, B, theta, h polarization parameter of elipses
- Parameters:
pol_state (None or (I, Q, U, V)) – Polarization state previously computed
Matrix (bool) – if True returns Matrix, else Scalar_field_X
- Returns:
A, B, theta, h for Matrix=True CA, CB, Ctheta, Ch for Matrix=False
- normalize(new_field=False)[source]
Normalizes the field so that intensity.max()=1.
- Parameters:
new_field (bool) – If False the computation goes to self.u. If True a new instance is produced
- Returns
u (numpy.array): normalized optical field
- draw(kind='intensity', logarithm=0, normalize=False, cut_value=None, filename='', draw=True, **kwargs)[source]
Draws electromagnetic field
- Parameters:
kind (str) – ‘intensity’, ‘intensities’, intensities_rz, ‘phases’, fields’, ‘stokes’
logarithm (float) – If >0, intensity is scaled in logarithm
normalize (bool) – If True, max(intensity)=1
cut_value (float) – If not None, cuts the maximum intensity to this value
filename (str) – if not ‘’ stores drawing in file,
- diffractio.vector_fields_XZ.polarization_ellipse(self, pol_state=None, matrix=False)[source]
returns A, B, theta, h polarization parameter of elipses
- Parameters:
pol_state (None or (I, Q, U, V)) – Polarization state previously computed
Matrix (bool) – if True returns Matrix, else Scalar_field_X
- Returns:
A, B, theta, h for Matrix=True CA, CB, Ctheta, Ch for Matrix=False
4.1.25. diffractio.vector_fields_Z module
This module generates Vector_field_Z class. It is required also for generating masks and fields. The main atributes are:
self.z - z positions of the field
self.Ex - x component of electric field
self.Ey - y component of electric field
self.Ez - z component of electric field
self.wavelength - wavelength of the incident field. The field is monocromatic
self.info (str): description of data
self.type (str): Class of the field
self.date (str): date when performed
The magnitude is related to microns: micron = 1.
Class for X vector fields
- Definition of a scalar field
add, substract fields
save, load data, clean, get, normalize
cut_resample
- Vector parameters
polarization_states
- Drawing functions
draw: intensity, intensities, phases, fields, stokes, param_ellipse, ellipses
- class diffractio.vector_fields_Z.Vector_field_Z(z, wavelength, info='')[source]
Bases:
object
Class for vectorial fields.
- Parameters:
x (numpy.array) – linear array with equidistant positions. The number of data is preferibly 2**n.
wavelength (float) – wavelength of the incident field
info (str) – String with info about the simulation
- self.z
linear array with equidistant positions. The number of data is preferibly 2**n.
- Type:
numpy.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.Ex
Electric_x field
- Type:
numpy.array
- self.Ey
Electric_y field
- Type:
numpy.array
- self.Ez
Electric_z field
- Type:
numpy.array
- save_data(filename, add_name='', description='', verbose=False)[source]
Common save data function to be used in all the modules. The methods included are: npz, matlab
- Parameters:
filename (str) – filename
add_name= (str) – sufix to the name, if ‘date’ includes a date
description (str) – text to be stored in the dictionary to save.
verbose (bool) – If verbose prints filename.
- Returns:
filename. If False, file could not be saved.
- Return type:
(str)
- load_data(filename, verbose=False)[source]
- Load data from a file to a Vector_field_Z.
The methods included are: npz, matlab
- Parameters:
filename (str) – filename
verbose (bool) – shows data process by screen
- get(kind='fields', is_matrix=True)[source]
Takes the vector field and divide in Scalar_field_Z.
- Parameters:
kind (str) – ‘fields’, ‘intensity’, ‘intensities’, ‘phases’, ‘stokes’, ‘params_ellipse’
- Returns:
(Ex, Ey, Ez),
- Return type:
- apply_mask(u)[source]
Multiply field by binary scalar mask: self.Ex = self.Ex * u.u
- Parameters:
u (Scalar_mask_X) – mask
- polarization_states(matrix=False)[source]
returns the Stokes parameters
- Parameters:
Matrix (bool) – if True returns Matrix, else Scalar_field_Z
- Returns:
S0,S1,S2,S3 images for Matrix=True S0,S1,S2,S3 for Matrix=False
- polarization_ellipse(pol_state=None, matrix=False)[source]
returns A, B, theta, h polarization parameter of elipses
- Parameters:
pol_state (None or (I, Q, U, V)) – Polarization state previously computed
Matrix (bool) – if True returns Matrix, else Scalar_field_Z
- Returns:
A, B, theta, h for Matrix=True CA, CB, Ctheta, Ch for Matrix=False
- normalize(new_field=False)[source]
Normalizes the field so that intensity.max()=1.
- Parameters:
new_field (bool) – If False the computation goes to self.u. If True a new instance is produced
- Returns
u (numpy.array): normalized optical field
- draw(kind='intensity', logarithm=0, normalize=False, cut_value=None, filename='', draw=True, **kwargs)[source]
Draws electromagnetic field
- Parameters:
kind (str) – ‘intensity’, ‘intensities’, intensities_rz, ‘phases’, fields’, ‘stokes’
logarithm (float) – If >0, intensity is scaled in logarithm
normalize (bool) – If True, max(intensity)=1
cut_value (float) – If not None, cuts the maximum intensity to this value
filename (str) – if not ‘’ stores drawing in file,
4.1.26. diffractio.vector_masks_XY module
This module generates Vector_mask_XY class for defining vector masks. Its parent is Vector_field_XY. The main atributes are:
self.x (numpy.array): linear array with equidistant positions. The number of data is preferibly 2**n. self.y (numpy.array): linear array with equidistant positions. The number of data is preferibly 2**n. self.wavelength (float): wavelength of the incident field. self.Ex (numpy.array): Electric_x field self.Ey (numpy.array): Electric_y field
Class for bidimensional vector XY masks
- Functions
unique_masks
equal_masks
global_mask
complementary_masks
from_py_pol
polarizer_linear
quarter_waveplate
half_wave
polarizer_retarder
- class diffractio.vector_masks_XY.Vector_mask_XY(x, y, wavelength, info='')[source]
Bases:
Vector_field_XY
- apply_circle(r0=None, radius=None)[source]
The same circular mask is applied to all the Jones Matrix.
- Parameters:
r0 (float, float) – center, if None it is generated
radius (float, float) – radius, if None it is generated
- pupil(r0=None, radius=None, angle=0.0)[source]
place a pupil in the mask. If r0 or radius are None, they are computed using the x,y parameters.
- Parameters:
r0 (float, float) – center of circle/ellipse
radius (float, float) or (float) – radius of circle/ellipse
angle (float) – angle of rotation in radians
Example
pupil(r0=(0 * um, 0 * um), radius=(250*um, 125*um), angle=0*degrees)
- scalar_to_vector_mask(mask, state, is_intensity=True)[source]
The same mask (binary) is applied to all the Jones Matrix.
- Parameters:
mask (scalar_mask_XY) – mask to apply.
state (Jones Matrix or Jones_matrix) – Polarization state to apply
intensity (is) – If True, abs(mask)**2 is applied.
- complementary_masks(mask, state_0, state_1, is_binarized=True)[source]
Creates a vector mask from a scalar mask. It assign an state_0 to 0 values and a state_1 to 1 values.. For generality, ik mask is a decimal number between 0 and 1, it takes the linear interpolation.
- Parameters:
mask (scalar_mask_XY) – Mask preferently binary. if not, it is binarized
state_0 (2x2 numpy.array or Jones_matrix) – Jones matrix for 0s.
state_1 (2x2 numpy.array or Jones_matrix) – Jones matrix for 1s.
Warning
TODO: Mask should be binary. Else the function should binarize it.
- multilevel_mask(mask, states, discretize=True, normalize=True)[source]
Generates a multilevel vector mask, based in a scalar_mask_XY. The levels should be integers in amplitude (0,1,…, N). If it is not like this, discretize generates N levels. Usually masks are 0-1. Then normalize generates levels 0-N.
- Parameters:
mask (scalar_mask_XY) – 0-N discrete scalar mask.
states (np.array or Jones_matrix) – Jones matrices to assign to each level
discretize (bool) – If True, a continuous mask is converted to N levels.
normalize (bool) – If True, levels are 0,1,.., N.
- from_py_pol(polarizer)[source]
Generates a constant polarization mask from py_pol Jones_matrix. This is the most general function to obtain a polarizer.
- Parameters:
polarizer (2x2 numpy.matrix) – Jones_matrix
- polarizer_linear(azimuth=0.0)[source]
Generates an XY linear polarizer.
- Parameters:
angle (float) – linear polarizer angle
- quarter_waveplate(azimuth=0.0)[source]
Generates an XY quarter wave plate.
- Parameters:
azimuth (float) – polarizer angle
- half_waveplate(azimuth=0.0)[source]
Generates an XY half wave plate.
- Parameters:
azimuth (float) – polarizer angle
4.1.27. diffractio.vector_sources_XY module
This module generates Vector_source_XY class for defining sources. Its parent is Vector_field_XY. The main atributes are:
x (numpy.array): linear array with equidistant positions. The number of data is preferibly 2**n.
y (numpy.array): linear array with equidistant positions. The number of data is preferibly 2**n.
wavelength (float): wavelength of the incident field
info (str): String with info about the simulation
The magnitude is related to microns: micron = 1.
Class for unidimensional scalar masks
- Functions
plane_wave
azimuthal_wave
radial_wave
gauss_wave
hermite_gauss_wave
local_polarized_vector_wave
local_polarized_vector_wave_radial
local_polarized_vector_wave_hybrid
- class diffractio.vector_sources_XY.Vector_source_XY(x, y, wavelength, info='')[source]
Bases:
Vector_field_XY
Class for vectorial fields.
- Parameters:
x (numpy.array) – linear array with equidistant positions. The number of data is preferibly 2**n.
y (numpy.array) – linear array with equidistant positions. The number of data is preferibly 2**n.
wavelength (float) – wavelength of the incident field
info (str) – String with info about the simulation
- self.x
linear array with equidistant positions. The number of data is preferibly 2**n.
- Type:
numpy.array
- self.y
linear array with equidistant positions. The number of data is preferibly 2**n.
- Type:
numpy.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.Ex
Electric_x field
- Type:
numpy.array
- self.Ey
Electric_y field
- Type:
numpy.array
- constant_polarization(u=1, v=(1, 0), has_normalization=False, radius=0.0)[source]
Provides a constant polarization to a scalar_source_xy
- Parameters:
u (Scalar_source_XY or np.complex) – field to apply the polarization or constant value
v (float, float) – polarization vector
normalize (bool) – If True, normalize polarization vector
- azimuthal_wave(u=1, r0=(0.0, 0.0), radius=0.0)[source]
Provides a constant polarization to a scalar_source_xy
- Parameters:
u (Scalar_source_XY or np.complex) – field to apply the polarization or constant value
r0 (float, float) – center of rotation
radius (float, float) – Radius of a circular mask
- radial_wave(u=1, r0=(0.0, 0.0), radius=0.0)[source]
Provides a constant polarization to a scalar_source_xy
- Parameters:
u (Scalar_source_XY or np.complex) – field to apply the polarization or constant value
r0 (float, float) – center of rotation
radius (float, float) – Radius of a circular mask
- radial_inverse_wave(u=1, r0=(0.0, 0.0), radius=0.0)[source]
Provides a constant polarization to a scalar_source_xy
- Parameters:
u (Scalar_source_XY or np.complex) – field to apply the polarization or constant value
r0 (float, float) – center of rotation
radius (float, float) – Radius of a circular mask
- azimuthal_inverse_wave(u=1, r0=(0.0, 0.0), radius=0.0)[source]
Provides a constant polarization to a scalar_source_xy
- Parameters:
u (Scalar_source_XY or np.complex) – field to apply the polarization or constant value
r0 (float, float) – center of rotation
radius (float, float) – Radius of a circular mask
- local_polarized_vector_wave(u=1, r0=(0.0, 0.0), m=1, fi0=0, radius=0.0)[source]
“local radial polarized vector wave.
- Parameters:
u (Scalar_source_XY or np.complex) – field to apply the polarization or constant value
r0 (float, float) – r0 of beam
m (integer) – integer with order
fi0 (float) – initial phase
radius (float, float) – Radius of a circular mask
References
Qwien Zhan ‘Vectorial Optical Fields’ page 33
- local_polarized_vector_wave_radial(u=1, r0=(0.0, 0.0), m=1, fi0=0, radius=0.0)[source]
local radial polarized vector wave.
- Parameters:
u (Scalar_source_XY or np.complex) – field to apply the polarization or constant value
r0 (float, float) – center of beam
m (integer) – integer with order
fi0 (float) – initial phase
radius (float, float) – Radius of a circular mask
References
Qwien Zhan ‘Vectorial Optical Fields’ page 36
- local_polarized_vector_wave_hybrid(u=1, r0=(0.0, 0.0), m=1, n=1, fi0=0, radius=(0, 0))[source]
- local hibrid polarized vector wave.
Qwien Zhan ‘Vectorial Optial Fields’ page 36
- Parameters:
u (Scalar_source_XY or np.complex) – field to apply the polarization or constant value
r0 (float, float) – center of beam
m (integer) – integer with order
n (integer) – integer with order
fi0 (float) – initial phase
radius (float, float) – Radius of a circular mask
- spiral_polarized_beam(u=1, r0=(0.0, 0.0), alpha=0, radius=(0, 0))[source]
Define spiral polarized beams:
- Parameters:
u (Scalar_source_XY or np.complex) – field to apply the polarization or constant value
r0 (float, float) – center of radiality
radius (float) – mask for circle if radius >0.
alpha (float) – angle of spiral.
- Reference:
Ramirez-Sanchez, G. Piquero, and M. Santarsiero,“Generation and characterization of spirally polarized fields,” J. Opt. A11,085708 (2009)
4.1.28. Module contents
Top-level package for Python Scalar and vector diffraction and interference.