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.diffractio module
Init module to control the rest of the modules.
- class diffractio.diffractio.Diffractio(kind: Literal['scalar', 'vector'], frame: Literal['field', 'mask', 'source'], x: ndarray[Any, dtype[floating]] | None = None, y: ndarray[Any, dtype[floating]] | None = None, z: ndarray[Any, dtype[floating]] | None = None, wavelength: float = 0, n_background: float = 1.0, info: str = '')[source]
Bases:
objectClass 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) – refractive 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
4.1.4. 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
- Args:
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: ndarray[Any, dtype[floating]] | None = None, wavelength: float = 0, n_background: float = 1.0, info: str = '')[source]
Bases:
objectClass 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) – refractive 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
- add(*args, **kwargs)
- rmul(*args, **kwargs)
- size(verbose: bool = False)[source]
returns the size of the instance in MB.
- Parameters:
verbose (bool, optional) – prints size in Mb. Defaults to False.
- Returns:
size in MB
- Return type:
float
- conjugate(*args, **kwargs)
- oversampling(*args, **kwargs)
- duplicate(clear: bool = 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.
- clear_field(*args, **kwargs)
- save_data(filename: str, add_name: str = '', description: str = '', verbose: bool = 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: str, verbose: bool = 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(*args, **kwargs)
- 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)
- get(*args, **kwargs)
- normalize(kind='amplitude', new_field: bool = False)[source]
Normalizes the field so that intensity.max()=1.
- Parameters:
kind (str) – ‘amplitude’, or ‘intensity’
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
- inverse_amplitude(*args, **kwargs)
- inverse_phase(*args, **kwargs)
- filter(*args, **kwargs)
- insert_mask(*args, **kwargs)
- pupil(*args, **kwargs)
- 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(*args, **kwargs)
- ifft(*args, **kwargs)
- RS(*args, **kwargs)
- CZT(*args, **kwargs)
- WPM(*args, **kwargs)
- to_far_field(angles: array, z_obs: float | None = None, has_draw: bool = True, has_logarithm=True, verbose: bool = True, **kwargs)[source]
Compute the far field of a source or mask.
The function calculates the far field (in angles) of a mask or source using the CZT function. In fact, the CZT function is used to compute the far field, and the x positions are computed considering far field.
- Parameters:
angles (np.array) – Angles to compute the far field.
z_obs (float | None, optional) – Distance where the far field is computed. If None, the distance is given by $pi size^2 /wavelength$. Defaults to None.
has_draw (bool, optional) – Draws the far field diffraction pattern, in angles. Defaults to False.
has_logarithm (bool, optional) – If True, the drawing is made in logarithm scale. Defaults to False.
verbose (bool, optional) – Prints information. Defaults to True.
- Returns:
Intensity at the far field
- Return type:
I_far (np.array)
- MTF(*args, **kwargs)
- intensity(*args, **kwargs)
- average_intensity(verbose: bool = 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(*args, **kwargs)
- get_RS_minimum_z(*args, **kwargs)
- draw(*args, **kwargs)
- diffractio.scalar_fields_X.kernelRS(x: ndarray[Any, dtype[floating]], wavelength: float, z: float, n: float = 1.0, kind: str = 'z', fast: bool = 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) – refractive 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: ndarray[Any, dtype[floating]], wavelength: float, z: float, n: float = 1.0, kind: str = 'z', fast: bool = 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) – refractive 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.kernelFresnel(x: ndarray[Any, dtype[floating]], wavelength: float, z: float, n: float = 1.0)[source]
Kernel for Fresnel propagation.
- Parameters:
x (numpy.np.array) – positions x
wavelength (float) – wavelength of incident fields
z (float) – distance for propagation
n (float) – refractive index of background
- Returns:
kernel
- Return type:
complex np.array
- diffractio.scalar_fields_X.PWD_kernel(u: ndarray[Any, dtype[complexfloating]], n: ndarray[Any, dtype[complexfloating]], k0: float, k_perp2: ndarray[Any, dtype[Any]], dz: float)[source]
Step for scalar (TE) Plane wave decomposition (PWD) algorithm.
- Parameters:
u (np.array) – fields
n (np.array) – refractive 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: ndarray[Any, dtype[complexfloating]], k0: float, k_perp2: ndarray[Any, dtype[complexfloating]], dz: float)[source]
Kernel for fast propagation of WPM method
- Parameters:
u (np.array) – fields
n (np.array) – refractive 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: ndarray[Any, dtype[floating]], spectrum: ndarray[Any, dtype[floating]], num_processors: int = 2, verbose: bool = 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 Args:
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: ndarray[Any, dtype[floating]], num_processors: int = 2, verbose: bool = 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 Args:
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: ndarray[Any, dtype[floating]], wavelengths: ndarray[Any, dtype[floating]], spectrum: ndarray[Any, dtype[floating]], num_processors: int = 2, verbose: bool = 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 Args:
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: ndarray[Any, dtype[floating]], num_x: int, z: float, wavelength: float, n: float = 1.0, verbose: bool = 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) – refractive index
- Returns:
_description_
- Return type:
_type_
- diffractio.scalar_fields_X.get_RS_minimum_z(range_x: float, num_x: int, wavelength: float, n: float = 1.0, quality=1.0, verbose: bool = 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.5. 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.
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.np.array): equal size to x * y. complex field
self.X (numpy.np.array): equal size to x * y. complex field
self.Y (numpy.np.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: ndarray[Any, dtype[floating]] | None = None, y: ndarray[Any, dtype[floating]] | None = None, wavelength: float = 0.0, n_background: float = 1.0, info: str = '')[source]
Bases:
objectClass for working with XY scalar fields.
- Parameters:
x (numpy.np.array) – linear np.array with equidistant positions. The number of data is preferibly \(2^n\) .
y (numpy.np.array) – linear np.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 np.array with equidistant positions. The number of data is preferibly \(2^n\) .
- Type:
numpy.np.array
- self.y
linear np.array wit equidistant positions for y values
- Type:
numpy.np.array
- self.wavelength
wavelength of the incident field.
- Type:
float
- self.u
(x,z) complex field
- Type:
numpy.np.array
- self.info
String with info about the simulation
- Type:
str
- add(other, kind)[source]
Adds two Scalar_field_xy. For example two light sources or two masks.
- Parameters:
other (Scalar_field_XY) – 2nd field to add
kind (str) – instruction how to add the fields: [‘source’, ‘mask’, ‘phases’, ‘distances’, ‘no_overlap].
'source' (-) – adds the fields as they are
'mask' (-) – adds the fields as complex numbers and then normalizes so that the maximum amplitude is 1.
'phases' (-) – adds the phases and then normalizes so that the maximum amplitude is 1.
'np_overlap' (-) – adds the fields as they are. If the sum of the amplitudes is greater than 1, an error is produced
'distances' (-) – adds the fields as they are. If the fields overlap, the field with the smallest distance is kept.
- Returns:
u3 = u1 + u2
- Return type:
- rmul(*args, **kwargs)
- size(verbose: bool = False)[source]
returns the size of the instance in MB.
- Parameters:
verbose (bool, optional) – prints size in Mb. Defaults to False.
- Returns:
size in MB
- Return type:
float
- conjugate(*args, **kwargs)
- reduce_to_1()[source]
All the values greater than 1 pass to 1. This is used for Scalar_masks when we add two masks.
- rotate(*args, **kwargs)
- apodization(*args, **kwargs)
- clear_field(*args, **kwargs)
- save_data(filename: str, add_name: str = '', description: str = '', verbose: bool = 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: str, verbose: bool = 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(*args, **kwargs)
- oversampling(*args, **kwargs)
- cut_resample(*args, **kwargs)
- 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)
- get(*args, **kwargs)
- pupil(*args, **kwargs)
- fft(*args, **kwargs)
- ifft(*args, **kwargs)
- RS(*args, **kwargs)
- WPM(*args, **kwargs)
- CZT(*args, **kwargs)
- profile(*args, **kwargs)
- draw_profile(*args, **kwargs)
- get_edges(kind_transition: str = 'amplitude', min_step: float = 0, verbose: bool = False, filename: str = '')[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:
np.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(*args, **kwargs)
- MTF(*args, **kwargs)
- beam_width_4s(*args, **kwargs)
- intensity(*args, **kwargs)
- average_intensity(*args, **kwargs)
- send_image_screen(*args, **kwargs)
- get_amplitude(*args, **kwargs)
- get_phase(*args, **kwargs)
- remove_phase(*args, **kwargs)
- binarize(*args, **kwargs)
- discretize(*args, **kwargs)
- normalize(*args, **kwargs)
- surface_detection(*args, **kwargs)
- get_RS_minimum_z(*args, **kwargs)
- draw(*args, **kwargs)
- diffractio.scalar_fields_XY.kernelRS(X: ndarray[Any, dtype[floating]], Y: ndarray[Any, dtype[floating]], wavelength: float, z: float, n: float = 1.0, kind: str = 'z')[source]
Kernel for RS propagation.
- Parameters:
X (numpy.np.array) – positions x
Y (numpy.np.array) – positions y
wavelength (float) – wavelength of incident fields
z (float) – distance for propagation
n (float) – refractive 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: ndarray[Any, dtype[floating]], Y: ndarray[Any, dtype[floating]], wavelength: float, z: float, n: float = 1.0, kind: str = 'z')[source]
Kernel for inverse RS propagation
- Parameters:
X (numpy.np.array) – positions x
Y (numpy.np.array) – positions y
wavelength (float) – wavelength of incident fields
z (float) – distance for propagation
n (float) – refractive 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: ndarray[Any, dtype[floating]], Y: ndarray[Any, dtype[floating]], wavelength: float, z: float, n: float = 1.0)[source]
Kernel for Fresnel propagation.
- Parameters:
X (numpy.np.array) – positions x
Y (numpy.np.array) – positions y
wavelength (float) – wavelength of incident fields
z (float) – distance for propagation
n (float) – refractive index of background
- Returns:
kernel
- Return type:
complex np.array
- diffractio.scalar_fields_XY.PWD_kernel(u: ndarray[Any, dtype[complexfloating]], n: float, k0: float, k_perp2: ndarray[Any, dtype[complexfloating]], dz: float)[source]
Step for scalar(TE) Plane wave decomposition(PWD) algorithm.
- Parameters:
u (np.array) – field
n (np.array) – refractive 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.np.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: ndarray[Any, dtype[complexfloating]], n: float, k0: float, k_perp2: ndarray[Any, dtype[complexfloating]], dz: float)[source]
Kernel for fast propagation of WPM method
- Parameters:
u (np.array) – fields
n (np.array) – refractive 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: float, range_y: float, num_x: int, num_y: int, wavelength: float, n: float = 1.0, quality: float = 1, verbose: bool = 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
n (float) – refractive index
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: float, range_y: float, num_x: int, num_y: int, z: float, wavelength: float, n: float = 1.0, verbose: bool = False)[source]
Determine the quality factor for RS algorithm
- 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
n (float) – refractive index
verbose (bool, optional) – prints info. Defaults to True.
- Returns:
_description_
- Return type:
_type_
4.1.6. 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 refractive index
self.n - refractive 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: ndarray[Any, dtype[floating]] | None = None, y: ndarray[Any, dtype[floating]] | None = None, z: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1.0, info: str = '')[source]
Bases:
objectClass 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) – refractive 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 refractive index.
- Type:
float
- self.n
refractive index. Same dimensions than self.u.
- Type:
numpy.array
- xy_2_xyz(u0_XY, z: ndarray[Any, dtype[floating]])[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
- add(other, kind)[source]
Adds two Scalar_field_xy. For example two light sources or two masks.
- Parameters:
other (Scalar_field_XY) – 2nd field to add
kind (str) – instruction how to add the fields: [‘source’, ‘mask’, ‘phases’, ‘distances’, ‘no_overlap].
'source' (-) – adds the fields as they are
'mask' (-) – adds the fields as complex numbers and then normalizes so that the maximum amplitude is 1.
'phases' (-) – adds the phases and then normalizes so that the maximum amplitude is 1.
'np_overlap' (-) – adds the fields as they are. If the sum of the amplitudes is greater than 1, an error is produced
'distances' (-) – adds the fields as they are. If the fields overlap, the field with the smallest distance is kept.
- Returns:
u3 = u1 + u2
- Return type:
- rmul(*args, **kwargs)
- size(verbose: bool = False)[source]
returns the size of the instance in MB.
- Parameters:
verbose (bool, optional) – prints size in Mb. Defaults to False.
- Returns:
size in MB
- Return type:
float
- conjugate(*args, **kwargs)
- normalize(kind='amplitude', new_field: bool = False)[source]
Normalizes the field so that intensity.max()=1.
- Parameters:
kind (str) – ‘amplitude’, or ‘intensity’
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
- duplicate(clear: bool = False)[source]
Duplicates the instance
- Parameters:
clear (bool, optional) – If True, clears the field. Defaults to False.
- Returns:
duplicated field
- Return type:
- reduce_to_1()[source]
All the values greater than 1 pass to 1. This is used for Scalar_masks when we add two masks.
- clear_field(*args, **kwargs)
- clear_refractive_index(*args, **kwargs)
- save_data(filename: str, add_name: str = '', description: str = '', verbose: bool = 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: str, verbose: bool = 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
- get(*args, **kwargs)
- intensity(*args, **kwargs)
- oversampling(*args, **kwargs)
- cut_resample(*args, **kwargs)
- incident_field(u0, z0: float | None = 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
- final_field(*args, **kwargs)
- RS(verbose: bool = False, num_processors=1)[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(*args, **kwargs)
- BPM(*args, **kwargs)
- PWD(*args, **kwargs)
- WPM(*args, **kwargs)
- to_Scalar_field_XY(*args, **kwargs)
- to_Scalar_field_XZ(*args, **kwargs)
- to_Scalar_field_YZ(*args, **kwargs)
- to_Scalar_field_Z(*args, **kwargs)
- average_intensity(*args, **kwargs)
- beam_widths(*args, **kwargs)
- surface_detection(*args, **kwargs)
- draw_proposal(*args, **kwargs)
- draw_XY(*args, **kwargs)
- draw_XZ(*args, **kwargs)
- draw_YZ(*args, **kwargs)
- draw_XYZ(*args, **kwargs)
- video_isovalue(filename: str, kind: Literal['intensity', 'refractive_index'] = 'refractive_index', **kwargs)[source]
_summary_
- Parameters:
filename (str) – filename. Defaults to ‘’.
kind (str, optional) – “intensity” or “refractive_index”. Defaults to ‘refractive_index’.
- video(*args, **kwargs)
4.1.7. 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 - refractive 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: ndarray[Any, dtype[floating]] | None = None, z: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1.0, info: str = '')[source]
Bases:
objectClass 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) – refractive 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) refractive 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
- rmul(*args, **kwargs)
- size(verbose: bool = False)[source]
returns the size of the instance in MB.
- Parameters:
verbose (bool, optional) – prints size in Mb. Defaults to False.
- Returns:
size in MB
- Return type:
float
- reduce_to_1()[source]
All the values greater than 1 pass to 1. This is used for Scalar_masks when we add two masks.
- duplicate(clear: bool = False)[source]
Duplicates the instance.
- Parameters:
clear (bool) – if True, it clears the field.
- Returns:
duplicated instance
- Return type:
- refractive_index_from_scalar_mask_XY(mask_XY, refractive_index_max: float)[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 refractive index.
- Returns:
_description_
- Return type:
_type_
- rotate_field(*args, **kwargs)
- clear_field(*args, **kwargs)
- clear_refractive_index(*args, **kwargs)
- normalize(kind='amplitude', new_field: bool = False)[source]
Normalizes the field so that intensity.max()=1.
- Parameters:
kind (str) – ‘amplitude’, or ‘intensity’
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(*args, **kwargs)
- smooth_refractive_index(*args, **kwargs)
- save_data(filename: str, add_name: str = '', description: str = '', verbose: bool = 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: str, verbose: bool = 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
- oversampling(*args, **kwargs)
- cut_resample(*args, **kwargs)
- incident_field(*args, **kwargs)
- final_field(*args, **kwargs)
- get(*args, **kwargs)
- BPM(*args, **kwargs)
- BPM_inverse(*args, **kwargs)
- BPM_back_propagation(verbose: bool = 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: float | None = None, verbose: bool = False, num_processors: int = 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:
Processing time
- PWD(*args, **kwargs)
- WPM(*args, **kwargs)
- RS_polychromatic(initial_field, wavelengths: ndarray[Any, dtype[floating]], spectrum: ndarray[Any, dtype[floating]] | None = None, verbose: bool = False, num_processors: int = 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(*args, **kwargs)
- WPM_polychromatic(*args, **kwargs)
- fast_propagation(*args, **kwargs)
- intensity(*args, **kwargs)
- average_intensity(*args, **kwargs)
- check_intensity(*args, **kwargs)
- detect_index_variations(*args, **kwargs)
- surface_detection(*args, **kwargs)
- draw(*args, **kwargs)
- draw_refractive_index(*args, **kwargs)
- draw_incident_field(*args, **kwargs)
- profile_longitudinal(*args, **kwargs)
- profile_transversal(*args, **kwargs)
- search_focus(*args, **kwargs)
- beam_widths(*args, **kwargs)
- video(*args, **kwargs)
- draw_profiles_interactive(*args, **kwargs)
4.1.8. 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
- Args:
intensity, average intensity
get_edges_transitions (mainly for pylithography)
- class diffractio.scalar_fields_Z.Scalar_field_Z(z: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1.0, info: str = '')[source]
Bases:
objectClass 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) – refractive 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
- rmul(*args, **kwargs)
- size(verbose: bool = False)[source]
returns the size of the instance in MB.
- Parameters:
verbose (bool, optional) – prints size in Mb. Defaults to False.
- Returns:
size in MB
- Return type:
float
- duplicate(*args, **kwargs)
- conjugate(*args, **kwargs)
- clear_field(*args, **kwargs)
- save_data(filename: str, add_name: str = '', description: str = '', verbose: bool = 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: str, verbose: bool = 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
- oversampling(*args, **kwargs)
- get(*args, **kwargs)
- cut_resample(*args, **kwargs)
- normalize(*args, **kwargs)
- intensity(*args, **kwargs)
- average_intensity(*args, **kwargs)
- FWHM1D(*args, **kwargs)
- DOF(*args, **kwargs)
- draw(kind: Literal['amplitude', 'intensity', 'field', 'phase'] = 'intensity', logarithm: float = 0.0, normalize: bool = False, cut_value: float | None = None, z_scale: str = 'um', unwrap: bool = False, filename: str = '')[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 (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
unwrap (bool) – If True, unwraps the phase.
filename (str) – if not ‘’ stores drawing in file,
4.1.9. 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: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1.0, info: str = '')[source]
Bases:
Scalar_field_XClass 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) – refractive 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(*args, **kwargs)
- mask_from_function(index: float = 1.5, f1: float = 0, f2: float = 0, v_globals: dict = {}, x0: float = 0.0, radius: float = 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) – refractive 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: float = 1.5, array1: ndarray[Any, dtype[floating]] | None = None, array2: ndarray[Any, dtype[floating]] | None = None, interp_kind: str = 'quadratic', radius: float = 0.0, x0: float = 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) – refractive 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: float | ndarray[Any, dtype[floating]])[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: float, size: float)[source]
Slit: 1 inside, 0 outside
- Parameters:
x0 (float) – center of slit
size (float) – size of slit
- double_slit(x0: float, size: float, separation: float)[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: float = 0.0, level2: float = 1.0, x_edge: float = 0.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: int, level_min: float = 0, level_max: float = 1)[source]
Divides the mask in n, vertical levels.
- Parameters:
num_levels (int) – number of levels
level_min (float) – minimum value of levels
level_max (float) – maximum value of levels
- prism(x0: float, n: float, angle: float)[source]
Prism.
- Parameters:
x0 (float) – vertex of prism
n (float) – refractive_index
angle (float) – angle of prism
- biprism_fresnel(angle: float, x0: float, radius: float = 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
- biprism_fresnel_nh(x0: float, width: float, height: float, n: float)[source]
Fresnel biprism, uses height and refractive index.
- Parameters:
x0 (float) – vertex of biprism
width (float) – size of biprism
height (float) – height of biprism
n (float) – refractive_index
- lens(x0: float, focal: float, radius: float = 0)[source]
Paraxial lens.
- Parameters:
x0 (float) – center of lens
focal (float) – focal length of lens
- lens_spherical(x0: float, radius: float, focal: float, refractive_index: float = 1.5)[source]
Spherical lens, without paraxial approximation. The focal distance and the refractive index are used for the definition. When the refractive 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 (refractive) – refractive index of the lens
- aspheric(x0: float, c: float, k: float, a: list, n0: float, n1: float, radius: float)[source]
Asferic surface. $z = frac{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 (tuple) – order aspheric coefficients: A4, A6, A8, …
n0 (float) – refractive index of first medium
n1 (float) – refractive index of second medium
radius (float) – radius of aspheric surface
Type (Conic Constant Surface)
spherical (k = 0)
Paraboloid (k = -1)
Hyperboloid (k < -1)
Ellipsoid (-1 < k < 0)
eliposid (k > 0 Oblate)
References
https://www.edmundoptics.com/knowledge-center/application-notes/optics/all-about-aspheric-lenses/
- fresnel_lens(x0: float, focal: float, kind: str = 'phase', binary: bool = False, phase: float = 3.141592653589793, radius: float = 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: float, s: float)[source]
Rough surface, phase
According to movile average (Ogilvy p.224). very good in time for long arrays
- Parameters:
t (float) – correlation length
s (float) – std of roughness
- Returns:
topography maps in microns
- Return type:
numpy.array
- dust_different_sizes(percentage: float, size: float, std: float = 0.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: float, size: float = 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: float, period: float, amp_min: float = 0, amp_max: float = 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: float, period: float, fill_factor: float = 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: float, period: float, fill_factor: float, a_min: float, a_max: float, phase: float)[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
a_min (float) – minimum amplitude
a_max (float) – maximum amplitude
phase (float) – phase shift (radians)
- blazed_grating(x0: float, period: float, phase_max: float)[source]
Phase, blazed grating. The phase shift is determined by heigth and refractive 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: str, p0: float, p1: float, amp_min: float, amp_max: float, phase_max: float, delta_x: float = 0, x0: float | None = None, length: float = 0, x_center: float = 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: str, p0: float, p1: float, amp_min: float, amp_max: float, phase_max: float, delta_x: float = 0, length: float = 0, x_center: float = 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: str, p_x: float, x0: float, amp_min: float, amp_max: float, phase_max: float, delta_x: float, length: float = 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: ndarray[Any, dtype[floating]], start: str = 'down', has_draw: bool = 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: float = 0.0, kind: str = 'standard', code: tuple[int] = [1, 1, 0, 0, 1, 0, 1], bit_width: float = 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.10. 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 - refractive 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: ndarray[Any, dtype[floating]] | None = None, y: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1.0, info: str = '')[source]
Bases:
Scalar_field_XYClass 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(*args, **kwargs)
- set_phase(*args, **kwargs)
- area(*args, **kwargs)
- inverse_amplitude(*args, **kwargs)
- inverse_phase(*args, **kwargs)
- filter(*args, **kwargs)
- widen(*args, **kwargs)
- extrude_mask_x(*args, **kwargs)
- mask_from_function(*args, **kwargs)
- image(*args, **kwargs)
- dxf(filename_dxf: str, num_pixels: tuple[int, int] | None = None, extent: tuple[float] | None = None, units: str = 'um', invert: bool = False, verbose: bool = False)[source]
Loads a dxf file. Internally it has the extension of the drawing, so it is not required to generate x,y spaces. It is possible with extent, but then the file is scaled. Warning: Dxf files are usually in mm. and diffractio works in um. To generate .u, a temporal .png file is generated. If x and y arrays are given, then num_pixels and extent are not used.
msp.units = 13 # 0 - sin , 4 mm, 12 nm, 13 um,
- Parameters:
filename_dxf (str) – DXF filename .dxf
num_pixels (tuple[int, int] | None, optional) – If . Defaults to None.
extent (_type_, optional) – _description_. Defaults to None.
units (str, optional) – _description_. Defaults to ‘mm’.
invert (bool, optional) – _description_. Defaults to False.
verbose (bool, optional) – _description_. Defaults to True.
- repeat_structure(*args, **kwargs)
- masks_to_positions(*args, **kwargs)
- polygon(*args, **kwargs)
- regular_polygon(*args, **kwargs)
- star(*args, **kwargs)
- triangle(*args, **kwargs)
- photon_sieve(*args, **kwargs)
- insert_array_masks(*args, **kwargs)
- dots(*args, **kwargs)
- dots_regular(*args, **kwargs)
- one_level(*args, **kwargs)
- two_levels(*args, **kwargs)
- edge_series(*args, **kwargs)
- edge_rough(*args, **kwargs)
- slit(*args, **kwargs)
- slit_rough(*args, **kwargs)
- slit_series(*args, **kwargs)
- double_slit(*args, **kwargs)
- double_slit_rough(*args, **kwargs)
- square(*args, **kwargs)
- gray_scale(*args, **kwargs)
- circle(r0: tuple[float, float], radius: float, angle: float = 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(*args, **kwargs)
- super_gauss(r0: tuple[float, float], radius: tuple[float] | float, power: float = 2, angle: float = 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(*args, **kwargs)
- angular_aperture(*args, **kwargs)
- ring(*args, **kwargs)
- rings(*args, **kwargs)
- cross(*args, **kwargs)
- prism(r0: tuple[float, float], angle_wedge: float, angle: float = 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(*args, **kwargs)
- lens_spherical(*args, **kwargs)
- aspheric(*args, **kwargs)
- lens_cylindrical(*args, **kwargs)
- fresnel_lens(*args, **kwargs)
- axicon(*args, **kwargs)
- axicon_binary(*args, **kwargs)
- biprism_fresnel(*args, **kwargs)
- radial_grating(*args, **kwargs)
- angular_grating(*args, **kwargs)
- hyperbolic_grating(*args, **kwargs)
- hammer(*args, **kwargs)
- archimedes_spiral(*args, **kwargs)
- laguerre_gauss_spiral(*args, **kwargs)
- forked_grating(r0: tuple[float, float], period: float, l: int, alpha: int, kind: str, angle: float = 0.0)[source]
Forked grating: np.exp(1.j * alpha * np.cos(l * THETA - 2 * np.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: float, period: float, amp_min: float = 0, amp_max: float = 1, angle: float = 0.0)[source]
Sinusoidal grating: self.u = amp_min + (amp_max - amp_min) * (1 + np.cos(2 * np.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)
- sine_edge_grating(*args, **kwargs)
- ronchi_grating(*args, **kwargs)
- binary_grating(*args, **kwargs)
- blazed_grating(*args, **kwargs)
- grating_2D(*args, **kwargs)
- grating_2D_chess(*args, **kwargs)
- squares_nxm(*args, **kwargs)
- roughness(*args, **kwargs)
- circle_rough(r0: tuple[float, float], radius: float, angle: float, sigma: float)[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(*args, **kwargs)
- fresnel_lens_rough(*args, **kwargs)
- super_ellipse(*args, **kwargs)
- superformula(*args, **kwargs)
- elliptical_phase(f1, f2, angle: float)[source]
Elliptical phase
- Parameters:
f1 (float) – focal f1
f2 (float) – focal f2
angle (float) – angle
- sinusoidal_slit(size: float, x0: float, amplitude: float, phase: float, period: float, angle: float = 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: tuple[float, float], slope: float, angle: float = 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(*args, **kwargs)
- laguerre_gauss_binary(*args, **kwargs)
4.1.11. 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 - refractive 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: ndarray[Any, dtype[floating]] | None = None, y: ndarray[Any, dtype[floating]] | None = None, z: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1.0, info: str = '')[source]
Bases:
Scalar_field_XYZ- mask_from_function(*args, **kwargs)
- object_by_surfaces(*args, **kwargs)
- extrude_mask_XY(txy: Scalar_mask_XY, refractive_index: float | complex | None, z0: float | None = None, z1: float | None = None, keep_rest=True, v_globals: dict = {})[source]
Converts a Scalar_mask_X in volumetric between z0 and z1 by growing between these two planes.
- Parameters:
t (Scalar_mask_X) – an amplitude mask of type Scalar_mask_X.
refractive_index (float, str) – can be a number or a function n(x,z). If none It just substitutes
z0 (float) – initial position of mask
z1 (float) – final position of mask
- extrude_mask_XZ(txz: Scalar_mask_XZ, y0: float | None, y1: float | None, refractive_index: float | None, n_new: float | None = None, v_globals: dict = {})[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 y0: initial position of mask :type y0: float :param z1: final position of mask :type z1: float :param refractive_index: If None takes the value of txz.n directly. TODO: can be a number or a function n(x,z) :type refractive_index: float, None
- sphere(r0: tuple[float, float, float], radius: tuple[float], refractive_index: float, rotation: dict | None = None) bool[source]
Insert a cylinder in background. If something previous, is removed.
- Parameters:
r0 (float, float, float) – (x0, y0,z0) Location of the square, 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) – refractive index , for example: 1.5 + 1.0j
rotation (dict) – kind: ‘axis’ or ‘point’ if ‘axis’: angle (float) and axis (tuple[float,float,float]) if ‘point’: angle (tuple[float,float,float]) and point (tuple[float,float,float])
- cube(*args, **kwargs)
- cylinder(*args, **kwargs)
- aspheric_lens(r0: tuple[float, float, float], refractive_index: complex | float | str, thickness: tuple[float, float], cx: tuple[float, float], diameter: float | None = None, mask: tuple | None = None, Qx: tuple[float, float] = (0, 0), a: tuple[tuple[float, float]] | None = None, rotation: dict | None = None)[source]
Define an aspheric surface as defined in Gomez-Pedrero.
- Parameters:
r0 (float, float) – position x,z of lens
refractive_index (float, str) – refractive index , for example: 1.5 + 1.0j
thickness (float, float) – distance of the apex
diamater (float |None) – diameter of the lens
mask (tuple) – mask to apply to the surface (thickness, refractive_index)
cx (float, float) – curvature radii
Qx (float, float) – Conic constant
a7 (float, float) – Aspheric coefficients a2, a3, a4, a5, a6, a7. Each (float, float)
rotation (dict) – kind: ‘axis’ or ‘point’ if ‘axis’: angle (float) and axis (tuple[float,float,float]) if ‘point’: angle (tuple[float,float,float]) and point (tuple[float,float,float])
Example
rotation = dict(kind = ‘axis’, point=(0,0,0), axis=(1,0,0), angle=5*degrees)
- Returns:
Bool array with positions inside the surface
- Return type:
numpy.array
- lens(r0: tuple[float, float], diameter: float, radii: tuple[float, float], thickness: float, refractive_index: float, mask: tuple | None = (50.0, 1 + 2.05j), rotation: dict | None = None)[source]
Lens defined by two radii of curvature and thickness.
- Parameters:
r0 (tuple[float, float]) – position of the initial point of the lens.
size (float) – _size of the lens, at x dimension
radii (tuple[float, float]) – radii of curvature of the two surfaces of the lens.
thickness (float) – thickness of the lens at the central axis.
refractive_index (float) – refractive index of the lens.
angles (float, optional) – angles of the lens. Defaults to 0*degrees.
mask (tuple | None, optional) – If not None, (thicknes, refractive index) of the pupil. Defaults to (50 * um, 1 + 2.05j).
Example
rotation = dict(kind = ‘axis’, point=(0,0,0), axis=(1,0,0), angle=5*degrees)
- Returns:
focal distance of the lens (theoretical)
- Return type:
focal
- stl(*args, **kwargs)
4.1.12. 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 - refractive 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, square, slit, cylinder, semi_cylinder
wedge, prism, biprism
ronchi_grating, sine_grating
probe
aspheric_lens, lens
roughness
- class diffractio.scalar_masks_XZ.Scalar_mask_XZ(x: ndarray[Any, dtype[floating]] | None = None, z: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1.0, info: str = '')[source]
Bases:
Scalar_field_XZClass 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) – refractive 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) refractive index
- Type:
numpy.array
- self.info
String with info about the simulation
- Type:
str
- object_by_surfaces(*args, **kwargs)
- extrude_mask(*args, **kwargs)
- mask_from_function(r0: tuple[float, float], refractive_index: complex | float | str, f1, f2, z_sides: tuple[float], angle: float, r_rot: tuple[float, float] | None = None, v_globals: dict = {})[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)
r_rot (float, float) – rotation point. If None then r_rot = r0.
v_globals (dict) – dict with global variables
- mask_from_array(*args, **kwargs)
- insert_array_masks(*args, **kwargs)
- repeat_structure(num_repetitions: tuple[int, int], position: str = 'center', new_field: bool = 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.
- add_surfaces(*args, **kwargs)
- discretize_refractive_index(*args, **kwargs)
- image(filename: str, n_max: float, n_min: float, angle: float = 0.0, invert: bool = False)[source]
Converts an image file in an xz-refractive index matrix. If the image is gray-scale the refractive 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 refractive index
n_min (float) – minimum refractive 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
- dxf(filename_dxf: str, n_max: float, n_min: float, num_pixels: tuple[int, int] | None = None, extent: tuple[float] | None = None, units: str = 'um', invert: bool = False, verbose: bool = False)[source]
Loads a dxf file. Internally it has the extension of the drawing, so it is not required to generate x,y spaces. It is possible with extent, but then the file is scaled. Warning: Dxf files are usually in mm. and diffractio works in um. To generate .u, a temporal .png file is generated.
- Parameters:
filename_dxf (str) – DXF filename .dxf
num_pixels (tuple[int, int] | None, optional) – If . Defaults to None.
extent (_type_, optional) – _description_. Defaults to None.
units (str, optional) – _description_. Defaults to ‘mm’.
invert (bool, optional) – _description_. Defaults to False.
filename_png (str, optional) – _description_. Defaults to ‘new.png’.
has_draw (bool, optional) – _description_. Defaults to True.
verbose (bool, optional) – _description_. Defaults to True.
- dots(*args, **kwargs)
- semi_plane(r0: tuple[float, float], refractive_index: complex | float | str, angle: float = 0.0, rotation_point: tuple[float, float] | None = None)[source]
Inserts a semi-cylinder 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) – refractive index.
angle (float) – angle of rotation of the semi-plane, in radians
rotation_point (float, float)
- layer(r0: tuple[float, float], depth: float, refractive_index: complex | float | str, angle: float = 0.0, rotation_point: tuple[float, float] | None = None)[source]
Insert a layer. If it is something else previous, it is removed.
Args: 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): refractive index , for example: 1.5 + 1.0j angle (float): angle of rotation of the semi-plane, in radians rotation_point (float, float). Rotation point
- square(r0: tuple[float, float], size: tuple[float, float], refractive_index: complex | float | str, angle: float = 0.0, rotation_point: tuple[float, float] | None = None)[source]
Insert a square in background. Anything previous, is removed.
- Parameters:
r0 (float, float) – (x0,z0) Location of the square, for example (0*um, 20*um)
size (float, float) – x,z size of the square
refractive_index (float, str) – refractive index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
rotation_point (float, float)
- slit(*args, **kwargs)
- cylinder(r0: tuple[float, float], radius: tuple[float, float], refractive_index: complex | float | str, angle: float = 0.0, rotation_point: tuple[float, float] | None = None)[source]
Insert a cylinder in background.
- Parameters:
r0 (float, float) – (x0,z0) Location of the cylinder, for example (0*um, 20*um)
radius (float, float) – radius x,y of the cylinder (ellipsoid)
refractive_index (float, str) – refractive index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
rotation_point (float, float)
- semi_cylinder(r0: tuple[float, float], radius: tuple[float, float], refractive_index: complex | float | str, angle: float = 0.0, rotation_point: tuple[float, float] | None = None)[source]
Insert a semi_cylinder in background.
- Parameters:
r0 (float, float) – (x0,z0) Location of the square, for example (0*um, 20*um)
radius (float, float) – radius x,y of the cylinder (ellipsoid)
refractive_index (float, str) – refractive index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
rotation_point (float, float)
- aspheric_surface_z(r0: tuple[float, float], refractive_index: complex | float | str, cx: float, Qx: float, a2: float, a3: float, a4: float, side: str, angle: float = 0.0)[source]
Define an aspheric surface
- Parameters:
r0 (float, float) – (x0,z0) position of apex
refractive_index (float, str) – refractive 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: tuple[float, float], angle: float, refractive_index: complex | float | str, cx: tuple[float, float], thickness: tuple[float, float], size: float, Qx: tuple[float, float] = (0, 0), a2: tuple[float, float] = (0, 0), a3: tuple[float, float] = (0, 0), a4: tuple[float, float] = (0, 0), a5: tuple[float, float] = (0, 0), a6: tuple[float, float] = (0, 0), a7=(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 radii
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
- lens(r0: tuple[float, float], size: float, radii: tuple[float, float], thickness: float, refractive_index: float, angle: float = 0.0, mask: tuple | None = (50.0, 1 + 2.05j))[source]
Lens defined by two radii of curvature and thickness.
- Parameters:
r0 (tuple[float, float]) – position of the initial point of the lens.
size (float) – _size of the lens, at x dimension
radii (tuple[float, float]) – radii of curvature of the two surfaces of the lens.
thickness (float) – thickness of the lens at the central axis.
refractive_index (float) – refractive index of the lens.
angle (float, optional) – angle of the lens. Defaults to 0*degrees.
mask (tuple | None, optional) – If not None, (thicknes, refractive index) of the pupil. Defaults to (50 * um, 1 + 2.05j).
- Returns:
focal distance of the lens (theoretical)
- Return type:
focal
- wedge(r0: tuple[float, float], length, refractive_index: complex | float | str, angle_wedge: float, angle: float = 0.0, rotation_point: tuple[float, float] | None = None)[source]
Insert a wedge pointing towards the light beam
- Parameters:
r0 (float, float) – (x0,z0) Location of the square, for example (0*um, 20*um)
length (float) – length of the long part (z direction)
refractive_index (float, str) – refractive 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: tuple[float, float], length: float, refractive_index: complex | float | str, angle_prism: float, angle: float = 0.0, rotation_point: tuple[float, float] | None = 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 square, for example (0*um, 20*um)
length (float) – length of the long part (z direction)
refractive_index (float, str) – refractive 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: tuple[float, float], length: float, height: float, refractive_index: complex | float | str, angle: float = 0.0)[source]
Fresnel biprism.
- Parameters:
r0 (float, float) – (x0,z0) Location of the square, for example (0*um, 20*um)
length (float) – length of the long part (z direction)
height (float) – height of biprism
refractive_index (float, str) – refractive index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
- ronchi_grating(r0: tuple[float, float], period: float, fill_factor: float, length: float, height: float, Dx: float, refractive_index: complex | float | str, heigth_substrate: float, refractive_index_substrate: float, angle: float = 0.0)[source]
Insert a ronchi grating in background.
- Parameters:
r0 (float, float) – (x0,z0) Location of the square, 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) – refractive index , for example: 1.5 + 1.0j
heigth_substrate (float) – height of the substrate
refractive_index_substrate (float, str) – refractive index of substrate, 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
- sine_grating(period: float, heigth_sine: float, heigth_substrate: float, r0: tuple[float, float], length: float, Dx: float, refractive_index: complex | float | str, angle: float = 0.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 square, 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) – refractive index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
- probe(r0: tuple[float, float], base: float, length: float, refractive_index: complex | float | str, angle: float = 0.0)[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) – refractive index , for example: 1.5 + 1.0j
angle (float) – angle of rotation of the semi-plane, in radians
- rough_sheet(*args, **kwargs)
4.1.13. 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: ndarray[Any, dtype[floating]] | None = None, wavelength: float = 0, n_background: float = 1.0, info: str = '')[source]
Bases:
Scalar_field_XClass 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) – refractive 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(*args, **kwargs)
- gauss_beam(*args, **kwargs)
- spherical_wave(*args, **kwargs)
- plane_waves_dict(*args, **kwargs)
- plane_waves_several_inclined(*args, **kwargs)
- gauss_beams_several_parallel(*args, **kwargs)
- gauss_beams_several_inclined(*args, **kwargs)
4.1.14. 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: ndarray[Any, dtype[floating]] | None = None, y: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1.0, info: str = '')[source]
Bases:
Scalar_field_XYClass 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(*args, **kwargs)
- gauss_beam(*args, **kwargs)
- spherical_wave(*args, **kwargs)
- vortex_beam(*args, **kwargs)
- hermite_gauss_beam(*args, **kwargs)
- laguerre_beam(*args, **kwargs)
- zernike_beam(*args, **kwargs)
- bessel_beam(*args, **kwargs)
- plane_waves_dict(*args, **kwargs)
- plane_waves_several_inclined(*args, **kwargs)
- gauss_beams_several_parallel(*args, **kwargs)
- gauss_beams_several_inclined(*args, **kwargs)
4.1.15. diffractio.utils_common module
Common functions to classes
- diffractio.utils_common.get_scalar(cls, kind: Literal['intensity', 'phase', 'field'])[source]
Get parameters from Scalar field
- Parameters:
kind (str) – ‘intensity’, ‘phase’, ‘field’
- Returns:
matrices with required values
- diffractio.utils_common.oversampling(cls, factor_rate: int | tuple)[source]
Function to oversampling the field
- Parameters:
factor_rate (int | tuple, optional) – factor rate. Defaults to 2.
- diffractio.utils_common.add(self, other, kind: Literal['source', 'mask', 'refractive_index', 'phases', 'no_overlap', 'distances'] = 'source')[source]
adds two fields. For example two light sources or two masks. The fields are added as complex numbers and then normalized so that the maximum amplitude is 1.
- Parameters:
other (Other field) – 2nd field to add
kind (str) – instruction how to add the fields: [‘source’, ‘mask’, ‘refractive_index’, ‘phases’, ‘no_overlap’, ‘distances’]. - ‘source’: adds the fields as they are - ‘mask’: adds the fields as complex numbers and then normalizes so that the maximum amplitude is 1. - ‘phases’: adds the phases and then normalizes so that the maximum amplitude is 1. - ‘np_overlap’: adds the fields as they are. If the sum of the amplitudes is greater than 1, an error is produced - ‘distances’: adds the fields as they are. If the fields overlap, the field with the smallest distance is kept.
- Returns:
sum of the two fields.
- diffractio.utils_common.sub(self, other, kind: Literal['source', 'mask', 'phases', 'no_overlap', 'refractive_index'] = 'source')[source]
substracts two fields. For example two light sources or two masks. The fields are added as complex numbers and then normalized so that the maximum amplitude is 1.
- Parameters:
other (Other field) – 2nd field to add
kind (str) – instruction how to add the fields: [‘source’, ‘mask’, ‘phases’, ‘no_overlap’, ‘refractive_index’]. - ‘source’: adds the fields as they are - ‘mask’: adds the fields as complex numbers and then normalizes so that the maximum amplitude is 1. - ‘phases’: adds the phases and then normalizes so that the maximum amplitude is 1. - ‘np_overlap’: adds the fields as they are. If the sum of the amplitudes is greater than 1, an error is produced
- Returns:
Substraction of the two fields.
- diffractio.utils_common.rmul(cls, number: float | complex | int, kind: Literal['intensity', 'amplitude', 'phase'] = 'intensity')[source]
Multiply a field by a number. For example :math: u_1(x)= m * u_0(x).
This function is general for all the SCALAR modules of the package. After, this function is called by the rmul method of each class. When module is for sources, any value for the number is valid. When module is for masks, the modulus is <=1.
The kind parameter is used to specify how to multiply the field. The options are: - ‘intensity’: Multiply the intensity of the field by the number. - ‘amplitude’: Multiply the amplitude of the field by the number. - ‘phase’: Multiply the phase of the field by the number.
- Parameters:
number (float | complex | int) – number to multiply the field.
kind (str) – instruction how to add the fields: [‘intensity’, ‘amplitude’, ‘phase’]. - ‘intensity’: Multiply the intensity of the field by the number. - ‘amplitude’: Multiply the amplitude of the field by the number. - ‘phase’: Multiply the phase of the field by the number.
- Returns:
The field multiplied by the number.
- diffractio.utils_common.computer_parameters(verbose: bool = False) tuple[int, float, float, float][source]
- Determine several computer Args:
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(source, masks, distances: tuple[float])[source]
performs RS propagation through several masks
- Parameters:
source (Scalar_source_XY) – illumination
masks (tuple) – list with several (Scalar_masks_XY)
distances (tuple) – 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: str, add_name: str = '', description: str = '', verbose: bool = False) str[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: str, verbose: bool = 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
- diffractio.utils_common.print_axis_info(cls, axis: str)[source]
Prints info about axis
- Parameters:
cls (class) – class of the modulus.
axis() – axis x, y, z… etc.
4.1.16. diffractio.utils_drawing module
Functions for drawing
- diffractio.utils_drawing.view_image(filename: str)[source]
reproduces image
- Parameters:
filename (str) – filename
- diffractio.utils_drawing.concatenate_drawings(kind1: str = 'png', kind2: str = 'png', nx: int = 5, ny: int = 3, geometria_x: int = 256, geometria_y: int = 256, raiz: str = 'fig4_nsensors_1', filename: str = 'figura2.png', directory: str = '')[source]
- diffractio.utils_drawing.draw2D(image: ndarray[Any, dtype[floating]], x: ndarray[Any, dtype[floating]], y: ndarray[Any, dtype[floating]], xlabel: str = '$x (\\mu m)$', ylabel: str = '$y (\\mu m)$', title: str = '', color: str = 'YlGnBu', interpolation: str = 'bilinear', scale: str = 'scaled', reduce_matrix: str = 'standard', range_scale: str = 'um', verbose: bool = False) tuple[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: list, titles: tuple[str] = '', title: str = '', figsize: tuple[float, float] | None = None, kinds: tuple[str] = '', logarithm: tuple[float] | float = False, normalize: bool = False)[source]
Draws several fields in subplots
- Parameters:
fields (tuple) – list with several scalar_fields_XY
titles (tuple) – list with titles
title (str) – suptitle
kinds (tuple) – list with kinds of figures (amplitude’, ‘intensity’, ‘phase’, ‘real_field’, ‘contour’)
logarithm (float) – If >0, intensity is scaled in logarithm
normalize (bool) – If True, max(intensity)=1
- diffractio.utils_drawing.change_image_size(image_name: str, length: str = '800x600', final_filename: str = 'prueba.png', dpi: int = 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: str | None = None, num_frame: str = '[0, ]', final_filename: str = '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: float | bool = False, normalize: bool = False, cut_value: float | None = 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: str = 'intensity', logarithm: float | bool = False, normalize: bool = 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.prepare_video(fps: int = 15, title: str = '', artist: str = '', comment: str = '')[source]
_summary_
- Parameters:
fps (int, optional) – FPS. Defaults to 15.
title (str, optional) – Titles. Defaults to “”.
artist (str, optional) – ?. Defaults to “”.
comment (str, optional) – comment. Defaults to “”.
- Returns:
_description_
- Return type:
_type_
- diffractio.utils_drawing.make_video_from_file(self, files: list, filename: str = '')[source]
make a video from file
- Parameters:
files (tuple) – files to add
filename (bool, optional) – final filename. Defaults to “”.
- diffractio.utils_drawing.reduce_matrix_size(reduce_matrix: str | tuple[int], x: ndarray[Any, dtype[floating]], y: ndarray[Any, dtype[floating]], image: ndarray[Any, dtype[floating]], verbose: bool = 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)
- diffractio.utils_drawing.draw_edges(vector_field, plt, draw_borders: bool = True, color: str = 'w.', ms: float = 0.1) None[source]
draw_edges _summary_
_extended_summary_
- Parameters:
vector_field (Vector_field_XY | Vector_field_XZ) – _description_
plt (_type_) – _description_
scale (str, optional) – _description_. Defaults to ‘scaled’.
draw_borders (bool, optional) – _description_. Defaults to True.
color (str, optional) – _description_. Defaults to ‘w.’.
ms (float, optional) – _description_. Defaults to 0.05.
4.1.17. diffractio.utils_drawing3D module
- diffractio.utils_drawing3D.load_stl(filename: str, has_draw: bool = False, verbose: bool = False)[source]
load_stl _summary_
_extended_summary_
- Parameters:
filename (str) – _description_
has_draw (bool, optional) – _description_. Defaults to False.
verbose (bool, optional) – _description_. Defaults to False.
- Returns:
mesh
- Return type:
_type_
- diffractio.utils_drawing3D.voxelize_volume_diffractio(self, mesh, refractive_index, check_surface=True)[source]
Voxelize mesh to create a RectilinearGrid voxel volume.
Creates a voxel volume that encloses the input mesh and discretizes the cells within the volume that intersect or are contained within the input mesh.
InsideMesh, an array incell_data, is1for cells inside and0outside.- Parameters:
mesh (pyvista.DataSet) – Mesh to voxelize.
- check_surfacebool, default: True
Specify whether to check the surface for closure. If on, then the algorithm first checks to see if the surface is closed and manifold. If the surface is not closed and manifold, a runtime error is raised.
- Returns:
RectilinearGrid as voxelized volume with discretized cells.
- Return type:
pyvista.RectilinearGrid
See also
pyvista.voxelize,pyvista.DataSetFilters.select_enclosed_points
- diffractio.utils_drawing3D.draw(self, kind: Literal['intensity', 'refractive_index'] = 'intensity', drawing: Literal['volume', 'clip', 'slices', 'projections'] = 'volume', has_grid: bool = False, filename: str = '', logarithm: float = 0.0, **kwargs)[source]
_summary_
- Parameters:
kind (str, optional) – “intensity” or “refractive_index”. Defaults to ‘refractive_index’.
drawing (str, optional) – volume, clip, slices, projections. Defaults to ‘volume’.
has_grid (bool, optional) – add grid. Defaults to False.
filename (str, optional) – saves images: html, png or svg. Defaults to ‘’.
- diffractio.utils_drawing3D.video_isovalue(self, filename: str, kind: Literal['intensity', 'refractive_index'] = 'refractive_index', **kwargs)[source]
_summary_
- Parameters:
filename (str) – filename. Defaults to ‘’.
kind (str, optional) – “intensity” or “refractive_index”. Defaults to ‘refractive_index’.
4.1.18. diffractio.utils_dxf module
- diffractio.utils_dxf.set_pixel_density(fig: Figure, ax: Axes, ppu: int)[source]
_summary_
- Parameters:
fig (plt.Figure) – _description_
ax (plt.Axes) – _description_
ppu (int) – pixels per drawing unit.
- diffractio.utils_dxf.set_pixel_size(fig: Figure, size: tuple[int, int])[source]
_summary_
- Parameters:
fig (plt.Figure) – _description_
size (tuple[int, int]) – _description_
- Returns:
_description_
- Return type:
_type_
- diffractio.utils_dxf.binarize(image, center_level=128)[source]
_summary_
- Parameters:
image (_type_) – _description_
center_level (int, optional) – _description_. Defaults to 128.
- Returns:
_description_
- Return type:
_type_
- diffractio.utils_dxf.load_dxf(filename_dxf: str, num_pixels: tuple[int, int], verbose: bool = False)[source]
_summary_
- Parameters:
filename_dxf (_type_) – _description_
num_pixels (_type_) – _description_
filename_png (str, optional) – _description_. Defaults to ‘’.
- Returns:
_description_
- Return type:
_type_
4.1.19. diffractio.utils_math module
Common functions to classes
- diffractio.utils_math.nextpow2(x: float)[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:
- 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: str, y: ndarray[Any, dtype[floating]], x: ndarray[Any, dtype[floating]], pixels_interpolation: float = 0.0)[source]
Determine local minima in a numpy np.array.
- Parameters:
kind (str) – ‘maxima’, ‘minima’
y (numpy.ndarray) – variable with local minima.
x (numpy.ndarray) – x position
pixels_interpolation (float)
- 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(p1: ndarray[Any, dtype[_ScalarType_co]] | float, p2: ndarray[Any, dtype[_ScalarType_co]] | float, verbose: bool = False)[source]
Distance between to floats or numpy arrays.
- Parameters:
p1 (NDArray | float) – Point 1
p2 (NDArray | float) – Point 2
verbose (bool, optional) – prints distance. Defaults to False.
- Returns:
distance between the two points
- Return type:
float
- diffractio.utils_math.distance_backup(x1: ndarray[Any, dtype[floating]], x2: ndarray[Any, dtype[floating]])[source]
Compute distance between two vectors.
- Parameters:
x1 (numpy.np.array) – vector 1
x2 (numpy.np.array) – vector 2
- Returns:
distance between vectors.
- Return type:
(float)
- diffractio.utils_math.nearest(vector: ndarray[Any, dtype[_ScalarType_co]], number: float | int, verbose: bool = False)[source]
find the nearest value in a vector to a given number
- Parameters:
vector (NDArray) – Array with values
number (float | int) – value to compare with vector
verbose (bool, optional) – prints something. Defaults to True.
- Returns:
index of the nearest value in numbers values: nearest values in numbers distances: distances between vector and nearest values in numbers
- Return type:
i_mins
- diffractio.utils_math.nearest_backup(vector: ndarray[Any, dtype[floating]], number: float)[source]
Computes the nearest element in vector to number.
- Parameters:
vector (numpy.np.array) – np.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: ndarray[Any, dtype[_ScalarType_co]], numbers: ndarray[Any, dtype[_ScalarType_co]], verbose: bool = False)[source]
find the nearest value of numbers to a given vector
- Parameters:
vector (NDArray) – N dimensional vector to compare with numbers
numbers (NDArray) – N dimensional array with values
- Returns:
index of the nearest value in numbers values: nearest values in numbers distances: distances between vector and nearest values in numbers
- Return type:
i_mins
- diffractio.utils_math.nearest2_backup(vector: ndarray[Any, dtype[floating]], numbers: ndarray[Any, dtype[floating]])[source]
Computes the nearest element in vector to numbers.
- Parameters:
vector (numpy.np.array) – np.array with numbers
number (numpy.np.array) – numbers to determine position
- Returns:
index - indexes of vector which is closest to number. (numpy.np.array): value - values of vector[indexes]. (numpy.np.array): distance - difference between numbers and chosen elements.
- Return type:
(numpy.np.array)
- diffractio.utils_math.find_extrema(array2D: ndarray[Any, dtype[floating]], x: ndarray[Any, dtype[floating]], y: ndarray[Any, dtype[floating]], kind: float | str = 'max', verbose: bool = False)[source]
In a 2D-np.array, formed by vectors x, and y, the maxima or minima are found
- Parameters:
array2D (np.array 2D) – 2D np.array with variable
x (np.array 1D) – 1D np.array with x axis
y (np.array 1D) – 1D np.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.get_amplitude(u: ndarray[Any, dtype[complexfloating]], sign: bool = False)[source]
Gets the amplitude of the field.
- Parameters:
u (numpy.np.array) – Field.
sign (bool) – If True, sign is kept, else, it is removed
- Returns:
numpy.np.array
- Return type:
(numpy.np.array)
- diffractio.utils_math.get_phase(u: ndarray[Any, dtype[complexfloating]])[source]
Gets the phase of the field.
- Parameters:
u (numpy.np.array) – Field.
- Returns:
numpy.np.array
- Return type:
(numpy.np.array)
- diffractio.utils_math.amplitude2phase(u: ndarray[Any, dtype[complexfloating]])[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.np.array, dtype=complex) – complex field
- Returns:
only-phase complex vector.
- Return type:
(numpy.np.array)
- diffractio.utils_math.phase2amplitude(u: ndarray[Any, dtype[complexfloating]])[source]
Passes the phase of a complex field to amplitude.
- Parameters:
u (numpy.np.array, dtype=complex) – complex field
- Returns:
amplitude without phase complex vector.
- Return type:
(numpy.np.array)
- diffractio.utils_math.normalize(v: ndarray[Any, dtype[_ScalarType_co]], order: int = 2)[source]
Normalize vectors with different L norm (standard is 2).
- Parameters:
v (numpy.np.array) – vector to normalize
order (int) – order for norm
- Returns:
normalized vector.
- Return type:
(numpy.np.array)
- diffractio.utils_math.binarize(vector: ndarray[Any, dtype[floating]], min_value: float = 0.0, max_value: float = 1.0)[source]
Binarizes vector between two levels, min and max. The central value is (min_value+max_value)/2
- Parameters:
vector – (numpy.np.array) np.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.np.array)
- diffractio.utils_math.discretize(u: ndarray[Any, dtype[complexfloating]], kind: str = 'amplitude', num_levels: int = 2, factor: float = 1.0, phase0: float = 0.0, new_field: bool = True, matrix: bool = False)[source]
Discretize in a number of levels equal to num_levels.
- Parameters:
u (np.array, dtype = comples) – field
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: float, b: float)[source]
Delta kronecker
- Parameters:
a (float) – number
b (float) – number
- Returns:
1 if a==b and 0 if a<>b
- diffractio.utils_math.vector_product(A: ndarray[Any, dtype[floating]], B: ndarray[Any, dtype[floating]])[source]
Returns the vector product between two vectors.
- Parameters:
A (numpy.np.array) – 3x1 vector np.array.
B (numpy.np.array) – 3x1 vector np.array.
- Returns:
3x1 vector product np.array
- Return type:
(numpy.np.array)
- diffractio.utils_math.dot_product(A: ndarray[Any, dtype[floating]], B: ndarray[Any, dtype[floating]])[source]
Returns the dot product between two vectors.
- Parameters:
A (numpy.np.array) – 3x1 vector np.array.
B (numpy.np.array) – 3x1 vector np.array.
- Returns:
3x1 dot product
- Return type:
(complex)
- diffractio.utils_math.divergence(E: ndarray[Any, dtype[floating]], r: ndarray[Any, dtype[floating]])[source]
Returns the divergence of a field a given point (x0,y0,z0).
- Parameters:
E (numpy.np.array) – complex field
r (numpy.np.array) – 3x1 np.array with position r=(x,y,z).
- Returns:
Divergence of the field at (x0,y0,z0)
- Return type:
(float)
- diffractio.utils_math.curl(E: ndarray[Any, dtype[floating]], r: ndarray[Any, dtype[floating]])[source]
Returns the Curl of a field a given point (x0,y0,z0)
- Parameters:
E (numpy.np.array) – complex field
r (numpy.np.array) – 3x1 np.array with position r=(x,y,z).
- Returns:
Curl of the field at (x0,y0,z0)
- Return type:
(numpy.np.array)
- diffractio.utils_math.get_edges(x: ndarray[Any, dtype[floating]], f: ndarray[Any, dtype[floating]], kind_transition: str = 'amplitude', min_step: float = 0.0, verbose: bool = False, filename: str = '')[source]
We have a binary mask and we obtain locations of edges. Valid for litography engraving of gratings
- Parameters:
x (NDArrayFloat) – position x
f (NDArrayFloat) – 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:
np.array with +1, -1 with rasing or falling edges pos_transition (numpy.np.array): positions x of transitions raising (numpy.np.array): positions of raising falling (numpy.np.array): positions of falling
- Return type:
type_transition (numpy.np.array)
- diffractio.utils_math.cut_function(x: ndarray[Any, dtype[floating]], y: ndarray[Any, dtype[floating]], length: float, x_center: float | None = None)[source]
Takes values of function inside (x_center+length/2: x_center+length/2)
- Parameters:
x (np.array) – x of function
y (np.array) – y of function
length (float) – range of data to keep
x_center (float or None, optional) – position of center of Range. If None, the center is x_center.
- Returns:
values in range.
- Return type:
y cutted (np.array)
- diffractio.utils_math.fft_convolution2d(x: ndarray[Any, dtype[floating]], y: ndarray[Any, dtype[floating]])[source]
2D convolution, using FFT
- Parameters:
x (numpy.np.array) – np.array 1 to convolve
y (numpy.np.array) – np.array 2 to convolve
- Returns:
convolved function
- diffractio.utils_math.fft_convolution1d(x: ndarray[Any, dtype[floating]], y: ndarray[Any, dtype[floating]])[source]
1D convolution, using FFT
- Parameters:
x (numpy.np.array) – np.array 1 to convolve
y (numpy.np.array) – np.array 2 to convolve
- Returns:
convolved function
- diffractio.utils_math.fft_filter(x: ndarray[Any, dtype[floating]], y: ndarray[Any, dtype[floating]], normalize: bool = False)[source]
1D convolution, using FFT
- Parameters:
x (numpy.np.array) – np.array 1 to convolve
y (numpy.np.array) – np.array 2 to convolve
- Returns:
convolved function
- diffractio.utils_math.fft_correlation1d(x: ndarray[Any, dtype[floating]], y: ndarray[Any, dtype[floating]])[source]
1D correlation, using FFT (fftconvolve)
- Parameters:
x (numpy.np.array) – np.array 1 to convolve
y (numpy.np.array) – np.array 2 to convolve
- Returns:
correlation function
- Return type:
numpy.np.array
- diffractio.utils_math.fft_correlation2d(x: ndarray[Any, dtype[floating]], y: ndarray[Any, dtype[floating]])[source]
- Parameters:
x (numpy.np.array) – np.array 1 to convolve
y (numpy.np.array) – np.array 2 to convolve
- Returns:
2d correlation function
- Return type:
numpy.np.array
- diffractio.utils_math.rotate_image(x: ndarray[Any, dtype[floating]], z: ndarray[Any, dtype[floating]], img: ndarray[Any, dtype[floating]], angle: float, pivot_point: tuple[float, float])[source]
similar to rotate image, but not from the center but from the given
- Parameters:
x (np.array) – x of image
z (np.array) – z of image
img (np.array) – image to rotate
angle (float) – np.angle to rotate
pivot_point (float, float) – (z,x) position for rotation
- Returns:
rotated image
- diffractio.utils_math.cart2pol(x: ndarray[Any, dtype[floating]], y: ndarray[Any, dtype[floating]])[source]
cartesian to polar coordinate transformation.
- Parameters:
x (np.array) – x coordinate
y (np.aray) – y coordinate
- Returns:
rho numpy.np.array: phi
- Return type:
numpy.np.array
- diffractio.utils_math.pol2cart(rho: ndarray[Any, dtype[floating]], phi: ndarray[Any, dtype[floating]])[source]
Polar to cartesian coordinate transformation
- Parameters:
rho (np.aray) – rho coordinate
rho – rho coordinate
- Returns:
x numpy.np.array: y
- Return type:
numpy.np.array
- diffractio.utils_math.fZernike(X: ndarray[Any, dtype[floating]], Y: ndarray[Any, dtype[floating]], n: int, m: int, radius: float)[source]
Zernike function for aberration computation.
- Parameters:
X (np.array) – X
Y (np.array) – Y
n (int) – _description_
m (int) – _description_
radius (_type_, optional) – _description_. Defaults to 5*mm.
- Returns:
_description_
- Return type:
zernike polinomial
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 and the second de imaginary part.
n m aberration
0 0 piston
1 -1 vertical tilt
1 1 1 horizontal tilt
2 -2 oblique astigmatism
2 0 defocus myopia if c>0 or defocus hypermetropia if c<0
2 2 2 abnormal astigmatism if c>0 or normal astigmatism if c<0
3 -3 oblique trefoil
3 -1 as vertical coma, c>0 upper steepening, c<0 lower steepening
3 1 as horizontal
3 3 3 horizontal trefoil
4 -4 oblique four-leaf clover
4 -2 oblique secondary astigmatism
4 0 spherical c>0 periphery more myopic than centre, c<0 periphery more hyperopic than centre
4 2 secondary astigmatism for or against the ruler
4 4 4 horizontal four-leaf clover
Reference:
Navarro, J. Arines, R. Rivera “Direct and inverse discrete Zernike transform” Opt. Express 17(26) 24269
- diffractio.utils_math.laguerre_polynomial_nk(x: ndarray[Any, dtype[floating]], n: int, k: int)[source]
Auxiliar laguerre polinomial of orders n and k. 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.
Calculation is done recursively using matrix operations for very fast execution time.
- Parameters:
x (-) – position
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}
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: ndarray[Any, dtype[complexfloating]], flavour: str = '-')[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 np.array
flavour (str) – ‘-’ (for ifftshifted axis)
- Returns:
k vector
- Return type:
kx (np.array)
Fixed by Bob-Swinkels
- diffractio.utils_math.filter_edge_1D(x: ndarray[Any, dtype[floating]], size: float = 1.1, exponent: float = 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: ndarray[Any, dtype[floating]], y: ndarray[Any, dtype[floating]], size: float = 1.1, exponent: float = 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.20. 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
- class diffractio.utils_multiprocessing.auxiliar_multiprocessing[source]
Bases:
object- execute_multiprocessing(function, var_iterable, dict_constants={}, Ncores=8)[source]
_summary_
- Parameters:
function (_type_) – _description_
var_iterable (_type_) – _description_
dict_constants (_type_, optional) – _description_. Defaults to dict().
Ncores (int, optional) – num of cores. Defaults to 8.
- Returns:
_description_
- Return type:
_type_
- diffractio.utils_multiprocessing.execute_multiprocessing(__function_process__, dict_Parameters, num_processors, verbose: bool = False)[source]
Executes multiprocessing reading a dictionary.
- Parameters:
process (__function_process__ function tu)
dictionary (it only accepts a)
dict_Parameters
Args (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 Args: 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.21. diffractio.utils_optics module
General purpose optics functions
- diffractio.utils_optics.roughness_1D(x: ndarray[Any, dtype[floating]], t: float, s: float, kind: str = '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: ndarray[Any, dtype[floating]], y: tuple[float, float], t: float, s: float)[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: ndarray[Any, dtype[complexfloating]], x: ndarray[Any, dtype[floating]], remove_background: bool = False)[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: ndarray[Any, dtype[floating]], y: ndarray[Any, dtype[floating]], percentage: float = 0.5, verbose: bool = 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 % (tuple): x_list: (x[i_left], x[i_max], x[i_right]) (tuple): 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: ndarray[Any, dtype[floating]], y: ndarray[Any, dtype[floating]], intensity: ndarray[Any, dtype[floating]], remove_background: bool = False, has_draw: bool = 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: str, wavelength: float, raw: bool = False, has_draw: bool = <class 'bool'>)[source]
gets refractive 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: ndarray[Any, dtype[floating]], intensity: ndarray[Any, dtype[floating]], percentage: float = 0.5, remove_background: str | None = None, has_draw: bool = False)[source]
FWHM
remove_background =
- Parameters:
x (NDArrayFloat) – x array
intensity (NDArrayFloat) – intensity array
percentage (float, optional) – heigth of peak to measure. Defaults to 0.5.
remove_background (str | None, optional) – ‘min’, ‘mean’, None. Defaults to None.
has_draw (bool, optional) – It draws. Defaults to False.
- Returns:
value of FWHM
- Return type:
float
- diffractio.utils_optics.FWHM2D(x: ndarray[Any, dtype[floating]], y: ndarray[Any, dtype[floating]], intensity: ndarray[Any, dtype[floating]], percentage: float = 0.5, remove_background: bool = False, has_draw: bool = False, xlim: tuple[float] | None = None)[source]
Get FWHM2D in x and i direction
- Parameters:
x (NDArrayFloat) – x array
y (NDArrayFloat) – y array
intensity (NDArrayFloat) – intensity
percentage (float, optional) – heigth of peak to measure. Defaults to 0.5.
remove_background (bool, optional) – ‘min’, ‘mean’, None. Defaults to False.
has_draw (bool, optional) – if True it draws. Defaults to False.
xlim (tuple[float] | None, optional) – xlim in drawing. Defaults to None.
- Returns:
width in x direction FWHM_y (float): width in y direction
- Return type:
FWHM_x (float)
TODO: perform profiles at several angles and fit to a ellipse.
- diffractio.utils_optics.DOF(z: ndarray[Any, dtype[floating]], widths: ndarray[Any, dtype[floating]], w_factor: float = 1.4142135623730951, w_fixed: float = 0, has_draw: bool = False, verbose: bool = 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: ndarray[Any, dtype[floating]], intensity: ndarray[Any, dtype[floating]], percentage: float = 0.95, has_draw: bool = 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 (float) – 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: ndarray[Any, dtype[floating]], wavelength: float, diameter: float, focal: float, kind: str, verbose: bool = False, has_draw: bool = 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: ndarray[Any, dtype[floating]], focal: float)[source]
Converts lines/mm to cycles/degree. JA Gomez-Pedrero :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: ndarray[Any, dtype[floating]], MTF_ideal: ndarray[Any, dtype[floating]], lines_mm: float = 50, verbose: bool = False)[source]
MTF Args: strehl_ratio, mtf_50_ratio, freq_50_real, freq_50_ideal
References
frequencies of mtf are given since both MTF can have different steps
- 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: ndarray[Any, dtype[floating]], w_central: float, Dw: float, normalize: bool = True)[source]
Returns weigths for a gaussian spectrum
- Parameters:
wavelengths (NDArrayFloat) – array with wavelengths
w_central (float) – central wavelength
Dw (float) – width of the spectrum
normalize (bool, optional) – if True sum of weights is 1. Defaults to True.
- Returns:
gaussian spectrum
- Return type:
weights (float)
- diffractio.utils_optics.lorentz_spectrum(wavelengths: ndarray[Any, dtype[floating]], w_central: float, Dw: float, normalize: bool = True)[source]
Returns weigths for a Lorentz spectrum
- Parameters:
wavelengths (NDArrayFloat) – array with wavelengths
w_central (float) – central wavelength
Dw (float) – width of the spectrum
normalize (bool, optional) – if True sum of weights is 1. Defaults to True.
- Returns:
Lorentz spectrum
- Return type:
weights (float)
- diffractio.utils_optics.uniform_spectrum(wavelengths: ndarray[Any, dtype[floating]], normalize: bool = True)[source]
returns weigths for a gaussian spectrum
- Parameters:
wavelengths – array with wavelengths
w_central – central wavelength
Dw – width of the spectrum
normalize – if True sum of weights is 1
- diffractio.utils_optics.normalize_field(self, kind='amplitude', new_field: bool = False)[source]
Normalize the field to maximum intensity.
- Parameters:
kind (str) – ‘amplitude’, or ‘intensity’
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: ndarray[Any, dtype[complexfloating]], has_amplitude_sign: bool = 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: ndarray[Any, dtype[floating]], wavelength: float, n: float, n_background: float)[source]
Phase 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) – refractive index of material
n_background (float) – refractive index of background
- Returns:
depths related to phases
- Return type:
(np.array)
- diffractio.utils_optics.convert_amplitude2heigths(amplitude: ndarray[Any, dtype[complexfloating]], wavelength: float, kappa: float, n_background: float)[source]
Amplitude 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) – refractive index of material.
n_background (float) – refractive index of background
- Returns:
depths related to amplitudes
- Return type:
(np.array)
- diffractio.utils_optics.fresnel_equations_kx(kx: ndarray[Any, dtype[complexfloating]], wavelength: float, n1: float, n2: float, outputs: tuple[bool, bool, bool, bool] = [True, True, True, True], has_draw: bool = True, kind: str = 'amplitude_phase')[source]
Fresnel_equations where input are kx part of wavevector.
- Parameters:
kx (np.array) – kx
wavelength (float) – wavelength
n1 (float) – refractive index of first materia
n2 (float) – refractive 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: ndarray[Any, dtype[complexfloating]], wavelength: float, n1: float, n2: float, outputs: tuple[bool, bool, bool, bool] = [True, True, True, True], has_draw: bool = True)[source]
Transmitances and reflectances, where input are kx part of wavevector.
- Parameters:
kx (np.array) – kx
wavelength (float) – wavelength
n1 (float) – refractive index of first materia
n2 (float) – refractive 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.
outputs – 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: ndarray[Any, dtype[floating]], wavelength: float, n1: float, n2: float, outputs: tuple[bool, bool, bool, bool] = [True, True, True, True], has_draw: bool = True, kind='amplitude_phase')[source]
Fresnel equations and reflectances, where input are angles of incidence.
- Parameters:
theta (np.array) – kx
wavelength (float) – wavelength
n1 (float) – refractive index of first material
n2 (float) – refractive index of second material
outputs (bool,bool,bool,bool) – Selects the outputs to compute
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: ndarray[Any, dtype[floating]], wavelength: float, n1: float, n2: float, outputs: tuple[bool] = [True, True, True, True], has_draw: bool = False)[source]
Transmitances and reflectances, where input are angles of incidence.
- Parameters:
theta (np.array) – angles
wavelength (float) – wavelength
n1 (float) – refractive index of first materia
n2 (float) – refractive 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.
- Returns:
T_TM, T_TE, R_TM, R_TE (TM is parallel and TE is perpendicular)
- Return type:
_type_
- diffractio.utils_optics.determine_extrema(I_far: array, angles_x: array, is_angles: bool = False, change_order_0: bool = True, has_draw: bool = True, has_logarithm: bool = True, verbose: bool = True, **kwargs)[source]
Determine the extrema of a 1D far field diffraction pattern.
It can be in positions x or angles.
- Parameters:
I_far (np.array) – Intensity distribution of the far field
angles_x (np.array) – angles of the far field.
is_angles (bool) – if True, the far field is in angles, if False, the far field is in x.
change_order_0 (bool) – if True, the central maxima is included in the minima
has_draw (bool) – It draws the far field with the maxima and minima.
has_logarithm (bool) – It draws the far field with logarithm or not.
verbose (bool) – if True, it prints the maxima and minima.
- Returns:
List with indexes of minima and maxima (angles[i_minima], angles[i_maxima]): List with angles of minima and maxima (I_far[i_minima], I_far[i_maxima]): List with intensities of minima and maxima
- Return type:
(i_minima, i_maxima)
- diffractio.utils_optics.size_from_diffraction_minima(angles_minima: array, wavelength, size_slit: float | None = None, has_draw: bool = False, verbose: bool = False)[source]
We have the minima of a 1D diffraction pattern and determine the size.
_extended_summary_
- Returns:
wavelength (float): size_slit (float | None): has_draw (bool): It draws the far field with the maxima and minima. verbose (bool): if True, it prints the maxima and minima.
- Return type:
angles_minima (np.array)
- diffractio.utils_optics.envelopes(angles: array, I_far: array, has_draw: bool = True, has_logarithm: bool = True)[source]
Generates envelopes, and also contrast from these envelopes.
- Parameters:
angles (np.array) – angles for the observaton
I_far (np.array) – Intensity at far field
has_draw (bool, optional) – If True, makes some drawingT. Defaults to True.
has_logarithm (bool, optional) – If True, drawings are in logarithm scale. Defaults to True.
- Returns:
I_max_interpolated (np.array) I_min_interpolated (np.array)) Contrast (np.array)
4.1.22. diffractio.utils_tests module
Common functions to classes
- diffractio.utils_tests.run_benchmark(num_pixels: int)[source]
_summary_
- Parameters:
num_pixels (int) – _description_
- diffractio.utils_tests.comparison(proposal: ndarray[Any, dtype[floating]], solution: ndarray[Any, dtype[floating]], maximum_diff: float)[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.save_figure_test(newpath: str, func_name: str, add_name: str = '')[source]
_summary_
- Parameters:
newpath (str) – _description_
func_name (str) – _description_
add_name (str, optional) – _description_. Defaults to ‘’.
- diffractio.utils_tests.ejecute_multiprocessing(num_cores: int, n_pixels: int)[source]
_summary_
- Parameters:
num_cores (int) – _description_
n_pixels (int) – _description_
- diffractio.utils_tests.benchmark_num_pixels(function, n_max: int = 10)[source]
This function is for benchmarking using an increasing number of pixels 2**n.
- Parameters:
function (function) – Functions that has as argument the number of pixels 2**n.
4.1.23. diffractio.utils_typing module
- class diffractio.utils_typing.integer
Bases:
numberAbstract base class of all integer scalar types.
- denominator
denominator of value (1)
- is_integer() bool
Return
Trueif the number is finite with integral value.Added in version 1.22.
Examples
>>> np.int64(-2).is_integer() True >>> np.uint32(5).is_integer() True
- numerator
numerator of value (the value itself)
4.1.24. 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
- Drawing functions
draw: intensity, intensities, phases, fields, stokes, param_ellipse, ellipses
- class diffractio.vector_fields_X.Vector_field_X(x: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1.0, info: str = '')[source]
Bases:
objectClass 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
- size(verbose: bool = False)[source]
returns the size of the instance in MB.
- Parameters:
verbose (bool, optional) – prints size in Mb. Defaults to False.
- Returns:
size in MB
- Return type:
float
- save_data(filename: str, add_name: str = '', description: str = '', verbose: bool = 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: str, verbose: bool = 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
- clear_field(*args, **kwargs)
- get(*args, **kwargs)
- apply_mask(*args, **kwargs)
- intensity(*args, **kwargs)
- normalize(*args, **kwargs)
- draw(*args, **kwargs)
4.1.25. 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
- Propagation
RS - Rayleigh Sommerfeld
- Drawing functions
draw: intensity, intensities, phases, fields, stokes, param_ellipse, ellipses
- class diffractio.vector_fields_XY.Vector_field_XY(x: ndarray[Any, dtype[floating]] | None = None, y: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1.0, info: str = '')[source]
Bases:
objectClass 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: str, add_name: str = '', description: str = '', verbose: bool = 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: str, verbose: bool = 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
- clear(*args, **kwargs)
- size(verbose: bool = False)[source]
returns the size of the instance in MB.
- Parameters:
verbose (bool, optional) – prints size in Mb. Defaults to False.
- Returns:
size in MB
- Return type:
float
- to_py_pol()[source]
Pass diffractio vector field or mask to py_pol package for software analysis. :returns: py_pol.jones_matrix or py_pol.jones_vector
- duplicate(clear: bool = False)[source]
Duplicates the instance,
- Parameters:
clear (bool, optional) – Clear the data. Defaults to False.
- Returns:
New instance
- Return type:
- get(*args, **kwargs)
- pupil(*args, **kwargs)
- apply_mask(*args, **kwargs)
- refractive_index_from_scalarXY(u_xy: Scalar_mask_XY)[source]
refractive_index_from_scalarXY. Gets the refractive index from a Scalar field and passes to a vector field.
Obviously, the refractive index is isotropic.
- Parameters:
self (Vector_field_XY) – Vector_field_XY
u_xy (Scalar_mask_XY) – Scalar_mask_XY
- intensity(*args, **kwargs)
- VFFT(*args, **kwargs)
- IVFFT(*args, **kwargs)
- VRS(*args, **kwargs)
- VCZT(*args, **kwargs)
- normalize(*args, **kwargs)
- cut_resample(*args, **kwargs)
- surface_detection(*args, **kwargs)
- draw(*args, **kwargs)
- diffractio.vector_fields_XY.draw2D_XY(image, x, y, ax=None, xlabel='r$x (\\mu m)$', ylabel='r$y (\\mu m)$', title='', color='YlGnBu', interpolation='bilinear', 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
() (ax) – axis
xlabel (str) – label for x
ylabel (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
4.1.26. 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: ndarray[Any, dtype[floating]] | None = None, y: ndarray[Any, dtype[floating]] | None = None, z: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1.0, info: str = '')[source]
Bases:
objectClass 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: str, add_name: str = '', description: str = '', verbose: bool = 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: str, verbose: bool = 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
- clear_field(*args, **kwargs)
- size(verbose: bool = False)[source]
returns the size of the instance in MB.
- Parameters:
verbose (bool, optional) – prints size in Mb. Defaults to False.
- Returns:
size in MB
- Return type:
float
- get(*args, **kwargs)
- incident_field(*args, **kwargs)
- refractive_index_from_scalarXYZ(u_xyz: Scalar_mask_XYZ)[source]
refractive_index_from_scalarXZ. Gets the refractive index from a Scalar field and passes to a vector field.
Obviously, the refractive index is isotropic.
- Parameters:
self (Vector_field_XZ) – Vector_field_XZ
u_xz (Scalar_mask_XZ) – Scalar_mask_XZ
- FP_WPM(has_edges: bool = True, pow_edge: int = 80, matrix: bool = False, has_H=True, verbose: bool = False)[source]
WPM Method. ‘schmidt methodTrue is very fast, only needs discrete number of refractive indexes’
- Parameters:
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
has_H (bool) – If True, it returns magnetic field H.
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.
- intensity(*args, **kwargs)
- normalize(*args, **kwargs)
- to_Vector_field_XY(*args, **kwargs)
- to_Vector_field_XZ(*args, **kwargs)
- to_Vector_field_YZ(*args, **kwargs)
- to_Vector_field_Z(*args, **kwargs)
- draw_XY(*args, **kwargs)
- draw_XZ(*args, **kwargs)
- draw_YZ(*args, **kwargs)
- diffractio.vector_fields_XYZ.FP_WPM_schmidt_kernel(Ex, Ey, n1, n2, k0, kx, ky, wavelength, dz, has_H=True)[source]
Kernel for fast propagation of WPM method
- Parameters:
Ex (np.array) – field Ex
Ey (np.array) – field Ey
n1 (np.array) – refractive index at the first layer
n2 (np.array) – refractive index at the second layer
k0 (float) – wavenumber
kx (np.array) – transversal wavenumber
wavelength (float) – wavelength
dz (float) – increment in distances: z[1]-z[0]
has_H (bool, optional) – If True computes magnetic field H. Defaults to True.
- Returns:
Field E(z+dz) at at distance dz from the incident field. H list(Hx, Hy, Hz): Field H(z+dz) at at distance dz from the incident field.
- Return type:
E list(Ex, Ey, Ez)
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.vector_fields_XYZ.FP_PWD_kernel_simple(Ex, Ey, n1, n2, k0, kx, ky, wavelength, dz, has_H=True)[source]
Step for Plane wave decomposition (PWD) algorithm.
- Parameters:
Ex (np.array) – field Ex
Ey (np.array) – field Ey
n1 (np.array) – refractive index at the first layer
n2 (np.array) – refractive index at the second layer
k0 (float) – wavenumber
kx (np.array) – transversal wavenumber
wavelength (float) – wavelength
dz (float) – increment in distances: z[1]-z[0]
has_H (bool, optional) – If True computes magnetic field H. Defaults to True.
- Returns:
Field E(z+dz) at at distance dz from the incident field. H list(Ex, Ey, Ez): Field H(z+dz) at at distance dz from the incident field.
- Return type:
E list(Ex, Ey, Ez)
4.1.27. 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: ndarray[Any, dtype[floating]] | None = None, z: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1.0, info: str = '')[source]
Bases:
objectClass 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: str, add_name: str = '', description: str = '', verbose: bool = 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: str, verbose: bool = 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
- clear_field(*args, **kwargs)
- size(verbose: bool = False)[source]
returns the size of the instance in MB.
- Parameters:
verbose (bool, optional) – prints size in Mb. Defaults to False.
- Returns:
size in MB
- Return type:
float
- normalize(kind='amplitude', new_field: bool = 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
kind (str) – ‘amplitude’, or ‘intensity’
- Returns
u (numpy.array): normalized optical field
- incident_field(*args, **kwargs)
- final_field(*args, **kwargs)
- refractive_index_from_scalarXZ(u_xz: Scalar_mask_XZ)[source]
Refractive_index_from_scalarXZ. Gets the refractive index from a Scalar field and passes to a vector field.
Obviously, the refractive index is isotropic.
- Parameters:
self (Vector_field_XZ) – Vector_field_XZ
u_xz (Scalar_mask_XZ) – Scalar_mask_XZ
- get(*args, **kwargs)
- apply_mask(*args, **kwargs)
- FP_WPM(*args, **kwargs)
- intensity(*args, **kwargs)
- check_energy(kind='all', has_draw: bool = True)[source]
check_energy. Integrates the Sz field and checks the energy conservation.
We have used the z component of the Poynting vector.
- Parameters:
kind (str) – ‘all’, ‘Sz’, ‘Stot’, ‘Strans’, ‘U’
has_draw (bool, optional) – If True, it draws the energy at each plane z. Defaults to True.
- Returns:
normalized (to the first data) energy at each plane z.
- Return type:
np.array
- surface_detection(*args, **kwargs)
- draw(kind: Literal['intensity', 'intensities', 'intensities_rz', 'phases', 'fields', 'EH', 'E2H2', 'poynting_vector', 'poynting_vector_averaged', 'poynting_total', 'energy_density', 'irradiance', 'stokes', 'param_ellipses'] = 'intensity', logarithm: float = 0, normalize: bool = False, cut_value: float | None = None, draw_borders: bool = True, filename='', scale: str = 'scaled', percentage_intensity: float | None = None, 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,
draw (bool) – If True, it draws the field. Defaults to True.
percentage_intensity (None or number) – If None it takes from CONF_DRAWING[‘percentage_intensity’], else uses this value
- diffractio.vector_fields_XZ.FP_PWD_kernel_simple(Ex, Ey, n1, n2, k0, kx, wavelength, dz, has_H=True)[source]
Step for Plane wave decomposition (PWD) algorithm.
- Parameters:
Ex (np.array) – field Ex
Ey (np.array) – field Ey
n1 (np.array) – refractive index at the first layer
n2 (np.array) – refractive index at the second layer
k0 (float) – wavenumber
kx (np.array) – transversal wavenumber
wavelength (float) – wavelength
dz (float) – increment in distances: z[1]-z[0]
has_H (bool, optional) – If True computes magnetic field H. Defaults to True.
- Returns:
Field E(z+dz) at at distance dz from the incident field. H list(Ex, Ey, Ez): Field H(z+dz) at at distance dz from the incident field.
- Return type:
E list(Ex, Ey, Ez)
- diffractio.vector_fields_XZ.FP_WPM_schmidt_kernel(Ex, Ey, n1, n2, k0, kx, wavelength, dz, has_H=True)[source]
Kernel for fast propagation of WPM method
- Parameters:
Ex (np.array) – field Ex
Ey (np.array) – field Ey
n1 (np.array) – refractive index at the first layer
n2 (np.array) – refractive index at the second layer
k0 (float) – wavenumber
kx (np.array) – transversal wavenumber
wavelength (float) – wavelength
dz (float) – increment in distances: z[1]-z[0]
has_H (bool, optional) – If True computes magnetic field H. Defaults to True.
- Returns:
Field E(z+dz) at at distance dz from the incident field. H list(Hx, Hy, Hz): Field H(z+dz) at at distance dz from the incident field.
- Return type:
E list(Ex, Ey, Ez)
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.vector_fields_XZ.draw2D_xz(image, x, y, ax=None, xlabel='x $(\\mu m)$', ylabel='r$y (\\mu m)$', title='', cmap='YlGnBu', interpolation='bilinear', 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
() (ax) – axis
xlabel (str) – label for x
ylabel (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
4.1.28. 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: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1.0, info: str = '')[source]
Bases:
objectClass 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: str, add_name: str = '', description: str = '', verbose: bool = 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: str, verbose: bool = 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
- size(verbose: bool = False)[source]
returns the size of the instance in MB.
- Parameters:
verbose (bool, optional) – prints size in Mb. Defaults to False.
- Returns:
size in MB
- Return type:
float
- get(*args, **kwargs)
- normalize(kind='amplitude', new_field: bool = 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
kind (str) – ‘amplitude’, or ‘intensity’
- Returns
u (numpy.array): normalized optical field
- draw(kind: str = 'intensity', logarithm: float = 0, normalize: bool = False, cut_value: float | None = None, filename: str = '', draw: bool = 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.29. 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: ndarray[Any, dtype[floating]] | None = None, y: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1, info: str = '')[source]
Bases:
Vector_field_XY- apply_circle(*args, **kwargs)
- pupil(*args, **kwargs)
- scalar_to_vector_mask(mask: Scalar_mask_XY, pol_state: None | Jones_matrix = None, is_intensity: bool = True)[source]
The same mask (binary) is applied to all the Jones Matrix.
- Parameters:
mask (scalar_mask_XY) – mask to apply.
pol_state (Jones Matrix or Jones_matrix) – Polarization state to apply
intensity (is) – If True, abs(mask)**2 is applied.
- complementary_masks(*args, **kwargs)
- multilevel_mask(mask: Scalar_mask_XY, states: Jones_matrix, discretize: bool = True, normalize: bool = 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: Jones_matrix)[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: float = 0.0)[source]
Generates an XY linear polarizer.
- Parameters:
angle (float) – linear polarizer angle
- quarter_waveplate(azimuth: float = 0.0)[source]
Generates an XY quarter wave plate.
- Parameters:
azimuth (float) – polarizer angle
- half_waveplate(azimuth: float = 0.0)[source]
Generates an XY half wave plate.
- Parameters:
azimuth (float) – polarizer angle
- polarizer_retarder(R: float = 0.0, p1: float = 1, p2: float = 1, azimuth: float = 0.0)[source]
Generates an XY retarder.
- Parameters:
R (float) – retardance between Ex and Ey components.
p1 (float) – transmittance of fast axis.
p2 (float) – transmittance of slow axis.
azimuth (float) – linear polarizer angle
- radial_polarizer(r0: tuple[float, float] = (0.0, 0.0))[source]
Radial polarizer.
- Parameters:
r0 (tuple[float, float]) – position of center
- azimuthal_polarizer(r0: tuple[float, float] = (0.0, 0.0))[source]
Generates an azimuthal-polarizer
- Parameters:
r0 (tuple[float, float]) – position of center
- q_plate(r0: tuple[float, float], q: float, phi: float = 3.141592653589793, theta=0.0)[source]
Generates a q_plate.
- Parameters:
r0 (tuple[float, float]) – position of 0.
q (float) – _description_
phi (float, optional) – _description_. Defaults to np.pi.
theta (_type_, optional) – angle of the q_plate. Defaults to 0*degrees.
- Reference:
J.A. Davis et al. “Analysis of a segmented q-plate tunable retarder for the generation of first-order vector beams” Applied Optics Vol. 54, No. 32 p. 9583 (2015) http://dx.doi.org/10.1364/AO.54.009583
- SLM(mask: Scalar_mask_XY, states_jones: Jones_matrix) None[source]
Mask for an Spatial Light Modulator (SLM).
Each pixel of the mask is converted to a Jones_matrix, according to its value
- Parameters:
mask (Scalar_mask_XY) – (0-1) Scalar_mask_XY to send to the SLM. It is a 2D array with values between 0 and 1. The function discretizes the values in the number of levels equal to the lenght of states_jones.
states_jones (Jones_matrix) – Jones matrix calibration of the SLM. It is a LUT with the Jones matrices of the SLM for each level of the mask.
- Returns:
Vector simulation of the Spatial Light Modulator.
- Return type:
- draw(kind: Literal['amplitudes', 'phases', 'jones', 'jones_ap'] = 'amplitudes', range_scale: str = 'um', cmap_max=1.0)[source]
Draws the mask. It must be different to sources.
- Parameters:
kind (str) – ‘amplitudes’, ‘phases’, ‘jones’, ‘jones_ap’.
parts. ('jones' is for real and imaginary)
phase. ('jones_ap' is for amplitud and)
4.1.30. 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: ndarray[Any, dtype[floating]] | None = None, y: ndarray[Any, dtype[floating]] | None = None, wavelength: float | None = None, n_background: float = 1, info: str = '')[source]
Bases:
Vector_field_XYClass 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(*args, **kwargs)
- azimuthal_wave(*args, **kwargs)
- radial_wave(*args, **kwargs)
- radial_inverse_wave(*args, **kwargs)
- azimuthal_inverse_wave(*args, **kwargs)
- local_polarized_vector_wave(*args, **kwargs)
- local_polarized_vector_wave_radial(*args, **kwargs)
- local_polarized_vector_wave_hybrid(*args, **kwargs)
- spiral_polarized_beam(*args, **kwargs)
4.1.31. Module contents
Top-level package for Python Scalar and vector diffraction and interference.