fathom-acoustics 1.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.
Files changed (137) hide show
  1. fathom/__init__.py +62 -0
  2. fathom/__main__.py +7 -0
  3. fathom/_config.py +65 -0
  4. fathom/_decimate.py +160 -0
  5. fathom/_version.py +24 -0
  6. fathom/analysis/__init__.py +105 -0
  7. fathom/analysis/_common.py +71 -0
  8. fathom/analysis/_results.py +820 -0
  9. fathom/analysis/ambiguity.py +196 -0
  10. fathom/analysis/array.py +150 -0
  11. fathom/analysis/compare.py +135 -0
  12. fathom/analysis/correlation.py +180 -0
  13. fathom/analysis/detection.py +159 -0
  14. fathom/analysis/measure.py +264 -0
  15. fathom/analysis/modulation.py +70 -0
  16. fathom/analysis/spectral.py +433 -0
  17. fathom/analysis/timedomain.py +64 -0
  18. fathom/analysis/transfer.py +75 -0
  19. fathom/cli/__init__.py +220 -0
  20. fathom/cli/_analyze.py +293 -0
  21. fathom/cli/_common.py +288 -0
  22. fathom/cli/_gen.py +447 -0
  23. fathom/cli/_lab.py +59 -0
  24. fathom/cli/_mcp.py +100 -0
  25. fathom/cli/_model.py +471 -0
  26. fathom/cli/_serve.py +92 -0
  27. fathom/cli/_studio.py +52 -0
  28. fathom/gui/__init__.py +139 -0
  29. fathom/gui/_analysis_views.py +325 -0
  30. fathom/gui/_app.py +114 -0
  31. fathom/gui/_axis_limits.py +307 -0
  32. fathom/gui/_canvas.py +785 -0
  33. fathom/gui/_channel_panels.py +1256 -0
  34. fathom/gui/_channel_state.py +845 -0
  35. fathom/gui/_channel_window.py +655 -0
  36. fathom/gui/_forms.py +449 -0
  37. fathom/gui/_generator.py +584 -0
  38. fathom/gui/_image_views.py +449 -0
  39. fathom/gui/_live_view.py +331 -0
  40. fathom/gui/_panels.py +528 -0
  41. fathom/gui/_qt.py +33 -0
  42. fathom/gui/_session.py +266 -0
  43. fathom/gui/_spectrum_view.py +164 -0
  44. fathom/gui/_state.py +282 -0
  45. fathom/gui/_style.py +164 -0
  46. fathom/gui/_tasks.py +180 -0
  47. fathom/gui/_time_view.py +297 -0
  48. fathom/gui/_view_base.py +314 -0
  49. fathom/gui/_window.py +260 -0
  50. fathom/io/__init__.py +271 -0
  51. fathom/io/_audio.py +323 -0
  52. fathom/io/_common.py +284 -0
  53. fathom/io/_csv.py +270 -0
  54. fathom/io/_hdf5.py +236 -0
  55. fathom/io/_mat.py +360 -0
  56. fathom/io/_netcdf.py +181 -0
  57. fathom/io/_numpy.py +264 -0
  58. fathom/io/_plot.py +32 -0
  59. fathom/io/_raw.py +225 -0
  60. fathom/io/_redpitaya.py +132 -0
  61. fathom/io/_registry.py +368 -0
  62. fathom/io/_sigmf.py +353 -0
  63. fathom/io/_tdms.py +157 -0
  64. fathom/io/_zarr.py +149 -0
  65. fathom/jupyter/__init__.py +91 -0
  66. fathom/jupyter/_display.py +558 -0
  67. fathom/jupyter/_lab.py +170 -0
  68. fathom/jupyter/_magics.py +243 -0
  69. fathom/jupyter/_session.py +594 -0
  70. fathom/jupyter/_widget.py +544 -0
  71. fathom/jupyter/static/signal_view.css +129 -0
  72. fathom/jupyter/static/signal_view.js +882 -0
  73. fathom/mcp/__init__.py +95 -0
  74. fathom/mcp/_docs.py +100 -0
  75. fathom/mcp/_guard.py +207 -0
  76. fathom/mcp/_jobs.py +230 -0
  77. fathom/mcp/_resources.py +250 -0
  78. fathom/mcp/_server.py +506 -0
  79. fathom/mcp/_tools.py +1518 -0
  80. fathom/models/__init__.py +111 -0
  81. fathom/models/_block.py +974 -0
  82. fathom/models/_catalog.py +104 -0
  83. fathom/models/_dsp.py +258 -0
  84. fathom/models/_engine.py +842 -0
  85. fathom/models/_graph.py +1070 -0
  86. fathom/models/_medium.py +78 -0
  87. fathom/models/_rng.py +88 -0
  88. fathom/models/_sweep.py +307 -0
  89. fathom/models/blocks/__init__.py +40 -0
  90. fathom/models/blocks/absorption.py +341 -0
  91. fathom/models/blocks/basic.py +89 -0
  92. fathom/models/blocks/boundaries.py +280 -0
  93. fathom/models/blocks/delay.py +705 -0
  94. fathom/models/blocks/electronics.py +476 -0
  95. fathom/models/blocks/multipath.py +410 -0
  96. fathom/models/blocks/noise.py +448 -0
  97. fathom/models/blocks/nonlinear.py +126 -0
  98. fathom/models/blocks/propagation.py +248 -0
  99. fathom/models/blocks/response.py +180 -0
  100. fathom/models/blocks/sources.py +219 -0
  101. fathom/models/blocks/transducers.py +333 -0
  102. fathom/models/blocks/utility.py +571 -0
  103. fathom/plotting.py +934 -0
  104. fathom/py.typed +0 -0
  105. fathom/schema/__init__.py +67 -0
  106. fathom/schema/_catalog.py +204 -0
  107. fathom/schema/_functions.py +706 -0
  108. fathom/signals/__init__.py +101 -0
  109. fathom/signals/_arbitrary.py +205 -0
  110. fathom/signals/_codes.py +191 -0
  111. fathom/signals/_common.py +273 -0
  112. fathom/signals/_impulses.py +224 -0
  113. fathom/signals/_metadata.py +280 -0
  114. fathom/signals/_modulation.py +438 -0
  115. fathom/signals/_noise.py +199 -0
  116. fathom/signals/_signal.py +514 -0
  117. fathom/signals/_sweeps.py +189 -0
  118. fathom/signals/_tones.py +265 -0
  119. fathom/stream/__init__.py +41 -0
  120. fathom/stream/_live.py +175 -0
  121. fathom/stream/fsp.py +565 -0
  122. fathom/stream/include/fsp.h +130 -0
  123. fathom/theme/__init__.py +650 -0
  124. fathom/theme/_tokens.py +126 -0
  125. fathom/units.py +182 -0
  126. fathom/workspace/__init__.py +85 -0
  127. fathom/workspace/_api.py +327 -0
  128. fathom/workspace/_client.py +490 -0
  129. fathom/workspace/_local.py +218 -0
  130. fathom/workspace/_protocol.py +145 -0
  131. fathom/workspace/_service.py +561 -0
  132. fathom/workspace/_store.py +1028 -0
  133. fathom_acoustics-1.2.0.dist-info/METADATA +204 -0
  134. fathom_acoustics-1.2.0.dist-info/RECORD +137 -0
  135. fathom_acoustics-1.2.0.dist-info/WHEEL +4 -0
  136. fathom_acoustics-1.2.0.dist-info/entry_points.txt +2 -0
  137. fathom_acoustics-1.2.0.dist-info/licenses/LICENSE +21 -0
fathom/__init__.py ADDED
@@ -0,0 +1,62 @@
1
+ """fathom: the Acoustic Workbench SDK.
2
+
3
+ The SDK is the product. The CLI, the studios, the Jupyter extension and the MCP
4
+ server are thin layers over it.
5
+
6
+ Modules:
7
+ fathom.signals: Signal type, generators and modulators.
8
+ fathom.analysis: Spectra, correlation, ambiguity, detection, measurements.
9
+ fathom.io: File read and write, format detection.
10
+ fathom.stream: Framed stream protocol (FSP).
11
+ fathom.units: dB helpers, reference levels, calibration chain.
12
+ fathom.theme: SIGE design tokens for all graphical output.
13
+ fathom.schema: Parameter schemas of SDK functions (MCP tools, studio forms).
14
+ fathom.gui: Signal Studio, the desktop work center (needs fathom-acoustics[gui]).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import TYPE_CHECKING
20
+
21
+ if TYPE_CHECKING:
22
+ from typing import Any
23
+
24
+ try:
25
+ from ._version import __version__
26
+ except ImportError: # pragma: no cover - source tree without a build
27
+ from importlib.metadata import PackageNotFoundError, version
28
+
29
+ try:
30
+ __version__ = version("fathom-acoustics")
31
+ except PackageNotFoundError:
32
+ __version__ = "0.0.0+unknown"
33
+
34
+ from .signals import Annotation, Calibration, Element, Medium, Provenance, Signal
35
+
36
+ __all__ = [
37
+ "Annotation",
38
+ "Calibration",
39
+ "Element",
40
+ "Medium",
41
+ "Provenance",
42
+ "Signal",
43
+ "__version__",
44
+ ]
45
+
46
+
47
+ def load_ipython_extension(ipython: Any) -> None:
48
+ """Load the Jupyter extension: ``%load_ext fathom`` registers ``%fathom`` (JUP-002).
49
+
50
+ The extension code lives in :mod:`fathom.jupyter`. It imports IPython only
51
+ here, so ``import fathom`` works without IPython (CORE-003).
52
+ """
53
+ from fathom.jupyter import load_ipython_extension as _load
54
+
55
+ _load(ipython)
56
+
57
+
58
+ def unload_ipython_extension(ipython: Any) -> None:
59
+ """Unload the Jupyter extension: ``%unload_ext fathom`` detaches the workspace."""
60
+ from fathom.jupyter import unload_ipython_extension as _unload
61
+
62
+ _unload(ipython)
fathom/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """``python -m fathom`` runs the CLI."""
2
+
3
+ import sys
4
+
5
+ from fathom.cli import main
6
+
7
+ sys.exit(main())
fathom/_config.py ADDED
@@ -0,0 +1,65 @@
1
+ """Package settings and large-array allocation (DATA-006)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import os
7
+ import tempfile
8
+ import uuid
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import numpy as np
13
+ import numpy.typing as npt
14
+
15
+ __all__ = ["alloc_array", "cache_dir", "get_memmap_threshold", "set_memmap_threshold"]
16
+
17
+ _DEFAULT_THRESHOLD = 512 * 1024**2 # 512 MiB
18
+ _threshold = int(os.environ.get("FATHOM_MEMMAP_THRESHOLD", _DEFAULT_THRESHOLD))
19
+
20
+
21
+ def get_memmap_threshold() -> int:
22
+ """Size in bytes above which readers return memory-mapped arrays."""
23
+ return _threshold
24
+
25
+
26
+ def set_memmap_threshold(nbytes: int) -> int:
27
+ """Set the memory-map threshold. Return the previous value.
28
+
29
+ The environment variable ``FATHOM_MEMMAP_THRESHOLD`` sets the initial value.
30
+ """
31
+ global _threshold
32
+ if nbytes < 0:
33
+ raise ValueError("threshold must not be negative")
34
+ old, _threshold = _threshold, int(nbytes)
35
+ return old
36
+
37
+
38
+ def cache_dir() -> Path:
39
+ """Directory for temporary memory-mapped arrays.
40
+
41
+ ``FATHOM_CACHE_DIR`` overrides the default, which is a ``fathom`` folder in
42
+ the system temporary directory.
43
+ """
44
+ path = Path(os.environ.get("FATHOM_CACHE_DIR", Path(tempfile.gettempdir()) / "fathom"))
45
+ path.mkdir(parents=True, exist_ok=True)
46
+ return path
47
+
48
+
49
+ def alloc_array(shape: tuple[int, ...], dtype: npt.DTypeLike) -> npt.NDArray[Any]:
50
+ """Allocate an output array. Use a memory map above the threshold.
51
+
52
+ Readers fill the result chunk by chunk, so a large file never needs to fit
53
+ in memory (IO-007).
54
+ """
55
+ dt = np.dtype(dtype)
56
+ nbytes = int(np.prod(shape, dtype=np.int64)) * dt.itemsize
57
+ if nbytes <= _threshold or nbytes == 0:
58
+ return np.empty(shape, dtype=dt)
59
+ path = cache_dir() / f"alloc-{uuid.uuid4().hex}.dat"
60
+ arr: npt.NDArray[Any] = np.memmap(path, dtype=dt, mode="w+", shape=shape)
61
+ # The mapping keeps the data alive. Remove the name now where the OS allows it
62
+ # (Windows keeps open files, so the file stays until the process ends).
63
+ with contextlib.suppress(OSError):
64
+ path.unlink()
65
+ return arr
fathom/_decimate.py ADDED
@@ -0,0 +1,160 @@
1
+ """Min/max pyramids: time-view decimation whose cost does not grow with the record (SIG-004).
2
+
3
+ A time view shows a record of N samples in about W screen columns. Each column
4
+ needs the minimum and the maximum of its samples, so that the line keeps every
5
+ peak. :func:`fathom.plotting.minmax_decimate` reads all the samples of the
6
+ window for each redraw. That is fast for short records, but a pan over a
7
+ 10⁸-sample record would read 10⁸ samples on each mouse move.
8
+
9
+ :class:`MinMaxPyramid` reads the record once and keeps the min/max envelope at
10
+ several resolutions (bins of ``base``, ``base * factor``, ... samples). A
11
+ query then reads at most about ``factor * W`` stored bins. Its cost depends
12
+ on the screen width only, not on the record length or the window length.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ from typing import Any
19
+
20
+ import numpy as np
21
+ import numpy.typing as npt
22
+
23
+ __all__ = ["MinMaxPyramid"]
24
+
25
+ #: Samples per bin at the finest level.
26
+ BASE = 64
27
+ #: Bin-size ratio between neighbor levels.
28
+ FACTOR = 4
29
+ #: Samples that the build reads at a time, so a memory-mapped record never
30
+ #: needs to fit in memory (DATA-006).
31
+ CHUNK = 1 << 22
32
+
33
+
34
+ def _minmax_rows(x: npt.NDArray[Any], size: int) -> tuple[npt.NDArray[Any], npt.NDArray[Any]]:
35
+ """Min and max of each run of ``size`` values. A short last run is its own bin."""
36
+ n_full = x.size // size
37
+ body = x[: n_full * size].reshape(n_full, size)
38
+ mins, maxs = body.min(axis=1), body.max(axis=1)
39
+ if n_full * size < x.size:
40
+ tail = x[n_full * size :]
41
+ mins = np.concatenate([mins, [tail.min()]])
42
+ maxs = np.concatenate([maxs, [tail.max()]])
43
+ return mins, maxs
44
+
45
+
46
+ class MinMaxPyramid:
47
+ """The min/max envelope of one real trace at several resolutions (SIG-004).
48
+
49
+ Args:
50
+ y: The trace, 1-D and real. Use one pyramid for the real part and one
51
+ for the imaginary part of complex data. A memory-mapped array is
52
+ read in chunks of :data:`CHUNK` samples.
53
+ base: Samples per bin at the finest level.
54
+ factor: Bin-size ratio between neighbor levels.
55
+
56
+ The pyramid keeps a reference to ``y``. A query for a short window reads
57
+ the samples directly. NaN samples make the bins that hold them NaN.
58
+
59
+ Example:
60
+ >>> pyr = MinMaxPyramid(sig.samples[0])
61
+ >>> idx, vals = pyr.query(0, sig.n_samples, 1500) # whole record, 1500 columns
62
+ """
63
+
64
+ def __init__(self, y: npt.ArrayLike, base: int = BASE, factor: int = FACTOR) -> None:
65
+ arr = np.asarray(y) if not isinstance(y, np.ndarray) else y
66
+ if arr.ndim != 1:
67
+ raise ValueError("MinMaxPyramid needs a 1-D trace")
68
+ if np.iscomplexobj(arr):
69
+ raise ValueError("MinMaxPyramid needs real values; give the real or imaginary part")
70
+ if base < 2 or factor < 2:
71
+ raise ValueError("base and factor must be 2 or more")
72
+ self._y = arr
73
+ self.n = int(arr.size)
74
+ self.base = int(base)
75
+ self.factor = int(factor)
76
+ #: ``(bin_size, mins, maxs)`` for each level, finest first.
77
+ self.levels: list[tuple[int, npt.NDArray[Any], npt.NDArray[Any]]] = []
78
+ self._build()
79
+
80
+ def _build(self) -> None:
81
+ if self.n <= self.base:
82
+ return
83
+ chunk = max(self.base, CHUNK // self.base * self.base)
84
+ parts_min: list[npt.NDArray[Any]] = []
85
+ parts_max: list[npt.NDArray[Any]] = []
86
+ for start in range(0, self.n, chunk):
87
+ mins, maxs = _minmax_rows(np.asarray(self._y[start : start + chunk]), self.base)
88
+ parts_min.append(mins)
89
+ parts_max.append(maxs)
90
+ mins, maxs = np.concatenate(parts_min), np.concatenate(parts_max)
91
+ size = self.base
92
+ self.levels.append((size, mins, maxs))
93
+ while mins.size > 2 * self.factor:
94
+ mins = _minmax_rows(mins, self.factor)[0]
95
+ maxs = _minmax_rows(maxs, self.factor)[1]
96
+ size *= self.factor
97
+ self.levels.append((size, mins, maxs))
98
+
99
+ @property
100
+ def nbytes(self) -> int:
101
+ """Memory that the stored levels use, in bytes."""
102
+ return sum(int(lo.nbytes + hi.nbytes) for _, lo, hi in self.levels)
103
+
104
+ def query(
105
+ self, start: int, stop: int, n_bins: int
106
+ ) -> tuple[npt.NDArray[np.float64], npt.NDArray[Any]]:
107
+ """The min/max envelope of samples ``start`` to ``stop`` in about ``n_bins`` bins.
108
+
109
+ Returns:
110
+ ``(index, values)`` in the form of
111
+ :func:`~fathom.plotting.minmax_decimate`: fractional sample
112
+ indices and values, a min and a max for each bin. A window of
113
+ ``2 * n_bins`` samples or less gives the samples themselves.
114
+
115
+ A bin edge falls on a stored bin edge, so the first and the last bin
116
+ can include up to one stored bin (fewer samples than one output bin)
117
+ outside the window.
118
+ """
119
+ n_bins = max(1, int(n_bins))
120
+ i0 = min(max(0, int(start)), self.n)
121
+ i1 = min(max(i0, int(stop)), self.n)
122
+ span = i1 - i0
123
+ if span <= 2 * n_bins:
124
+ return np.arange(i0, i1, dtype=np.float64), np.asarray(self._y[i0:i1])
125
+ per_bin = span / n_bins
126
+ level = None
127
+ for lev in self.levels:
128
+ if lev[0] <= per_bin:
129
+ level = lev
130
+ if level is None:
131
+ # Finer than the finest level: read the samples (at most base * n_bins).
132
+ from fathom.plotting import minmax_decimate
133
+
134
+ idx, vals = minmax_decimate(np.asarray(self._y[i0:i1]), n_bins)
135
+ return idx + i0, vals
136
+ size, mins, maxs = level
137
+ j0 = i0 // size
138
+ j1 = min(mins.size, -(-i1 // size))
139
+ m = j1 - j0
140
+ groups = min(n_bins, m)
141
+ edges = j0 + np.unique(np.round(np.linspace(0, m, groups + 1)).astype(np.int64))
142
+ starts = edges[:-1]
143
+ lo = np.minimum.reduceat(mins[j0:j1], starts - j0)
144
+ hi = np.maximum.reduceat(maxs[j0:j1], starts - j0)
145
+ s_first = np.maximum(starts * size, i0)
146
+ s_last = np.minimum(edges[1:] * size, i1) - 1
147
+ centers = (s_first + s_last) / 2.0
148
+ idx = np.repeat(centers.astype(np.float64), 2)
149
+ vals = np.empty(2 * lo.size, dtype=lo.dtype)
150
+ vals[0::2], vals[1::2] = lo, hi
151
+ return idx, vals
152
+
153
+ def range(self, start: int = 0, stop: int | None = None) -> tuple[float, float]:
154
+ """The minimum and the maximum of samples ``start`` to ``stop`` (for axis limits)."""
155
+ stop = self.n if stop is None else stop
156
+ _, vals = self.query(start, stop, 64)
157
+ if vals.size == 0:
158
+ return 0.0, 0.0
159
+ lo, hi = float(np.nanmin(vals)), float(np.nanmax(vals))
160
+ return (lo, hi) if math.isfinite(lo) and math.isfinite(hi) else (0.0, 0.0)
fathom/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '1.2.0'
22
+ __version_tuple__ = version_tuple = (1, 2, 0)
23
+
24
+ __commit_id__ = commit_id = None
@@ -0,0 +1,105 @@
1
+ """Analysis: spectra, correlation, ambiguity, detection, array processing, measurements.
2
+
3
+ Every function takes a :class:`~fathom.signals.Signal` and returns a Signal or
4
+ a result object. Result objects carry their provenance, a small numeric
5
+ summary (``to_dict()``) and the full data as labeled arrays (``to_xarray()``).
6
+
7
+ ========================== ===================================================
8
+ Function Result
9
+ ========================== ===================================================
10
+ :func:`spectrum` FFT amplitude and phase (:class:`Spectrum`)
11
+ :func:`psd` Welch power spectral density (:class:`Spectrum`)
12
+ :func:`spectrogram` STFT power density (:class:`Spectrogram`)
13
+ :class:`StreamingSpectrogram` STFT columns of a stream, frame by frame
14
+ :func:`envelope` Envelope (Signal)
15
+ :func:`instantaneous_phase` Unwrapped phase in rad (Signal)
16
+ :func:`instantaneous_frequency` Frequency in Hz (Signal)
17
+ :func:`matched_filter` Correlation with a replica (Signal)
18
+ :func:`autocorrelation` Autocorrelation with PSL and ISL (:class:`Correlation`)
19
+ :func:`sidelobe_levels` PSL and ISL in dB
20
+ :func:`ambiguity` Wideband or narrowband (:class:`AmbiguitySurface`)
21
+ :func:`cfar` CA or OS CFAR detections (:class:`DetectionList`)
22
+ :func:`gcc_phat` Time delay between channels (:class:`DelayEstimate`)
23
+ :func:`beamform` Delay-and-sum beam power (:class:`BeamPattern`)
24
+ :func:`transfer_function` H1, H2 and coherence (:class:`TransferFunction`)
25
+ :func:`measure` Measurement panel values (:class:`Measurements`)
26
+ :func:`compare` A signal against a reference (:class:`SignalComparison`)
27
+ :func:`constellation` Symbol-rate samples
28
+ :func:`eye_diagram` Eye diagram traces
29
+ ========================== ===================================================
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ from ._results import (
35
+ AmbiguitySurface,
36
+ BeamPattern,
37
+ Correlation,
38
+ DelayEstimate,
39
+ DetectionList,
40
+ Measurements,
41
+ SignalComparison,
42
+ Spectrogram,
43
+ Spectrum,
44
+ TransferFunction,
45
+ )
46
+ from .ambiguity import ambiguity, doppler_scale
47
+ from .array import beamform, gcc_phat
48
+ from .compare import compare
49
+ from .correlation import autocorrelation, matched_filter, sidelobe_levels
50
+ from .detection import cfar, cfar_alpha
51
+ from .measure import measure
52
+ from .modulation import constellation, eye_diagram
53
+ from .spectral import StreamingSpectrogram, frame_psd, psd, spectrogram, spectrum
54
+ from .timedomain import envelope, instantaneous_frequency, instantaneous_phase
55
+ from .transfer import transfer_function
56
+
57
+ #: All result types, for ``isinstance`` checks.
58
+ RESULT_TYPES = (
59
+ AmbiguitySurface,
60
+ BeamPattern,
61
+ Correlation,
62
+ DelayEstimate,
63
+ DetectionList,
64
+ Measurements,
65
+ SignalComparison,
66
+ Spectrogram,
67
+ Spectrum,
68
+ TransferFunction,
69
+ )
70
+
71
+ __all__ = [
72
+ "RESULT_TYPES",
73
+ "AmbiguitySurface",
74
+ "BeamPattern",
75
+ "Correlation",
76
+ "DelayEstimate",
77
+ "DetectionList",
78
+ "Measurements",
79
+ "SignalComparison",
80
+ "Spectrogram",
81
+ "Spectrum",
82
+ "StreamingSpectrogram",
83
+ "TransferFunction",
84
+ "ambiguity",
85
+ "autocorrelation",
86
+ "beamform",
87
+ "cfar",
88
+ "cfar_alpha",
89
+ "compare",
90
+ "constellation",
91
+ "doppler_scale",
92
+ "envelope",
93
+ "eye_diagram",
94
+ "frame_psd",
95
+ "gcc_phat",
96
+ "instantaneous_frequency",
97
+ "instantaneous_phase",
98
+ "matched_filter",
99
+ "measure",
100
+ "psd",
101
+ "sidelobe_levels",
102
+ "spectrogram",
103
+ "spectrum",
104
+ "transfer_function",
105
+ ]
@@ -0,0 +1,71 @@
1
+ """Helpers shared by the analysis functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+ import numpy.typing as npt
9
+ import scipy.signal as ss
10
+
11
+ from fathom.signals import Provenance, Signal
12
+
13
+ __all__ = [
14
+ "analytic",
15
+ "energy_level_label",
16
+ "make_provenance",
17
+ "next_fast_len",
18
+ "round_or_none",
19
+ "spectral_level_label",
20
+ ]
21
+
22
+
23
+ def make_provenance(name: str, params: dict[str, Any], *signals: Signal | None) -> Provenance:
24
+ """Provenance record for an analysis result, linked to its inputs."""
25
+ inputs = tuple(s.provenance for s in signals if s is not None and s.provenance is not None)
26
+ return Provenance(source=f"fathom.analysis.{name}", parameters=params, inputs=inputs)
27
+
28
+
29
+ def analytic(sig: Signal) -> npt.NDArray[np.complexfloating[Any, Any]]:
30
+ """Complex samples of a signal: the analytic signal for passband data.
31
+
32
+ Baseband data returns as is. The result has shape ``(n_channels, n_samples)``.
33
+ """
34
+ if sig.is_complex:
35
+ return np.asarray(sig.samples)
36
+ if sig.n_samples == 0:
37
+ return np.zeros(sig.samples.shape, dtype=np.complex128)
38
+ return np.asarray(ss.hilbert(np.asarray(sig.samples, dtype=np.float64), axis=-1))
39
+
40
+
41
+ def next_fast_len(n: int) -> int:
42
+ """FFT length at least ``n`` that SciPy computes fast."""
43
+ import scipy.fft
44
+
45
+ return int(scipy.fft.next_fast_len(max(1, n)))
46
+
47
+
48
+ def spectral_level_label(sig: Signal) -> str:
49
+ """Label for spectral density levels, for example ``"dB re 1 µPa²/Hz"`` (SIG-005)."""
50
+ if sig.units == "Pa":
51
+ ref = sig.medium.ref_label.removeprefix("re ")
52
+ if ref.startswith("1 "):
53
+ return f"dB re 1 {ref[2:]}²/Hz"
54
+ return f"dB re ({ref})²/Hz"
55
+ if sig.units == "V":
56
+ return "dB re 1 V²/Hz"
57
+ if sig.units == "counts":
58
+ return "dB re 1 count²/Hz"
59
+ return "dBFS/Hz"
60
+
61
+
62
+ def energy_level_label(sig: Signal) -> str:
63
+ """Label for energy levels, for example ``"dB re 1 µPa²·s"``."""
64
+ return spectral_level_label(sig).replace("/Hz", "·s")
65
+
66
+
67
+ def round_or_none(value: float | None, digits: int = 6) -> float | None:
68
+ """Round a float for JSON summaries. Keep ``None`` and non-finite as ``None``."""
69
+ if value is None or not np.isfinite(value):
70
+ return None
71
+ return float(f"{float(value):.{digits}g}")