pyoptics.utils

Utils for pyoptics.

Functions

Ez

Compute z-component of electrical field from x&y components.

I

Get intensity from field amplitude.

Z

Impedance of medium of (possbily complex) refractive index.

add_camera_noise

Apply a camera noise model to an image or an image stack.

center_of_mass

Return the center of mass (centroid) of a (non-negative) image.

complex_average

Compute average of complex numbers from r, phi instead of real and imaginary part.

deg_to_rad

ensure_meshgrid

Return meshed coordinates for linear or meshed input.

freq_grid

Compute a Fourier frequency grid corresponding to given x, y.

frequencies

Return frequencies as used in DFTs.

get_dx

Get dx using a formulation that does not suffer from numerical cancellation of significant digits.

get_length_scales

Return two length scales for an imaging system: the resolution limit/Airy diameter and depth of focus (DOF, for small NA known as the Rayleigh unit).

get_z_derivative

Get the derivative partial_z I for an image stack.

grid1d

Generate a one-dimensional coordinate array from boundary values and number of samples.

grid2d

Generate a two-dimensional grid from boundary values and number of samples.

image_energy

Return energy in an image.

k_z

Return z component of k vector from k_x and k_y.

kronecker_delta

local_momentum

Local momentum of a field (not implemented yet, returns None).

normalize_img_to_energy

Normalize a given field to a given energy.

pad

Pad a field symmetrically and extend its coordinate arrays.

rad_to_deg

scalar_product

Compute the scalar product <field_1|field_2> (using the physicist's convention of complex conjugation for field1).

scalar_product_with_weights

Compute the scalar product <field_1|field_2> (using the physicist's convention of complex conjugation for field1).

scalar_product_without_weights

Compute the scalar product <field_1|field_2> (using the physicist's convention of complex conjugation for field1).

sgn

Sign function using the convention sgn(0) = 1.0.

simpson_weights

Return Simpson integration weights (for 1d integration).

sin_cos

super_gaussian

Super Gaussian exp(-|x - x0|**N/(2*sigma_x**N) - |y - y0|**N/(2*sigma_y**N)).

unpad

Crop a field to the central region of a given shape; inverse of pad().

wavenumber

Wavenumber k = 2*pi*n/wavelength.

weight_grid

Meshed weight grid from 1D weights.

pyoptics.utils.get_dx(x)[source]

Get dx using a formulation that does not suffer from numerical cancellation of significant digits.

pyoptics.utils.complex_average(z_vals)[source]

Compute average of complex numbers from r, phi instead of real and imaginary part.

Parameters:
z_valsiterable
Returns:
z_avgcomplex
pyoptics.utils.ensure_meshgrid(x, y)[source]

Return meshed coordinates for linear or meshed input.

Parameters:
x, yarrays

Both 1d (meshed with np.meshgrid) or both 2d (returned as they are).

Returns:
XX, YY2d arrays
Raises:
ValueError

If x and y are neither both 1d nor both 2d.

pyoptics.utils.pad(field, x, y, shape=None, factor=None, value=0.0)[source]

Pad a field symmetrically and extend its coordinate arrays.

The sample at index N//2 is moved to index N_pad//2 of the padded array, so a grid that is centered as pyoptics.fft expects (x = 0 at index N//2) stays centered and FT() of the padded field has no additional phase.

Parameters:
fieldarray

Field of shape (Ny, Nx) or a stack of shape (Ny, Nx, …) (images along the last axes, as in pyoptics.processing).

x, yarrays

Linear, equidistant coordinates of the field.

shapetuple of ints, optional

New shape (Ny_pad, Nx_pad) of the first two axes.

factornumber, optional

Alternatively to shape: enlarge both axes by this factor (rounded up to the next integer number of samples). Exactly one of shape and factor must be given.

valuenumber, optional

Value to pad with. Defaults to 0.

Returns:
field_padarray

Padded field of the same dtype.

x_pad, y_padarrays

Coordinates of the padded field with the same spacing.

pyoptics.utils.unpad(field, x, y, shape)[source]

Crop a field to the central region of a given shape; inverse of pad().

Parameters:
fieldarray

Field of shape (Ny_pad, Nx_pad) or a stack (Ny_pad, Nx_pad, …).

x, yarrays

Coordinates of the field.

shapetuple of ints

Shape (Ny, Nx) of the cropped field.

Returns:
field_croppedarray
x_cropped, y_croppedarrays
pyoptics.utils.sgn(x)[source]

Sign function using the convention sgn(0) = 1.0.

pyoptics.utils.Z(n)[source]

Impedance of medium of (possbily complex) refractive index.

pyoptics.utils.I(E, n=1.0)[source]

Get intensity from field amplitude. Returns correct result as obtained by time-avergaing the Poynting vector.

Parameters:
Earray

Field amplitude

ndouble, optional

Refractive index of medium

Returns:
Iarray

Field amplitude E**2*n/(2*Z_0)

pyoptics.utils.wavenumber(wavelength, n=1.0)[source]

Wavenumber k = 2*pi*n/wavelength.

Parameters:
wavelengthnumber or array

Vacuum wavelength.

nnumber, optional

Refractive index (default: vacuum).

Returns:
knumber or array
pyoptics.utils.k_z(k, k_x, k_y)[source]

Return z component of k vector from k_x and k_y.

Parameters:
knumber
k_x, k_yarrays
Returns:
k_zarray

Notes

The function carefully handles evanescent waves: the branch with Im(k_z) >= 0 is returned, so that exp(+i*k_z*z) decays for z > 0 (exp(-i*omega*t) time dependence). The same holds for complex k in absorbing media (k = k_0*(n + i*kappa), kappa > 0).

pyoptics.utils.grid2d(x_min, x_max, y_min, y_max, Nx, Ny=None, assume_periodicity=True)[source]

Generate a two-dimensional grid from boundary values and number of samples.

Parameters:
x_min, x_max, y_min, y_maxnumbers

Boundary values.

Nx, Nyints

Number of samples (Ny is optional and defaults to a value equal to Nx).

assume_periodicityboolean, optional

If True, the endpoints are not included in the sampled values. This matches FFT conventions.

Returns:
x, yarrays

Linear coordinate arrays.

X, Yarrays

Meshed coordinate arrays.

pyoptics.utils.grid1d(x_min, x_max, N, assume_periodicity=True)[source]

Generate a one-dimensional coordinate array from boundary values and number of samples.

Parameters:
x_min, x_maxnumbers

Boundary values.

Nint

Number of samples.

assume_periodicityboolean, optional

If True, the endpoints are not included in the sampled values. This matches FFT conventions.

Returns:
xarray

Linear coordinate array. With assume_periodicity=True, x_min = -x_max and even N, x = 0 lies at index N//2 as pyoptics.fft.FT() expects; for odd N it does not. Linear coordinate array.

pyoptics.utils.frequencies(x, wavenumbers=True, normal_order=True)[source]

Return frequencies as used in DFTs.

Parameters:
xarray
wavenumbers, boolean, optional

If True, wavenumbers instead of spatial frequencies will be returned.

normal_orderbool, optional

If True, the grid is returned in ‘normal’ order with zero frequency components centered and increasing frequencies. If False, the zero frequency component is to the ‘left’, which is sometimes referred to as ‘standard order’.

Returns:
freq_xarrays

Arrays of frequencies/wavenumbers. In normal order, the zero frequency is at index N//2, which matches the spectra of pyoptics.fft.FT().

pyoptics.utils.freq_grid(x, y, wavenumbers=True, normal_order=True)[source]

Compute a Fourier frequency grid corresponding to given x, y.

Parameters:
x,yarrays

x and y values to use.

wavenumbers, boolean, optional

If True, wavenumbers instead of spatial frequencies will be returned.

normal_orderbool, optional

If True, the grid is returned in ‘normal’ order with zero frequency components centered and increasing frequencies. If False, the zero frequency component is to the ‘left’, which is sometimes referred to as ‘standard order’.

Returns:
freq_x, freq_yarrays

Meshed spatial frequencies/wavenumbers.

pyoptics.utils.get_length_scales(wavelength, NA, n=1.0, use_small_NA=False)[source]

Return two length scales for an imaging system: the resolution limit/Airy diameter and depth of focus (DOF, for small NA known as the Rayleigh unit).

Parameters:
wavelengthdouble

The vacuum wavelength.

NAdouble

Numerical aperture n*sin(alpha) (already includes the refractive index).

ndouble, optional

Refractive index of the medium. Defaults to 1 (air/vacuum).

use_small_NAboolean, optional

If True, use the small NA approximation commonly used in microscopy for the DOF.

Returns:
airydouble

The Airy diameter (not radius!).

DOFdouble

The Rayleigh unit.

pyoptics.utils.get_z_derivative(stack, dz, order)[source]

Get the derivative partial_z I for an image stack. This quantity may be used in transport of intensity computations.

Finite difference quotients are used in the computation. Finite differences amplfiy noise. To avoid this, a Savitzky-Golay filter is used here for a noise smoothing derivative. The idea is to approximate the the derivative by a low order polynomial and use a larger number of samples (here: images) to define the polynomial in a least squares sense.

Parameters:
stackarray

Intensity stack. An odd number of equidistant image plane centered around the plane of interest is expected.

dzdouble

Distance of individual image planes.

orderint

Order of approximating polynomial. Must be smaller than the number of images.

Returns:
dIdZarray

z-derivative in the central z-plane.

pyoptics.utils.add_camera_noise(stack, model='camera', **kwargs)[source]

Apply a camera noise model to an image or an image stack.

Shortcut for processing.CameraNoiser(model, **kwargs)(stack); see there for the models and parameters.

Parameters:
stackarray

Image (2d) or image stack (3d, last index numbering the images). For the “poisson” and “camera” models: expected photons per pixel.

modelstr, optional

“gaussian”, “poisson” or “camera”.

Returns:
noisyarray
pyoptics.utils.center_of_mass(img, x, y, threshold=0.0)[source]

Return the center of mass (centroid) of a (non-negative) image.

Parameters:
imgarray

Image of shape (len(y), len(x)), usually an intensity.

x, yarrays

1d coordinate grids.

thresholdfloat, optional

Pixels below threshold*max(img) are ignored (set to zero).

Returns:
x_c, y_cfloat

Coordinates of the centroid.

pyoptics.utils.scalar_product(field1, field2, x, y, weight_func=None)[source]

Compute the scalar product <field_1|field_2> (using the physicist’s convention of complex conjugation for field1).

Parameters:
field1, field2arrays

Sampled fields.

x, yarrays

Linear x and y arrays.

weight_funccallable, optional

Function w = w(n) return weights for the one-dimensional integration scheme to use. If omitted, a simple midpoint rule is used.

Returns:
scomplex

Scalar product.

pyoptics.utils.scalar_product_with_weights(field1, field2, x, y, weights)[source]

Compute the scalar product <field_1|field_2> (using the physicist’s convention of complex conjugation for field1).

Parameters:
field1, field2arrays

Sampled fields.

x, yarrays

Linear x and y arrays.

weightsarray

Weights array of same shape as field1, field2.

Returns:
scomplex

Scalar product.

pyoptics.utils.scalar_product_without_weights(field1, field2, x, y)[source]

Compute the scalar product <field_1|field_2> (using the physicist’s convention of complex conjugation for field1).

Parameters:
field1, field2arrays

Sampled fields.

x, yarrays

Linear x and y arrays.

Returns:
scomplex

Scalar product.

pyoptics.utils.local_momentum(field, wavelength)[source]

Local momentum of a field (not implemented yet, returns None).

Parameters:
fieldarray
wavelengthnumber
pyoptics.utils.simpson_weights(N)[source]

Return Simpson integration weights (for 1d integration).

Parameters:
Nint
Returns:
warray

Simpson weigths.

Notes

If N is even, the right-most indices will be treated by a different interpolation formula (of same order). This allows Simpson integration for even length sampled data.

pyoptics.utils.weight_grid(func, Nx, Ny)[source]

Meshed weight grid from 1D weights.

Parameters:
funccallable

func(N) returns a weight vector of length N, e.g. simpson_weights.

Nx, Nyint

Number of samples in x and y.

Returns:
w2d array

Shape (Ny, Nx), the outer product of the y and x weights.

pyoptics.utils.Ez(x, y, Ex, Ey, wl, n=1.0)[source]

Compute z-component of electrical field from x&y components. Assumes charge-free region.

Parameters:
x, yarrays

x and y coordinates of sampled fields.

Ex, Eyarrays

x and y field components.

wlnumber

Wavelength in same units as x and y.

nnumber, optional

Refractive index of medium.

pyoptics.utils.super_gaussian(x, y, x0, y0, sigma_x, sigma_y, N)[source]

Super Gaussian exp(-|x - x0|**N/(2*sigma_x**N) - |y - y0|**N/(2*sigma_y**N)).

Parameters:
x, yarrays

Linear or meshed coordinates.

x0, y0numbers

Centre.

sigma_x, sigma_ynumbers

Widths.

Nnumber

Order (N = 2: Gaussian).

Returns:
g2d array
pyoptics.utils.image_energy(img)[source]

Return energy in an image.

Parameters:
imgarray
Returns:
Enumber
pyoptics.utils.normalize_img_to_energy(img, E)[source]

Normalize a given field to a given energy.

Parameters:
imgarray
Enumber
Returns:
img_primearray