miepython 3.3.1__py3-none-any.whl → 3.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
miepython/__init__.py CHANGED
@@ -22,7 +22,7 @@ If the size parameter is known, then use::
22
22
 
23
23
  mie.efficiencies_mx(m, x)
24
24
 
25
- Mie scattering amplitudes S1 and S2 (complex numbers):
25
+ Mie scattering amplitudes S1 and S2 (complex numbers)::
26
26
 
27
27
  mie.S1_S2(m, x, mu)
28
28
 
@@ -38,10 +38,25 @@ Mie scattering intensities normalized to one when integrated over all angles::
38
38
  mie.i_par(m, x, mu, norm='one')
39
39
  mie.i_unpolarized(m, x, mu, norm='one')
40
40
 
41
- The scattering matrix
41
+ The scattering matrix::
42
42
 
43
43
  mie.phase_matrix(m, x, mu)
44
44
 
45
+ Time convention
46
+ ---------------
47
+
48
+ Complex results (coefficients, S1 and S2, fields, the S34 element of the phase
49
+ matrix) depend on whether the time dependence is written exp(+jωt) or exp(-iωt);
50
+ the two are complex conjugates. The default is exp(+jωt), which goes with the
51
+ m = n - ik form of the refractive index and reproduces Wiscombe's MIEV0. Bohren
52
+ & Huffman, Jackson and scattnlay use exp(-iωt)::
53
+
54
+ mie.set_time_convention("-") # for the rest of the session
55
+ with mie.time_convention("-"): # or just for a block
56
+ a, b = mie.coefficients(m, x)
57
+
58
+ Efficiencies, g and intensities are the same either way.
59
+
45
60
  Submodules
46
61
  ----------
47
62
 
@@ -56,7 +71,7 @@ the textbook formulas. It is a reference for development and cross-checking rat
56
71
  than a fast path, it requires the optional ``scipy`` dependency, and so it is bound
57
72
  only when scipy is installed::
58
73
 
59
- mie.vsh.M_odd(1, k, d_sphere, r, theta, phi)
74
+ mie.vsh.M_odd(1, 0.5, 1.0, 1.5, 0.8, 0.7, 0.2)
60
75
 
61
76
  ``miepython.monte_carlo`` samples scattering angles from the Mie phase function. It
62
77
  imports this package, so importing it from here would be circular; ask for it
@@ -91,6 +106,8 @@ from ._backend import single_sphere, small_conducting_sphere, small_sphere
91
106
  from .core import efficiencies, intensities, i_par, i_per, i_unpolarized
92
107
  from .core import efficiencies_mx, S1_S2, phase_matrix, coefficients
93
108
 
109
+ from ._convention import get_time_convention, set_time_convention, time_convention
110
+
94
111
  from . import rayleigh
95
112
 
96
113
  _FIELD_IMPORT_ERROR = None
@@ -148,6 +165,9 @@ else:
148
165
  # scipy is installed, and a star-import must not depend on that.
149
166
  __all__ = (
150
167
  "rayleigh",
168
+ "get_time_convention",
169
+ "set_time_convention",
170
+ "time_convention",
151
171
  "intensities",
152
172
  "i_par",
153
173
  "i_per",
@@ -178,7 +198,7 @@ __all__ = (
178
198
  "_D_downwards",
179
199
  )
180
200
 
181
- __version__ = "3.3.1"
201
+ __version__ = "3.4.0"
182
202
  __author__ = "Scott Prahl"
183
203
  __email__ = "scott.prahl@oit.edu"
184
204
  __copyright__ = "2017-2026, Scott Prahl"
@@ -0,0 +1,109 @@
1
+ """Time-harmonic sign convention for the complex values miepython returns.
2
+
3
+ A monochromatic field can be written with time dependence exp(+jωt) or
4
+ exp(-iωt). The two descriptions carry the same physics and, for the
5
+ non-magnetic spheres handled here, every complex result in one is the complex
6
+ conjugate of the same result in the other:
7
+
8
+ ``"+"`` (the default), exp(+jωt)
9
+ The convention of van de Hulst, Kerker and Wiscombe's MIEV0, natural for the
10
+ m = n - ik form of the refractive index that miepython has always used.
11
+ Outgoing spherical waves go as h_n^(2)(kr), a plane wave travelling along +z
12
+ as exp(-jkz), and ``S1_S2`` reproduces MIEV0's amplitudes directly.
13
+
14
+ ``"-"``, exp(-iωt)
15
+ The convention of Bohren & Huffman, Jackson and scattnlay. Outgoing waves go
16
+ as h_n^(1)(kr), a plane wave along +z as exp(+ikz), and the amplitudes,
17
+ coefficients and phase matrix match Bohren & Huffman's equations and tables.
18
+
19
+ Only complex results depend on the choice: the Mie coefficients, S1 and S2, the
20
+ near and far fields, the vector spherical harmonics, and the S34 element of the
21
+ phase matrix (which changes sign, along with the handedness of the Stokes V).
22
+ Efficiencies, g, intensities and the other phase-matrix elements are identical.
23
+
24
+ The refractive index is accepted with either sign of its imaginary part and is
25
+ always taken to be absorbing, whatever convention is active.
26
+
27
+ The setting is global to the process. Library code that needs a particular
28
+ convention should use the context manager, which restores the caller's choice::
29
+
30
+ with miepython.time_convention("-"):
31
+ a, b = miepython.coefficients(m, x)
32
+
33
+ The raw kernels (``an_bn``, ``cn_dn``, ``_S1_S2``, ...) ignore this setting and
34
+ always work in exp(-iωt); the public functions convert on the way out.
35
+ """
36
+
37
+ import contextlib
38
+
39
+ import numpy as np
40
+
41
+ __all__ = ("get_time_convention", "set_time_convention", "time_convention")
42
+
43
+ _VALID = ("+", "-")
44
+ _current = "+"
45
+
46
+
47
+ def _validate(sign):
48
+ """Return ``sign`` if it names a convention, else raise ``ValueError``."""
49
+ if not isinstance(sign, str) or sign not in _VALID:
50
+ raise ValueError(f"time convention must be '+' for exp(+jωt) or '-' for exp(-iωt), not {sign!r}")
51
+ return sign
52
+
53
+
54
+ def get_time_convention():
55
+ """Return the active time convention.
56
+
57
+ Returns:
58
+ str: ``"+"`` for exp(+jωt) or ``"-"`` for exp(-iωt).
59
+ """
60
+ return _current
61
+
62
+
63
+ def set_time_convention(sign):
64
+ """Choose the time convention for every complex result miepython returns.
65
+
66
+ Args:
67
+ sign (str): ``"+"`` for exp(+jωt), the default, or ``"-"`` for exp(-iωt).
68
+
69
+ Returns:
70
+ str: The convention that was active before the call, so it can be restored.
71
+
72
+ Raises:
73
+ ValueError: if ``sign`` is neither ``"+"`` nor ``"-"``.
74
+ """
75
+ global _current # pylint: disable=global-statement
76
+ previous = _current
77
+ _current = _validate(sign)
78
+ return previous
79
+
80
+
81
+ @contextlib.contextmanager
82
+ def time_convention(sign):
83
+ """Use a time convention inside a ``with`` block, then restore the previous one.
84
+
85
+ Args:
86
+ sign (str): ``"+"`` for exp(+jωt) or ``"-"`` for exp(-iωt).
87
+
88
+ Yields:
89
+ str: The convention in force inside the block.
90
+
91
+ Raises:
92
+ ValueError: if ``sign`` is neither ``"+"`` nor ``"-"``.
93
+ """
94
+ previous = set_time_convention(sign)
95
+ try:
96
+ yield sign
97
+ finally:
98
+ set_time_convention(previous)
99
+
100
+
101
+ def _convert(value):
102
+ """Convert between exp(-iωt), used internally, and the active convention.
103
+
104
+ Conjugation is its own inverse, so the same call takes an internal value out
105
+ to the user and a user-supplied value (such as ``abcd``) in.
106
+ """
107
+ if _current == "+":
108
+ return np.conjugate(value)
109
+ return value
miepython/core.py CHANGED
@@ -35,6 +35,7 @@ Normalized Mie scattering intensities for angles mu=cos(theta)::
35
35
 
36
36
  import numpy as np
37
37
  from ._backend import _S1_S2, an_bn, cn_dn, single_sphere
38
+ from ._convention import _convert
38
39
 
39
40
  # not really needed but included for clarity
40
41
  __all__ = (
@@ -118,6 +119,11 @@ def _check_one_sphere(m, x):
118
119
  raise ValueError("this function takes one sphere, so m and x must be scalars; loop over spheres for more")
119
120
 
120
121
 
122
+ def _scalarize_0d(value):
123
+ """Pass a zero-dimensional NumPy array to scalar kernels as a scalar."""
124
+ return value.item() if isinstance(value, np.ndarray) and value.ndim == 0 else value
125
+
126
+
121
127
  def coefficients(m, x, n_pole=0, internal=False):
122
128
  """
123
129
  Computes the Mie coefficients for a sphere.
@@ -125,18 +131,21 @@ def coefficients(m, x, n_pole=0, internal=False):
125
131
  This function calculates the Mie coefficients for electromagnetic scattering
126
132
  by a sphere. It supports both single values and arrays for the refractive
127
133
  index and size parameter. For arrays, the lengths of `m` and `x` must match.
128
- If the length of `m` or `x` is zero, the function assumes scalar values.
134
+ Zero-dimensional NumPy arrays are treated as scalar values.
129
135
 
130
- If `n_pole > 0`, the function returns only the 1 to nth multipole coefficients
131
- for each input.
136
+ If `n_pole > 0`, the function returns the coefficients of orders 1 through
137
+ `n_pole` for each input, so the last entry is the order-`n_pole` term. This
138
+ differs from `efficiencies_mx` and `S1_S2`, where a nonzero `n_pole` isolates
139
+ that single order.
132
140
 
133
141
  Args:
134
142
  m (complex or array-like): The complex refractive index of the sphere.
135
143
  If an array, must match the length of `x`.
136
144
  x (float or array-like): The size parameter of the sphere. If an array,
137
145
  must match the length of `m`.
138
- n_pole (int, optional): The specific multipole order to compute. Defaults to 0,
139
- which calculates all terms and returns the full arrays of coefficients.
146
+ n_pole (int, optional): The number of orders to compute, 1 through
147
+ `n_pole`. Defaults to 0, which uses Wiscombe's criterion for the
148
+ number of terms.
140
149
  internal (bool, optional): If True then returns Mie coefficients needed to
141
150
  calculate fields inside the sphere.
142
151
 
@@ -150,6 +159,10 @@ def coefficients(m, x, n_pole=0, internal=False):
150
159
  Notes:
151
160
  - If the imaginary part of the refractive index is positive, it is
152
161
  automatically corrected to its conjugate value to ensure a valid input.
162
+ - The coefficients follow the active time convention (see
163
+ ``miepython.set_time_convention``). With the default exp(+jωt) they
164
+ are the conjugates of Bohren & Huffman's a_n and b_n; inside
165
+ ``miepython.time_convention("-")`` they are Bohren & Huffman's own.
153
166
  - Every returned coefficient is a real term; the arrays carry no padding.
154
167
 
155
168
  Raises:
@@ -164,9 +177,9 @@ def coefficients(m, x, n_pole=0, internal=False):
164
177
  >>> len(a), len(b)
165
178
  (3, 3)
166
179
  >>> print(f"{a[0]:.6e}")
167
- 3.333700e-05-1.973631e-04j
180
+ 3.333700e-05+1.973631e-04j
168
181
  >>> print(f"{b[0]:.6e}")
169
- 6.672963e-08-2.754694e-07j
182
+ 6.672963e-08+2.754694e-07j
170
183
 
171
184
  Keep only the dipole term for each of several spheres:
172
185
 
@@ -174,9 +187,15 @@ def coefficients(m, x, n_pole=0, internal=False):
174
187
  >>> a.shape
175
188
  (2, 1)
176
189
  >>> print(f"{a[0, 0]:.6f}")
177
- 0.447946-0.386652j
190
+ 0.447946+0.386652j
178
191
  """
192
+ return _convert(_coefficients(m, x, n_pole, internal))
193
+
194
+
195
+ def _coefficients(m, x, n_pole=0, internal=False):
196
+ """Return ``coefficients`` in exp(-iωt), whatever the active convention."""
179
197
  _check_m_x(m, x)
198
+ m, x = _scalarize_0d(m), _scalarize_0d(x)
180
199
  mlen = np.size(m) if np.ndim(m) > 0 else 0
181
200
  xlen = np.size(x) if np.ndim(x) > 0 else 0
182
201
 
@@ -233,6 +252,7 @@ def efficiencies_mx(m, x, n_pole=0, e_field=True):
233
252
  Multipole order to compute:
234
253
  - If 0 (default), computes contributions from all multipoles.
235
254
  - If non-zero, computes contributions from the specified multipole order.
255
+ - A nonzero order beyond ``wiscombe_terms(x)`` raises ValueError.
236
256
  e_field (boolean):
237
257
  When n_pole>0, selects which multipole of that order contributes:
238
258
  True gives the electric multipole a_n, False the magnetic
@@ -287,6 +307,7 @@ def efficiencies_mx(m, x, n_pole=0, e_field=True):
287
307
  known rather than the size parameter.
288
308
  """
289
309
  _check_m_x(m, x)
310
+ m, x = _scalarize_0d(m), _scalarize_0d(x)
290
311
 
291
312
  # ensure imaginary part of refractive index is negative
292
313
  if np.isscalar(m):
@@ -349,6 +370,9 @@ def normalization_factor(m, x, norm_str, efficiency_source=_mie_efficiencies):
349
370
  Returns:
350
371
  scaling factor needed for scattering function
351
372
  """
373
+ m, x = _scalarize_0d(m), _scalarize_0d(x)
374
+ if np.imag(m) > 0: # ensure imaginary part of refractive index is negative
375
+ m = np.conj(m)
352
376
  factor = None
353
377
  norm = norm_str.lower()
354
378
 
@@ -359,7 +383,9 @@ def normalization_factor(m, x, norm_str, efficiency_source=_mie_efficiencies):
359
383
  factor = 1
360
384
 
361
385
  elif norm in ["qsca", "scattering_efficiency"]:
362
- factor = x * np.sqrt(np.pi)
386
+ # a zero-size sphere has zero amplitudes, so any nonzero factor leaves
387
+ # them zero; x * sqrt(pi) would give 0/0
388
+ factor = x * np.sqrt(np.pi) if x > 0 else 1
363
389
 
364
390
  else:
365
391
  qext, qsca, _, _ = efficiency_source(m, x)
@@ -396,8 +422,9 @@ def S1_S2(m, x, mu, norm="albedo", n_pole=0):
396
422
  """
397
423
  Calculate the scattering amplitude functions for spheres.
398
424
 
399
- The amplitude functions have been normalized so that when integrated
400
- over all 4*pi solid angles, the integral will be qext*pi*x**2.
425
+ With the default ``norm='albedo'`` the unpolarized intensity
426
+ ``(abs(S1)**2 + abs(S2)**2)/2`` integrated over all 4*pi solid angles equals the
427
+ single-scattering albedo qsca/qext.
401
428
 
402
429
  The normalization is controlled by `norm` and should be one of
403
430
  ['albedo', 'one', '4pi', 'qext', 'qsca', 'bohren', or 'wiscombe']
@@ -420,15 +447,25 @@ def S1_S2(m, x, mu, norm="albedo", n_pole=0):
420
447
  series raise a ValueError.
421
448
 
422
449
  Returns:
423
- S1, S2: the scattering amplitudes at each angle mu [sr**(-0.5)]
450
+ S1, S2: the scattering amplitudes at each angle mu [sr**(-0.5)]. They
451
+ follow the active time convention: with the default exp(+jωt) they are
452
+ Wiscombe's MIEV0 amplitudes, the conjugates of Bohren & Huffman's, and
453
+ inside ``miepython.time_convention("-")`` they are Bohren & Huffman's.
424
454
 
425
455
  Raises:
426
456
  ValueError: if m or x is not finite, x is negative, or the real part of
427
457
  m is negative. A perfect conductor is m.real == 0, not m.real < 0.
428
458
  Also if m or x is an array, since this describes one sphere.
429
459
  """
460
+ S1, S2 = _S1_S2_normalized(m, x, mu, norm, n_pole)
461
+ return _convert(S1), _convert(S2)
462
+
463
+
464
+ def _S1_S2_normalized(m, x, mu, norm="albedo", n_pole=0):
465
+ """Return ``S1_S2`` in exp(-iωt), whatever the active convention."""
430
466
  _check_m_x(m, x)
431
467
  _check_one_sphere(m, x)
468
+ m, x = _scalarize_0d(m), _scalarize_0d(x)
432
469
  if np.imag(m) > 0: # ensure imaginary part of refractive index is negative
433
470
  m = np.conj(m)
434
471
 
@@ -462,6 +499,12 @@ def phase_matrix(m, x, mu, norm="albedo", n_pole=0):
462
499
  Bohren and Huffman, *Absorption and Scattering of Light by Small Particles*,
463
500
  JOHN WILEY & SONS, page 112, (1983).
464
501
 
502
+ S11, S12 and S33 do not depend on the time convention, but S34 does, and so
503
+ does the handedness of the Stokes V it couples to. With exp(-iωt), inside
504
+ ``miepython.time_convention("-")``, the matrix is Bohren & Huffman's
505
+ eq. 3.16 with ``p[2, 3] = S34`` and ``p[3, 2] = -S34``. With the default
506
+ exp(+jωt) both elements change sign.
507
+
465
508
  The normalization is controlled by `norm` and should be one of
466
509
  ['albedo', 'one', '4pi', 'qext', 'qsca', 'bohren', or 'wiscombe']
467
510
  The normalization describes the integral of the scattering phase
miepython/field.py CHANGED
@@ -64,9 +64,15 @@ Reuse precomputed Mie coefficients for repeated field evaluations:
64
64
 
65
65
  Conventions
66
66
  -----------
67
- - Phasor time dependence: ``exp(-i * omega * t)``.
67
+ - Phasor time dependence: the active time convention, ``exp(+j * omega * t)`` by
68
+ default or ``exp(-i * omega * t)`` inside ``miepython.time_convention("-")``.
69
+ Every field returned here is the complex conjugate of the field in the other
70
+ convention. The calculation itself is done in ``exp(-i * omega * t)`` and
71
+ converted on return, and a caller's ``abcd`` is converted on the way in, so
72
+ ``abcd`` must come from ``miepython.coefficients`` under the same convention.
68
73
  - Incident plane wave: propagation along ``+z``, ``E`` along ``+x``, ``H`` along ``+y``,
69
- incident amplitude ``E0 = 1``.
74
+ incident amplitude ``E0 = 1``. It is ``exp(-jkz)`` for exp(+jωt) and
75
+ ``exp(+ikz)`` for exp(-iωt).
70
76
  - Spherical coordinates: ``theta`` from ``+z`` and ``phi`` from ``+x`` toward ``+y``.
71
77
  - ``lambda0`` is vacuum wavelength.
72
78
  - ``n_env`` is the surrounding-medium index and ``m_sphere`` is the sphere index;
@@ -82,7 +88,8 @@ import numpy as np
82
88
  from scipy.special import factorial2, spherical_jn
83
89
  from ._backend import D_calc, pi_tau
84
90
  from .bessel import spherical_h1
85
- from .core import S1_S2, _check_m_x, coefficients, wiscombe_terms
91
+ from ._convention import _convert
92
+ from .core import _S1_S2_normalized, _check_m_x, _coefficients, wiscombe_terms
86
93
  from .util import cartesian_to_spherical, spherical_vector_to_cartesian
87
94
 
88
95
  __all__ = (
@@ -208,20 +215,33 @@ def e_far(lambda0, d_sphere, m_sphere, n_env, r, theta, phi):
208
215
  Returns:
209
216
  ndarray: Complex spherical components ``[E_r, E_theta, E_phi]`` with
210
217
  shape ``(3, ...)`` following broadcasted input shape.
218
+
219
+ Notes:
220
+ This is Bohren & Huffman eq. 4.74 for a unit x-polarized incident wave,
221
+ ``E_theta = S2 cos(phi) exp(ikr)/(-ikr)`` and
222
+ ``E_phi = -S1 sin(phi) exp(ikr)/(-ikr)``, evaluated in exp(-iωt) with
223
+ Bohren & Huffman's own S1 and S2 and then converted, like every other
224
+ result, to the active time convention. It is the leading term of
225
+ ``e_near(..., include_incident=False)`` and differs from it by O(1/kr).
211
226
  """
212
227
  x = np.pi * d_sphere * n_env / lambda0
213
228
  m_rel = m_sphere / n_env
229
+ r, theta, phi = np.broadcast_arrays(
230
+ np.asarray(r, dtype=float), np.asarray(theta, dtype=float), np.asarray(phi, dtype=float)
231
+ )
214
232
  jkr = 1j * 2 * np.pi * n_env * r / lambda0
215
233
  amp = np.exp(jkr) / (-jkr)
216
234
 
217
- S1, S2 = S1_S2(m_rel, x, np.cos(theta), norm="wiscombe")
235
+ # the amplitudes depend on theta alone; evaluate them on the flattened,
236
+ # broadcast grid and restore its shape so every component matches
237
+ S1, S2 = _S1_S2_normalized(m_rel, x, np.cos(theta).ravel(), norm="wiscombe")
238
+ S1 = S1.reshape(theta.shape)
239
+ S2 = S2.reshape(theta.shape)
218
240
 
219
241
  E_r = np.zeros_like(S1, dtype=complex)
220
242
  E_theta = S2 * amp * np.cos(phi)
221
- E_phi = S1 * amp * np.sin(phi)
222
- E_theta = np.conjugate(-E_theta)
223
- E_phi = np.conjugate(-E_phi)
224
- return np.array([E_r, E_theta, E_phi])
243
+ E_phi = -S1 * amp * np.sin(phi)
244
+ return _convert(np.array([E_r, E_theta, E_phi]))
225
245
 
226
246
 
227
247
  def _incident_e_spherical(lambda0, n_env, r, theta, phi, amplitude=1.0):
@@ -296,10 +316,21 @@ def _coefficients_abcd(lambda0, d_sphere, m_sphere, n_env, n_pole):
296
316
  # 3.6e-6 with one extra order and 3.2e-6 with two, then flattens out, so
297
317
  # two is where it stops being worth more terms.
298
318
  n_pole = wiscombe_terms(x) + 2
299
- a, b, c, d = coefficients(m_rel, x, n_pole=n_pole, internal=True)
319
+ a, b, c, d = _coefficients(m_rel, x, n_pole=n_pole, internal=True)
300
320
  return np.array([a, b, c, d])
301
321
 
302
322
 
323
+ def _internal_abcd(lambda0, d_sphere, m_sphere, n_env, n_pole, abcd):
324
+ """Return exp(-iωt) coefficients, computing them or converting the caller's.
325
+
326
+ A caller's ``abcd`` comes from ``miepython.coefficients`` and so is in the
327
+ active convention; everything in this module works in exp(-iωt).
328
+ """
329
+ if abcd is None:
330
+ return _coefficients_abcd(lambda0, d_sphere, m_sphere, n_env, n_pole)
331
+ return _convert(np.asarray(abcd))
332
+
333
+
303
334
  def _near_fields(abcd, lambda0, d_sphere, m_sphere, n_env, r, theta, phi, include_incident, want_e, want_h):
304
335
  """Evaluate the near fields at every requested point.
305
336
 
@@ -345,15 +376,17 @@ def _near_fields(abcd, lambda0, d_sphere, m_sphere, n_env, r, theta, phi, includ
345
376
  e_out = np.empty((3, r_flat.size), dtype=complex) if want_e else None
346
377
  h_out = np.empty((3, r_flat.size), dtype=complex) if want_h else None
347
378
 
379
+ # The coefficient kernels treat either imaginary sign as absorption. Use the
380
+ # same physical index for the interior radial functions and H-field factor.
381
+ m_absorbing = np.conjugate(m_sphere) if np.imag(m_sphere) > 0 else m_sphere
348
382
  is_inside = r_flat < d_sphere / 2
349
383
  for inside in (True, False):
350
384
  group = is_inside if inside else ~is_inside
351
385
  if not group.any():
352
386
  continue
353
387
 
354
- # miepython coefficients follow the n-ik convention and are conjugated
355
- # internally; use conjugated sphere index so internal fields are consistent.
356
- m_index = np.conjugate(m_sphere) if inside else n_env
388
+ # This module works in exp(-iωt), where an absorbing index is n + ik.
389
+ m_index = np.conjugate(m_absorbing) if inside else n_env
357
390
  M_the_base, M_phi_base, N_r_base, N_the_base, N_phi_base = _vsh_components_base(
358
391
  n_terms, lambda0, m_index, r_flat[group], theta_flat[group], inside
359
392
  )
@@ -394,7 +427,7 @@ def _near_fields(abcd, lambda0, d_sphere, m_sphere, n_env, r, theta, phi, includ
394
427
  cos_phi * N_phi_base,
395
428
  )
396
429
  if inside:
397
- m_rel = np.conjugate(m_sphere / n_env)
430
+ m_rel = m_index / n_env
398
431
  h_rad = m_rel * _sum_two_scaled_terms(scale, d, M_even_rad, -1.0 + 0.0j, c, N_odd_rad, -1.0j)
399
432
  h_the = m_rel * _sum_two_scaled_terms(scale, d, M_even_the, -1.0 + 0.0j, c, N_odd_the, -1.0j)
400
433
  h_phi = m_rel * _sum_two_scaled_terms(scale, d, M_even_phi, -1.0 + 0.0j, c, N_odd_phi, -1.0j)
@@ -445,17 +478,17 @@ def e_near(lambda0, d_sphere, m_sphere, n_env, r, theta, phi, include_incident=T
445
478
  n_pole (int): Number of multipole terms to keep. ``0`` (the default) keeps
446
479
  two more than Wiscombe's criterion, which converges the near field at
447
480
  the sphere surface roughly five times closer than the criterion alone.
448
- abcd (ndarray or None): Optional precomputed coefficients ``[a, b, c, d]``.
449
- If provided, ``n_pole`` is ignored.
481
+ abcd (ndarray or None): Optional precomputed coefficients ``[a, b, c, d]``
482
+ from ``miepython.coefficients(..., internal=True)`` under the same time
483
+ convention. If provided, ``n_pole`` is ignored.
450
484
 
451
485
  Returns:
452
486
  ndarray: Spherical electric components ``[E_r, E_theta, E_phi]`` with
453
487
  shape ``(3, ...)``.
454
488
  """
455
- if abcd is None:
456
- abcd = _coefficients_abcd(lambda0, d_sphere, m_sphere, n_env, n_pole)
489
+ abcd = _internal_abcd(lambda0, d_sphere, m_sphere, n_env, n_pole, abcd)
457
490
 
458
- return _near_fields(
491
+ e_sph = _near_fields(
459
492
  abcd,
460
493
  lambda0,
461
494
  d_sphere,
@@ -468,6 +501,7 @@ def e_near(lambda0, d_sphere, m_sphere, n_env, r, theta, phi, include_incident=T
468
501
  want_e=True,
469
502
  want_h=False,
470
503
  )[0]
504
+ return _convert(e_sph)
471
505
 
472
506
 
473
507
  def h_near(lambda0, d_sphere, m_sphere, n_env, r, theta, phi, include_incident=True, n_pole=0, abcd=None):
@@ -485,17 +519,17 @@ def h_near(lambda0, d_sphere, m_sphere, n_env, r, theta, phi, include_incident=T
485
519
  n_pole (int): Number of multipole terms to keep. ``0`` (the default) keeps
486
520
  two more than Wiscombe's criterion, which converges the near field at
487
521
  the sphere surface roughly five times closer than the criterion alone.
488
- abcd (ndarray or None): Optional precomputed coefficients ``[a, b, c, d]``.
489
- If provided, ``n_pole`` is ignored.
522
+ abcd (ndarray or None): Optional precomputed coefficients ``[a, b, c, d]``
523
+ from ``miepython.coefficients(..., internal=True)`` under the same time
524
+ convention. If provided, ``n_pole`` is ignored.
490
525
 
491
526
  Returns:
492
527
  ndarray: Spherical magnetic components ``[H_r, H_theta, H_phi]`` with
493
528
  shape ``(3, ...)``.
494
529
  """
495
- if abcd is None:
496
- abcd = _coefficients_abcd(lambda0, d_sphere, m_sphere, n_env, n_pole)
530
+ abcd = _internal_abcd(lambda0, d_sphere, m_sphere, n_env, n_pole, abcd)
497
531
 
498
- return _near_fields(
532
+ h_sph = _near_fields(
499
533
  abcd,
500
534
  lambda0,
501
535
  d_sphere,
@@ -508,6 +542,7 @@ def h_near(lambda0, d_sphere, m_sphere, n_env, r, theta, phi, include_incident=T
508
542
  want_e=False,
509
543
  want_h=True,
510
544
  )[1]
545
+ return _convert(h_sph)
511
546
 
512
547
 
513
548
  def eh_near(
@@ -536,17 +571,17 @@ def eh_near(
536
571
  n_pole (int): Number of multipole terms to keep. ``0`` (the default) keeps
537
572
  two more than Wiscombe's criterion, which converges the near field at
538
573
  the sphere surface roughly five times closer than the criterion alone.
539
- abcd (ndarray or None): Optional precomputed coefficients ``[a, b, c, d]``.
540
- If provided, ``n_pole`` is ignored.
574
+ abcd (ndarray or None): Optional precomputed coefficients ``[a, b, c, d]``
575
+ from ``miepython.coefficients(..., internal=True)`` under the same time
576
+ convention. If provided, ``n_pole`` is ignored.
541
577
 
542
578
  Returns:
543
579
  tuple[ndarray, ndarray]: Tuple ``(E, H)`` in spherical components,
544
580
  each with shape ``(3, ...)``.
545
581
  """
546
- if abcd is None:
547
- abcd = _coefficients_abcd(lambda0, d_sphere, m_sphere, n_env, n_pole)
582
+ abcd = _internal_abcd(lambda0, d_sphere, m_sphere, n_env, n_pole, abcd)
548
583
 
549
- return _near_fields(
584
+ e_sph, h_sph = _near_fields(
550
585
  abcd,
551
586
  lambda0,
552
587
  d_sphere,
@@ -559,6 +594,7 @@ def eh_near(
559
594
  want_e=True,
560
595
  want_h=True,
561
596
  )
597
+ return _convert(e_sph), _convert(h_sph)
562
598
 
563
599
 
564
600
  def e_near_cartesian(
@@ -587,7 +623,8 @@ def e_near_cartesian(
587
623
  n_pole (int): Number of multipole terms to keep. ``0`` (the default) keeps
588
624
  two more than Wiscombe's criterion, which converges the near field at
589
625
  the sphere surface roughly five times closer than the criterion alone.
590
- abcd (ndarray or None): Optional precomputed coefficients ``[a, b, c, d]``.
626
+ abcd (ndarray or None): Optional precomputed coefficients ``[a, b, c, d]``,
627
+ in the active time convention.
591
628
 
592
629
  Returns:
593
630
  ndarray: Cartesian electric components ``[E_x, E_y, E_z]``.
@@ -623,7 +660,8 @@ def h_near_cartesian(
623
660
  n_pole (int): Number of multipole terms to keep. ``0`` (the default) keeps
624
661
  two more than Wiscombe's criterion, which converges the near field at
625
662
  the sphere surface roughly five times closer than the criterion alone.
626
- abcd (ndarray or None): Optional precomputed coefficients ``[a, b, c, d]``.
663
+ abcd (ndarray or None): Optional precomputed coefficients ``[a, b, c, d]``,
664
+ in the active time convention.
627
665
 
628
666
  Returns:
629
667
  ndarray: Cartesian magnetic components ``[H_x, H_y, H_z]``.
@@ -659,7 +697,8 @@ def eh_near_cartesian(
659
697
  n_pole (int): Number of multipole terms to keep. ``0`` (the default) keeps
660
698
  two more than Wiscombe's criterion, which converges the near field at
661
699
  the sphere surface roughly five times closer than the criterion alone.
662
- abcd (ndarray or None): Optional precomputed coefficients ``[a, b, c, d]``.
700
+ abcd (ndarray or None): Optional precomputed coefficients ``[a, b, c, d]``,
701
+ in the active time convention.
663
702
 
664
703
  Returns:
665
704
  tuple[ndarray, ndarray]: Tuple ``(E_xyz, H_xyz)`` where each array is
miepython/mie_jit.py CHANGED
@@ -58,7 +58,7 @@ def _D_downwards(z, N, D):
58
58
  Args:
59
59
  z: function argument
60
60
  N: order of Ricatti-Bessel function
61
- D: gets filled with ψ_k'(z)/ψ_k(z) for k=0 to N-1
61
+ D: gets filled with ψ_k'(z)/ψ_k(z) for k=0 to N-1; D[N] is untouched
62
62
  """
63
63
  last_D = _Lentz_Dn(z, N)
64
64
  for n in range(N, 0, -1):
@@ -74,7 +74,7 @@ def _D_upwards(z, N, D):
74
74
  Args:
75
75
  z: function argument
76
76
  N: order of Ricatti-Bessel function
77
- D: gets filled with ψ_k'(z)/ψ_k(z) for k=0 to N-1
77
+ D: gets filled with ψ_k'(z)/ψ_k(z) for k=1 to N-1; D[0] is untouched
78
78
  """
79
79
  exp = np.exp(-2j * z)
80
80
  D[1] = -1 / z + (1 - exp) / ((1 - exp) / z - 1j * (1 + exp))
@@ -132,19 +132,18 @@ def _D_calc_down_nb(z, N):
132
132
  """
133
133
  Compute D_1(z)..D_N(z) using only the downwards recurrence.
134
134
 
135
- ``_D_calc_nb`` picks between the upwards and downwards recurrences with
136
- Wiscombe's criterion, which considers the refractive index but not the number
137
- of terms. The upwards recurrence loses accuracy once N exceeds ``|z|`` (about
138
- 4 digits for a small sphere), and the resulting noise differs between the
139
- numba and pure-python backends. The internal-field coefficients are not on
140
- the hot path, so they always take the stable route.
135
+ The upwards recurrence loses accuracy once N exceeds ``|z|`` (about 4 digits
136
+ for a small sphere), and the resulting noise differs between the numba and
137
+ pure-python backends, so every caller, ``_D_calc_nb`` included, uses this
138
+ stable route.
141
139
 
142
140
  Args:
143
141
  z: function argument (already multiplied by the refractive index)
144
142
  N: highest order needed
145
143
 
146
144
  Returns:
147
- Array of logarithmic derivatives D_k(z) for k=1 to N
145
+ Array of length N holding D_k(z) for k=1 to N-1, followed by a zero.
146
+ Callers that need orders 1..n therefore ask for N = n + 1.
148
147
  """
149
148
  D = np.zeros(N + 1, dtype=np.complex128)
150
149
  _D_downwards(z, N, D)
@@ -177,7 +176,7 @@ def _D_calc_nb(m, x, N):
177
176
  N: order of Ricatti-Bessel function
178
177
 
179
178
  Returns:
180
- Array of logarithmic derivatives D_k(z) for k=1 to N-1.
179
+ Array of length N holding D_k(z) for k=1 to N-1, followed by a zero.
181
180
  """
182
181
  return _D_calc_down_nb(np.complex128(m * x), N)
183
182
 
@@ -211,6 +210,9 @@ def _an_bn_nb(m, x, n_pole=0):
211
210
  Returns:
212
211
  a, b: arrays of Mie coefficents An and Bn, one entry per order,
213
212
  with no padding. ``_cn_dn`` returns the same number of terms.
213
+ They are in the exp(-iωt) convention of Bohren & Huffman: the series is
214
+ built with m = n - ik and xi = x h_n^(2), which is exp(+jωt), and the
215
+ conjugate is returned.
214
216
  """
215
217
  # make sure sign of imaginary part is negative
216
218
  m_re = m.real
@@ -275,6 +277,7 @@ def _an_bn_nb(m, x, n_pole=0):
275
277
  chi_nm1 = chi_n
276
278
  chi_n = chi
277
279
 
280
+ # computed in exp(+jωt); every kernel returns exp(-iωt)
278
281
  return np.conjugate(a), np.conjugate(b)
279
282
 
280
283
 
@@ -282,18 +285,20 @@ def _an_bn_nb(m, x, n_pole=0):
282
285
  # folded the np.isinf guard below to False and let an infinite index divide by
283
286
  # zero, and its reassociation also broke the exact Re(a_n) == |a_n|**2 identity
284
287
  # that a lossless sphere has to satisfy. Do not add it back.
285
- @njit((complex128, float64, int64))
286
- def _cn_dn_nb(m, x, n_pole):
288
+ # Lazily compiled for the same reason as _an_bn_nb: n_pole defaults to 0.
289
+ @njit(cache=True)
290
+ def _cn_dn_nb(m, x, n_pole=0):
287
291
  """
288
292
  Calculate Mie coefficients c_n and d_n for the internal field of a sphere.
289
293
 
290
294
  Args:
291
295
  m (np.complex128): Refractive index of the sphere relative to the surrounding medium.
292
296
  x (float): Size parameter of the sphere (2πr/λ).
293
- n_pole (int): Number of terms to calculate (n_pole).
297
+ n_pole (int): Number of terms to calculate (0, the default, uses Wiscombe's criterion).
294
298
 
295
299
  Returns:
296
300
  (np.ndarray, np.ndarray): Arrays of c_n and d_n coefficients.
301
+ Like a_n and b_n they are returned in the exp(-iωt) convention.
297
302
  """
298
303
  # make sure sign of imaginary part is negative
299
304
  m_re = m.real
@@ -391,8 +396,9 @@ def _S1_S2_nb(m, x, mu, n_pole):
391
396
  """
392
397
  Calculate the scattering amplitude functions for spheres.
393
398
 
394
- The amplitude functions have been normalized so that when integrated
395
- over all 4*pi solid angles, the integral will be qext*pi*x**2.
399
+ The amplitudes are unnormalized (``norm='wiscombe'``): the unpolarized
400
+ intensity ``(abs(S1)**2 + abs(S2)**2)/2`` integrated over all 4*pi solid angles is
401
+ pi*x**2*qsca. The public ``S1_S2`` applies the requested normalization.
396
402
 
397
403
  The units are weird, sr**(-0.5)
398
404
 
@@ -404,6 +410,8 @@ def _S1_S2_nb(m, x, mu, n_pole):
404
410
 
405
411
  Returns:
406
412
  S1, S2: the scattering amplitudes at each angle mu [sr**(-0.5)]
413
+ in the exp(-iωt) convention of Bohren & Huffman, like every kernel.
414
+ The public ``S1_S2`` converts them to the active time convention.
407
415
  """
408
416
  a, b = _an_bn_nb(m, x, 0)
409
417
  N = len(a)
@@ -437,7 +445,8 @@ def _S1_S2_nb(m, x, mu, n_pole):
437
445
  S1[k] = scale[j] * (pi[j] * a[j] + tau[j] * b[j])
438
446
  S2[k] = scale[j] * (tau[j] * a[j] + pi[j] * b[j])
439
447
 
440
- return np.conjugate(S1), np.conjugate(S2)
448
+ # a and b are already exp(-iωt), so the sums need no further conjugation
449
+ return S1, S2
441
450
 
442
451
 
443
452
  @njit((complex128, float64), cache=True)
@@ -550,6 +559,9 @@ def _single_sphere_nb(m, x, n_pole, e_field):
550
559
  if x <= 0:
551
560
  return 0.0, 0.0, 0.0, 0.0
552
561
 
562
+ if m.imag > 0.0: # ensure imaginary part of refractive index is negative
563
+ m = complex(m.real, -m.imag)
564
+
553
565
  # case when sphere matches its environment
554
566
  if abs(m.real - 1) <= 1e-8 and abs(m.imag) < 1e-8:
555
567
  return 0, 0, 0, 0
@@ -561,9 +573,9 @@ def _single_sphere_nb(m, x, n_pole, e_field):
561
573
  if m.real > 0.0 and np.abs(m) * x < 0.1 and n_pole == 0:
562
574
  return _small_sphere_nb(m, x)
563
575
 
564
- # sometimes m=0 is used to signal perfectly conducting sphere
565
- if abs(m.real) < 1e-8 and abs(m.imag) < 1e-8:
566
- m = 1 - 10000j
576
+ n_max = int(x + 4.05 * x**0.33333 + 2.0)
577
+ if n_pole < 0 or n_pole > n_max:
578
+ raise ValueError("n_pole must be 0 (all terms) or a multipole order in 1.." + str(n_max))
567
579
 
568
580
  a, b = _an_bn_nb(m, x, n_pole)
569
581
  x2 = x * x
miepython/mie_nojit.py CHANGED
@@ -86,8 +86,7 @@ def _D_downwards(z, N, D):
86
86
  Args:
87
87
  z: function argument
88
88
  N: order of Ricatti-Bessel function
89
- D: gets filled with the Ricatti-Bessel function values for orders
90
- from 0 to N for an argument z using the downwards recurrence relations.
89
+ D: gets filled with ψ_k'(z)/ψ_k(z) for k=0 to N-1; D[N] is untouched
91
90
  """
92
91
  last_D = _Lentz_Dn(z, N)
93
92
  for n in range(N, 0, -1):
@@ -102,8 +101,7 @@ def _D_upwards(z, N, D):
102
101
  Args:
103
102
  z: function argument
104
103
  N: order of Ricatti-Bessel function
105
- D: gets filled with the Ricatti-Bessel function values for orders
106
- from 0 to N for an argument z using the upwards recurrence relations.
104
+ D: gets filled with ψ_k'(z)/ψ_k(z) for k=1 to N-1; D[0] is untouched
107
105
  """
108
106
  exp = np.exp(-2j * z)
109
107
  D[1] = -1 / z + (1 - exp) / ((1 - exp) / z - 1j * (1 + exp))
@@ -156,19 +154,18 @@ def _D_calc_down_py(z, N):
156
154
  """
157
155
  Compute D_1(z)..D_N(z) using only the downwards recurrence.
158
156
 
159
- ``_D_calc_py`` picks between the upwards and downwards recurrences with
160
- Wiscombe's criterion, which considers the refractive index but not the number
161
- of terms. The upwards recurrence loses accuracy once N exceeds ``|z|`` (about
162
- 4 digits for a small sphere), and the resulting noise differs between the
163
- numba and pure-python backends. The internal-field coefficients are not on
164
- the hot path, so they always take the stable route.
157
+ The upwards recurrence loses accuracy once N exceeds ``|z|`` (about 4 digits
158
+ for a small sphere), and the resulting noise differs between the numba and
159
+ pure-python backends, so every caller, ``_D_calc_py`` included, uses this
160
+ stable route.
165
161
 
166
162
  Args:
167
163
  z: function argument (already multiplied by the refractive index)
168
164
  N: highest order needed
169
165
 
170
166
  Returns:
171
- Array of logarithmic derivatives D_k(z) for k=1 to N
167
+ Array of length N holding D_k(z) for k=1 to N-1, followed by a zero.
168
+ Callers that need orders 1..n therefore ask for N = n + 1.
172
169
  """
173
170
  D = np.zeros(N + 1, dtype=np.complex128)
174
171
  _D_downwards(z, N, D)
@@ -200,7 +197,7 @@ def _D_calc_py(m, x, N):
200
197
  N: order of Ricatti-Bessel function
201
198
 
202
199
  Returns:
203
- Array of logarithmic derivatives D_k(z) for k=1 to N-1.
200
+ Array of length N holding D_k(z) for k=1 to N-1, followed by a zero.
204
201
  """
205
202
  return _D_calc_down_py(np.complex128(m * x), N)
206
203
 
@@ -229,6 +226,9 @@ def _an_bn_py(m, x, n_pole=0):
229
226
  Returns:
230
227
  a, b: arrays of Mie coefficents An and Bn, one entry per order,
231
228
  with no padding. ``_cn_dn`` returns the same number of terms.
229
+ They are in the exp(-iωt) convention of Bohren & Huffman: the series is
230
+ built with m = n - ik and xi = x h_n^(2), which is exp(+jωt), and the
231
+ conjugate is returned.
232
232
  """
233
233
  if m.imag > 0: # ensure imaginary part of refractive index is negative
234
234
  m = np.conj(m)
@@ -286,20 +286,22 @@ def _an_bn_py(m, x, n_pole=0):
286
286
  chi_nm1 = chi_n
287
287
  chi_n = chi
288
288
 
289
+ # computed in exp(+jωt); every kernel returns exp(-iωt)
289
290
  return np.conjugate(a), np.conjugate(b)
290
291
 
291
292
 
292
- def _cn_dn_py(m, x, n_pole):
293
+ def _cn_dn_py(m, x, n_pole=0):
293
294
  """
294
295
  Calculate Mie coefficients c_n and d_n for the internal field of a sphere.
295
296
 
296
297
  Args:
297
298
  m (np.complex128): Refractive index of the sphere relative to the surrounding medium.
298
299
  x (float): Size parameter of the sphere (2πr/λ).
299
- n_pole (int): Number of terms to calculate (n_pole).
300
+ n_pole (int): Number of terms to calculate (0, the default, uses Wiscombe's criterion).
300
301
 
301
302
  Returns:
302
303
  (np.ndarray, np.ndarray): Arrays of c_n and d_n coefficients.
304
+ Like a_n and b_n they are returned in the exp(-iωt) convention.
303
305
  """
304
306
  # ensure imaginary part of refractive index is negative
305
307
  if m.imag > 0:
@@ -390,8 +392,9 @@ def _S1_S2_py(m, x, mu, n_pole):
390
392
  """
391
393
  Calculate the scattering amplitude functions for spheres.
392
394
 
393
- The amplitude functions have been normalized so that when integrated
394
- over all 4*pi solid angles, the integral will be qext*pi*x**2.
395
+ The amplitudes are unnormalized (``norm='wiscombe'``): the unpolarized
396
+ intensity ``(abs(S1)**2 + abs(S2)**2)/2`` integrated over all 4*pi solid angles is
397
+ pi*x**2*qsca. The public ``S1_S2`` applies the requested normalization.
395
398
 
396
399
  The units are weird, sr**(-0.5)
397
400
 
@@ -403,6 +406,8 @@ def _S1_S2_py(m, x, mu, n_pole):
403
406
 
404
407
  Returns:
405
408
  S1, S2: the scattering amplitudes at each angle mu [sr**(-0.5)]
409
+ in the exp(-iωt) convention of Bohren & Huffman, like every kernel.
410
+ The public ``S1_S2`` converts them to the active time convention.
406
411
  """
407
412
  a, b = _an_bn_py(m, x, 0)
408
413
  N = len(a)
@@ -431,7 +436,8 @@ def _S1_S2_py(m, x, mu, n_pole):
431
436
  S1[k] = scale[j] * (pi[j] * a[j] + tau[j] * b[j])
432
437
  S2[k] = scale[j] * (tau[j] * a[j] + pi[j] * b[j])
433
438
 
434
- return np.conjugate(S1), np.conjugate(S2)
439
+ # a and b are already exp(-iωt), so the sums need no further conjugation
440
+ return S1, S2
435
441
 
436
442
 
437
443
  def _small_conducting_sphere_py(_m, x):
@@ -541,6 +547,9 @@ def _single_sphere_py(m, x, n_pole, e_field):
541
547
  if x <= 0:
542
548
  return 0.0, 0.0, 0.0, 0.0
543
549
 
550
+ if m.imag > 0: # ensure imaginary part of refractive index is negative
551
+ m = np.conj(m)
552
+
544
553
  # case when sphere matches its environment
545
554
  if abs(m.real - 1) <= 1e-8 and abs(m.imag) < 1e-8:
546
555
  return 0, 0, 0, 0
@@ -552,9 +561,9 @@ def _single_sphere_py(m, x, n_pole, e_field):
552
561
  if m.real > 0.0 and np.abs(m) * x < 0.1 and n_pole == 0:
553
562
  return _small_sphere_py(m, x)
554
563
 
555
- # sometimes m=0 is used to signal perfectly conducting sphere
556
- if abs(m.real) < 1e-8 and abs(m.imag) < 1e-8:
557
- m = 1 - 10000j
564
+ n_max = int(x + 4.05 * x**0.33333 + 2.0)
565
+ if n_pole < 0 or n_pole > n_max:
566
+ raise ValueError("n_pole must be 0 (all terms) or a multipole order in 1.." + str(n_max))
558
567
 
559
568
  a, b = _an_bn_py(m, x, n_pole)
560
569
  x2 = x * x
miepython/rayleigh.py CHANGED
@@ -119,6 +119,7 @@ Examples:
119
119
 
120
120
  import numpy as np
121
121
 
122
+ from ._convention import _convert
122
123
  from .core import _check_m_x, _check_one_sphere
123
124
  from .core import normalization_factor as core_normalization_factor
124
125
 
@@ -157,6 +158,10 @@ def efficiencies_mx(m, x):
157
158
  m is negative, exactly as for the full Mie functions
158
159
  """
159
160
  _check_m_x(m, x)
161
+ if not np.isscalar(x):
162
+ x = np.asarray(x, dtype=float)
163
+ if np.ndim(m) > 0 and np.ndim(x) > 0 and np.size(m) != np.size(x):
164
+ raise RuntimeError("m and x arrays to mie must be same length")
160
165
 
161
166
  # ensure imaginary part of refractive index is negative, as core.py does
162
167
  if np.isscalar(m):
@@ -236,19 +241,23 @@ def S1_S2(m, x, mu, norm="albedo"):
236
241
  Based on equation 5.4 in Bohren and Huffman. A perfect conductor,
237
242
  m.real == 0, adds the magnetic dipole b1 = -a1/2 to its electric one.
238
243
 
239
- The amplitude functions are normalized so that when integrated
240
- over all 4*pi solid angles, the integral will be qext*pi*x**2.
244
+ With the default ``norm='albedo'`` the unpolarized intensity
245
+ ``(abs(S1)**2 + abs(S2)**2)/2`` integrated over all 4*pi solid angles equals the
246
+ single-scattering albedo qsca/qext.
241
247
 
242
248
  The units are weird, sr**(-0.5)
243
249
 
244
250
  Args:
245
251
  m: the complex index of refraction of the sphere
246
252
  x: the size parameter of the sphere
247
- mu: the angles, cos(theta), to calculate scattering amplitudes
253
+ mu: the angles, cos(theta), to calculate scattering amplitudes. A scalar
254
+ is treated as one angle and yields a length-one array.
248
255
  norm: (optional) string describing scattering function normalization
249
256
 
250
257
  Returns:
251
- S1, S2: the scattering amplitudes at each angle mu [sr**(-0.5)]
258
+ S1, S2: length-one or longer arrays of scattering amplitudes at each
259
+ angle mu [sr**(-0.5)], in the active time convention, as for
260
+ ``miepython.S1_S2``
252
261
 
253
262
  Raises:
254
263
  ValueError: if m or x is not finite, x is negative, or the real part of
@@ -257,6 +266,7 @@ def S1_S2(m, x, mu, norm="albedo"):
257
266
  """
258
267
  _check_m_x(m, x)
259
268
  _check_one_sphere(m, x)
269
+ mu = np.atleast_1d(np.asarray(mu, dtype=float))
260
270
  if np.imag(m) > 0: # ensure imaginary part of refractive index is negative
261
271
  m = np.conj(m)
262
272
 
@@ -278,7 +288,10 @@ def S1_S2(m, x, mu, norm="albedo"):
278
288
  S1 /= normalization
279
289
  S2 /= normalization
280
290
 
281
- return S1, S2
291
+ # a1 above is written for m = n - ik in exp(+jωt), so these amplitudes are
292
+ # exp(+jωt) already; conjugate to the internal exp(-iωt) and then convert to
293
+ # whichever convention is active, exactly as core.S1_S2 does
294
+ return _convert(np.conjugate(S1)), _convert(np.conjugate(S2))
282
295
 
283
296
 
284
297
  def i_per(m, x, mu, norm="albedo"):
@@ -369,7 +382,6 @@ def intensities(m, d, lambda0, mu, n_env=1.0, norm="albedo"):
369
382
  mu: the cos(theta) of each direction desired [-]
370
383
  n_env: real index of medium around sphere, optional.
371
384
  norm: (optional) string describing scattering function normalization
372
- n_pole: return n_pole term from series (default=0 means include all terms)
373
385
 
374
386
  Returns:
375
387
  ipar, iper: scattered intensity in parallel and perpendicular planes [1/sr]
@@ -401,7 +413,6 @@ def phase_matrix(m, x, mu, norm="albedo"):
401
413
  m: the complex index of refraction of the sphere
402
414
  x: the size parameter of the sphere
403
415
  mu: the angles, cos(theta), of the phase scattering matrix
404
- n_pole: return n_pole term from series (default=0 means include all terms)
405
416
  norm: (optional) string describing scattering function normalization
406
417
 
407
418
  Returns:
miepython/vsh.py CHANGED
@@ -24,8 +24,12 @@ Bessel Function Selection:
24
24
  - For points inside the sphere (r < d_sphere/2), the regular spherical
25
25
  Bessel functions (``spherical_jn``) are used.
26
26
  - For points outside the sphere (r >= d_sphere/2), the spherical Hankel
27
- functions of the first kind (``spherical_h1``) are employed to represent
28
- the radiating field.
27
+ function that radiates outward in the active time convention is used:
28
+ the second kind (``spherical_h2``) for the default exp(+jωt), the first
29
+ kind (``spherical_h1``) inside ``miepython.time_convention("-")``.
30
+
31
+ ``m_index`` is used exactly as given, so pass an absorbing index in the form
32
+ that matches the active convention: n - ik for exp(+jωt), n + ik for exp(-iωt).
29
33
 
30
34
  Functions:
31
35
 
@@ -63,7 +67,8 @@ Additional Utility Functions:
63
67
 
64
68
  import numpy as np
65
69
  from scipy.special import spherical_jn, lpmv, factorial2
66
- from .bessel import spherical_h1, d_riccati_bessel_h1
70
+ from .bessel import spherical_h1, spherical_h2, d_riccati_bessel_h1, d_riccati_bessel_h2
71
+ from ._convention import get_time_convention
67
72
  from ._backend import D_calc
68
73
 
69
74
  __all__ = (
@@ -138,6 +143,16 @@ def mie_tau(n, theta, deg=False):
138
143
  return ((n + 1) * x * lpmv(1, n, x) - n * lpmv(1, n + 1, x)) / np.sqrt(1 - x * x)
139
144
 
140
145
 
146
+ def _outgoing_h(n, rho):
147
+ """Spherical Hankel function of an outgoing wave in the active time convention."""
148
+ return spherical_h2(n, rho) if get_time_convention() == "+" else spherical_h1(n, rho)
149
+
150
+
151
+ def _outgoing_d_riccati_h(n, rho):
152
+ """Derivative of the outgoing Riccati-Hankel function in the active time convention."""
153
+ return d_riccati_bessel_h2(n, rho) if get_time_convention() == "+" else d_riccati_bessel_h1(n, rho)
154
+
155
+
141
156
  def M_base(n, rho, theta, inside):
142
157
  """
143
158
  Compute the non-phi part of magnetic vector spherical harmonic (m=1).
@@ -154,7 +169,7 @@ def M_base(n, rho, theta, inside):
154
169
  if inside:
155
170
  factor = spherical_jn(n, rho)
156
171
  else:
157
- factor = spherical_h1(n, rho)
172
+ factor = _outgoing_h(n, rho)
158
173
 
159
174
  M_r = 0
160
175
  M_theta = mie_pi(n, theta) * factor
@@ -325,8 +340,8 @@ def N_base(n, m_index, kr, theta, inside):
325
340
  factor2 = factor1 * Dn
326
341
  factor1 /= rho
327
342
  else:
328
- factor1 = spherical_h1(n, rho) / rho
329
- factor2 = d_riccati_bessel_h1(n, rho) / rho
343
+ factor1 = _outgoing_h(n, rho) / rho
344
+ factor2 = _outgoing_d_riccati_h(n, rho) / rho
330
345
 
331
346
  N_r = n * (n + 1) * np.sin(theta) * mie_pi(n, theta) * factor1
332
347
  N_theta = mie_tau(n, theta) * factor2
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: miepython
3
- Version: 3.3.1
3
+ Version: 3.4.0
4
4
  Summary: Mie scattering of a plane wave by a sphere
5
5
  Author-email: Scott Prahl <scott.prahl@oit.edu>
6
6
  License-Expression: MIT
@@ -23,7 +23,6 @@ Requires-Python: >=3.11
23
23
  Description-Content-Type: text/x-rst
24
24
  License-File: LICENSE.txt
25
25
  Requires-Dist: numpy
26
- Requires-Dist: matplotlib
27
26
  Requires-Dist: scipy
28
27
  Requires-Dist: numba; sys_platform != "emscripten"
29
28
  Provides-Extra: docs
@@ -35,8 +34,8 @@ Requires-Dist: sphinx_rtd_theme; extra == "docs"
35
34
  Provides-Extra: dev
36
35
  Requires-Dist: pytest; extra == "dev"
37
36
  Requires-Dist: pytest-cov; extra == "dev"
38
- Requires-Dist: imageio; extra == "dev"
39
37
  Requires-Dist: requests; extra == "dev"
38
+ Requires-Dist: matplotlib; extra == "dev"
40
39
  Requires-Dist: ruff; extra == "dev"
41
40
  Requires-Dist: yamllint; extra == "dev"
42
41
  Requires-Dist: rstcheck[sphinx,toml]; extra == "dev"
@@ -45,13 +44,13 @@ Requires-Dist: pyroma; extra == "dev"
45
44
  Requires-Dist: black[jupyter]; extra == "dev"
46
45
  Requires-Dist: build; extra == "dev"
47
46
  Requires-Dist: check-manifest; extra == "dev"
48
- Requires-Dist: libarchive-c; extra == "dev"
49
47
  Requires-Dist: pyyaml; extra == "dev"
50
48
  Requires-Dist: jupyterlab; extra == "dev"
51
49
  Requires-Dist: nbconvert; extra == "dev"
52
50
  Requires-Dist: nbformat; extra == "dev"
53
51
  Provides-Extra: lite
54
52
  Requires-Dist: jupyterlite-core<0.8,>=0.7; extra == "lite"
53
+ Requires-Dist: libarchive-c; extra == "lite"
55
54
  Requires-Dist: jupyterlite-pyodide-kernel<0.8,>=0.7; extra == "lite"
56
55
  Dynamic: license-file
57
56
 
@@ -210,7 +209,7 @@ Citation
210
209
 
211
210
  If you use ``miepython`` in academic, instructional, or applied technical work, please cite:
212
211
 
213
- Prahl, S. (2026). *miepython: Pure python calculation of Mie scattering* (Version 3.3.0) [Computer software]. Zenodo. https://doi.org/10.5281/zenodo.7949263
212
+ Prahl, S. (2026). *miepython: Pure python calculation of Mie scattering* (Version 3.3.1) [Computer software]. Zenodo. https://doi.org/10.5281/zenodo.7949263
214
213
 
215
214
  BibTeX:
216
215
 
@@ -222,7 +221,7 @@ BibTeX:
222
221
  url = {https://github.com/scottprahl/miepython},
223
222
  doi = {10.5281/zenodo.7949263},
224
223
  year = {2026},
225
- version = {3.3.0},
224
+ version = {3.3.1},
226
225
  publisher = {Zenodo}
227
226
  }
228
227
 
@@ -0,0 +1,19 @@
1
+ miepython/__init__.py,sha256=0d0ItbVQ1dtbqgRIyotHkQ0mjDxCl_UjY8YbDlVRJeo,6690
2
+ miepython/_backend.py,sha256=l_faAa6zanygRZKA9vMVcfcutHPFFkpqZzHqwjU8QcE,1619
3
+ miepython/_convention.py,sha256=b_Y0Y2Vg5OUKWse8zNs5H3JgUtF_-RHpMRyrrAPSEQU,3762
4
+ miepython/bessel.py,sha256=U094wY_5RFqrVjXZgMbacmt_yqpP8GBtRZ24-MNzBsU,3647
5
+ miepython/core.py,sha256=pk_dxdLxVtsEMjj2HLJd7ZucZQJrA-MbYaxBDcARIC0,27233
6
+ miepython/field.py,sha256=tQ2OwNqqE_KlYbIyJhSQdgL9DerT5Ze4EUko2zb8I_w,28950
7
+ miepython/mie_jit.py,sha256=f55uQaP7JN4K1cBI-tDRzens3jZDrYmu75C9Oc9gVdE,22500
8
+ miepython/mie_nojit.py,sha256=Z2weX0N0VJkIc-MJMs914C9l-k9flK2YjTTVpFWxUk4,20866
9
+ miepython/monte_carlo.py,sha256=1pRELa63NcZOkhSe2AviObPztPaKe7JRqMBQn3rp9Ls,8422
10
+ miepython/rayleigh.py,sha256=KtuHfyctzidnzkZ5z7mKDSVeWZgUVcPLRqboKySpUdc,17579
11
+ miepython/util.py,sha256=3jxGd0jmPFYolllQXISLDmz0jE4C1AyFD1OyD65dUGo,3648
12
+ miepython/vsh.py,sha256=7t-Dj91K7icLM92G-_Cy-lHmcITJ_xAo7bVc4Qj87Ew,18925
13
+ miepython/data/Johnson.txt,sha256=PcdEhJ3ZKUnt--86ukEvUt-w-814uOyWXtE-G3qWTNE,1337
14
+ miepython/data/segelstein81_index.txt,sha256=aJLqcPIkw-0WDY37GRcTefLV0WGhyMt6IbOKY8JxGww,36719
15
+ miepython-3.4.0.dist-info/licenses/LICENSE.txt,sha256=g9-BWWRLvMDMQ1Zflxliku7Sleom1_SbXHQHOLGgqqk,1055
16
+ miepython-3.4.0.dist-info/METADATA,sha256=PQMN5wDZl77fyShApvaS6wczwWaH8jAY7g4KUmnW-xY,7767
17
+ miepython-3.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
18
+ miepython-3.4.0.dist-info/top_level.txt,sha256=bfkk6YwrKm_aIzInR5y03YbywpwCzUjJEHaFkEiSKxI,10
19
+ miepython-3.4.0.dist-info/RECORD,,
@@ -1,18 +0,0 @@
1
- miepython/__init__.py,sha256=oWYwelBWxyV7Rc9DQSVKvy-Mx4Ck-k2PjfyShl-5pW0,5888
2
- miepython/_backend.py,sha256=l_faAa6zanygRZKA9vMVcfcutHPFFkpqZzHqwjU8QcE,1619
3
- miepython/bessel.py,sha256=U094wY_5RFqrVjXZgMbacmt_yqpP8GBtRZ24-MNzBsU,3647
4
- miepython/core.py,sha256=zv0hkVBBpcr9GA2xwNAxWHancnh7o5X1mp2xZUoz2Js,24974
5
- miepython/field.py,sha256=zvTf2g0qca0WRfJ9r2SL5YDGObfTYlOpcXUY9BoOQjA,26583
6
- miepython/mie_jit.py,sha256=kYy9UCfuEgPSL0XY7P8Qx4IqBr9BbffusF6oeZdTnvQ,21685
7
- miepython/mie_nojit.py,sha256=EGWqpvdnWOOV72x2wPy8TOSYXLguKXKQn-LzRXYpkrs,20315
8
- miepython/monte_carlo.py,sha256=1pRELa63NcZOkhSe2AviObPztPaKe7JRqMBQn3rp9Ls,8422
9
- miepython/rayleigh.py,sha256=6PMTNRs_0u3n9-7bBgJ9-QTB-pmGoPs29iOxj3Eub78,16939
10
- miepython/util.py,sha256=3jxGd0jmPFYolllQXISLDmz0jE4C1AyFD1OyD65dUGo,3648
11
- miepython/vsh.py,sha256=bPmEBCxbjCcNgisw3qQR-Zso46-aGPrnv9VBu7jhyTM,18114
12
- miepython/data/Johnson.txt,sha256=PcdEhJ3ZKUnt--86ukEvUt-w-814uOyWXtE-G3qWTNE,1337
13
- miepython/data/segelstein81_index.txt,sha256=aJLqcPIkw-0WDY37GRcTefLV0WGhyMt6IbOKY8JxGww,36719
14
- miepython-3.3.1.dist-info/licenses/LICENSE.txt,sha256=g9-BWWRLvMDMQ1Zflxliku7Sleom1_SbXHQHOLGgqqk,1055
15
- miepython-3.3.1.dist-info/METADATA,sha256=AlX1gk-tBQ2Z6km4sptmW2cGUx51DDAw4nEE0Gz30YE,7789
16
- miepython-3.3.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
17
- miepython-3.3.1.dist-info/top_level.txt,sha256=bfkk6YwrKm_aIzInR5y03YbywpwCzUjJEHaFkEiSKxI,10
18
- miepython-3.3.1.dist-info/RECORD,,