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

# Utils

Utility functions available for any project.

This library is a general collection of utility functions and constants with minimal requirements. Requires Python 3.12+.

## Installation

```bash
pip install gri-utils
```

For development:

```bash
git clone https://gitlab.com/geosol-foss/python/gri-utils.git
cd gri-utils
. .init_venv.sh
```

## Quick Start

```python
from gri_utils import conversion, distance, constants

# Convert LLA (lat, lon, alt) to ECEF XYZ
xyz = conversion.lla_to_xyz([40.0, -105.0, 1600.0])

# Surface distance between two points (Vincenty, accurate to ~0.5 mm)
d_m = distance.vincenty([40.0, -105.0], [41.0, -104.0])

# Coordinate deltas
enu = conversion.get_enu(xyz_from, xyz_to)
aer = conversion.get_aer(xyz_from, xyz_to)

# Earth constants
print(constants.ER_M)   # Earth equatorial radius (meters)
print(constants.C)       # Speed of light (m/s)
```

## Constants

Common geolocation constants including Earth's equatorial and polar radii, eccentricity, flattening, and statistical scaling factors for sigma to 95% confidence conversions.

See [Constants README](https://gitlab.com/geosol-foss/python/gri-utils/-/blob/main/gri_utils/constants/README.md)

## Conversion

Coordinate system transformations between XYZ (ECEF), LLA (Lat/Lon/Alt), ENU, NED, AER, CCR, and ECI. Includes:

- **ECEF <-> ECI**: Time-dependent transformations between Earth-fixed and inertial frames via GMST
- **Julian Date**: Unix timestamp and datetime conversions to/from Julian Date
- **GMST**: Greenwich Mean Sidereal Time calculations (IAU 2006 precession model)
- **Rotation matrices**: `xyz_enu_rotation`, `enu_xyz_rotation`, `xyz_ned_rotation`, `ned_xyz_rotation`
- **Delta operations**: `get_*`, `translate_*`, `xyz_to_*`, `*_to_xyz` for each coordinate type
- **Covariance matrix transformations**: `xyz_to_enu_cov`, `enu_to_xyz_cov`, `xyz_to_ned_cov`, `ned_to_xyz_cov`
- **DMS conversions**: Degrees/Minutes/Seconds <-> decimal degrees

All conversion functions support **vectorized inputs** for efficient batch processing of `(N, 3)` arrays. Covariance matrix functions support stacked `(N, 3, 3)` matrices.

See [Conversion README](https://gitlab.com/geosol-foss/python/gri-utils/-/blob/main/gri_utils/conversion/README.md)

## Distance

Surface distance calculations with multiple formulas: simple spherical approximation (fast, good for relative distances <500km), Haversine (standard spherical, ~0.5% error), and Vincenty (iterative oblate spheroid, accurate to ~0.5mm). Also includes central angle calculations and osculating sphere computations.

Most distance functions support **vectorized inputs** for efficient batch processing of `(N, 2+)` LLA or `(N, 3)` XYZ arrays.

See [Distance README](https://gitlab.com/geosol-foss/python/gri-utils/-/blob/main/gri_utils/distance/README.md)

## Ellipsoids

Conversions between 2D/3D ellipse parameters (SMA, SMI, ORI, ALT) and covariance matrices. Includes sigma <-> 95% confidence scaling for scalars, vectors, and matrices.

See [Ellipsoids README](https://gitlab.com/geosol-foss/python/gri-utils/-/blob/main/gri_utils/ellipsoids/README.md)

## Matrices

Matrix and vector rotation utilities for 2D and 3D operations around one or more axes. Also includes block diagonal matrix construction and decomposition utilities.

See [Matrices README](https://gitlab.com/geosol-foss/python/gri-utils/-/blob/main/gri_utils/matrices/README.md)

## Resources

Programming utilities including a memory/CPU usage measuring decorator and a Thread subclass that returns values from its target function.

See [Resources README](https://gitlab.com/geosol-foss/python/gri-utils/-/blob/main/gri_utils/resources/README.md)

## Stats

Statistical utilities for confidence intervals and scale factor analysis. Includes Poisson CI (Garwood method), quantile CI (normal approximation to binomial), ratio CI (Walters logarithm method), and scale factor analysis for ellipse calibration.

See [Stats README](https://gitlab.com/geosol-foss/python/gri-utils/-/blob/main/gri_utils/stats/README.md)

## Geolocation

Mathematical building blocks for geolocation solvers:

- **Whitened least squares**: Generic Cholesky-whitened nonlinear solver with correlated measurement support
- **Predicted covariance**: Analytical GDOP computation from Jacobian and measurement noise (no solver iteration needed)
- **Default initial guess**: Projects collector centroid onto Earth surface for solver initialization

Observable-specific locators (TDOA, AOA, FDOA, hybrid) that wrap these primitives live in gri-geosim.

See [Geolocation README](https://gitlab.com/geosol-foss/python/gri-utils/-/blob/main/gri_utils/geolocation/README.md)

## Observables

Sensor measurement simulation (forward problem - state to measurements):

- **Range**: Euclidean distance from collector to emitter
- **AOA**: Angle of Arrival direction cosines (ENU-based and quaternion-based for arbitrary sensor orientation)
- **TDOA**: Time Difference of Arrival between two collectors
- **FDOA**: Frequency Difference of Arrival (Doppler)
- **PDOA**: Phase Difference of Arrival for interferometer arrays
- **Gradients**: Jacobians available for optimization workflows
- **Residual factories**: Each observable provides a `get_*_residual` function for use with terrain intersection algorithms

Quaternions use scipy convention `[x, y, z, w]` (scalar-last).

See [Observables README](https://gitlab.com/geosol-foss/python/gri-utils/-/blob/main/gri_utils/observables/README.md)

## Orbit

Two-body Keplerian orbit mechanics for orbital propagation and analysis:

- **Orbital Elements**: Classical Keplerian parameters (SMA, eccentricity, inclination, RAAN, arg_periapsis, true_anomaly)
- **State Vectors**: Position, velocity, acceleration at specific times
- **TLE Parsing**: Two-Line Element data conversion to orbital elements
- **Orbit Fitting**: Fit elements from position/velocity state or multiple observations
- **Propagation**: `elements_to_state` for forward propagation
- **Properties**: Period, apogee, perigee, specific energy, angular momentum

Note: Pure Keplerian mechanics only (no perturbations). For TLE propagation with J2/drag, use SGP4 library.

See [Orbit README](https://gitlab.com/geosol-foss/python/gri-utils/-/blob/main/gri_utils/orbit/README.md)

## Terrain

Pure math functions for terrain represented as XYZ surface grids (sheets) in ECEF coordinates:

- **Sheet operations**: LLA-to-XYZ conversion, bicubic interpolation, resolution measurement
- **Sheet bounds**: Radial bounding surfaces for fast ray rejection
- **Ray intersection**: Adaptive-step ray-sheet intersection
- **Visibility/shadow**: Shadow depth scalar field, visibility masks, shadow boundary contours
- **Marching squares**: Iso-contour extraction from 2D scalar fields
- **Sheet intersection**: Generic terrain intersection with observable iso-surfaces (range, TDOA, FDOA, AOA)
- **TerrainSource ABC**: Abstract interface for terrain data providers (implemented by gri-terrain)
- **Sheet stitching**: Mosaic multiple tiles into a single contiguous array
- **Adaptive intersection**: Subsample-based efficient intersection for large terrain datasets

See [Terrain README](https://gitlab.com/geosol-foss/python/gri-utils/-/blob/main/gri_utils/terrain/README.md)

## Dependencies

- **numpy**: Array operations and linear algebra
- **scipy**: Scientific computing (coordinate conversions, optimization)
- **psutil**: System resource monitoring (optional, for `resources` module)


## Other Projects

Current list of other [GRI FOSS Projects](https://gitlab.com/geosol-foss/python/gri-utils/-/blob/main/.docs_other_projects.md) we are building and maintaining.

## License

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