rjdoa 0.2.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.
rjdoa/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ """Bayesian wideband DoA estimation and detection with reversible-jump samplers.
2
+
3
+ :func:`estimate` is the one-call entry point: array data in, number of sources and
4
+ bearings out.
5
+
6
+ Subpackages
7
+ -----------
8
+ reversible_jump
9
+ Model-agnostic RJMCMC, nRJMCMC and RJSMC samplers.
10
+ doa
11
+ Wideband DoA model, array geometries, inference kernels, relabelling and plotting.
12
+ mixture
13
+ Richardson-Green Gaussian mixture used to reproduce the RJSMC paper.
14
+ dists
15
+ Fast scalar log-densities with Distributions.jl parametrisations.
16
+ """
17
+
18
+ from . import dists, reversible_jump
19
+ from .doa.estimate import DoAEstimate, estimate
20
+
21
+ __all__ = ["DoAEstimate", "dists", "estimate", "reversible_jump"]
22
+ __version__ = "0.2.0"
rjdoa/dists.py ADDED
@@ -0,0 +1,518 @@
1
+ """Light-weight probability distributions.
2
+
3
+ `scipy.stats` frozen distributions carry ~20-50us of overhead per scalar call, which
4
+ dominates the MCMC hot loop. These classes implement closed-form scalar log-densities
5
+ with the :mod:`math` module and delegate sampling / CDFs to numpy and scipy.
6
+
7
+ Parametrisations follow Distributions.jl so that Julia model definitions port 1:1:
8
+
9
+ * ``Normal(mu, sigma)``
10
+ * ``Uniform(a, b)``
11
+ * ``InverseGamma(shape, scale)``
12
+ * ``Gamma(shape, scale)``
13
+ * ``Beta(a, b)``
14
+ * ``LogNormal(mu, sigma)``
15
+ * ``Poisson(lam)``
16
+ * ``NegativeBinomial(r, p)`` (failures before the r-th success; == ``scipy.stats.nbinom``)
17
+ * ``DiscreteUniform(a, b)``
18
+ * ``Dirac(value)``
19
+ * ``Truncated(dist, lower, upper)`` for discrete distributions
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import math
25
+ from dataclasses import dataclass
26
+ from functools import cached_property
27
+
28
+ import numpy as np
29
+ from scipy import stats
30
+
31
+ NEG_INF = -math.inf
32
+ _LOG_SQRT_2PI = 0.5 * math.log(2.0 * math.pi)
33
+
34
+
35
+ class Distribution:
36
+ """Base class of the distributions; subclasses implement ``logpdf``, ``rvs`` and ``scipy``."""
37
+
38
+ def logpdf(self, x: float) -> float: # pragma: no cover - abstract
39
+ """Return the log density (or log mass) at a scalar ``x``.
40
+
41
+ Parameters
42
+ ----------
43
+ x : float
44
+ Point of evaluation.
45
+
46
+ Returns
47
+ -------
48
+ float
49
+ ``-inf`` outside the support.
50
+ """
51
+ raise NotImplementedError
52
+
53
+ def pdf(self, x: float) -> float:
54
+ """Return the density (or mass) at a scalar ``x``."""
55
+ return math.exp(self.logpdf(x))
56
+
57
+ def rvs(self, rng: np.random.Generator, size=None): # pragma: no cover - abstract
58
+ """Draw random variates.
59
+
60
+ Parameters
61
+ ----------
62
+ rng : numpy.random.Generator
63
+ Random number generator.
64
+ size : int or tuple of int, optional
65
+ Output shape; a scalar is returned when None.
66
+
67
+ Returns
68
+ -------
69
+ float or numpy.ndarray
70
+ """
71
+ raise NotImplementedError
72
+
73
+ def scipy(self): # pragma: no cover - abstract
74
+ """Equivalent frozen ``scipy.stats`` distribution."""
75
+ raise NotImplementedError
76
+
77
+
78
+ class DiscreteDistribution(Distribution):
79
+ """Integer-valued distribution; ``logpmf`` and ``pmf`` alias ``logpdf`` and ``pdf``.
80
+
81
+ Attributes
82
+ ----------
83
+ lower, upper : float
84
+ Ends of the support.
85
+ """
86
+
87
+ lower: float = -math.inf
88
+ upper: float = math.inf
89
+
90
+ def logpmf(self, k: int) -> float:
91
+ """Return the log probability of ``k``."""
92
+ return self.logpdf(k)
93
+
94
+ def pmf(self, k: int) -> float:
95
+ """Return the probability of ``k``."""
96
+ return self.pdf(k)
97
+
98
+ def cdf(self, k: float) -> float:
99
+ """Return ``P(X <= k)``."""
100
+ return float(self.scipy().cdf(k))
101
+
102
+
103
+ # --------------------------------------------------------------------------- continuous
104
+
105
+
106
+ @dataclass(frozen=True)
107
+ class Normal(Distribution):
108
+ """Normal distribution.
109
+
110
+ Parameters
111
+ ----------
112
+ mu : float, optional
113
+ Mean.
114
+ sigma : float, optional
115
+ Standard deviation.
116
+ """
117
+
118
+ mu: float = 0.0
119
+ sigma: float = 1.0
120
+
121
+ def logpdf(self, x):
122
+ """Return the log density at ``x``; see :meth:`Distribution.logpdf`."""
123
+ z = (x - self.mu) / self.sigma
124
+ return -0.5 * z * z - math.log(self.sigma) - _LOG_SQRT_2PI
125
+
126
+ def rvs(self, rng, size=None):
127
+ """Draw random variates; see :meth:`Distribution.rvs`."""
128
+ return rng.normal(self.mu, self.sigma, size)
129
+
130
+ def scipy(self):
131
+ """Return the equivalent frozen ``scipy.stats`` distribution."""
132
+ return stats.norm(self.mu, self.sigma)
133
+
134
+
135
+ @dataclass(frozen=True)
136
+ class Uniform(Distribution):
137
+ """Continuous uniform distribution on ``[a, b]``.
138
+
139
+ Parameters
140
+ ----------
141
+ a, b : float, optional
142
+ Ends of the support.
143
+ """
144
+
145
+ a: float = 0.0
146
+ b: float = 1.0
147
+
148
+ def logpdf(self, x):
149
+ """Return the log density at ``x``; see :meth:`Distribution.logpdf`."""
150
+ return -math.log(self.b - self.a) if self.a <= x <= self.b else NEG_INF
151
+
152
+ def rvs(self, rng, size=None):
153
+ """Draw random variates; see :meth:`Distribution.rvs`."""
154
+ return rng.uniform(self.a, self.b, size)
155
+
156
+ def scipy(self):
157
+ """Return the equivalent frozen ``scipy.stats`` distribution."""
158
+ return stats.uniform(self.a, self.b - self.a)
159
+
160
+
161
+ @dataclass(frozen=True)
162
+ class InverseGamma(Distribution):
163
+ """Inverse-gamma distribution.
164
+
165
+ Parameters
166
+ ----------
167
+ shape : float
168
+ Shape parameter.
169
+ scale : float
170
+ Scale parameter.
171
+ """
172
+
173
+ shape: float
174
+ scale: float
175
+
176
+ @cached_property
177
+ def _c(self):
178
+ return self.shape * math.log(self.scale) - math.lgamma(self.shape)
179
+
180
+ def logpdf(self, x):
181
+ """Return the log density at ``x``; see :meth:`Distribution.logpdf`."""
182
+ if x <= 0:
183
+ return NEG_INF
184
+ return self._c - (self.shape + 1.0) * math.log(x) - self.scale / x
185
+
186
+ def rvs(self, rng, size=None):
187
+ """Draw random variates; see :meth:`Distribution.rvs`."""
188
+ return self.scale / rng.gamma(self.shape, 1.0, size)
189
+
190
+ def scipy(self):
191
+ """Return the equivalent frozen ``scipy.stats`` distribution."""
192
+ return stats.invgamma(self.shape, scale=self.scale)
193
+
194
+
195
+ @dataclass(frozen=True)
196
+ class Gamma(Distribution):
197
+ """Gamma distribution.
198
+
199
+ Parameters
200
+ ----------
201
+ shape : float
202
+ Shape parameter.
203
+ scale : float, optional
204
+ Scale parameter.
205
+ """
206
+
207
+ shape: float
208
+ scale: float = 1.0
209
+
210
+ @cached_property
211
+ def _c(self):
212
+ return -math.lgamma(self.shape) - self.shape * math.log(self.scale)
213
+
214
+ def logpdf(self, x):
215
+ """Return the log density at ``x``; see :meth:`Distribution.logpdf`."""
216
+ if x <= 0:
217
+ return NEG_INF
218
+ return self._c + (self.shape - 1.0) * math.log(x) - x / self.scale
219
+
220
+ def rvs(self, rng, size=None):
221
+ """Draw random variates; see :meth:`Distribution.rvs`."""
222
+ return rng.gamma(self.shape, self.scale, size)
223
+
224
+ def scipy(self):
225
+ """Return the equivalent frozen ``scipy.stats`` distribution."""
226
+ return stats.gamma(self.shape, scale=self.scale)
227
+
228
+
229
+ @dataclass(frozen=True)
230
+ class Beta(Distribution):
231
+ """Beta distribution.
232
+
233
+ Parameters
234
+ ----------
235
+ a, b : float
236
+ Shape parameters.
237
+ """
238
+
239
+ a: float
240
+ b: float
241
+
242
+ @cached_property
243
+ def _c(self):
244
+ return math.lgamma(self.a + self.b) - math.lgamma(self.a) - math.lgamma(self.b)
245
+
246
+ def logpdf(self, x):
247
+ """Return the log density at ``x``; see :meth:`Distribution.logpdf`."""
248
+ if not (0.0 < x < 1.0):
249
+ return NEG_INF
250
+ return self._c + (self.a - 1.0) * math.log(x) + (self.b - 1.0) * math.log1p(-x)
251
+
252
+ def rvs(self, rng, size=None):
253
+ """Draw random variates; see :meth:`Distribution.rvs`."""
254
+ return rng.beta(self.a, self.b, size)
255
+
256
+ def scipy(self):
257
+ """Return the equivalent frozen ``scipy.stats`` distribution."""
258
+ return stats.beta(self.a, self.b)
259
+
260
+
261
+ @dataclass(frozen=True)
262
+ class LogNormal(Distribution):
263
+ """Log-normal distribution.
264
+
265
+ Parameters
266
+ ----------
267
+ mu : float, optional
268
+ Mean of the log.
269
+ sigma : float, optional
270
+ Standard deviation of the log.
271
+ """
272
+
273
+ mu: float = 0.0
274
+ sigma: float = 1.0
275
+
276
+ def logpdf(self, x):
277
+ """Return the log density at ``x``; see :meth:`Distribution.logpdf`."""
278
+ if x <= 0:
279
+ return NEG_INF
280
+ lx = math.log(x)
281
+ z = (lx - self.mu) / self.sigma
282
+ return -0.5 * z * z - math.log(self.sigma) - _LOG_SQRT_2PI - lx
283
+
284
+ def rvs(self, rng, size=None):
285
+ """Draw random variates; see :meth:`Distribution.rvs`."""
286
+ return rng.lognormal(self.mu, self.sigma, size)
287
+
288
+ def scipy(self):
289
+ """Return the equivalent frozen ``scipy.stats`` distribution."""
290
+ return stats.lognorm(self.sigma, scale=math.exp(self.mu))
291
+
292
+
293
+ # ----------------------------------------------------------------------------- discrete
294
+
295
+
296
+ def _is_int(k) -> bool:
297
+ """Return True if ``k`` is a whole number."""
298
+ return float(k).is_integer()
299
+
300
+
301
+ @dataclass(frozen=True)
302
+ class Poisson(DiscreteDistribution):
303
+ """Poisson distribution.
304
+
305
+ Parameters
306
+ ----------
307
+ lam : float
308
+ Mean.
309
+ """
310
+
311
+ lam: float
312
+ lower = 0
313
+
314
+ def logpdf(self, k):
315
+ """Return the log probability of ``k``; see :meth:`Distribution.logpdf`."""
316
+ if k < 0 or not _is_int(k):
317
+ return NEG_INF
318
+ if self.lam == 0:
319
+ return 0.0 if k == 0 else NEG_INF
320
+ return k * math.log(self.lam) - self.lam - math.lgamma(k + 1.0)
321
+
322
+ def rvs(self, rng, size=None):
323
+ """Draw random variates; see :meth:`Distribution.rvs`."""
324
+ return rng.poisson(self.lam, size)
325
+
326
+ def scipy(self):
327
+ """Return the equivalent frozen ``scipy.stats`` distribution."""
328
+ return stats.poisson(self.lam)
329
+
330
+
331
+ @dataclass(frozen=True)
332
+ class NegativeBinomial(DiscreteDistribution):
333
+ """Negative binomial distribution: failures before the ``r``-th success.
334
+
335
+ Parameters
336
+ ----------
337
+ r : float
338
+ Number of successes.
339
+ p : float
340
+ Success probability.
341
+ """
342
+
343
+ r: float
344
+ p: float
345
+ lower = 0
346
+
347
+ @cached_property
348
+ def _c(self):
349
+ return self.r * math.log(self.p) - math.lgamma(self.r)
350
+
351
+ def logpdf(self, k):
352
+ """Return the log probability of ``k``; see :meth:`Distribution.logpdf`."""
353
+ if k < 0 or not _is_int(k):
354
+ return NEG_INF
355
+ return (
356
+ self._c
357
+ + math.lgamma(k + self.r)
358
+ - math.lgamma(k + 1.0)
359
+ + k * math.log1p(-self.p)
360
+ )
361
+
362
+ def rvs(self, rng, size=None):
363
+ """Draw random variates; see :meth:`Distribution.rvs`."""
364
+ return rng.negative_binomial(self.r, self.p, size)
365
+
366
+ def scipy(self):
367
+ """Return the equivalent frozen ``scipy.stats`` distribution."""
368
+ return stats.nbinom(self.r, self.p)
369
+
370
+
371
+ @dataclass(frozen=True)
372
+ class DiscreteUniform(DiscreteDistribution):
373
+ """Discrete uniform distribution on ``a..b``.
374
+
375
+ Parameters
376
+ ----------
377
+ a, b : int
378
+ Ends of the support (inclusive).
379
+ """
380
+
381
+ a: int
382
+ b: int
383
+
384
+ @property
385
+ def lower(self):
386
+ """Lower end of the support."""
387
+ return self.a
388
+
389
+ @property
390
+ def upper(self):
391
+ """Upper end of the support."""
392
+ return self.b
393
+
394
+ def logpdf(self, k):
395
+ """Return the log probability of ``k``; see :meth:`Distribution.logpdf`."""
396
+ if self.a <= k <= self.b and _is_int(k):
397
+ return -math.log(self.b - self.a + 1)
398
+ return NEG_INF
399
+
400
+ def rvs(self, rng, size=None):
401
+ """Draw random variates; see :meth:`Distribution.rvs`."""
402
+ return rng.integers(self.a, self.b + 1, size)
403
+
404
+ def scipy(self):
405
+ """Return the equivalent frozen ``scipy.stats`` distribution."""
406
+ return stats.randint(self.a, self.b + 1)
407
+
408
+
409
+ @dataclass(frozen=True)
410
+ class Dirac(DiscreteDistribution):
411
+ """Point mass at ``value``.
412
+
413
+ Parameters
414
+ ----------
415
+ value : int
416
+ Location of the mass.
417
+ """
418
+
419
+ value: int
420
+
421
+ @property
422
+ def lower(self):
423
+ """Lower end of the support."""
424
+ return self.value
425
+
426
+ @property
427
+ def upper(self):
428
+ """Upper end of the support."""
429
+ return self.value
430
+
431
+ def logpdf(self, k):
432
+ """Return the log probability of ``k``; see :meth:`Distribution.logpdf`."""
433
+ return 0.0 if k == self.value else NEG_INF
434
+
435
+ def cdf(self, k):
436
+ """Return ``P(X <= k)``."""
437
+ return 1.0 if k >= self.value else 0.0
438
+
439
+ def rvs(self, rng, size=None):
440
+ """Draw random variates; see :meth:`Distribution.rvs`."""
441
+ if size is None:
442
+ return self.value
443
+ return np.full(size, self.value)
444
+
445
+ def scipy(self): # pragma: no cover - no scipy equivalent
446
+ """Return the equivalent frozen ``scipy.stats`` distribution."""
447
+ raise NotImplementedError("Dirac has no scipy equivalent")
448
+
449
+
450
+ @dataclass(frozen=True)
451
+ class Truncated(DiscreteDistribution):
452
+ """Discrete distribution truncated to ``[lower, upper]`` (inclusive).
453
+
454
+ Parameters
455
+ ----------
456
+ dist : DiscreteDistribution
457
+ Distribution to truncate.
458
+ lower, upper : float, optional
459
+ Bounds of the support.
460
+ """
461
+
462
+ dist: DiscreteDistribution
463
+ lower: float = -math.inf
464
+ upper: float = math.inf
465
+
466
+ @cached_property
467
+ def _cdf_lo(self):
468
+ return 0.0 if self.lower == -math.inf else self.dist.cdf(self.lower - 1)
469
+
470
+ @cached_property
471
+ def _cdf_hi(self):
472
+ return 1.0 if self.upper == math.inf else self.dist.cdf(self.upper)
473
+
474
+ @cached_property
475
+ def _logz(self):
476
+ return math.log(self._cdf_hi - self._cdf_lo)
477
+
478
+ def logpdf(self, k):
479
+ """Return the log probability of ``k``; see :meth:`Distribution.logpdf`."""
480
+ if k < self.lower or k > self.upper:
481
+ return NEG_INF
482
+ return self.dist.logpdf(k) - self._logz
483
+
484
+ def cdf(self, k):
485
+ """Return ``P(X <= k)``."""
486
+ if k < self.lower:
487
+ return 0.0
488
+ if k >= self.upper:
489
+ return 1.0
490
+ return (self.dist.cdf(k) - self._cdf_lo) / (self._cdf_hi - self._cdf_lo)
491
+
492
+ def rvs(self, rng, size=None):
493
+ """Draw random variates; see :meth:`Distribution.rvs`."""
494
+ u = rng.uniform(self._cdf_lo, self._cdf_hi, size)
495
+ k = self.dist.scipy().ppf(u)
496
+ k = np.clip(k, self.lower, self.upper).astype(np.int64)
497
+ return int(k) if size is None else k
498
+
499
+ def scipy(self): # pragma: no cover
500
+ """Return the equivalent frozen ``scipy.stats`` distribution."""
501
+ raise NotImplementedError
502
+
503
+
504
+ def truncated(dist: DiscreteDistribution, lower=-math.inf, upper=math.inf) -> Truncated:
505
+ """Truncate a discrete distribution, as Distributions.jl's ``truncated``.
506
+
507
+ Parameters
508
+ ----------
509
+ dist : DiscreteDistribution
510
+ Distribution to truncate.
511
+ lower, upper : float, optional
512
+ Inclusive bounds.
513
+
514
+ Returns
515
+ -------
516
+ Truncated
517
+ """
518
+ return Truncated(dist, lower, upper)
rjdoa/doa/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """Wideband DoA estimation model (port of WidebandDoA.jl)."""
2
+
3
+ from .estimate import DoAEstimate, estimate
4
+ from .filters import ComplexShift, DelayFilter, WindowedSinc
5
+ from .geometry import AngleDomain, ArrayGeometry, LineArray, SensorArray, inter_sensor_delay
6
+ from .likelihood import WidebandIsoIsoLikelihood, loglikelihood, loglikelihood_reference
7
+ from .model import (
8
+ EMPTY_PARAMS,
9
+ PriorStart,
10
+ UniformNormalLocalProposal,
11
+ WidebandConditioned,
12
+ WidebandData,
13
+ WidebandIsoIsoModel,
14
+ make_params,
15
+ preprocess,
16
+ )
17
+ from .prior import WidebandIsoSourcePrior
18
+
19
+ __all__ = [
20
+ "AngleDomain", "ArrayGeometry", "ComplexShift", "DelayFilter", "DoAEstimate", "EMPTY_PARAMS", "LineArray",
21
+ "PriorStart", "SensorArray", "UniformNormalLocalProposal",
22
+ "WidebandConditioned", "WidebandData", "WidebandIsoIsoLikelihood", "WidebandIsoIsoModel",
23
+ "WidebandIsoSourcePrior", "WindowedSinc", "inter_sensor_delay", "loglikelihood",
24
+ "estimate", "loglikelihood_reference", "make_params", "preprocess",
25
+ ]