Metadata-Version: 2.5
Name: gri-iqp
Version: 0.1.0
Summary: Composable numpy/CuPy-based RF IQ signal processing pipeline utilities (SDR/EW)
Project-URL: Homepage, https://geosolresearch.com
Project-URL: Repository, https://gitlab.com/geosol-foss/python/gri-iqp
Project-URL: Issues, https://gitlab.com/geosol-foss/python/gri-iqp/-/issues
Project-URL: Changelog, https://gitlab.com/geosol-foss/python/gri-iqp/-/releases
Author-email: GeoSol Research Inc <contact@geosolresearch.com>
License-Expression: MIT
License-File: LICENSE
Keywords: CAF,CuPy,GPU,IQ,RF,SDR,signal-processing
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Python: >=3.12
Requires-Dist: gri-nsepoch>=0.2.3
Requires-Dist: numpy>=2.3.3
Requires-Dist: scipy>=1.16.3
Provides-Extra: gpu
Requires-Dist: cupy-cuda12x>=13.3.0; extra == 'gpu'
Requires-Dist: nvidia-cublas-cu12>=12.9.2.10; extra == 'gpu'
Requires-Dist: nvidia-cuda-nvrtc-cu12>=12.9.86; extra == 'gpu'
Requires-Dist: nvidia-cuda-runtime-cu12>=12.9.79; extra == 'gpu'
Requires-Dist: nvidia-cufft-cu12>=11.4.1.4; extra == 'gpu'
Requires-Dist: nvidia-curand-cu12>=10.3.10.19; extra == 'gpu'
Requires-Dist: nvidia-cusolver-cu12>=11.7.5.82; extra == 'gpu'
Requires-Dist: nvidia-cusparse-cu12>=12.5.10.65; extra == 'gpu'
Requires-Dist: nvidia-nvjitlink-cu12>=12.9.86; extra == 'gpu'
Description-Content-Type: text/markdown

[![GeoSol Research Logo](https://geosolresearch.com/logos/foss_logo.png "GeoSol Research")](https://geosolresearch.com)

# gri-iqp (IQ Pipeline)

Composable signal-processing primitives to support correlation-based
processing of digitally sampled RF signal data ("__IQ__ data"). Includes
support for signal extraction (time-slicing, frequency-filtering, and
sample-rate decimation) based on time-frequency boxes; Cross Ambiguity
Function (CAF) implementations; CAF peak picking, grouping, ambiguity
detection, and characterization; and wideband coherent combining of
chunk-CAFs.

Written to run unchanged on CPU (numpy/scipy) or NVIDIA GPU (CuPy), dispatching
on the array module applicable to where the data presides (see Status for what
is tested). Primitives are designed to be used in a __pipeline__ by your application
such that the input data and intermediate data products (such as a time-
sliced and decimated IQ stream, or a CAF surface) remains in memory on
either the CPU (*host*) or GPU (*device*) with minimal host/device data transfers.
The nearly-equivalent behavior on CPU and GPU (via cupy) enables development
and testing on CPU-only machines while GPU is only required for performance
testing.



MIT licensed.

## Status

**Alpha, pre-1.0.** The CPU path is implemented and tested; the API may still
change between releases. GPU code paths are written against the same backend
dispatch but are not yet exercised in CI on CUDA hardware.

## Install

```sh
pip install gri-iqp
# or, with CUDA GPU support:
pip install "gri-iqp[gpu]"
```

Requires Python >= 3.12.

## Quick Start

Estimate TDOA between two sensors that saw the same emitter:

```python
>>> import numpy as np
>>> from gri_nsepoch import Time
>>> from gri_iqp import CafSearchRange, Stream, caf_estimate

>>> fs_hz, fc_hz = 2e6, 1.2e9
>>> epoch = Time(s=1_700_000_000.0)
>>> rng = np.random.default_rng(0)

>>> # Stand-in for two real captures: the primary sees the emitter 12 us LATER
>>> # than the secondary, so tdoa = t_primary - t_secondary = +12 us. Each
>>> # receiver adds independent noise, as strong as the emitter.
>>> n, shift = 4096, 24
>>> emitter = rng.standard_normal(n + 64) + 1j * rng.standard_normal(n + 64)
>>> def receive(iq):
...     return iq + rng.standard_normal(n) + 1j * rng.standard_normal(n)
>>> primary_iq = receive(emitter[:n])
>>> secondary_iq = receive(emitter[shift : shift + n])

>>> def sensor(iq):
...     return Stream(
...         data=iq,
...         start_time=epoch,
...         fs=fs_hz,
...         fc=fc_hz,
...         f_min=fc_hz - 0.8e6,
...         f_max=fc_hz + 0.8e6,
...         phase_epoch=epoch,
...     )

>>> estimate = caf_estimate(
...     sensor(primary_iq),
...     sensor(secondary_iq),
...     CafSearchRange(tau_range=(-40e-6, 40e-6), tau_dot_range=(-5e-7, 5e-7)),
...     snr_threshold=100.0,
... )
>>> for group in estimate.detections:
...     peak = max(group.points, key=lambda p: p.snr)
...     lo, hi = peak.confidence_range(0.95).tau_range
...     print(f"tdoa {peak.tdoa * 1e6:.3f} us  (95%: {lo * 1e6:.3f}..{hi * 1e6:.3f})")
...     print(f"  snr {peak.snr:.0f}, points in this ambiguity group: {len(group.points)}")
tdoa 11.994 us  (95%: 11.975..12.012)
  snr 961, points in this ambiguity group: 1

```

`caf_estimate` is the top-level entry point: it checks whether the requested
delay-rate range is narrowband enough for a plain CAF, pre-compensates by
resampling when only the range ends fail, and raises with a pointer to the
wideband path when even the midpoint does. Its result carries the detections,
the search range that produced them, and the largest delay acceleration under
which its linear-delay model holds.

## Conventions

The following conventions are adopted by `gri-iqp`:

- The two sensors are **primary** and **secondary**, and they do *not* enter
  symmetrically: the primary supplies the independent time-of-measurement variable: the time of arrival (TOA) at the primary sensor.
- Both differences are primary minus secondary:
  - `tdoa = t_primary - t_secondary`,
  - `fdoa = f_primary - f_secondary`, and
  - `tdoadot = -fdoa / f_secondary`. The denominator is the frequency *received at the secondary*.
- Surfaces carry a `tdoadot` axis rather than `fdoa`, because TDOA-Dot is
  carrier-independent, comparable across bands, and the
  geo-observable.
- `CafSurface.value` is volts-like squared, but `value_db` is
  `20*log10(abs(value))`, so a peak's height above the noise floor in dB is
  its SNR in dB (`snr` is the power ratio `abs(value)**2 / noise_power`).

## What's Here

| Piece | What it does |
|---|---|
| `Stream`, `StreamBatch`, `ExtractBox` | Sampled IQ plus metadata; slice/tune/filter/decimate (`extract`, `extract_batch`), resample (`dilate`). Single- or multi-channel, samples on the last axis. `combined_residual_phase` relates an extracted pair's deferred tune phases. |
| `tune_filter_decimate`, `design_lowpass_taps` | The array-level form of extraction: tune, anti-alias filter and decimate in one polyphase step, returning the tune frequency actually realized. |
| `caf_estimate` | The top-level measurement: checks the delay-rate range is narrowband enough, runs `caf` and `find_caf_peaks`, and groups the results; returns a `CafEstimate`. |
| `caf` | Stream-aware CAF: two `Stream`s + a `CafSearchRange` -> `CafSurface`, owning all unit conversion. |
| `caf_batch`, `align_stream_batches` | The same for many chunks in one engine call: two row-paired `StreamBatch`es (e.g. pulses from `extract_batch`) -> one `CafSurface` per row. |
| `gri_iqp.caf_engines` | Three pure-array CAF engines: `caf_direct` (reference), `caf_time_domain` (Stein's), `caf_freq_domain`, each batching over any leading dimensions. `caf_bytes_required` sizes a call's peak memory before you commit to it. |
| `find_caf_peaks`, `find_caf_peaks_batch` | Detects peaks on a surface and characterizes each: sub-cell location, fitted magnitude, curvature `hessian`, `snr`, and a `PeakQuality` flag. The batch form handles a list of same-shaped surfaces in one pass. |
| `CafPoint.covariance` / `.confidence_range` | Curvature + SNR -> covariance -> a search range for the next stage ("range in, estimate out"). |
| `select_ambiguity_groups` | Groups grating-lobe replicas into `AmbiguityGroup`s by detecting regular lattices along each axis. |
| `cluster_caf_points`, `CrossChunkGroup` | Associates chunk peaks that lie on one `(tdoa, tdoadot)` trajectory, with a chi-square gate; a group's fused estimate gives `confidence_range(level, at=...)` for sizing an IWCAF search. |
| `iwcaf_refine`, `recenter_to_centroid`, `recenter_to_centroid_batch` | Interferometric wideband CAF: coherently combines many chunk peaks into one aperture-level surface, resolving far finer than any single chunk. |
| `iwcaf_phase_fit`, `IwcafFit` | Locates the IWCAF peak from the chunk phases directly, by weighted least squares rather than a grid, and fuses each chunk's `(tdoa, tdoadot)` measurement, which supplies any axis the aperture cannot resolve. |
| `sic_components`, `SicComponent`, `reconstruct_composite`, `effective_beam_covariance` | Successive interference cancellation: attributes chunks to overlapping emitters with soft per-chunk weights. |
| `gri_iqp.peak_detect` | Generic surface primitives: `noise_floor`, `noise_floors`, `detect_peaks`, `extract_patches`. |
| `gri_iqp.gaussian_fusion` | Gaussian gate and fuse primitives (host-side): `match_statistic`, `fuse`, and their N-D forms `match_statistic_nd`, `fuse_nd`, `generalized_variance`. |
| `gri_iqp.scalar_grouping` | Scalar clustering and lattice detection (host-side): `cluster_1d`, `find_ladder`. |
| `gri_iqp.backend` | numpy/CuPy dispatch: `get_array_module`, `get_signal_module`, `asarray`, `to_cpu`, `Device`. |

`resample_poly` and `stft` deliberately have no wrapper; call
`scipy.signal`/`cupyx.scipy.signal` directly via `backend.get_signal_module`.

### Not Yet Implemented

These exist as documented stubs and raise `NotImplementedError`:

- `gri_iqp.channelize.channelize`: polyphase channelizer (designed, not
  scheduled; `extract_batch` covers non-uniform band placement today).
- `Stream.pairer`: combinatorial primary/secondary pair filtering.

`iwcaf_search` (the detection-regime IWCAF, as opposed to `iwcaf_refine`'s
refinement regime) is designed but deliberately deferred.

## CPU/GPU

Primitives infer their array module from their inputs, so a pipeline's
intermediate data stays on one device end to end. Placement is explicit only
at the boundaries:

```python
from gri_iqp.backend import Device, asarray, to_cpu

gpu_iq = asarray(host_iq, device=Device.GPU)   # on the way in
result = to_cpu(surface.value)                 # on the way out
```

Operands must be co-located: CuPy raises on an operation that mixes a numpy
and a CuPy array rather than copying silently (not yet exercised here, since
CI has no GPU). The caller sets a memory budget (`max_bytes`) and the
FFT engines split their work to stay under it; `caf_bytes_required`
makes a call's peak footprint knowable in advance.

## Documentation

The wheel ships its documentation inside the package, in `gri_iqp/docs/`, so
it is available wherever the package is installed: `overview.md` (the sign
conventions, an end-to-end measurement, a map of the pieces), a generated
`api_summary.md` of every public signature, and the design references listed
below except the notebook. Print the directory with
`python -c "import gri_iqp, pathlib; print(pathlib.Path(gri_iqp.__file__).parent / 'docs')"`.
Every example in `overview.md`, the docstrings and this README's Quick Start
is run by the test suite.

In the GitLab repository:

- [`notebooks/tutorial.ipynb`](https://gitlab.com/geosol-foss/python/gri-iqp/-/blob/main/notebooks/tutorial.ipynb):
  an end-to-end tour of the pipeline on synthetic data with known truth:
  streams and the phase-epoch convention, CAF surfaces, peak uncertainty and
  the coarse-to-fine handoff, sign conventions, ambiguity groups, extraction
  and batching, IWCAF, SIC attribution of overlapping emitters, and CPU/GPU
  placement. Start here.
- [`design.md`](https://gitlab.com/geosol-foss/python/gri-iqp/-/blob/main/design.md): the architecture document, and the authority
  on what the implementation does and why.
- [`glossary.md`](https://gitlab.com/geosol-foss/python/gri-iqp/-/blob/main/glossary.md): what each domain term (chunk, aperture,
  tau vs. tdoa, the search range and its epoch, the SIC vocabulary, and
  more) means as this library uses it.
- [`caf_variants.md`](https://gitlab.com/geosol-foss/python/gri-iqp/-/blob/main/caf_variants.md): comparison table and signatures
  for the three CAF engines, and how they batch.
- [`chunk_phase_reference.md`](https://gitlab.com/geosol-foss/python/gri-iqp/-/blob/main/chunk_phase_reference.md): why a chunk's
  time/frequency origin is a free choice, and why the energy centroid is the
  right place to put it.
- [`noise_estimator.md`](https://gitlab.com/geosol-foss/python/gri-iqp/-/blob/main/noise_estimator.md): bias/variance of the
  quantile noise-floor estimator.

## Contributing

```sh
uv sync
uv run pytest --cov
uv run pre-commit run --all-files --hook-stage pre-push
```

`uv sync` also wires up the git hooks, so there is no separate
`pre-commit install` step.

See [CONTRIBUTING.md](https://gitlab.com/geosol-foss/python/gri-iqp/-/blob/main/CONTRIBUTING.md)
for the full setup, code style, and the project-specific conventions (the
design document is binding, and the sign/phase conventions are easy to get
silently wrong).

## License

MIT. See [LICENSE](https://gitlab.com/geosol-foss/python/gri-iqp/-/blob/main/LICENSE).
