commkit 1.0.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 (84) hide show
  1. commkit/__init__.py +74 -0
  2. commkit/_cuda/__init__.py +321 -0
  3. commkit/_cuda/compiler.py +88 -0
  4. commkit/_cuda/src/bps_min_d2.cu +104 -0
  5. commkit/_cuda/src/cs_block.cu +119 -0
  6. commkit/_cuda/src/selftest.cu +14 -0
  7. commkit/analysis/__init__.py +55 -0
  8. commkit/analysis/_common.py +236 -0
  9. commkit/analysis/allan.py +108 -0
  10. commkit/analysis/drift.py +213 -0
  11. commkit/analysis/interferometry.py +887 -0
  12. commkit/analysis/linewidth.py +480 -0
  13. commkit/analysis/trajectory.py +91 -0
  14. commkit/backend.py +507 -0
  15. commkit/coding/__init__.py +23 -0
  16. commkit/coding/base.py +17 -0
  17. commkit/coding/bch.py +6 -0
  18. commkit/coding/convolutional.py +7 -0
  19. commkit/coding/crc.py +7 -0
  20. commkit/coding/galois.py +8 -0
  21. commkit/coding/hamming.py +6 -0
  22. commkit/coding/interleaving.py +7 -0
  23. commkit/coding/ldpc.py +8 -0
  24. commkit/coding/polar.py +8 -0
  25. commkit/coding/ratematch.py +6 -0
  26. commkit/coding/reed_solomon.py +6 -0
  27. commkit/coding/turbo.py +8 -0
  28. commkit/core/__init__.py +32 -0
  29. commkit/core/frame.py +992 -0
  30. commkit/core/generation.py +581 -0
  31. commkit/core/signal.py +725 -0
  32. commkit/equalization/__init__.py +49 -0
  33. commkit/equalization/_block.py +1855 -0
  34. commkit/equalization/_common.py +606 -0
  35. commkit/equalization/_kernels_jax.py +1720 -0
  36. commkit/equalization/_kernels_numba.py +1704 -0
  37. commkit/equalization/blind.py +223 -0
  38. commkit/equalization/linear.py +365 -0
  39. commkit/equalization/polarization.py +790 -0
  40. commkit/equalization/result.py +191 -0
  41. commkit/equalization/sequential.py +2805 -0
  42. commkit/filtering.py +1120 -0
  43. commkit/frequency.py +1191 -0
  44. commkit/helpers.py +489 -0
  45. commkit/impairments/__init__.py +43 -0
  46. commkit/impairments/channel/__init__.py +20 -0
  47. commkit/impairments/channel/linear.py +310 -0
  48. commkit/impairments/channel/nonlinear.py +11 -0
  49. commkit/impairments/frontend.py +229 -0
  50. commkit/impairments/noise.py +105 -0
  51. commkit/impairments/source.py +219 -0
  52. commkit/io.py +308 -0
  53. commkit/logger.py +103 -0
  54. commkit/mapping/__init__.py +46 -0
  55. commkit/mapping/bits.py +240 -0
  56. commkit/mapping/constellation.py +153 -0
  57. commkit/mapping/gray.py +429 -0
  58. commkit/mapping/llr.py +253 -0
  59. commkit/mapping/shaping.py +218 -0
  60. commkit/metrics.py +949 -0
  61. commkit/multirate.py +476 -0
  62. commkit/plotting/__init__.py +78 -0
  63. commkit/plotting/analysis.py +627 -0
  64. commkit/plotting/constellation.py +483 -0
  65. commkit/plotting/equalizer.py +390 -0
  66. commkit/plotting/eye.py +388 -0
  67. commkit/plotting/spectral.py +575 -0
  68. commkit/plotting/sync.py +953 -0
  69. commkit/plotting/theme.py +203 -0
  70. commkit/plotting/waveform.py +200 -0
  71. commkit/py.typed +0 -0
  72. commkit/recovery/__init__.py +51 -0
  73. commkit/recovery/bps.py +337 -0
  74. commkit/recovery/corrections.py +751 -0
  75. commkit/recovery/pilots.py +803 -0
  76. commkit/recovery/pll.py +482 -0
  77. commkit/recovery/tikhonov.py +424 -0
  78. commkit/recovery/viterbi_viterbi.py +227 -0
  79. commkit/spectral.py +560 -0
  80. commkit/timing.py +841 -0
  81. commkit-1.0.0.dist-info/METADATA +145 -0
  82. commkit-1.0.0.dist-info/RECORD +84 -0
  83. commkit-1.0.0.dist-info/WHEEL +4 -0
  84. commkit-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,223 @@
1
+ """Block blind equalizers (block_cma, block_rde) and pilot reference builder."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+
9
+ from ..backend import ArrayType
10
+ from ._block import _block_fdaf_blind
11
+ from ._common import _godard_radius, _rde_ring_radii
12
+ from .result import EqualizerResult
13
+
14
+
15
+ def block_cma(
16
+ samples: ArrayType,
17
+ num_taps: int = 21,
18
+ sps: int = 2,
19
+ step_size: float = 2e-4,
20
+ block_size: int = 256,
21
+ modulation: str | None = None,
22
+ order: int | None = None,
23
+ unipolar: bool = False,
24
+ w_init: ArrayType | None = None,
25
+ pilot_ref: ArrayType | None = None,
26
+ pilot_mask: np.ndarray | None = None,
27
+ pilot_gain_db: float = 0.0,
28
+ pmf: Any | None = None,
29
+ input_norm_factor: float | np.ndarray | None = None,
30
+ samples_prefix: ArrayType | None = None,
31
+ pad_mode: str = "zeros",
32
+ cuda_graph: bool = True,
33
+ debug_plot: bool = False,
34
+ plot_smoothing: int = 50,
35
+ ) -> EqualizerResult:
36
+ """Blind frequency-domain CMA equalizer (overlap-save FDAF).
37
+
38
+ The blind, phase-directed sibling of :func:`block_lms`: the same
39
+ overlap-save frequency-domain adaptive filter, but driven by the Godard
40
+ constant-modulus error instead of a trained/DD slicer. Use it for blind
41
+ acquisition at the high-throughput frequency-domain operating point (slow or
42
+ static channels, GPU/CuPy input); for the trained/DD case use
43
+ :func:`block_lms`, and for fastest dynamics on a single stream use
44
+ :func:`cma` with ``backend='numba'``.
45
+
46
+ Like :func:`cma`, it is fully blind and recovers the channel up to a phase
47
+ ambiguity - run a carrier-phase recovery stage afterwards. Supplying
48
+ ``pilot_ref``/``pilot_mask`` (build them with :func:`build_pilot_ref`)
49
+ switches pilot positions to the LMS residual error, resolving the phase
50
+ ambiguity there while data positions stay blind.
51
+
52
+ ``step_size`` is on the same scale as :func:`cma`; because the weights are
53
+ frozen across each ``block_size``-symbol block, the stability ceiling is
54
+ ~``block_size``x lower (reduce ``mu`` only if the run raises divergence).
55
+ The primary target is GPU (CuPy); on CPU :func:`cma` is usually faster.
56
+
57
+ Parameters mirror :func:`cma` (no ``cpr_type`` - CMA is phase-blind, see
58
+ :func:`cma` Notes). On GPU, ``cuda_graph=True`` (default) captures the
59
+ per-block FDAF body once and replays it, collapsing the per-block kernel
60
+ launches into a single graph launch (a large win at small ``block_size``);
61
+ it is ignored on CPU and silently disabled for the pilot-aided path.
62
+ Returns an :class:`EqualizerResult` with ``y_hat``, ``weights``, ``error``
63
+ on the input's device.
64
+ """
65
+ r2, c_ps = _godard_radius(modulation, order, unipolar, pmf)
66
+ return _block_fdaf_blind(
67
+ "cma",
68
+ samples,
69
+ num_taps=num_taps,
70
+ sps=sps,
71
+ step_size=step_size,
72
+ block_size=block_size,
73
+ r2=r2,
74
+ radii_np=None,
75
+ w_init=w_init,
76
+ input_norm_factor=input_norm_factor,
77
+ samples_prefix=samples_prefix,
78
+ pad_mode=pad_mode,
79
+ pilot_ref=pilot_ref,
80
+ pilot_mask=pilot_mask,
81
+ pilot_gain_db=pilot_gain_db,
82
+ c_ps=c_ps,
83
+ cuda_graph=cuda_graph,
84
+ debug_plot=debug_plot,
85
+ plot_smoothing=plot_smoothing,
86
+ name="Block-CMA" if pilot_ref is None else "Block-CMA(PA)",
87
+ )
88
+
89
+
90
+ def block_rde(
91
+ samples: ArrayType,
92
+ num_taps: int = 21,
93
+ sps: int = 2,
94
+ step_size: float = 2e-4,
95
+ block_size: int = 256,
96
+ modulation: str | None = None,
97
+ order: int | None = None,
98
+ unipolar: bool = False,
99
+ w_init: ArrayType | None = None,
100
+ pilot_ref: ArrayType | None = None,
101
+ pilot_mask: np.ndarray | None = None,
102
+ pilot_gain_db: float = 0.0,
103
+ pmf: Any | None = None,
104
+ input_norm_factor: float | np.ndarray | None = None,
105
+ samples_prefix: ArrayType | None = None,
106
+ pad_mode: str = "zeros",
107
+ cuda_graph: bool = True,
108
+ debug_plot: bool = False,
109
+ plot_smoothing: int = 50,
110
+ ) -> EqualizerResult:
111
+ """Blind frequency-domain radius-directed equalizer (overlap-save FDAF).
112
+
113
+ The multi-ring blind sibling of :func:`block_lms`, related to
114
+ :func:`block_cma` as :func:`rde` is to :func:`cma`: it drives each symbol
115
+ toward its nearest constellation ring instead of a single Godard circle,
116
+ giving correct blind convergence on higher-order QAM (16/64-QAM) where CMA's
117
+ single-radius target stalls. Same overlap-save frequency-domain engine and
118
+ throughput positioning as :func:`block_cma`.
119
+
120
+ Fully blind up to a phase ambiguity (run CPR afterwards);
121
+ ``pilot_ref``/``pilot_mask`` resolve the ambiguity at pilot positions.
122
+ ``step_size`` is on the same scale as :func:`rde`, with the
123
+ ~``block_size``x-lower stability ceiling of frozen-block adaptation.
124
+
125
+ Parameters mirror :func:`rde`. On GPU, ``cuda_graph=True`` (default)
126
+ captures the per-block FDAF body once and replays it, collapsing the
127
+ per-block kernel launches into a single graph launch (a large win at small
128
+ ``block_size``); it is ignored on CPU and silently disabled for the
129
+ pilot-aided path. Returns an :class:`EqualizerResult` with ``y_hat``,
130
+ ``weights``, ``error`` on the input's device.
131
+ """
132
+ radii_np, c_ps = _rde_ring_radii(modulation, order, unipolar, pmf)
133
+ return _block_fdaf_blind(
134
+ "rde",
135
+ samples,
136
+ num_taps=num_taps,
137
+ sps=sps,
138
+ step_size=step_size,
139
+ block_size=block_size,
140
+ r2=1.0,
141
+ radii_np=radii_np,
142
+ w_init=w_init,
143
+ input_norm_factor=input_norm_factor,
144
+ samples_prefix=samples_prefix,
145
+ pad_mode=pad_mode,
146
+ pilot_ref=pilot_ref,
147
+ pilot_mask=pilot_mask,
148
+ pilot_gain_db=pilot_gain_db,
149
+ c_ps=c_ps,
150
+ cuda_graph=cuda_graph,
151
+ debug_plot=debug_plot,
152
+ plot_smoothing=plot_smoothing,
153
+ name="Block-RDE" if pilot_ref is None else "Block-RDE(PA)",
154
+ )
155
+
156
+
157
+ def build_pilot_ref(
158
+ pilot_symbols: np.ndarray,
159
+ pilot_mask: np.ndarray,
160
+ n_sym: int,
161
+ num_ch: int,
162
+ ) -> tuple:
163
+ """Build dense pilot reference array and uint8 mask for the hybrid PA kernel.
164
+
165
+ Packs sparse pilot symbols into a dense ``(C, n_sym)`` array suitable for
166
+ passing to ``cma`` or ``rde`` as ``pilot_ref`` / ``pilot_mask``.
167
+ Data positions are filled with zeros; the mask marks which positions carry
168
+ known reference symbols.
169
+
170
+ Parameters
171
+ ----------
172
+ pilot_symbols : (K,) or (C, K) complex64 ndarray
173
+ Known pilot symbols in transmission order (only the K pilot positions,
174
+ no data symbols). A 1-D array is broadcast to all C channels.
175
+ pilot_mask : (n_sym,) bool ndarray
176
+ ``True`` at the K pilot positions within the equalized body region.
177
+ n_sym : int
178
+ Total number of output symbols (payload + pilots).
179
+ num_ch : int
180
+ Number of receive channels C.
181
+
182
+ Returns
183
+ -------
184
+ pilot_ref : (C, n_sym) complex64 ndarray
185
+ Dense reference array - zeros at data positions, pilot symbols at
186
+ pilot positions.
187
+ pilot_mask_u8 : (n_sym,) uint8 ndarray
188
+ ``1`` at pilot positions, ``0`` elsewhere.
189
+
190
+ Examples
191
+ --------
192
+ Build the reference from a ``SingleCarrierFrame`` and
193
+ pass it directly to ``rde``:
194
+
195
+ ::
196
+
197
+ struct = frame.get_structure_map(unit="symbols", sps=1, include_preamble=False)
198
+ pilot_ref, pilot_mask_u8 = build_pilot_ref(
199
+ pilot_symbols=frame.pilot_symbols,
200
+ pilot_mask=np.asarray(struct["pilots"]),
201
+ n_sym=n_body_symbols,
202
+ num_ch=num_ch,
203
+ )
204
+ result = rde(body_samples, ..., pilot_ref=pilot_ref, pilot_mask=pilot_mask_u8)
205
+ """
206
+ pilot_ref_arr = np.zeros((num_ch, n_sym), dtype=np.complex64)
207
+ mask_uint8 = np.zeros(n_sym, dtype=np.uint8)
208
+
209
+ pilot_positions = np.where(pilot_mask)[0]
210
+ n_pilots = len(pilot_positions)
211
+
212
+ if pilot_symbols.ndim == 1:
213
+ pilot_symbols = np.broadcast_to(
214
+ pilot_symbols[np.newaxis, :], (num_ch, n_pilots)
215
+ )
216
+ else:
217
+ pilot_symbols = np.asarray(pilot_symbols, dtype=np.complex64)
218
+
219
+ for ch in range(num_ch):
220
+ pilot_ref_arr[ch, pilot_positions] = pilot_symbols[ch, :n_pilots]
221
+ mask_uint8[pilot_positions] = 1
222
+
223
+ return pilot_ref_arr, mask_uint8
@@ -0,0 +1,365 @@
1
+ """Linear block equalizers: zero-forcing and static tap application."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ from ..backend import ArrayType, dispatch, to_device
8
+ from ..filtering import _ols_backward, _ols_forward
9
+ from ..logger import logger
10
+ from ._common import _build_padded_samples, _normalize_inputs
11
+
12
+ # -----------------------------------------------------------------------------
13
+ # BLOCK equalization
14
+ # -----------------------------------------------------------------------------
15
+
16
+
17
+ def zf_equalizer(
18
+ samples: ArrayType,
19
+ channel_estimate: ArrayType,
20
+ noise_variance: float = 0.0,
21
+ debug_plot: bool = False,
22
+ ) -> ArrayType:
23
+ """
24
+ Zero-Forcing / MMSE frequency-domain block equalizer.
25
+
26
+ Given a channel impulse response estimate, equalizes the received signal
27
+ in the frequency domain. Supports both SISO and MIMO channels.
28
+
29
+ When ``noise_variance=0``, this is a pure Zero-Forcing equalizer.
30
+ When ``noise_variance > 0``, this becomes an MMSE equalizer that
31
+ regularizes spectral nulls to avoid noise enhancement.
32
+
33
+ Parameters
34
+ ----------
35
+ samples : array_like
36
+ Received samples. Shape: ``(N,)`` for SISO or ``(C, N)`` for MIMO.
37
+ channel_estimate : array_like
38
+ Channel impulse response. Shape: ``(L,)`` for SISO or
39
+ ``(C, C, L)`` for MIMO (each ``[i, j]`` is the FIR from input j
40
+ to output i).
41
+ noise_variance : float, default 0.0
42
+ Noise variance (sigma^2) for MMSE regularization.
43
+ ``0.0`` gives pure ZF.
44
+
45
+ Returns
46
+ -------
47
+ array_like
48
+ Equalized samples. Same shape and backend as input.
49
+ """
50
+ logger.info("ZF/MMSE equalizer: noise_variance=%.2e", noise_variance)
51
+ samples, xp, _ = dispatch(samples)
52
+ channel_estimate = xp.asarray(channel_estimate)
53
+
54
+ # Capture BEFORE any reshape so the later frequency-domain branch
55
+ # can still take the efficient scalar path for SISO channels.
56
+ siso_channel = channel_estimate.ndim == 1
57
+
58
+ was_1d = samples.ndim == 1
59
+ if was_1d:
60
+ samples = samples[None, :]
61
+ if siso_channel:
62
+ channel_estimate = channel_estimate[None, None, :]
63
+
64
+ num_ch, N = samples.shape
65
+ L = channel_estimate.shape[-1] if channel_estimate.ndim > 0 else 1
66
+ reg = noise_variance if noise_variance > 0 else 1e-12
67
+
68
+ # N_fft must satisfy discard = N_fft//4 >= L so the IIR filter's causal
69
+ # and anti-causal tails both decay within the discarded guard regions.
70
+ N_fft = max(1024, 1 << (max(1, 4 * L) - 1).bit_length())
71
+
72
+ logger.debug(
73
+ "ZF/MMSE internals: N=%s, L=%s, num_ch=%s, N_fft=%s", N, L, num_ch, N_fft
74
+ )
75
+
76
+ # --- Shared OLS forward pass: pad -> stride_tricks -> batch FFT ---
77
+ Y, meta = _ols_forward(samples, N_fft) # Y: (num_ch, num_blocks, N_fft)
78
+
79
+ if siso_channel:
80
+ # SISO: scalar frequency-domain ZF/MMSE inversion.
81
+ # channel_estimate was reshaped to (1,1,L) for was_1d; flatten to 1D.
82
+ H = xp.fft.fft(channel_estimate.reshape(-1), n=N_fft)
83
+ W = xp.conj(H) / (xp.abs(H) ** 2 + reg)
84
+ X_hat_f = Y * W
85
+ else:
86
+ # MIMO: per-bin (CxC) matrix inversion - cannot reduce to scalar multiply.
87
+ H_f = xp.fft.fft(channel_estimate, n=N_fft, axis=-1)
88
+ Hk = xp.transpose(H_f, (2, 0, 1)) # (N_fft, C_rx, C_tx)
89
+ Hk_H = xp.conj(xp.transpose(Hk, (0, 2, 1))) # (N_fft, C_tx, C_rx)
90
+ HHh = Hk @ Hk_H # (N_fft, C_rx, C_rx)
91
+
92
+ eye = xp.eye(num_ch, dtype=samples.dtype)[None, :, :]
93
+ if num_ch == 2:
94
+ # Fast-path: Explicit 2x2 matrix inversion via Cramer's Rule avoiding
95
+ # GPU LAPACK solver overheads (e.g. cuSOLVER batch inversion).
96
+ H_reg = HHh + reg * eye
97
+ a = H_reg[:, 0, 0]
98
+ b = H_reg[:, 0, 1]
99
+ c = H_reg[:, 1, 0]
100
+ d = H_reg[:, 1, 1]
101
+ det = a * d - b * c
102
+
103
+ inv_term = xp.empty_like(H_reg)
104
+ inv_term[:, 0, 0] = d / det
105
+ inv_term[:, 0, 1] = -b / det
106
+ inv_term[:, 1, 0] = -c / det
107
+ inv_term[:, 1, 1] = a / det
108
+ else:
109
+ inv_term = xp.linalg.inv(HHh + reg * eye)
110
+
111
+ Wk = Hk_H @ inv_term # (N_fft, C_tx, C_rx)
112
+
113
+ # Vectorized batch matrix multiplication across frequency bins and blocks.
114
+ # Uses explicit batched GEMM instead of einsum for better GPU utilization.
115
+ Y_t = xp.transpose(Y, (2, 0, 1)) # (N_fft, num_ch, num_blocks)
116
+ X_hat_k = Wk @ Y_t # (N_fft, C_tx, C_rx) @ (N_fft, C_rx, num_blocks)
117
+ X_hat_f = xp.transpose(X_hat_k, (1, 2, 0)) # (num_ch, num_blocks, N_fft)
118
+
119
+ # --- Shared OLS backward pass: batch IFFT -> symmetric discard -> reshape ---
120
+ out = _ols_backward(X_hat_f, meta)
121
+
122
+ if debug_plot:
123
+ from .. import plotting as _plotting # lazy import avoids circular dep
124
+
125
+ _plotting.plot_zf_equalizer_response(
126
+ channel_estimate=to_device(channel_estimate, "cpu"),
127
+ noise_variance=noise_variance,
128
+ show=True,
129
+ )
130
+
131
+ return out[0] if was_1d else out
132
+
133
+
134
+ def apply_taps(
135
+ samples: ArrayType,
136
+ weights: ArrayType,
137
+ sps: int = 2,
138
+ normalize: bool = True,
139
+ input_norm_factor: float | np.ndarray | None = None,
140
+ samples_prefix: ArrayType | None = None,
141
+ pad_mode: str = "zeros",
142
+ ) -> ArrayType:
143
+ """Apply frozen equalizer taps to a signal (inference pass, no weight updates).
144
+
145
+ Performs the butterfly FIR forward pass using pre-converged weights,
146
+ decimating by ``sps`` to produce one output symbol per ``sps`` input samples.
147
+ Suitable for reusing frozen taps from a prior equalizer run on a new signal
148
+ without re-running adaptation.
149
+
150
+ The forward pass implements::
151
+
152
+ y[i, n] = sum_j sum_t conj(W[i,j,t]) * x[j, n*sps + t]
153
+
154
+ which is the same inner computation as the Numba/JAX adaptive-equalizer
155
+ kernels, fully vectorized over ``n`` via a single batched ``einsum``.
156
+
157
+ Parameters
158
+ ----------
159
+ samples : array_like
160
+ Input samples. Shape: ``(N_samples,)`` for SISO or
161
+ ``(C, N_samples)`` for MIMO. Typically at ``sps`` samples/symbol.
162
+ weights : array_like
163
+ Frozen tap weights, typically ``EqualizerResult.weights`` from a
164
+ prior equalizer run. Shape: ``(num_taps,)`` for SISO or
165
+ ``(C, C, num_taps)`` for MIMO butterfly.
166
+ sps : int, default 2
167
+ Samples per symbol. Output length is ``N_samples // sps``.
168
+ Unlike the adaptive equalizers, any ``sps >= 1`` is accepted.
169
+ normalize : bool, default True
170
+ If ``True``, normalize ``samples`` to unit symbol power before
171
+ filtering (same pre-processing as the adaptive equalizers via
172
+ ``_normalize_inputs``). Set to ``False`` if the caller has already
173
+ scaled the input consistently with the original training run.
174
+ input_norm_factor : float or ndarray, optional
175
+ Pre-computed RMS normalization factor. When provided and
176
+ ``normalize=True``, skips RMS recomputation and uses this value
177
+ directly. Typically ``EqualizerResult.input_norm_factor`` from the
178
+ prior equalizer run that produced ``weights``.
179
+ samples_prefix : array_like, optional
180
+ Signal history from the end of the previous block. See ``lms()``
181
+ for the full description; behaviour is identical.
182
+ pad_mode : {'zeros', 'edge'}, default 'zeros'
183
+ Padding strategy when ``samples_prefix`` is ``None``. See
184
+ ``lms()`` for the full description; behaviour is identical.
185
+
186
+ Returns
187
+ -------
188
+ array_like
189
+ Equalized symbols. Shape: ``(N_sym,)`` for SISO or
190
+ ``(C, N_sym)`` for MIMO, where ``N_sym = N_samples // sps``.
191
+ Resides on the same backend as ``samples``.
192
+
193
+ Examples
194
+ --------
195
+ Freeze taps from a training run and apply to a new capture::
196
+
197
+ result = equalization.lms(train_signal, training_symbols, num_taps=31)
198
+ y = equalization.apply_taps(new_signal, result.weights,
199
+ input_norm_factor=result.input_norm_factor)
200
+ """
201
+ samples, xp, _ = dispatch(samples)
202
+ weights = xp.asarray(weights)
203
+
204
+ was_1d = samples.ndim == 1
205
+
206
+ # Promote SISO -> MIMO shapes for uniform butterfly code path
207
+ if was_1d:
208
+ samples = samples[None, :] # (N,) -> (1, N)
209
+ if weights.ndim == 1:
210
+ weights = weights[None, None, :] # (T,) -> (1, 1, T)
211
+
212
+ C, N = samples.shape
213
+ num_taps = weights.shape[-1]
214
+ n_sym = N // sps
215
+
216
+ _at_eq_norm = None
217
+ if normalize:
218
+ samples, _, _at_eq_norm = _normalize_inputs(
219
+ samples, None, sps, input_norm_factor=input_norm_factor
220
+ )
221
+
222
+ # Pad left by center tap so window[0] is center-aligned with sample 0,
223
+ # pad right to fill the last window completely - mirrors LMS pre-processing.
224
+ c_tap = num_taps // 2
225
+ pad_left = c_tap
226
+ pad_right = n_sym * sps - N + num_taps - 1 - pad_left
227
+ if samples_prefix is None and pad_mode == "zeros":
228
+ samples_padded = xp.pad(samples, ((0, 0), (pad_left, pad_right)))
229
+ else:
230
+ # _build_padded_samples is backend-generic: pad on the input device
231
+ # instead of round-tripping the full signal through the host.
232
+ samples_padded = xp.ascontiguousarray(
233
+ _build_padded_samples(
234
+ samples.astype(xp.complex64),
235
+ pad_left,
236
+ pad_right,
237
+ samples_prefix,
238
+ pad_mode,
239
+ _at_eq_norm,
240
+ sps,
241
+ )
242
+ )
243
+
244
+ # Zero-copy sliding-window view: (C, N_sym, num_taps)
245
+ # windows[c, n, t] = samples_padded[c, n*sps + t]
246
+ s0, s1 = samples_padded.strides
247
+ windows = xp.lib.stride_tricks.as_strided(
248
+ samples_padded,
249
+ shape=(C, n_sym, num_taps),
250
+ strides=(s0, sps * s1, s1),
251
+ )
252
+
253
+ # Butterfly forward pass - single batched GEMM (dispatches to cuBLAS on GPU)
254
+ # y[i, n] = Σ_j Σ_t conj(W[i,j,t]) * windows[j, n, t]
255
+ y = xp.einsum("ijt,jnt->in", xp.conj(weights), windows) # (C, N_sym)
256
+
257
+ return y[0] if was_1d else y
258
+
259
+
260
+ # -----------------------------------------------------------------------------
261
+ # DATA-AIDED CHANNEL ESTIMATION (Welch H1 transfer function)
262
+ # -----------------------------------------------------------------------------
263
+
264
+
265
+ def estimate_transfer_function(
266
+ reference: ArrayType,
267
+ received: ArrayType,
268
+ *,
269
+ n_fft: int = 512,
270
+ reg: float = 1e-2,
271
+ max_windows: int = 4096,
272
+ num_taps: int | None = None,
273
+ ) -> ArrayType:
274
+ r"""Data-aided (MIMO) channel estimate via Welch's H1 transfer-function method.
275
+
276
+ Estimates the frequency response :math:`B(f) \approx S_{yx}(f)\,S_{xx}(f)^{-1}`
277
+ mapping a known ``reference`` ``x`` to the measured ``received`` ``y``, where
278
+ :math:`S_{xx}` / :math:`S_{yx}` are the Welch auto/cross spectra - Hann-windowed,
279
+ averaged periodograms. This is the classic H1 channel-sounding estimator,
280
+ generalised to a full ``(C, C)`` cross-spectral matrix so the MIMO response is
281
+ recovered in one shot (the reference is FFT'd once and every channel pair is
282
+ formed by a single einsum).
283
+
284
+ Pair it with :func:`zf_equalizer` / :func:`apply_taps` (which consume a
285
+ ``(C, C, L)`` impulse response) to invert the estimated channel, or use the
286
+ impulse response to seed an adaptive butterfly equalizer.
287
+
288
+ Parameters
289
+ ----------
290
+ reference, received : array_like
291
+ Time-aligned, same-rate input / output. ``(N,)`` SISO or ``(C, N)`` MIMO.
292
+ n_fft : int, default 512
293
+ Welch segment length (frequency resolution ``fs / n_fft``).
294
+ reg : float, default 1e-2
295
+ Relative Tikhonov loading for the :math:`S_{xx}` inverse - a diagonal term
296
+ scaled to the mean auto-spectrum, so it stabilises the estimate where the
297
+ reference has little power (band edges) without depending on the absolute
298
+ signal level. The H1 ratio is invariant to overall scale and window count.
299
+ max_windows : int, default 4096
300
+ Cap on the number of averaged segments. An LTI channel is static, so a few
301
+ thousand windows spread over the record give a stable estimate; capping
302
+ bounds the vectorised FFT batch (the averaging only trades variance, not
303
+ bias, so the cap does not move the estimate).
304
+ num_taps : int, optional
305
+ If given, return the centred, Hann-tapered impulse response truncated to
306
+ ``num_taps`` taps - ``(C, C, num_taps)`` MIMO or ``(num_taps,)`` SISO, ready
307
+ for :func:`zf_equalizer`. If ``None`` (default), return the frequency
308
+ response ``B(f)`` in FFT-bin order - ``(n_fft, C, C)`` MIMO or ``(n_fft,)``
309
+ SISO.
310
+
311
+ Returns
312
+ -------
313
+ array_like
314
+ Frequency response or impulse response (see ``num_taps``).
315
+ """
316
+ x, xp, _ = dispatch(reference)
317
+ y = xp.asarray(received)
318
+ single = x.ndim == 1
319
+ if single:
320
+ x, y = x[None, :], y[None, :]
321
+ x = x.astype(xp.complex128)
322
+ y = y.astype(xp.complex128)
323
+ C, N = x.shape
324
+ n_fft = int(min(n_fft, N))
325
+ win = xp.asarray(np.hanning(n_fft))
326
+
327
+ # Welch auto/cross spectra, vectorised over windows (capped). One batched FFT
328
+ # of the reference and the received, then every (C, C) cross term via einsum -
329
+ # no per-window Python loop, no redundant re-FFT of shared channels.
330
+ step = max(n_fft // 2, (N - n_fft) // max(max_windows - 1, 1))
331
+ starts = xp.arange(0, N - n_fft + 1, step)
332
+ idx = starts[:, None] + xp.arange(n_fft)[None, :] # (n_win, n_fft)
333
+ X = xp.fft.fft(x[:, idx] * win, axis=-1) # (C, n_win, n_fft)
334
+ Y = xp.fft.fft(y[:, idx] * win, axis=-1)
335
+ Sxx = xp.einsum("cwf,dwf->fcd", X, X.conj()) # (n_fft, C, C)
336
+ Syx = xp.einsum("cwf,dwf->fcd", Y, X.conj())
337
+
338
+ eye = xp.eye(C, dtype=xp.complex128)
339
+ reg_xx = reg * float(xp.einsum("fcc->f", Sxx).real.mean() / C)
340
+ B = Syx @ xp.linalg.inv(Sxx + reg_xx * eye) # (n_fft, C, C), H1 estimate
341
+
342
+ logger.info(
343
+ "estimate_transfer_function (Welch H1): n_fft=%d, n_win=%d, reg=%.2e "
344
+ "[C=%d, N=%d, %s]",
345
+ n_fft,
346
+ int(starts.shape[0]),
347
+ reg,
348
+ C,
349
+ N,
350
+ "taps" if num_taps is not None else "freq-response",
351
+ )
352
+
353
+ if num_taps is None:
354
+ return B[:, 0, 0] if single else B
355
+
356
+ # Centred, Hann-tapered impulse response, truncated to num_taps.
357
+ n_taps = int(min(num_taps, n_fft))
358
+ b_t = xp.fft.fftshift(xp.fft.ifft(B, axis=0), axes=0) # (n_fft, C, C), lag axis 0
359
+ center = n_fft // 2
360
+ half = n_taps // 2
361
+ taps = b_t[center - half : center + half + 1] # (L, C, C)
362
+ taps = taps * xp.asarray(np.hanning(taps.shape[0]))[:, None, None]
363
+ if single:
364
+ return taps[:, 0, 0] # (L,)
365
+ return xp.transpose(taps, (1, 2, 0)) # (C, C, L), matches zf_equalizer layout