API for miepython package
miepython.core Module
Mie scattering calculations for perfect spheres.
Extensive documentation is at <https://miepython.readthedocs.io>
miepython is a pure Python module to calculate light scattering of a plane wave by non-absorbing, partially-absorbing, or perfectly conducting spheres.
The extinction efficiency, scattering efficiency, backscattering, and scattering asymmetry for a sphere with complex index of refraction m, diameter d, and wavelength lambda can be found by:
import miepython as mie
qext, qsca, qback, g = mie.efficiencies(m, d, lambda0)
The normalized scattering values for angles mu=cos(theta) are:
Ipar, Iper = mie.intensities(m, d, lambda0, mu)
If the size parameter is known, then use:
mie.efficiencies_mx(m, x)
Mie scattering amplitudes S1 and S2 (complex numbers):
mie.S1_S2(m, x, mu)
Normalized Mie scattering intensities for angles mu=cos(theta):
mie.i_per(m, x, mu)
mie.i_par(m, x, mu)
mie.i_unpolarized(m, x, mu)
Functions
|
Return the scattered intensities from a sphere. |
|
Compute the scattered intensity for parallel incident light. |
|
Compute the scattered intensity for perpendicular incident light. |
|
Return the unpolarized scattered intensity at specified angles. |
|
Computes scattering and extinction efficiencies for a spherical particle using Mie theory. |
|
Calculate the efficiencies of a sphere. |
|
Calculate the scattering amplitude functions for spheres. |
|
Calculate the scattering (Mueller) matrix. |
|
Computes the Mie coefficients for a sphere. |
Return the number of Mie series terms from Wiscombe's criterion. |
|
|
Figure out scattering function normalization. |
miepython._convention Module
Time-harmonic sign convention for the complex values miepython returns.
A monochromatic field can be written with time dependence exp(+jωt) or exp(-iωt). The two descriptions carry the same physics and, for the non-magnetic spheres handled here, every complex result in one is the complex conjugate of the same result in the other:
"+"(the default), exp(+jωt)The convention of van de Hulst, Kerker and Wiscombe’s MIEV0, natural for the m = n - ik form of the refractive index that miepython has always used. Outgoing spherical waves go as h_n^(2)(kr), a plane wave travelling along +z as exp(-jkz), and
S1_S2reproduces MIEV0’s amplitudes directly."-", exp(-iωt)The convention of Bohren & Huffman, Jackson and scattnlay. Outgoing waves go as h_n^(1)(kr), a plane wave along +z as exp(+ikz), and the amplitudes, coefficients and phase matrix match Bohren & Huffman’s equations and tables.
Only complex results depend on the choice: the Mie coefficients, S1 and S2, the near and far fields, the vector spherical harmonics, and the S34 element of the phase matrix (which changes sign, along with the handedness of the Stokes V). Efficiencies, g, intensities and the other phase-matrix elements are identical.
The refractive index is accepted with either sign of its imaginary part and is always taken to be absorbing, whatever convention is active.
The setting is global to the process. Library code that needs a particular convention should use the context manager, which restores the caller’s choice:
with miepython.time_convention("-"):
a, b = miepython.coefficients(m, x)
The raw kernels (an_bn, cn_dn, _S1_S2, …) ignore this setting and
always work in exp(-iωt); the public functions convert on the way out.
Functions
Return the active time convention. |
|
|
Choose the time convention for every complex result miepython returns. |
|
Use a time convention inside a |
miepython.mie_nojit Module
Low-level Mie calculations that do not use numba.
Functions
|
Compute the logarithmic derivative of ψ_n(z) using the downwards recurrence. |
|
Compute arrays of Mie coefficients A and B for a sphere. |
|
Calculate Mie coefficients c_n and d_n for the internal field of a sphere. |
|
Compute the Mie scattering functions π_n and τ_n for given cosine angles. |
|
Calculate the scattering amplitude functions for spheres. |
|
Calculate the efficiencies for a sphere when both m and x are scalars. |
|
Calculate the efficiencies for a small conducting spheres. |
|
Calculate the efficiencies for a small sphere. |
miepython.mie_jit Module
Low-level Mie calculations that use numba.
Functions
|
Compute the logarithmic derivative of ψ_n(z) using the downwards recurrence. |
|
Compute arrays of Mie coefficients a_n and b_n for a sphere. |
|
Calculate Mie coefficients c_n and d_n for the internal field of a sphere. |
|
Compute the Mie scattering functions π_n and τ_n for given cosine angles. |
|
Calculate the scattering amplitude functions for spheres. |
|
Calculate the efficiencies for a single sphere (both m and x are scalars). |
|
Calculate the efficiencies for a small conducting spheres. |
|
Calculate the efficiencies for a small sphere. |
miepython.rayleigh Module
Rayleigh approximation for scattering by spheres much smaller than the wavelength.
When a sphere is small both outside (x << 1) and inside (abs(m) * x << 1), the incident field is nearly uniform across it, and it radiates as a single oscillating electric dipole. Every scattering quantity then follows in closed form from the ratio (m**2 - 1) / (m**2 + 2), with no series of multipoles to sum. This module evaluates those expressions, following Bohren and Huffman, equations 5.4 and 5.7 to 5.9. A perfect conductor also radiates a magnetic dipole, and has its own expressions, described below.
The functions mirror those of the same names in miepython, with the same
arguments and the same norm choices, so one can stand in for the other:
efficiencies_mx(m, x),efficiencies(m, d, lambda0, n_env)qext, qsca, qback and g.
S1_S2(m, x, mu, norm)The scattering amplitudes at each mu = cos(theta).
i_par,i_per,i_unpolarized,intensitiesScattered intensities at each mu.
phase_matrix(m, x, mu, norm)The 4x4 Mueller matrix at each mu.
Nothing here takes n_pole, since there is only the dipole.
- Order of approximation:
Strictly, Rayleigh scattering is only the leading term in x: an electric dipole whose strength is set by the static polarizability. Not every expression here stops at that term, so this is better described as a small-particle approximation.
qsca and qback are the leading terms, 8/3 x**4 abs(ratio)**2 and 4 x**4 abs(ratio)**2.
qext carries Bohren and Huffman’s next-order correction. Its absorption term includes a relative x**2 correction, the order at which the magnetic dipole and the electric quadrupole first contribute (the 2 m**2 + 3 in its denominator is the quadrupole’s), and scattering is added as 8/3 x**4 Re(ratio**2).
S1_S2gives the electric dipole its own relative x**2 correction, the x**5 term, but leaves out the magnetic dipole and quadrupole. The angular pattern is therefore exactly that of a dipole, and g is 0.A perfect conductor gets only the leading terms of its electric and magnetic dipoles.
The corrections are not applied evenly, so a dielectric’s qext is more accurate than its qsca.
miepythonitself goes further for x < 0.1, using Wiscombe’s expansions, which keep the electric dipole, the magnetic dipole and the electric quadrupole, each with its own corrections.- Accuracy:
Relative error in qext against the full Mie solution:
m
x = 0.01
x = 0.1
x = 0.5
1.5
-7e-6
-7e-4
-1e-2
1.5 - 0.1j
8e-10
6e-6
4e-3
0.05 - 1.43j
2e-6
2e-2
14
-1j (conductor)
-2e-5
-2e-3
-4e-2
The last row is a silver-like sphere near its plasmon resonance, where m**2 is close to -2 and the denominator of the ratio nearly vanishes. There the approximation fails at much smaller x than for an ordinary dielectric.
For a dielectric the asymmetry parameter g is 0, because dipole scattering is the same forwards and backwards. The Mie value is 0.002 at x = 0.1 and 0.05 at x = 0.5 for m = 1.5.
- Conventions:
The index is m = n - ik, as in the rest of the package, and an index with a positive imaginary part is conjugated. The inputs that
miepythonrejects, a NaN or infinite m or x, a negative x or a negative real part of m, raise the sameValueErrorhere. The efficiencies accept an array of m or x and return arrays, g included. The angular functions describe one sphere and vectorize over mu only.- Perfect conductors:
As in the rest of the package, m.real == 0 means a perfect conductor, whatever the imaginary part, and m = 0 is one too. No field enters such a sphere, so the dielectric expressions, which describe the field inside, do not apply. Instead the surface currents radiate an electric dipole and a magnetic dipole half as strong and opposite in sign, a1 = 2i x**3/3 and b1 = -a1/2. The sphere absorbs nothing, qext = qsca = 10/3 x**4, and qback = 9 x**4. The two dipoles add backwards and partly cancel forwards, so g = -2/5 and the backscattered intensity is nine times the forward one.
Examples
A small absorbing sphere, compared with the full Mie solution:
>>> import numpy as np
>>> import miepython as mie
>>> from miepython import rayleigh
>>> qext, qsca, qback, g = rayleigh.efficiencies_mx(1.5 - 0.1j, 0.1)
>>> print(f"{qext:.5f} {qsca:.6f} {g:.4f}")
0.02006 0.000024 0.0000
>>> qext, qsca, qback, g = mie.efficiencies_mx(1.5 - 0.1j, 0.1)
>>> print(f"{qext:.5f} {qsca:.6f} {g:.4f}")
0.02006 0.000024 0.0020
The dipole pattern scatters equally forwards and backwards, and half as much at 90 degrees:
>>> mu = np.array([-1.0, 0.0, 1.0])
>>> print(np.round(rayleigh.i_unpolarized(1.5, 0.1, mu), 4))
[0.1195 0.0597 0.1195]
>>> print(np.round(mie.i_unpolarized(1.5, 0.1, mu), 4))
[0.1188 0.0597 0.1199]
A perfect conductor scatters mostly backwards:
>>> qext, qsca, qback, g = rayleigh.efficiencies_mx(-1j, 0.1)
>>> print(f"{qsca:.4e} {qback:.4e} {g:.4f}")
3.3333e-04 9.0000e-04 -0.4000
>>> qext, qsca, qback, g = mie.efficiencies_mx(-1j, 0.1)
>>> print(f"{qsca:.4e} {qback:.4e} {g:.4f}")
3.3413e-04 8.9834e-04 -0.3973
Functions
|
Calculate the efficiencies for a small sphere. |
|
Calculate the efficiencies of a sphere using Rayleigh's approximation. |
|
Calculate the scattering amplitude functions for small spheres. |
|
Return the parallel scattered intensity for small spheres. |
|
Return the perpendicular scattered intensity for small spheres. |
|
Return the unpolarized scattered intensity for small spheres. |
|
Return the scattered intensities from a sphere. |
|
Calculate the scattering (Mueller) matrix. |
miepython.bessel Module
Module for Bessel and Riccati-Bessel functions.
This module provides a collection of functions related to spherical Bessel functions, Hankel functions, Riccati-Bessel functions, and their derivatives. This supplements those provided by scipy.special
Functions provided:
Spherical Bessel functions:
spherical_h1: Spherical Hankel function of the first kind h_n^{(1)}(z).
spherical_h2: Spherical Hankel function of the second kind h_n^{(2)}(z).
Derivatives of Bessel functions:
d_spherical_jn: Derivative of the spherical Bessel function j_n’(z).
d_spherical_h1: Derivative of the spherical Hankel function of first kind h_n^{(1)}’(z).
d_spherical_h2: Derivative of the spherical Hankel function of second kind h_n^{(2)}’(z).
Riccati-Bessel functions:
riccati_bessel_jn: Riccati-Bessel function of the first kind ψ_n(z).
riccati_bessel_h1: Riccati-Bessel function of the second kind ξ_n(z).
riccati_bessel_h2: Riccati-Bessel function of the third kind ζ_n(z).
Derivatives of Riccati-Bessel functions:
d_riccati_bessel_jn: Derivative of the Riccati-Bessel function of the first kind ψ_n’(z).
d_riccati_bessel_h1: Derivative of the Riccati-Bessel function of the second kind ξ_n’(z).
d_riccati_bessel_h2: Derivative of the Riccati-Bessel function of the third kind ζ_n’(z).
Functions
|
Spherical Hankel function of the first kind. |
|
Spherical Hankel function of the second kind. |
|
Riccati-Bessel function of the first kind ψ_n(z). |
|
Riccati-Bessel function of the second kind ξ_n(z). |
|
Riccati-Bessel function of the third kind ζ_n(z). |
|
Derivative of the spherical Bessel function of the first kind. |
|
Derivative of the spherical Hankel function of the first kind h_n^{(1)}'(z). |
|
Derivative of the spherical Hankel function of the second kind h_n^{(2)}'(z). |
|
Derivative of the Riccati-Bessel function of the first kind ψ_n'(z). |
|
Derivative of the Riccati-Bessel function of the second kind ξ_n'(z). |
|
Derivative of the Riccati-Bessel function of the third kind ζ_n'(z). |
miepython.vsh Module
Vector Spherical Harmonics for Mie Scattering.
This module calculates the electric and magnetic vector spherical harmonics (VSH) required for Mie scattering computations. The functions in this module compute the VSH corresponding to the m=1 mode, which is commonly used in scattering problems.
Sign Conventions:
The sign conventions used in this module follow those presented on the “Vector Spherical Harmonics” webpage on Wikipedia as well as those described in the paper by Ladutenko (DOI: https://doi.org/10.1016/j.cpc.2017.01.017). In particular, the odd and even modes are consistent with these references.
The even and odd magnetic modes of Bohren & Huffman are reversed from those used here.
Bessel Function Selection:
The appropriate spherical Bessel function is chosen based on the spatial region where the field is evaluated:
For points inside the sphere (r < d_sphere/2), the regular spherical Bessel functions (
spherical_jn) are used.For points outside the sphere (r >= d_sphere/2), the spherical Hankel function that radiates outward in the active time convention is used: the second kind (
spherical_h2) for the default exp(+jωt), the first kind (spherical_h1) insidemiepython.time_convention("-").
m_indexis used exactly as given, so pass an absorbing index in the form that matches the active convention: n - ik for exp(+jωt), n + ik for exp(-iωt).
Functions:
All four take the same arguments
(n, lambda0, d_sphere, m_index, r, theta, phi): the multipole order, the vacuum wavelength, the sphere diameter, the refractive index of the medium the point lies in, and the spherical coordinates of that point.lambda0,d_sphereandrshare one length unit.
- M_odd(n, lambda0, d_sphere, m_index, r, theta, phi)
Compute the nth odd magnetic vector spherical harmonic (m=1).
- M_even(n, lambda0, d_sphere, m_index, r, theta, phi)
Compute the nth even magnetic vector spherical harmonic (m=1).
- N_odd(n, lambda0, d_sphere, m_index, r, theta, phi)
Compute the nth odd electric vector spherical harmonic (m=1).
- N_even(n, lambda0, d_sphere, m_index, r, theta, phi)
Compute the nth even electric vector spherical harmonic (m=1).
Each has an
*_arraycounterpart –M_odd_array,M_even_array,N_odd_array,N_even_array– with the identical signature, taking array-valuedr,thetaandphi.
Additional Utility Functions:
- mie_pi(n, theta, deg=False)
Computes the angular variation (𝜋ₙ(𝜃)) for the electric multipole field, based on the associated Legendre polynomial.
- mie_tau(n, theta, deg=False)
Computes the angular variation (𝛕ₙ(𝜃)) for the magnetic multipole field, corresponding to the derivative of the associated Legendre polynomial.
Functions
|
Computes the angular variation of the electric field arising from the nth magnetic multipole 𝛕_n(𝜃). |
|
Computes the angular variation of the electric field arising from the nth electric multipole 𝜋_n(𝜃). |
|
Compute the nth even magnetic vector spherical harmonic (m=1). |
|
Compute the nth odd magnetic vector spherical harmonic (m=1). |
|
Compute the nth even electric vector spherical harmonic (m=1). |
|
Compute the nth odd electric vector spherical harmonic (m=1). |
|
Compute the nth even magnetic vector spherical harmonic (m=1). |
|
Generate the first n odd magnetic vector spherical harmonics (m=1). |
|
Compute the first n even electric vector spherical harmonics. |
|
Generate first n odd electric vector spherical harmonics (m=1). |
miepython.field Module
Near- and far-field electromagnetic fields for a homogeneous sphere.
This module evaluates complex phasor electric and magnetic fields for a sphere embedded in a uniform medium.
Main entry points
Use these for most workflows:
e_near(...): electric field in spherical components[E_r, E_theta, E_phi].h_near(...): magnetic field in spherical components[H_r, H_theta, H_phi].eh_near(...): both electric and magnetic fields in one call.e_near_cartesian(...)/h_near_cartesian(...)/eh_near_cartesian(...): same near-field calculations in Cartesian components[Fx, Fy, Fz].e_far(...): scattered far-field electric components.
Quick examples
Evaluate the near electric field on a ring of points:
>>> import numpy as np
>>> import miepython.field as fields
>>> theta = np.linspace(0.0, np.pi, 181)
>>> phi = np.zeros_like(theta)
>>> r = np.full_like(theta, 1.5) # same length units as lambda0 and d_sphere
>>> E = fields.e_near(
... lambda0=1.0,
... d_sphere=1.0,
... m_sphere=1.5 + 0.0j,
... n_env=1.0,
... r=r,
... theta=theta,
... phi=phi,
... )
>>> E.shape
(3, 181)
Evaluate both fields in Cartesian coordinates on a 2D x-z slice:
>>> u = np.linspace(-1.5, 1.5, 101)
>>> X, Z = np.meshgrid(u, u, indexing="xy")
>>> E_xyz, H_xyz = fields.eh_near_cartesian(
... lambda0=1.0,
... d_sphere=1.0,
... m_sphere=1.5 + 0.0j,
... n_env=1.0,
... x=X,
... y=np.zeros_like(X),
... z=Z,
... )
>>> E_xyz.shape, H_xyz.shape
((3, 101, 101), (3, 101, 101))
Reuse precomputed Mie coefficients for repeated field evaluations:
>>> import miepython as mie
>>> m_rel = (1.5 + 0.0j) / 1.0
>>> x_size = np.pi * 1.0 * 1.0 / 1.0
>>> a, b, c, d = mie.coefficients(m_rel, x_size, internal=True)
>>> abcd = np.array([a, b, c, d])
>>> E2, H2 = fields.eh_near(
... 1.0, 1.0, 1.5 + 0.0j, 1.0, r, theta, phi, abcd=abcd
... )
Conventions
Phasor time dependence: the active time convention,
exp(+j * omega * t)by default orexp(-i * omega * t)insidemiepython.time_convention("-"). Every field returned here is the complex conjugate of the field in the other convention. The calculation itself is done inexp(-i * omega * t)and converted on return, and a caller’sabcdis converted on the way in, soabcdmust come frommiepython.coefficientsunder the same convention.Incident plane wave: propagation along
+z,Ealong+x,Halong+y, incident amplitudeE0 = 1. It isexp(-jkz)for exp(+jωt) andexp(+ikz)for exp(-iωt).Spherical coordinates:
thetafrom+zandphifrom+xtoward+y.lambda0is vacuum wavelength.n_envis the surrounding-medium index andm_sphereis the sphere index; relative index ism_rel = m_sphere / n_env.Size parameter is
x = pi * d_sphere * n_env / lambda0.Near field definition: outside the sphere, returned field is incident plus scattered; inside the sphere, returned field is the internal field.
Non-magnetic materials are assumed (relative permeability
mu_r = 1).
Functions
|
Calculate the electric field in and around a sphere. |
|
Calculate the magnetic field in and around a sphere. |
|
Calculate electric and magnetic fields in and around a sphere. |
|
Calculate electric near field in Cartesian coordinates. |
|
Calculate magnetic near field in Cartesian coordinates. |
|
Calculate electric and magnetic near fields in Cartesian coordinates. |
|
Evaluate the scattered electric far field. |
miepython.monte_carlo Module
Sample random scattering angles from the Mie phase function.
A Monte Carlo simulation of light transport needs, at every scattering event, a random direction in which the photon leaves the sphere. For unpolarized light only the polar angle theta depends on the sphere, and it must be drawn so that its cosine mu follows the phase function. This module does that by inverse transform sampling: build the cumulative distribution of mu once, then map each uniform random number u to the cosine at which the distribution reaches u.
cdfThe cumulative distribution at evenly spaced cosines.
mu_with_uniform_cdfThe cosines at which the cumulative distribution reaches evenly spaced probabilities, a lookup table that makes each draw cheap.
generate_mie_costhetaOne random cosine drawn from that table.
docs/06_random_deviates.ipynb works through the whole procedure.
This module is not imported with the package, because it imports
miepython itself and doing so from miepython/__init__.py would be
circular. Import it by name, as the examples below do.
Examples
Invert the distribution with np.interp to draw many cosines at once.
Their average is the asymmetry parameter g:
>>> import numpy as np
>>> import miepython as mie
>>> import miepython.monte_carlo as mc
>>> m, x = 1.33, 2.0 # a water droplet
>>> mu, cdf = mc.cdf(m, x, 1000)
>>> rng = np.random.default_rng(42)
>>> cosines = np.interp(rng.random(100_000), cdf, mu)
>>> print(f"{np.mean(cosines):.2f}")
0.67
>>> qext, qsca, qback, g = mie.efficiencies_mx(m, x)
>>> print(f"{g:.2f}")
0.67
Or build a lookup table once and draw one cosine at a time, as a photon transport loop does:
>>> mu_table, _ = mc.mu_with_uniform_cdf(m, x, 1000)
>>> cosines = [mc.generate_mie_costheta(mu_table, rng=rng) for _ in range(100_000)]
>>> print(f"{np.mean(cosines):.2f}")
0.67
Building either table costs a full Mie calculation, while each draw costs only a
random number or two, so build it once and reuse it. Evenly spaced cosines
resolve the narrow forward peak of a large sphere poorly; cdf explains how
many are needed and warns when there are too few, while mu_with_uniform_cdf
chooses enough by itself.
Passing rng keeps the draws reproducible without disturbing the process-wide
numpy.random; omitting it falls back to that global generator.
Functions
|
Cumulative distribution of the unpolarized phase function in cos(theta). |
|
Inverse-transform table for sampling the unpolarized phase function. |
|
Generate a new scattering angle using a cdf. |
miepython.util Module
Functions to format complex numbers or arrays of complex numbers.
Functions
|
Convert complex number to string for printing. |
|
Convert a tuple to string for printing. |
|
Convert complex numbers to string for printing. |
|
Convert complex scalar to phasors for printing. |
|
Convert complex numbers to phasor for printing. |
|
Convert Cartesian coordinates (x, y, z) to spherical (r, theta, phi). |
|
Convert spherical coordinates (r, theta, phi) to Cartesian (x, y, z). |
|
Convert spherical components (E_r, E_theta, E_phi) to Cartesian (Ex, Ey, Ez). |