miepython 3.3.0__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/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/monte_carlo.py CHANGED
@@ -1,37 +1,64 @@
1
1
  """
2
- Sample scattering angles from the Mie phase function.
3
-
4
- Monte Carlo photon transport needs a random exit direction distributed according to
5
- the phase function. This module builds the inverse-transform table that provides
6
- one: ``mu_with_uniform_cdf`` returns angles spaced so that equal steps along the
7
- cumulative distribution are equally likely, and ``generate_mie_costheta`` draws from
8
- that table. ``docs/06_random_deviates.ipynb`` works through the whole procedure.
9
-
10
- Importing
11
- ---------
12
-
13
- This module is *not* imported with the package, because it imports ``miepython``
14
- itself and doing so from ``miepython/__init__.py`` would be circular. Ask for it by
15
- name::
16
-
17
- import numpy as np
18
- import miepython.monte_carlo as mc
19
-
20
- m, x = 1.33, 2.0 # a water droplet
21
- mu, cdf = mc.mu_with_uniform_cdf(m, x, 500) # 500-entry lookup table
22
-
23
- rng = np.random.default_rng(12345)
24
- cosines = [mc.generate_mie_costheta(mu, rng=rng) for _ in range(10000)]
25
-
26
- Build the table once and reuse it: it costs a full Mie calculation, while each draw
27
- off it costs one random number. The number of table entries sets how finely the
28
- phase function is resolved, so strongly forward-scattering spheres need more of
29
- them.
2
+ Sample random scattering angles from the Mie phase function.
3
+
4
+ A Monte Carlo simulation of light transport needs, at every scattering event, a
5
+ random direction in which the photon leaves the sphere. For unpolarized light
6
+ only the polar angle theta depends on the sphere, and it must be drawn so that
7
+ its cosine mu follows the phase function. This module does that by inverse
8
+ transform sampling: build the cumulative distribution of mu once, then map each
9
+ uniform random number u to the cosine at which the distribution reaches u.
10
+
11
+ ``cdf``
12
+ The cumulative distribution at evenly spaced cosines.
13
+ ``mu_with_uniform_cdf``
14
+ The cosines at which the cumulative distribution reaches evenly spaced
15
+ probabilities, a lookup table that makes each draw cheap.
16
+ ``generate_mie_costheta``
17
+ One random cosine drawn from that table.
18
+
19
+ ``docs/06_random_deviates.ipynb`` works through the whole procedure.
20
+
21
+ This module is *not* imported with the package, because it imports
22
+ ``miepython`` itself and doing so from ``miepython/__init__.py`` would be
23
+ circular. Import it by name, as the examples below do.
24
+
25
+ Examples:
26
+ Invert the distribution with ``np.interp`` to draw many cosines at once.
27
+ Their average is the asymmetry parameter g:
28
+
29
+ >>> import numpy as np
30
+ >>> import miepython as mie
31
+ >>> import miepython.monte_carlo as mc
32
+ >>> m, x = 1.33, 2.0 # a water droplet
33
+ >>> mu, cdf = mc.cdf(m, x, 1000)
34
+ >>> rng = np.random.default_rng(42)
35
+ >>> cosines = np.interp(rng.random(100_000), cdf, mu)
36
+ >>> print(f"{np.mean(cosines):.2f}")
37
+ 0.67
38
+ >>> qext, qsca, qback, g = mie.efficiencies_mx(m, x)
39
+ >>> print(f"{g:.2f}")
40
+ 0.67
41
+
42
+ Or build a lookup table once and draw one cosine at a time, as a photon
43
+ transport loop does:
44
+
45
+ >>> mu_table, _ = mc.mu_with_uniform_cdf(m, x, 1000)
46
+ >>> cosines = [mc.generate_mie_costheta(mu_table, rng=rng) for _ in range(100_000)]
47
+ >>> print(f"{np.mean(cosines):.2f}")
48
+ 0.67
49
+
50
+ Building either table costs a full Mie calculation, while each draw costs only a
51
+ random number or two, so build it once and reuse it. Evenly spaced cosines
52
+ resolve the narrow forward peak of a large sphere poorly; ``cdf`` explains how
53
+ many are needed and warns when there are too few, while ``mu_with_uniform_cdf``
54
+ chooses enough by itself.
30
55
 
31
56
  Passing ``rng`` keeps the draws reproducible without disturbing the process-wide
32
57
  ``numpy.random``; omitting it falls back to that global generator.
33
58
  """
34
59
 
60
+ import warnings
61
+
35
62
  import numpy as np
36
63
  import miepython as mie
37
64
 
@@ -41,87 +68,102 @@ __all__ = (
41
68
  "generate_mie_costheta",
42
69
  )
43
70
 
71
+ # Largest acceptable relative error in the integral of the phase function
72
+ CDF_TOLERANCE = 0.01
73
+
44
74
 
45
75
  def cdf(m, x, num):
46
76
  """
47
- Create a CDF for unpolarized scattering uniformly spaced in cos(theta).
77
+ Cumulative distribution of the unpolarized phase function in cos(theta).
48
78
 
49
- The CDF covers scattered (exit) angles ranging from 180 to 0 degrees.
50
- (The cosines are uniformly distributed over -1 to 1.) Because the angles
51
- are uniformly distributed in cos(theta), the scattering function is not
52
- sampled uniformly and therefore huge array sizes are needed to adequately
53
- sample highly anisotropic phase functions.
79
+ The cosines mu are evenly spaced from -1 (backscattering) to 1 (forward
80
+ scattering), and cdf[i] is the probability that a scattered photon leaves
81
+ with a cosine no greater than mu[i]. It is found by integrating the phase
82
+ function with the trapezoidal rule, so cdf[0] is exactly 0 and the values
83
+ never decrease.
54
84
 
55
- Since this is a cumulative distribution function, the maximum value
56
- should be 1.
85
+ A large sphere scatters much of its light into a diffraction peak about
86
+ 4/x radians wide around the forward direction. Near theta = 0, mu = cos(theta)
87
+ is close to 1 - theta**2/2, so that peak spans only about 8/x**2 in mu,
88
+ while the cosines are 2/(num - 1) apart. To put several cosines inside the
89
+ peak, num must therefore grow roughly as x**2; x = 30 needs about 5000.
90
+
91
+ The phase function integrates to exactly one, so the raw trapezoidal sum
92
+ shows how well num resolves it. If that sum is off by more than
93
+ ``CDF_TOLERANCE``, a ``RuntimeWarning`` is issued; increase num until it
94
+ stops. The result is then divided by the sum so that cdf[-1] is exactly 1.
57
95
 
58
96
  Args:
59
- m: the complex index of refraction of the sphere
60
- x: the size parameter of the sphere
61
- num: length of desired CDF array
97
+ m: complex index of refraction of the sphere
98
+ x: size parameter of the sphere
99
+ num: number of cosines, at least two
62
100
 
63
101
  Returns:
64
- mu: array of cosines of angles
65
- cdf: array of cumulative distribution function values
102
+ mu: evenly spaced cosines of the scattering angle, from -1 to 1
103
+ cdf: cumulative probability at each cosine, from 0 to 1
104
+
105
+ Raises:
106
+ ValueError: if num is less than two or the phase function is not finite
66
107
  """
108
+ if num < 2:
109
+ raise ValueError("num must be at least 2")
110
+ return _trapezoid_cdf(m, x, num, stacklevel=3)
111
+
112
+
113
+ def _trapezoid_cdf(m, x, num, stacklevel):
114
+ """Integrate the phase function at num cosines, warning at the caller's caller."""
67
115
  mu = np.linspace(-1, 1, num)
68
- intensity_per_mu = mie.i_unpolarized(m, x, mu, norm="4pi") / num
69
- cdf_values = np.cumsum(intensity_per_mu)
116
+ intensity_per_mu = mie.i_unpolarized(m, x, mu, norm="4pi") / 2
117
+ cdf_values = np.zeros(num)
118
+ cdf_values[1:] = np.cumsum((intensity_per_mu[1:] + intensity_per_mu[:-1]) * np.diff(mu) / 2)
119
+ total = cdf_values[-1]
120
+ if not np.isfinite(total):
121
+ raise ValueError(f"phase function is not finite for m={m}, x={x}")
122
+ if abs(total - 1) > CDF_TOLERANCE:
123
+ warnings.warn(
124
+ f"phase function under-resolved for x={x}: integral over {num} angles is {total:.4g}, "
125
+ "not 1, so sampled angles will be inaccurate; use more angles",
126
+ RuntimeWarning,
127
+ stacklevel=stacklevel,
128
+ )
129
+ cdf_values /= total
70
130
  return mu, cdf_values
71
131
 
72
132
 
73
133
  def mu_with_uniform_cdf(m, x, num):
74
134
  """
75
- Create a CDF for unpolarized scattering for uniform CDF.
76
-
77
- The CDF covers scattered (exit) angles ranging from 180 to 0 degrees.
78
- (The cosines are uniformly distributed over -1 to 1.) These angles mu
79
- correspond to uniform spacing of the cumulative distribution function
80
- for unpolarized Mie scattering where cdf[i] = i/(num-1).
135
+ Inverse-transform table for sampling the unpolarized phase function.
81
136
 
82
- This is a brute force implementation that solves the problem by
83
- calculating the CDF at many points and then scanning to find the
84
- specific angles that correspond to uniform interval of the CDF.
137
+ The table holds num cosines mu running from -1 (backscattering) to 1
138
+ (forward scattering), spaced so that a scattered photon is equally likely
139
+ to fall between any two neighbours: cdf[i] is exactly i/(num - 1). The
140
+ cosines are therefore bunched where scattering is strong and sparse where
141
+ it is weak. ``generate_mie_costheta`` draws random cosines from this table.
85
142
 
86
- Since this is a cumulative distribution function, the maximum value
87
- should be 1.
143
+ The table is found by calculating ``cdf`` at max(2000, 5*x**2) evenly
144
+ spaced cosines, enough to resolve the forward peak whatever num is (see
145
+ ``cdf``), and interpolating to find where it reaches each step. Because
146
+ that count grows as x**2, building the table takes seconds at x = 100 and
147
+ over a minute at x = 300.
88
148
 
89
149
  Args:
90
- m: the complex index of refraction of the sphere
91
- x: the size parameter of the sphere
92
- num: length of desired CDF array
150
+ m: complex index of refraction of the sphere
151
+ x: size parameter of the sphere
152
+ num: number of entries in the table, at least two
93
153
 
94
154
  Returns:
95
- mu: array of cosines of angles (irregularly spaced)
96
- cdf: array of cumulative distribution function values
97
- """
98
- big_num = 2000 # large to work with x up to 10
99
- big_mu, big_cdf = cdf(m, x, big_num)
100
- mu = np.empty(num)
101
- cdf_values = np.empty(num)
102
-
103
- mu[0] = -1 # cos[180 degrees] is -1
104
- cdf_values[0] = 0 # initial cdf is zero
105
-
106
- big_k = 0 # index into big_cdf
107
- for k in range(1, num - 1):
155
+ mu: unevenly spaced cosines of the scattering angle, from -1 to 1
156
+ cdf: evenly spaced cumulative probabilities, from 0 to 1
108
157
 
109
- target = k / (num - 1)
110
- while big_cdf[big_k] < target:
111
- big_k += 1
112
-
113
- delta = big_cdf[big_k] - target
114
- delta_cdf = big_cdf[big_k] - big_cdf[big_k - 1]
115
- delta_mu = big_mu[big_k] - big_mu[big_k - 1]
116
-
117
- mu[k] = big_mu[big_k] - delta / delta_cdf * delta_mu # interpolate
118
- cdf_values[k] = target
119
-
120
- # print(' mu[',k,']=% .5f'%mu[k],' cdf[',k,']=% .5f'%cdf[k],
121
- # 'cdf=',big_cdf[big_k], fraction)
122
-
123
- mu[num - 1] = 1 # cos[0 degrees] is 1
124
- cdf_values[num - 1] = 1 # last cdf is one
158
+ Raises:
159
+ ValueError: if num is less than two or the phase function is not finite
160
+ """
161
+ if num < 2:
162
+ raise ValueError("num must be at least 2")
163
+ big_num = max(2000, int(5 * x**2)) # resolve the forward peak, see cdf
164
+ big_mu, big_cdf = _trapezoid_cdf(m, x, big_num, stacklevel=3)
165
+ cdf_values = np.arange(num) / (num - 1)
166
+ mu = np.interp(cdf_values, big_cdf, big_mu)
125
167
 
126
168
  return [mu, cdf_values]
127
169