Metadata-Version: 2.4
Name: libxrk
Version: 0.14.0
Summary: Library for reading AIM XRK files from AIM automotive data loggers
Author-email: Christopher Dewan <chris.dewan@m3rlin.net>
Project-URL: Homepage, https://github.com/m3rlin45/libxrk
Project-URL: Repository, https://github.com/m3rlin45/libxrk
Project-URL: Issues, https://github.com/m3rlin45/libxrk/issues
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Cython
Classifier: Environment :: WebAssembly :: Emscripten
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.26.0; python_version < "3.13"
Requires-Dist: numpy>=2.1.0; python_version >= "3.13" and python_version < "3.14"
Requires-Dist: numpy>=2.4.0; python_version >= "3.14"
Requires-Dist: cython>=3.0.0
Requires-Dist: pyarrow>=18.1.0; python_version < "3.14"
Requires-Dist: pyarrow>=22.0.0; python_version >= "3.14"
Provides-Extra: test
Requires-Dist: pytest>=7.0.0; extra == "test"
Requires-Dist: parameterized>=0.9.0; extra == "test"
Dynamic: license-file

# libxrk

A Python library for reading AIM XRK and XRZ files from AIM automotive data loggers.

## Features

- Read AIM XRK files (raw data logs)
- Read AIM XRZ files (zlib-compressed XRK files)
- Parse track data and telemetry channels
- GPS coordinate conversion and lap detection
- High-performance Cython implementation
- Supports Python 3.10 - 3.14

## Installation

### Install from PyPI

```bash
pip install libxrk
```

### Install from Source

#### Prerequisites

On Ubuntu/Debian:
```bash
sudo apt install build-essential python3-dev
```

##### Install with uv

```bash
uv sync
```

The Cython extension will be automatically compiled during installation.

## Usage

```python
from libxrk import aim_xrk

# Read an XRK file
log = aim_xrk('path/to/file.xrk')

# Read an XRZ file (automatically decompressed)
log = aim_xrk('path/to/file.xrz')

# Access channels (each channel is a PyArrow table with 'timecodes' and value columns)
for channel_name, channel_table in log.channels.items():
    print(f"{channel_name}: {channel_table.num_rows} samples")

# Get all channels merged into a single PyArrow table
# (handles different sample rates with interpolation/forward-fill)
merged_table = log.get_channels_as_table()
print(merged_table.column_names)

# Convert to pandas DataFrame
df = merged_table.to_pandas()

# Access laps (PyArrow table with 'num', 'start_time', 'end_time' columns)
print(f"Laps: {log.laps.num_rows}")
for i in range(log.laps.num_rows):
    lap_num = log.laps.column("num")[i].as_py()
    start = log.laps.column("start_time")[i].as_py()
    end = log.laps.column("end_time")[i].as_py()
    print(f"Lap {lap_num}: {start} - {end}")

# Access metadata
print(log.metadata)
# Includes: Driver, Vehicle, Venue, Log Date/Time, Logger ID, Logger Model, Device Name, etc.
```

### Channel Value Types

A channel's value column has the type its samples are stored in. Most analog, IMU, gyro and CAN channels are stored as half floats, so their column is **float16** (Arrow `halffloat`, numpy `float16`), not float32:

| Samples in the file | Value column |
|---------------------|--------------|
| float16 | float16 |
| float32 | float32 |
| int16, uint16, int32, uint8 | the same integer type |
| any channel in volts (`V`) | float32 (float64 if stored as an integer) |
| GPS-derived channels | float64 or float32 |

Channels in volts are the exception: they are stored in millivolts and divided by 1000, and the result is not a float16 value, so they are float32.

**Cast float16 columns before doing arithmetic on them.** Neither pyarrow nor numpy handles them well:

- `pyarrow.compute` has no half-float kernels for aggregation (`pc.mean`, `pc.sum`, `pc.min_max`), arithmetic (`pc.multiply`, `pc.abs`, `pc.round`), comparison (`pc.greater`, `pc.equal`), `pc.unique` or `Table.sort_by`; they raise `ArrowNotImplementedError`.
- numpy computes in float16: `values.sum()` overflows to `inf` above 65504 and `values.mean()` is rounded to 11 significant bits.

The cast is exact and takes one line:

```python
import numpy as np
import pyarrow as pa
import pyarrow.compute as pc

column = log.channels['LateralAcc'].column('LateralAcc')   # halffloat

pc.mean(pc.cast(column, pa.float32()))                      # pyarrow
column.to_numpy().astype(np.float32).mean()                 # numpy
```

`to_numpy()`, `to_pandas()` (a `float16` column), `Table.filter`/`take`/`slice`, `pa.concat_tables`, `pc.cast` and Parquet or Arrow IPC files all work on float16 columns as they are, as do all `LogFile` methods.

Resampling (`resample_to_channel`, `resample_to_timecodes`, `get_channels_as_table`) returns interpolated float16 channels as **float32**, because interpolated values are not float16 values. A merged table of a parsed file therefore has no float16 column.

### Filtering and Resampling

```python
from libxrk import aim_xrk

log = aim_xrk('session.xrk')

# Select specific channels
gps_log = log.select_channels(['GPS Latitude', 'GPS Longitude', 'GPS Speed'])

# Filter to a time range (milliseconds, inclusive start, exclusive end)
segment = log.filter_by_time_range(60000, 120000)

# Filter to a specific lap
lap5 = log.filter_by_lap(5)

# Combine filtering and channel selection
lap5_gps = log.filter_by_lap(5, channel_names=['GPS Latitude', 'GPS Longitude'])

# Resample all channels to match a reference channel's timebase
aligned = log.resample_to_channel('GPS Speed')

# Resample to a custom timebase
import pyarrow as pa
target = pa.array(range(0, 100000, 100), type=pa.int64())  # 10 Hz
resampled = log.resample_to_timecodes(target)

# Chain operations for analysis workflows
df = (log
    .filter_by_lap(5)
    .select_channels(['Engine RPM', 'GPS Speed'])
    .resample_to_channel('GPS Speed')
    .get_channels_as_table()
    .to_pandas())
```

All filtering and resampling methods return new `LogFile` instances (immutable pattern), enabling method chaining for complex analysis workflows.

### Channel Metadata

Each channel carries typed metadata accessible via `ChannelMetadata`:

```python
from libxrk import aim_xrk, ChannelMetadata

log = aim_xrk('session.xrk')

# Extract typed metadata from a channel
meta = ChannelMetadata.from_channel_table(log.channels['Engine RPM'])
print(meta.units)        # "rpm"
print(meta.dec_pts)      # 0
print(meta.interpolate)  # True
print(meta.function)     # "Engine RPM"

# Or from a PyArrow field directly
field = log.channels['Engine RPM'].schema.field('Engine RPM')
meta = ChannelMetadata.from_field(field)

# Create metadata for custom channels
meta = ChannelMetadata(units="m/s", dec_pts=1, interpolate=True)
field = pa.field("speed", pa.float32(), metadata=meta.to_field_metadata())
```

Available fields: `units`, `dec_pts`, `interpolate`, `function`, `source_type`, `source_channel_id`, `device_tag`, `cal_value_1`, `cal_value_2`, `display_range_min`, `display_range_max`.

## Using libxrk from other languages

`crates/libxrk-ffi` builds the Rust parser as a shared library with a small C
ABI, for programs that are not Python. It hands out exactly what the Python
`LogFile` holds: each channel and the laps table as Arrow record batches
through the [Arrow C Data Interface](https://arrow.apache.org/docs/format/CDataInterface.html)
(`ArrowArrayStream`), and the metadata as a JSON document.

```bash
just ffi-build    # target/release/libxrk_ffi.so, libxrk_ffi.dylib or xrk_ffi.dll
```

```c
char *err = NULL;
XrkSession *session = xrk_open_path("session.xrk", &err);   /* or xrk_open_bytes */
if (!session) { fprintf(stderr, "%s\n", err); xrk_string_free(err); return 1; }

for (size_t i = 0; i < xrk_channel_count(session); i++) {
    char *name = xrk_channel_name(session, i);
    struct ArrowArrayStream stream;
    if (xrk_channel_stream(session, i, &stream) == 0) {
        /* one record batch: "timecodes" (int64 ms) and the channel's values */
        stream.release(&stream);
    }
    xrk_string_free(name);
}

char *metadata = xrk_metadata_json(session);   /* the LogFile.metadata dict */
xrk_string_free(metadata);
xrk_close(session);
```

The functions, their error values and the ownership rules are documented in
[`crates/libxrk-ffi/src/lib.rs`](crates/libxrk-ffi/src/lib.rs). There is no
released binary yet: build the crate from a pinned commit.

## Development

### Quick Check
```bash
# Run all quality checks (format check, type check, tests)
just check
```

### Code Formatting

This project uses [Black](https://black.readthedocs.io/) for code formatting.

```bash
# Format all Python files
just format
```

### Type Checking

This project uses [mypy](https://mypy.readthedocs.io/) for static type checking.

```bash
# Run type checker on all Python files
just typecheck
```

### Running Tests

This project uses [pytest](https://pytest.org/) for testing.

```bash
# Run all tests
just test

# Run specific test file
uv run pytest tests/test_xrk_loading.py

# Run tests with coverage
uv run pytest --cov=libxrk
```

### Testing with Pyodide (WebAssembly)

You can test the library in a WebAssembly environment using Pyodide.
This requires Node.js to be installed.

```bash
# Build and run tests in Pyodide (Python 3.14)
just pyodide-test
```

Note: Pyodide tests run automatically in CI via GitHub Actions.

### Building

```bash
# Build CPython wheel and sdist
uv build

# Build all wheels (CPython, Pyodide/WebAssembly, and sdist)
just build-all
```

### Clean Build

```bash
# Clean all build artifacts and rebuild
rm -rf build/ dist/ src/libxrk/*.so && uv sync
```

## Testing

The project includes end-to-end tests that validate XRK and XRZ file loading and parsing.

Test files are located in `tests/test_data/` and include real XRK and XRZ files for validation.

## Credits

This project incorporates code from [TrackDataAnalysis](https://github.com/racer-coder/TrackDataAnalysis) by Scott Smith, used under the MIT License.

## License

MIT License - See LICENSE file for details.
