Metadata-Version: 2.4
Name: sensorfusion-tools
Version: 2026.0.2
Summary: Python helper library for the TSRT14 Sensor Fusion Course at LiU
Author: Gustaf Hendeby
Author-email: Gustaf Hendeby <hendeby@gmail.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering
Requires-Dist: matplotlib>=3.10.8
Requires-Dist: numpy>=2.4.4
Requires-Dist: scipy>=1.17.1
Requires-Dist: tqdm>=4.67.3
Requires-Python: >=3.14
Description-Content-Type: text/markdown

# sensorfusion-tools

Signal-systems utilities for estimation, modeling, and plotting.

## Versioning

This library uses calendar-style semantic versions: `YYYY.FEATURE.BUGFIX`.

- `YYYY`: release year (for long-term timeline tracking)
- `FEATURE`: increments for new functionality
- `BUGFIX`: increments for patches and fixes

## Framework And Tooling

- Language: Python 3.14+
- Build backend: `uv_build`
- Package/dependency workflow: `uv`
- Numerical stack: `numpy`, `scipy`
- Plotting: `matplotlib`

## Testing Framework

- Test runner: `pytest`
- Property-based testing: `hypothesis`
- Coverage: `pytest-cov` (configured for `src/sftools`)

Run tests:

```bash
uv run pytest
```

Run only sftools tests:

```bash
uv run pytest tests/sftools
```

## Code Quality

- Linting: `ruff`

Run lint:

```bash
uv run ruff check .
```

## CI (GitLab)

The pipeline is defined in [.gitlab-ci.yml](.gitlab-ci.yml) and includes:

- `quality` stage: `ruff` lint checks
- `test` stage: `pytest` with JUnit artifact output

CI uses `python:3.14-slim` and installs dependencies with:

```bash
uv sync --group dev
```

## License

Distributed under the MIT License. See [LICENSE](LICENSE) for details.

## Project Structure

```text
src/
	sftools/        # Main signal-system models, estimators, helpers, plotting, shared types

tests/
	sftools/          # Pytest suite for src/sftools (one test file per source file)
	fixtures/         # Regression test input/output fixtures
```

For sftools, tests mirror the source layout:

- `src/sftools/model_obs.py` -> `tests/sftools/test_model.py`
- `src/sftools/estimator.py` -> `tests/sftools/test_estimator.py`
- `src/sftools/helper.py` -> `tests/sftools/test_helper.py`
- `src/sftools/plot.py` -> `tests/sftools/test_plot.py`

Shared state/trajectory datatypes are defined in `src/sftools/types.py`:

- `GaussianState`
- `ParticleState`
- `StateTrajectory` (supports probabilistic trajectories via `write_state` and deterministic trajectories via `write_mean`)

## Dimension Conventions

Model calculations use columns for states, observations, and samples:

| Quantity | Shape |
| --- | --- |
| One state | `(n, 1)` |
| One observation | `(m, 1)` |
| State or sample collection | `(n, N)` |
| Predicted observations for a collection | `(m, N)` |
| Measurement Jacobian at one state | `(m, n)` |
| Measurement covariance | `(m, m)` |

`ls`, `wls`, `nls`, `helper.llh`, and filter measurement updates require one
observation column. They reject flat, row, and batched observations instead of
reshaping them or allowing accidental NumPy broadcasting. To construct a column
from a flat observation array, explicitly use `y[:, None]`. A filter update uses
the same observation for every particle, not a separate observation per particle.

`GaussianState.x` stores a flat `(n,)` mean; use `state.mean()` for its `(n, 1)`
column view. Existing model support for flat state inputs is unchanged.
`nls` converts its optimization state to and from SciPy's flat-vector convention
internally. Custom model callbacks remain responsible for their output shapes;
the library does not automatically transpose or reshape them to match a model.

`sftools.helper.mct` accepts vectorized mappings with output shape
`(n_outputs, n_samples)`, or `(n_samples,)` for scalar outputs.
It requires at least two samples and always returns a matrix covariance,
including shape `(1, 1)` for a scalar output.

`sftools.estimator.ls` reports the unweighted estimator's covariance
`A @ R @ A.T`, where `A` is the least-squares gain and `R` is the measurement
covariance. The design matrix must have full column rank. With unequal or
correlated measurement noise, this covariance generally differs from the
covariance reported by `sftools.estimator.wls`.

Useful `StateTrajectory` iteration helpers:

- `for y in traj` yields state columns with shape `(n, 1)`
- `traj.iter_samples(include_cov=True, include_time=True)` yields `(y, cov, t)` tuples when available

Plotting helpers in `src/sftools/plot.py` use `StateTrajectory` inputs.

Particle filter helper:

- `ParticleFilter.init_state_gaussian(mean, cov, n_particles)` initializes a `ParticleState` from a Gaussian prior using the filter RNG.

## Nonlinear Least-Squares Diagnostics

`estimator.nls(model, y, x0)` returns a `GaussianState` as before when the solver
succeeds and its local covariance is available. To inspect the solver, request
the frozen `estimator.NLSResult` container:

```python
from sftools import estimator

fit = estimator.nls(model, y, x0, return_result=True)
print(fit.optimizer.success, fit.optimizer.message)
print("Weighted residual sum of squares:", 2 * fit.optimizer.cost)
if fit.estimate is not None:
	print(fit.estimate.mean(), fit.estimate.P)
```

`fit.optimizer` is SciPy's original `OptimizeResult`, including termination
`status` and `message`, `optimality`, evaluation counts `nfev` and `njev`, and
the final candidate `x`. Its `fun` contains the whitened residuals
`solve(L, y - h(x))`, flattened for SciPy, where `L @ L.T = R`.
Its `jac` is their Jacobian, `-solve(L, H(x))`. Twice `cost` equals both
`fun @ fun` and the weighted residual sum of squares
`(y - h(x)).T @ solve(R, y - h(x))`.

Without diagnostics, solver nonconvergence raises `RuntimeError` with SciPy's
termination message; singular local covariance raises `numpy.linalg.LinAlgError`.
With `return_result=True`, either case returns `estimate=None` while preserving
the optimizer result. Check `optimizer.success` to distinguish nonconvergence
from unavailable covariance after successful termination. Input errors still
raise normally, and no pseudoinverse is substituted for singular covariance.

The solver remains Levenberg-Marquardt with the supplied analytic Jacobian and
measurement covariance. Successful termination does not establish global
optimality, identifiability, or confidence-region coverage. Use SciPy directly
for bounds, custom residuals, or other optimizer controls.

## CRLB Grid Exclusions

`helper.crlb(model, region, n_points=..., scalar_fun=...)` keeps its existing
interface and returns the position grid and scalar bound array. Undefined or
nonfinite Jacobians, nonfinite information or covariance, and numerically
rank-deficient information produce `NaN` entries instead of aborting the map.
Rank is checked on the whitened Jacobian using NumPy's default numerical rank
criterion. One `RuntimeWarning` per call reports the number of excluded points.
If all points are valid, no warning is issued.

Plotting leaves holes at the excluded positions. `NaN` means that the full
covariance bound is unavailable there, not zero uncertainty. To locate those
positions, use `excluded = ~np.isfinite(bound)`. No pseudoinverse is substituted
for singular information.

The built-in TOA, TDOA, and offset-range models raise `ValueError` when their
Jacobian is requested at a sensor location, where range is not differentiable;
the CRLB grid helper recognizes this specific domain error and excludes the
point. Range predictions themselves remain defined there. Custom models can
signal undefined derivatives with nonfinite Jacobian entries.
Choose estimator starting points away from sensor locations when an analytic
range Jacobian is required.

Malformed Jacobians, invalid measurement covariance, and ordinary exceptions
from model or scalarization callbacks still raise. Measurement covariance must
be finite, symmetric, and positive definite, and `scalar_fun` must return a
finite scalar. Exclusion handling is for mathematical grid-point limitations,
not a way to suppress programming errors or establish estimator performance.

## Transformation Inspection

`helper.sigma_points(state, alpha=..., beta=..., kappa=...)` returns a frozen
`helper.SigmaPoints` container with `points`, `mean_weights`, and `cov_weights`.
It uses the same parameter defaults as `helper.ut`, which now shares this
construction. For an `n`-dimensional input, points have shape `(n, 2*n+1)` and
each weight array has shape `(2*n+1,)`. The first point is the mean, followed by
positive and negative Cholesky-column offsets. Mean and covariance weights are
separate arrays; covariance weights need not sum to one, and weights can be
negative.

To inspect the transformation explicitly:

```python
from sftools import helper

sigma = helper.sigma_points(state, alpha=1, beta=0, kappa=2)
transformed = h(sigma.points)
mean = transformed @ sigma.mean_weights
centered = transformed - mean[:, None]
covariance = (centered * sigma.cov_weights[None, :]) @ centered.T
```

`helper.ut` still returns a `GaussianState` by default, and its existing
`return_sigma_points=True` option still returns the three-item tuple
`(estimate, input_points, output_points)`. No new UT return option is required.

`helper.mct` also keeps its ordinary `GaussianState` return. To retain the samples
used to compute its moments, request the frozen `helper.MCTResult` container:

```python
fit = helper.mct(state, h, n_samples=1000, rng=rng, return_result=True)
estimate = fit.estimate
input_samples = fit.input_samples
output_samples = fit.output_samples
```

The arrays have shapes `(n_inputs, n_samples)` and `(n_outputs, n_samples)`,
including `(1, n_samples)` for scalar outputs. They are the arrays used in the
original calculation, not a second realization: the option adds no random draws
or callback evaluations. The result retains those arrays in memory for plotting
or inspection. MCT uses the unbiased sample covariance normalization `N-1`.

Finite sigma-point summaries or finite sample moments do not establish that the
transformed distribution has finite population moments or is Gaussian. This is
especially important for mappings with singularities such as ratios.
