Metadata-Version: 2.4
Name: bivital
Version: 0.1.15
Summary: BiVital Library
Author-email: University Bielefeld <ks-bivital-support@techfak.uni-bielefeld.de>
License: MIT
Project-URL: Homepage, https://bivital.eu/
Project-URL: Repository, https://gitlab.ub.uni-bielefeld.de/bi-vital-open-source/py_bivital.git
Project-URL: Issues, https://gitlab.ub.uni-bielefeld.de/bi-vital-open-source/py_bivital/-/issues
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
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 :: Python :: 3.15
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: <3.16,>=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pandas<4.0,>=2.2
Requires-Dist: pyserial<4.0,>=3.5
Requires-Dist: matplotlib<4.0,>=3.10
Requires-Dist: usb-monitor<2.0,>=1.23
Requires-Dist: ntplib<1.0,>=0.4.0
Requires-Dist: requests<3.0,>=2.32.4
Requires-Dist: bleak<2.0,>=0.22
Requires-Dist: pydfuutil[libusb]<0.12,>=0.11.2
Provides-Extra: notebook
Requires-Dist: jupyterlab<5,>=4; extra == "notebook"
Requires-Dist: ipykernel>=6; extra == "notebook"
Dynamic: license-file

# bivital

[![PyPI - Version](https://img.shields.io/pypi/v/bivital)](https://pypi.org/project/bivital/)
[![Python Versions](https://img.shields.io/pypi/pyversions/bivital.svg)](https://pypi.org/project/bivital/)
[![License](https://img.shields.io/pypi/l/bivital)](https://pypi.org/project/bivital/)

**bivital** is the official Python library for the BI-Vital data workflow.  
It helps you organize, preprocess, and manage measurement projects, series, and raw data collected via BI-Vital systems.

---

## 🚀 Features

- Project structure setup
- Series and data import
- Label management
- Command-line tool (`bvtool`) for fast interaction
- Optional Jupyter workflow extras (`[notebook]`)
- Bluetooth (BLE) API and CLI support

---

## 📦 Installation

> **Supports CPython 3.10–3.15.** Python 3.12 is a conservative choice.
> Python 3.9 and older, and Python 3.16 and newer, are outside the declared range.
> New Python versions are added after dependency and runtime checks.
>
> Python 3.10 uses pandas 2; newer Python versions can use pandas 2 or 3.
> pip selects compatible releases automatically. No compiler is required for the
> tested Windows x64 installations. Other CPU architectures, PyPy and
> free-threaded CPython builds have not been validated.

### Stable release (PyPI)
```bash
python -m pip install "bivital>=0.1.12"
```

### With notebook extras
Notebook execution was tested on Python 3.10–3.15 under Windows x64, and on
Python 3.10 and 3.15 under Ubuntu x64. The Jupyter
dependency chain currently builds PyYAML from source using the pure-Python
implementation; the optional C extension is not required. Do not force
`--only-binary=:all:` when installing the notebook extra on Python 3.15.

```bash
python -m pip install "bivital[notebook]>=0.1.12"
```

### From source (local checkout)
```bash
# in the repo root
pip install .
# or in editable/development mode (plus notebook extras)
pip install -e ".[notebook]"
```

---

## 🛠 Usage

### Command-Line Interface (CLI)
```bash
bvtool -h
bvtool project -p PATH -n NAME
bvtool series  -p PATH -n NAME
bvtool data    -p PATH -s pc
bvtool label   -p PATH
bvtool commander
bvtool time sync
bvtool time calibrate
```

STM firmware derives its USB serial number from the factory UID using the
STM32L476 ROM DFU format: eight hex digits of UID0 + UID2 (32-bit sum), followed
by the upper four hex digits of UID1. Serial and DFU therefore report the same
12-character serial number, independent of the nRF identity. The first update
from the shared legacy USB
serial number can change the Windows COM port. The Python STM updater follows
the unique USB serial number or physical USB location, including when other
BI-Vitals are connected. BLE identifiers and the ROM DFU identity are unchanged.

Commander provides Upload and Download actions for `LogConf.txt` and
`UserConf.txt`, plus Record CRC and User CRC columns for comparing devices.
Actions use selected serial devices, or all idle serial devices when none are
selected. Configuration downloads from multiple devices use separate device
folders. User Configuration uploads require the firmware JSON configuration
interface and are validated by the device before replacing saved settings.
Missing settings in older files use the target firmware defaults. Unknown and
duplicate settings are rejected; reset requirements appear in device details.

Commander calibration uses at least ten valid measurement rounds, spaced at least
one minute apart, and at least ten minutes of observation. Drift uncertainty is estimated
from USB/NTP repeatability (with a timestamp-resolution noise floor) and agreement
between the evaluation fit and fits of its two halves. A change-point detector
excludes supported initial/transient sections after confirmation in three distinct
minute rounds. Each side of a detected change must span at least 20 minutes;
detection uses a penalized two-line fit and the measured noise floor, independently
of the requested ppm target. Raw history is retained. The remaining evaluation
history grows without a fixed sliding-window limit, allowing tighter targets such
as 0.01 ppm when noise, reference stability and device stability permit it. A factor of 2.5 is applied
to the statistical slope error; the split-window allowance is added separately.
This is an estimated calibration quality, not an absolute worst-case guarantee.
Constant NTP offsets and absolute network-delay bounds do not limit the drift fit.
Three successful minute checks are required before automatically saving. Failed
or inconsistent NTP rounds are skipped and pause the success counter; a valid
round that fails the quality target resets the counter but retains the data.
Commander continues monitoring the unchanged active clock and automatically saves
updated corrections while the quality gates remain passed. Only a changed integer
ppb value triggers another flash write (at most once per measurement round).
Unchanged values can still receive a refined in-memory error estimate. If quality
fails, automatic updates pause and the last accepted correction/error are kept.
The compact status shows the saved correction and its accepted error; detailed
measurement progress is available in its tooltip and the log. Activation remains
restart pending. Apply ends calibration and restarts the device with the currently saved settings;
Continue keeps measuring. Before the target is reached, Apply anyway explicitly
uses the latest estimate (at least three samples); Abort ends measurement and
retains saved settings. If several devices are being calibrated, all must reach
the target before the two-button Apply/Continue dialog is shown. The standalone
`bvtool time calibrate --auto` uses the same quality checks, then saves, restarts
and finishes. Longer CLI observation/sample limits remain supported.

### Recordings

```bash
bvtool recording convert log00.bin -o log00.csv
bvtool recording convert log00.bin
bvtool recording view log00.bin log01.bin log02.csv
bvtool recording view log00.bin 20260723_124839.csv
```

The recording viewer is hosted at
[bivital.eu](https://bivital.eu/docs/webtools/web-viewer/); decoding and plotting
happen locally in the browser. The Python command starts a small localhost adapter
which passes command-line files to the hosted viewer. CSV recordings are converted
in the browser to the same internal binary representation used for BIN recordings.
Without `-o`, `recording convert` opens a sparse millisecond terminal table.
One app annotation `.csv` can be added globally; loading another replaces it.
The viewer starts with a 30-second detail range, pre-aggregates the full
overview while indexing and provides two point cursors for Δt and Δy.
Choose `Set A` or `Set B`, then click anywhere in a detail plot to place it.

### BLE (via `bvtool`)
```bash
# Scan BI-Vital devices
bvtool ble scan

# Read one value (short device token from name is supported)
bvtool ble read --address <XXXX> battery_level

# Write one value
bvtool ble write --address <XXXX> led_color green

# Stream one or multiple values
bvtool ble stream --address <XXXX> heart_rate.bpm
bvtool ble stream --address <XXXX> heart_rate.bpm,motion_raw.acc_ms2
```

### Python (minimal check)
```python
import bivital
print("bivital version:", getattr(bivital, "__version__", "unknown"))
```

---

## 📂 Example Project Structure
```
BiVitalProject/
├── Series1/
│   └── MAC_01/
│       └── log_01.csv
└── Series2/
    └── ...
```

---

## 💬 Support & Contributing

- Issues & feature requests: https://gitlab.ub.uni-bielefeld.de/bi-vital-open-source/py_bivital/-/issues  
- Homepage: https://bivital.eu/

Contributions are welcome—please open an issue to discuss changes first.

---

## 📜 License

MIT © University Bielefeld

### Calibration diagnostics

Commander and `bvtool time calibrate` automatically write local JSONL diagnostics
(one JSON object per line) to `~/.bivital/calibration_logs/`. Set
`BIVITAL_CALIBRATION_LOG_DIR` to choose another directory. Each run has a unique
file; these files are not uploaded or automatically deleted.

The versioned records include session parameters, raw NTP request timestamps,
round consensus and uncertainty, USB timestamp samples, full incremental drift
history, selected history boundaries, fit/quality decisions and confirmed writes.
Units are encoded in field names (`_ms`, `_ns`, `_ppm`, `_ppb`). Non-finite
estimates are represented by JSON `null`. Records are flushed after each event;
logging failure emits a warning and does not interrupt calibration. USB bursts
are captured before writing their diagnostic records. Device IDs/ports are
included; consider this before sharing a log.

The calibration overview separates **Current**, **Best stable** (lowest uncertainty after full qualification, with time), and **Saved** (confirmed device setting). Automatic
updates retain the best fully qualified estimate rather than replacing it with
a worse estimate that merely still passes the target. Best stable is updated only after the configured observation limits and three
consecutive successful quality checks. Preliminary estimates are kept separately
for explicit application and never appear as a stable best.

The stop dialog has separate **Stop calibration** and **Apply calibration**
controls. Stop ends monitoring without writes or restarts. The top-right close
button returns to the running calibration. **Completed** retains qualified,
saved calibrations; **Completed + preliminary** also saves the best estimates
for devices which have not met the target. Devices without results stay unchanged.
**Restart to apply calibration** is checked by default; clear it to save without
restarting. Buttons are enabled only when the corresponding results exist.

The dialog shows each nonempty status category once: finished (green),
preliminary (orange), no results (red). IDs are sorted by uncertainty, or by ID
when no uncertainty is available. Device tooltips show position and port;
category tooltips explain saved/pending results and missing-result reasons.
A reference round whose NTP scatter exceeds the selected reference uncertainty
is logged and skipped before device measurements enter the calibration history.
