diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aec131d..91b5730 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,5 +38,28 @@ jobs: with: python-version: ${{ matrix.python-version }} cache: pip - - run: pip install -r requirements-dev.txt + - run: pip install -e ".[dev]" - run: pytest -q + + package: + # Build the distributions and prove that a core-only install (no pandas, + # scipy or matplotlib) can still run the flashing and logging commands. + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: pip install build + - run: python -m build + - name: Core-only install + run: | + python -m venv /tmp/core + /tmp/core/bin/pip install dist/*.whl + /tmp/core/bin/nav --version + /tmp/core/bin/nav --workspace /tmp/ws doctor + /tmp/core/bin/python -c "import sys, navkit.cli, navkit.flash, navkit.firmware, navkit.logger; assert not {'pandas','scipy','matplotlib'} & set(sys.modules)" + - uses: actions/upload-artifact@v4 + with: + name: dist + path: dist/ diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..455eacf --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,57 @@ +name: Release + +# Pushing a tag like v0.2.0 builds the package and publishes a GitHub Release +# with the wheel and sdist attached. The tag must match the version in +# src/navkit/__init__.py. +# +# PyPI: set the repository variable PYPI_PUBLISH=true after registering this +# workflow as a trusted publisher for the `navkit` project on pypi.org +# (Publishing → Add a new pending publisher: this repo, workflow release.yml, +# environment "pypi"). + +on: + push: + tags: ["v*"] + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: pip install build + - run: python -m build + - name: Check the tag matches the package version + run: | + version="$(ls dist/*.tar.gz | sed -E 's/.*navkit-(.*)\.tar\.gz/\1/')" + test "v${version}" = "${GITHUB_REF_NAME}" || { + echo "Tag ${GITHUB_REF_NAME} does not match package version ${version}"; exit 1; } + - run: sha256sum dist/* > dist/SHA256SUMS + - name: Publish GitHub release + env: + GH_TOKEN: ${{ github.token }} + run: gh release create "$GITHUB_REF_NAME" dist/* --title "navkit $GITHUB_REF_NAME" --generate-notes + - uses: actions/upload-artifact@v4 + with: + name: dist + path: | + dist/*.whl + dist/*.tar.gz + + pypi: + needs: build + if: vars.PYPI_PUBLISH == 'true' + runs-on: ubuntu-latest + environment: pypi + permissions: + id-token: write + steps: + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist/ + - uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 0860b3c..cae60cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,32 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Added +- **`navkit` package and the `nav` command.** The pipeline is now an + installable Python package (`pip install navkit`, `navkit[pipeline]` for + the analysis stages) with subcommands: `flash`, `firmware`, `ports`, + `doctor`, `record`, `process`, `calibrate`, `sessions`, `log`, `wizard`, + `where`. +- `nav flash`: detects the chip, downloads the matching firmware release, + verifies its SHA-256 and flashes it with esptool. Images are cached. +- `nav doctor`: checks Python, serial access, drivers and the workspace. +- A workspace directory (`~/navkit`, `--workspace`, or `NAVKIT_HOME`) holds + sessions, outputs and calibration parameters, so the tool no longer has + to run from a source checkout. + +### Fixed +- On Windows, writing the session summary failed because of the `μ` in it; + all files are now written as UTF-8. + +### Changed +- Modules moved from `pipeline/` to `src/navkit/`; `session_trimmer.py` is + now `trimmer.py`. +- Flashing and logging no longer import pandas, scipy or matplotlib. +- Without a terminal attached, a missing calibration file aborts the run + (strict) instead of waiting for input. +- `run_pipeline.py` is a thin wrapper around the wizard and keeps using the + checkout as its workspace. + ### Added - `pipeline/wire.py`: decoder for the firmware's binary wire protocol v1 (COBS framing, CRC-16), tested against a golden stream produced by the diff --git a/README.md b/README.md index d72d555..aefb438 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ The pipeline follows a deterministic multi-stage flow: | Stage | Module | Responsibility | Output | |---|---|---|---| | **1. Log** | `logger.py` + `wire.py` | Binary frames (or CSV debug stream) → CSV | `raw/raw.csv`, `raw/firmware.json` | -| **2. Trim** | `session_trimmer.py` | Signal/Noise segmentation | `clean/signal_v1.csv` | +| **2. Trim** | `trimmer.py` | Signal/Noise segmentation | `clean/signal_v1.csv` | | **3. Diagnose** | `diagnostics.py` | Timing, jitter & alignment | `diagnostics/timing_v1.json` | | **4. Calibrate** | `calibrator.py` | Bias, scale & hard-iron | `calibrated/calibrated_v1.csv` | | **5. Plot** | `plotter.py` | Visual validation | `outputs/plots/*.png` | @@ -40,7 +40,7 @@ graph LR subgraph Pipeline["Repo 2: Data Pipeline"] LOG["logger.py
Serial Listener"] --> RAW[/"raw.csv"/] - RAW --> TRIM["session_trimmer.py
Signal Trimmer"] + RAW --> TRIM["trimmer.py
Signal Trimmer"] TRIM --> CLN[/"signal_v1.csv"/] @@ -184,62 +184,112 @@ Each session is categorized as: --- -## Repo-02 Structure +## Install + +`navkit` is the Python package in this repo; it installs the `nav` command. + +```bash +# Flash and log only (small: pyserial + esptool) +pip install "navkit @ git+https://github.com/multi-sensor-navigation-system/data-pipeline" + +# Everything, including trim / diagnose / calibrate / plot +pip install "navkit[pipeline] @ git+https://github.com/multi-sensor-navigation-system/data-pipeline" ``` -data-pipeline/ -├── data/ # Raw and processed session data -├── outputs/ -│ ├── plots/ # Visual validation plots -│ └── reports/ # Markdown session summaries -├── pipeline/ -│ ├── logger.py # High-speed UART listener -│ ├── wire.py # Wire protocol v1 decoder (binary + CSV detection) -│ ├── session_trimmer.py # Signal/Noise segmenter -│ ├── diagnostics.py # Timing & jitter analysis -│ ├── calibrator.py # Bias, scale & hard-iron calibration -│ └── plotter.py # Multi-stage signal visualisation -├── run_pipeline.py # Unified CLI entry point -└── README.md # Technical documentation + +From a checkout, for development: + +```bash +python -m venv .nav && source .nav/bin/activate +pip install -e ".[dev]" +pytest ``` + +Requires Python 3.10+. + --- -## Setup +## Quick start -1. **Environment:** Create a virtualenv and install dependencies: - ```bash - python -m venv .nav - source .nav/bin/activate - pip install -r requirements.txt - ``` -2. **Hardware:** Connect the ESP32 via USB and identify the port (e.g., `/dev/cu.usbserial-0001`). -3. **Run:** Execute the pipeline and follow the prompts. +```bash +nav doctor # is this machine ready? is a board connected? +nav flash # detect the board, download the latest firmware, verify, flash +nav record --type static_calib --note "flat on desk" # log (Ctrl-C to stop), then process +nav record --type free_label --note "bike ride" +nav sessions +``` + +`nav wizard` walks through the same steps as an interactive menu. --- -## Automation & CLI +## Commands -The pipeline can be run interactively or fully automated via command-line arguments. +| Command | What it does | +|---|---| +| `nav doctor [--online]` | Checks Python, serial access, drivers, the workspace and (with `--online`) firmware releases | +| `nav ports` | Lists serial ports that look like a board | +| `nav flash [--board ID] [--version TAG] [--port P]` | Downloads a firmware release, verifies its SHA-256 and flashes it. `--board auto` (default) detects the chip. `--file image.bin` flashes a local build | +| `nav firmware list` / `nav firmware fetch` | Lists releases and their boards / downloads an image without flashing | +| `nav record --type T [--note N]` | Logs a new session from the board, then runs the whole pipeline on it | +| `nav process SESSION [--from STEP]` | Runs the pipeline on an existing session, from `trim`, `diagnose`, `calibrate` or `plot` | +| `nav calibrate SESSION` | Computes calibration parameters from a static session | +| `nav sessions` | Lists sessions with type, duration and validity | +| `nav log [-o FILE]` | Logs the serial stream to one CSV file and does nothing else | +| `nav wizard` | Interactive menu | +| `nav where` | Shows where sessions, outputs and cached firmware live | -```bash -# Interactive mode (default) -python run_pipeline.py +Session types: `static_calib`, `accel_6pos`, `mag_rotation`, `free_label`. + +When a dynamic session has no calibration parameters, `record` and `process` ask what to do. Decide up front with `--strict` (abort), `--allow-uncalibrated` (continue; the session is flagged `valid_for_analysis: false`) or `--calib-path FILE`. A custom path wins over the other two. Without a terminal attached the default is strict. + +`python run_pipeline.py` still works from a checkout and uses the checkout itself as the workspace. + +--- + +## Workspace + +Sessions, plots and calibration parameters live in one directory, the workspace: -# Automated mode (Action 2 = Run on existing, Action 3 = Re-run from step) -python run_pipeline.py --action 2 --session-dir data/session_XYZ --calib-mode 0 ``` -### Key CLI Arguments -| Argument | Options | Description | -|---|---|---| -| `--action` | `1-5` | Choose log, process, re-run, calibrate or list | -| `--session-type` | `static_calib`, `free_label`, etc | Set the session intent | -| `--session-dir` | session_id | Target session for processing | -| `--start-from` | `trim`, `diagnose`, `calibrate`, etc | Entry point for re-runs | -| `--calib-mode` | `0` (Strict), `1` (Permissive) | Handling of missing params | -| `--calib-path` | path/to/params.json | Custom path for calibration params | +~/navkit/ +├── data// +│ ├── raw/ raw.csv, firmware.json +│ ├── clean/ signal_v*.csv, noise_v*.csv, cleaning_v*.json +│ ├── diagnostics/ timing_v*.json, jitter_v*.png, alignment_v*.png +│ ├── calibrated/ calibrated_v*.csv, calibration_v*.json +│ └── metadata.json +├── outputs/ +│ ├── plots// +│ └── reports/ +└── calibration_params.json +``` -*If --calib-path is provided, it overrides --calib-mode.* +It defaults to `~/navkit`. Change it with `nav --workspace DIR …` or the `NAVKIT_HOME` environment variable. Downloaded firmware is cached separately in the per-user cache directory (`nav where` prints both). -For complete list, use `python run_pipeline.py --help` +--- + +## Repo-02 Structure +``` +data-pipeline/ +├── src/navkit/ +│ ├── cli.py # The `nav` command +│ ├── pipeline.py # Orchestration, calibration gate, metadata, wizard +│ ├── logger.py # High-speed UART listener +│ ├── wire.py # Wire protocol v1 decoder (binary + CSV detection) +│ ├── trimmer.py # Signal/Noise segmenter +│ ├── diagnostics.py # Timing & jitter analysis +│ ├── calibrator.py # Bias, scale & hard-iron calibration +│ ├── plotter.py # Multi-stage signal visualisation +│ ├── firmware.py # Firmware releases: resolve, download, verify, cache +│ ├── flash.py # esptool wrapper, chip detection +│ ├── doctor.py # Environment checks +│ ├── ports.py # Serial port discovery +│ └── workspace.py # Where sessions and outputs live +├── tests/ # pytest suite on synthetic sessions and a golden wire stream +├── run_pipeline.py # Backwards-compatible entry point (wizard) +├── pyproject.toml # Package metadata and tooling +└── README.md +``` --- diff --git a/pyproject.toml b/pyproject.toml index e03af99..d7da59b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,61 @@ -# Tooling configuration only. Packaging metadata arrives with the navkit -# restructure; until then the pipeline runs from a source checkout. +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "navkit" +dynamic = ["version"] +description = "Host tools for the Multi-Sensor Navigation System: flash firmware, log sessions, calibrate." +readme = "README.md" +license = "MIT" +license-files = ["LICENSE"] +requires-python = ">=3.10" +authors = [{ name = "Shivtej Gaikwad" }] +keywords = ["esp32", "imu", "gps", "sensor-fusion", "calibration", "data-logging"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Science/Research", + "Topic :: Scientific/Engineering", + "Topic :: System :: Hardware", + "Programming Language :: Python :: 3", +] +# Core: everything needed to flash a board and log from it. +dependencies = [ + "pyserial>=3.5", + "esptool>=5.0", + "platformdirs>=4.0", +] + +[project.optional-dependencies] +# Trim, diagnose, calibrate and plot. +pipeline = [ + "pandas>=2.0", + "numpy>=1.24", + "matplotlib>=3.7", + "scipy>=1.10", +] +dev = [ + "navkit[pipeline]", + "pytest>=8.0", + "ruff>=0.6", +] + +[project.scripts] +nav = "navkit.cli:main" + +[project.urls] +Homepage = "https://github.com/multi-sensor-navigation-system" +Repository = "https://github.com/multi-sensor-navigation-system/data-pipeline" +Changelog = "https://github.com/multi-sensor-navigation-system/data-pipeline/blob/main/CHANGELOG.md" + +[tool.hatch.version] +path = "src/navkit/__init__.py" + +[tool.hatch.build.targets.wheel] +packages = ["src/navkit"] + +[tool.hatch.build.targets.sdist] +include = ["src", "tests", "README.md", "LICENSE", "CHANGELOG.md"] [tool.ruff] target-version = "py310" @@ -18,4 +74,3 @@ ignore = [ [tool.pytest.ini_options] testpaths = ["tests"] -pythonpath = [".", "pipeline"] diff --git a/requirements-dev.txt b/requirements-dev.txt deleted file mode 100644 index 795bb0a..0000000 --- a/requirements-dev.txt +++ /dev/null @@ -1,3 +0,0 @@ --r requirements.txt -pytest>=8.0 -ruff>=0.6 diff --git a/requirements.txt b/requirements.txt index ac2641a..7208a60 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,3 @@ -pyserial>=3.5 -pandas>=2.0 -numpy>=1.24 -matplotlib>=3.7 -scipy>=1.10 +# Kept for people who run from a checkout. The package metadata in +# pyproject.toml is the source of truth: pip install -e ".[pipeline]" +-e .[pipeline] diff --git a/run_pipeline.py b/run_pipeline.py index a388b94..ceee2e5 100644 --- a/run_pipeline.py +++ b/run_pipeline.py @@ -1,513 +1,40 @@ #!/usr/bin/env python3 """ -run_pipeline.py — Single entry point for the nav-stack data pipeline. +run_pipeline.py — Backwards-compatible entry point. -Run from the project root: - python run_pipeline.py +Runs the interactive wizard with this checkout as the workspace, exactly as +before. The supported interface is now the `nav` command (see README): -No arguments needed — the script walks you through everything interactively. - -Pipeline order: - 1. logger.py → raw/raw.csv - 2. session_trimmer.py → clean/signal_vi.csv + noise_vi.csv + cleaning_vi.json - 3. diagnostics.py → diagnostics/ jitter + alignment plots + timing_vi.json - 4. calibrator.py → calibrated/calibrated_vi.csv + calibration_vi.json - 5. plotter.py → outputs/plots// raw + clean + calibrated pngs - 6. (this script) → data//metadata.json + outputs/reports/session_level/_summary.md + pip install -e ".[pipeline]" + nav wizard """ import argparse -import importlib.util -import json import sys -import time -from datetime import datetime from pathlib import Path -# ── project paths ─────────────────────────────────────────────────────────────── -ROOT = Path(__file__).parent.resolve() -PIPELINE_DIR = ROOT / "pipeline" -DATA_DIR = ROOT / "data" -OUTPUTS_DIR = ROOT / "outputs" -PARAMS_FILE = ROOT / "calibration_params.json" - -SESSION_TYPES = { - "1": "static_calib", - "2": "accel_6pos", - "3": "mag_rotation", - "4": "free_label", -} - -PIPELINE_STEPS = { - "1": "log", - "2": "trim", - "3": "diagnose", - "4": "calibrate", - "5": "plot", -} - - -# ── helpers ───────────────────────────────────────────────────────────────────── -def hr(char="─", width=52): - print(char * width) - - -def ask(prompt: str, options: dict, default: str | None = None) -> str: - for k, v in options.items(): - print(f"\n [{k}] {v}") - suffix = f" (default {default})" if default else "" - while True: - choice = input(f"\n{prompt}{suffix}: ").strip() or default - if choice in options: - return choice - print(f"\n Please enter one of: {', '.join(options.keys())}") - - -def run_step(label: str, fn, *args, **kwargs): - print(f"\n\n{'─'*52}") - print(f"\n Running: {label}") - print(f"\n{'─'*52}") - t0 = time.time() - result = fn(*args, **kwargs) - elapsed = time.time() - t0 - print(f"\n ✓ done in {elapsed:.1f}s") - return result - - -def import_pipeline(name: str): - spec = importlib.util.spec_from_file_location(name, PIPELINE_DIR / f"{name}.py") - mod = importlib.util.module_from_spec(spec) - spec.loader.exec_module(mod) - return mod - - -# ── session name generation ───────────────────────────────────────────────────── -def make_session_name(session_type: str) -> str: - ts = datetime.now().strftime("%Y%m%d_%H%M%S") - return f"session_{ts}_{session_type}" - - -# ── metadata + summary ────────────────────────────────────────────────────────── -def write_metadata(session_dir: Path, session_type: str, steps_run: list[str], - timing_json: dict | None, calib_json: dict | None, - calib_state: dict | None = None, user_note: str = ""): - meta = { - "session_name": session_dir.name, - "session_type": session_type, - } - - # Add calibration metadata at the top - if calib_state: - meta.update({ - "is_calibrated": calib_state.get("is_calibrated", True), - "calibration_source": calib_json.get("params_source_session", "none") if calib_json else "none", - "calibration_valid": calib_json.get("calibration_valid", True) if calib_json else True, - "user_overridden": calib_state.get("user_overridden", False), - "override_type": calib_state.get("override_type", "none"), - "valid_for_analysis": calib_state.get("valid_for_analysis", True), - }) - if "reason" in calib_state: - meta["reason"] = calib_state["reason"] - else: - # Default for legacy sessions or static_calib where no check was needed - meta.update({ - "is_calibrated": True, - "calibration_source": calib_json.get("params_source_session", "none") if calib_json else "none", - "calibration_valid": calib_json.get("calibration_valid", True) if calib_json else True, - "user_overridden": False, - "override_type": "none", - "valid_for_analysis": True, - }) - - # Enforce consistency: if internal calibration checks failed, it's NOT valid for analysis - if not meta["calibration_valid"]: - meta["valid_for_analysis"] = False - if "reason" not in meta: - meta["reason"] = "Internal calibration check failed (insufficient signal or failed sanity limits)." - - # Dynamic sensor detection from timing analysis - sensor_map = {"imu": "MPU-6050", "mag": "QMC5883L", "baro": "BMP280", "gps": "NEO-6M GPS"} - if timing_json and "sensors" in timing_json: - detected = [sensor_map[s] for s in sensor_map if s in timing_json["sensors"]] - else: - detected = list(sensor_map.values()) - - # Identity reported by the firmware itself (binary builds only). - firmware = _load_json_safe(session_dir / "raw" / "firmware.json") - - meta.update({ - "created_at": datetime.now().isoformat(timespec="seconds"), - "user_note": user_note, - "platform": "ESP32 nav-stack v1", - "firmware": firmware, - "sensors": detected, - "steps_run": steps_run, - "files": { - "raw": "raw/raw.csv", - "signal": f"clean/signal_v{_latest_v(session_dir/'clean','signal')}.csv", - "calibrated": f"calibrated/calibrated_v{_latest_v(session_dir/'calibrated','calibrated')}.csv", - "timing": f"diagnostics/timing_v{_latest_v(session_dir/'diagnostics','timing')}.json", - }, - }) - - if timing_json: - meta["duration_s"] = timing_json.get("total_duration_s") - meta["total_rows"] = timing_json.get("total_rows") - meta["imu_hz"] = timing_json.get("sensors", {}).get("imu", {}).get("actual_hz") - meta["gps_hdop_ok"] = True # already filtered in timing analysis - if calib_json: - meta["gyro_bias"] = calib_json.get("gyro_bias") - meta["accel_scale"] = calib_json.get("accel_scale") - - (session_dir / "metadata.json").write_text(json.dumps(meta, indent=2)) - print("\n ✓ metadata.json written") - return meta - - -def write_summary(session_dir: Path, meta: dict, - timing_json: dict | None, calib_json: dict | None): - rep_dir = OUTPUTS_DIR / "reports" - rep_dir.mkdir(parents=True, exist_ok=True) - - imu = (timing_json or {}).get("sensors", {}).get("imu", {}) - gps = (timing_json or {}).get("sensors", {}).get("gps", {}) - dur = meta.get("duration_s", "?") - dur_min = f"{float(dur)/60:.1f}" if dur != "?" else "?" - - lines = [ - f"# Session {session_dir.name} summary", - "", - "## Overview", - f"- Duration : {dur_min} min ({dur} s)", - f"- Session type : {meta.get('session_type', '?')}", - f"- Platform : {meta.get('platform', '?')}", - f"- Sensors : {', '.join(meta.get('sensors', []))}", - "", - "## Timing", - f"- IMU : p50={imu.get('p50_dt_ms','?')} ms " - f"p95={imu.get('p95_dt_ms','?')} ms " - f"p99={imu.get('p99_dt_ms','?')} ms " - f"actual={imu.get('actual_hz','?')} Hz", - f"- GPS : p50={gps.get('p50_dt_ms','?')} ms", - f"- Gaps : {imu.get('gaps','?')} Dups : {imu.get('duplicates','?')}", - "", - ] - - if calib_json: - gb = calib_json.get("gyro_bias", []) - lines += [ - "## Calibration", - f"- Gyro bias : {gb} °/s", - f"- Post-cal |a| : {calib_json.get('post_cal_accel_mean_g','?')} g (target 1.0)", - f"- Post-cal |B| : {calib_json.get('post_cal_mag_mean_uT','?')} μT", - f"- Baro temp R² : {calib_json.get('baro_model_r2','?')}", - "", - ] - - lines += [ - "## Links", - f"- [Jitter plot](../../data/{session_dir.name}/diagnostics/jitter_v1.png)", - f"- [Alignment plot](../../data/{session_dir.name}/diagnostics/alignment_v1.png)", - f"- [Calibrated data](../../data/{session_dir.name}/calibrated/)", - f"- [Raw plots](../plots/{session_dir.name}/)", - ] - - out = rep_dir / f"{session_dir.name}_summary.md" - out.write_text("\n".join(lines)) - print(f"\n ✓ session summary → {out.relative_to(ROOT)}") - - -def _latest_v(folder: Path, prefix: str) -> int: - if not folder.exists(): - return 1 - files = list(folder.glob(f"{prefix}_v*.csv")) + list(folder.glob(f"{prefix}_v*.json")) - if not files: - return 1 - nums = [] - for f in files: - try: - nums.append(int(f.stem.split("_v")[-1])) - except ValueError: - pass - return max(nums, default=1) - - -def _load_json_safe(path: Path) -> dict | None: - try: - return json.loads(path.read_text()) - except Exception: - return None - - -UNCALIBRATED_STATE = { - "is_calibrated": False, - "user_overridden": True, - "override_type": "allowed uncalibrated", - "valid_for_analysis": False, - "reason": "Missing calibration parameters; run was forced in permissive mode.", -} +ROOT = Path(__file__).parent.resolve() +sys.path.insert(0, str(ROOT / "src")) +from navkit import pipeline, workspace # noqa: E402 -def enforce_calibration_check(session_type: str, args) -> dict: - """Decide how to proceed when calibration params may be missing. - Always returns the calibration-state dict consumed by write_metadata(), - or exits the process when the run must not continue. - """ - global PARAMS_FILE - - state = { - "is_calibrated": True, - "user_overridden": False, - "override_type": "none", - "valid_for_analysis": True - } - - if session_type == "static_calib" or PARAMS_FILE.exists(): - return state - - print(f"\n \033[93m⚠ WARNING: No calibration_params.json found at {PARAMS_FILE}\033[0m") - print(" Dynamic sessions require calibration parameters to produce valid output.") - - # An explicit --calib-path wins over --calib-mode (documented behaviour). - if args.calib_path: - p = Path(args.calib_path) - if p.is_file(): - PARAMS_FILE = p - print(f" [Auto] Using custom params file: {PARAMS_FILE}") - state.update({ - "user_overridden": True, - "override_type": "custom path provided", - }) - return state - print(" [Auto] Custom params file not found. Aborting.") - sys.exit(1) - - if args.calib_mode == "0": - print(" [Auto] Aborting (strict mode).") - sys.exit(1) - if args.calib_mode == "1": - print(" [Auto] Continuing without calibration (permissive mode).") - state.update(UNCALIBRATED_STATE) - return state - - opts = { - "0": "Abort pipeline (strict mode: run a static_calib session first)", - "1": "Continue without calibration (permissive mode: NOT suitable for analysis)", - "p": "Enter custom path to a calibration_params.json file", - } - choice = ask("How to proceed?", opts, default="0") - if choice == "1": - print(" Continuing in permissive mode. 'calibrate' step will be skipped.\nOutputs NOT valid for analysis.\n") - state.update(UNCALIBRATED_STATE) - return state - if choice == "p": - custom_path = input(" Enter full path to parameters file: ").strip() - p = Path(custom_path) - if p.is_file(): - PARAMS_FILE = p - print(f"\n Using custom params file: {PARAMS_FILE}") - state.update({ - "user_overridden": True, - "override_type": "custom path provided", - }) - return state - print(" File not found. Aborting.") - sys.exit(1) - - print(" Aborting. Please run a static_calib session to generate parameters.") - sys.exit(1) - - -# ── main menu ────────────────────────────────────────────────────────────────── -def menu_new_session(args) -> tuple[str, Path, str]: - print("\nSession type:") - session_type = args.session_type if args.session_type else SESSION_TYPES[ask("Select type", SESSION_TYPES, default="1")] - name = make_session_name(session_type) - session_dir = DATA_DIR / name - session_dir.mkdir(parents=True, exist_ok=True) - (session_dir / "raw").mkdir(exist_ok=True) - print(f"\n\n Session folder: data/{name}") - - # Prompt for session note for all new sessions - user_note = args.user_note if args.user_note else input("\n Enter a note for this session (e.g., 'desk', 'bike ride') [none]: ").strip() - - return session_type, session_dir, user_note - - -def menu_existing_session(args) -> Path: - sessions = sorted([d for d in DATA_DIR.iterdir() if d.is_dir()], reverse=True) - if not sessions: - print(" No sessions found in data/. Run a new session first.") - sys.exit(0) - opts = {str(i+1): s.name for i, s in enumerate(sessions[:10])} - if args.session_dir: - p = Path(args.session_dir) - if p.exists(): return p - print(f"\n Session dir {p} not found.") - sys.exit(1) - print("\nExisting sessions (most recent first):") - idx = ask("Select session", opts, default="1") - return sessions[int(idx)-1] - - -def menu_from_step(args) -> str: - print("\nStart from step:") - # Filter out 'log' since re-running from log on an existing session is redundant - steps = {k: v for k, v in PIPELINE_STEPS.items() if v != "log"} - return args.start_from if args.start_from else steps[ask("Select step", steps, default="2")] - - -# ── pipeline runner ───────────────────────────────────────────────────────────── -def run_pipeline(session_dir: Path, session_type: str, start_from: str = "log", args=None, calib_state=None, user_note: str = ""): - steps_run = [] - timing_json = None - calib_json = None - order = ["log", "trim", "diagnose", "calibrate", "plot"] - start_idx = order.index(start_from) - - # ── 1. Log ──────────────────────────────────────────────────────────────── - if order.index("log") >= start_idx: - logger = import_pipeline("logger") - raw_path = session_dir / "raw" / "raw.csv" - print(f"\n\n Logger will write to: data/{session_dir.name}/raw/raw.csv") - print(" Press Ctrl-C in the logger to stop and continue the pipeline.\n") - logger.log_session(raw_path) - steps_run.append("log") - - # ── 2. Trim ─────────────────────────────────────────────────────────────── - if order.index("trim") >= start_idx: - trimmer = import_pipeline("session_trimmer") - run_step("session_trimmer", trimmer.run, session_dir) - steps_run.append("trim") - - # ── 3. Diagnose ─────────────────────────────────────────────────────────── - if order.index("diagnose") >= start_idx: - diagnostics = import_pipeline("diagnostics") - json_path = run_step("diagnostics", diagnostics.run, session_dir) - timing_json = _load_json_safe(json_path) - steps_run.append("diagnose") - - # ── 4. Calibrate ────────────────────────────────────────────────────────── - if order.index("calibrate") >= start_idx: - calibrator = import_pipeline("calibrator") - - # Always compute new parameters if this is a calibration session - if session_type == "static_calib": - print("\n Computing NEW calibration params from this static session...") - # Use the session note if we're in Action 1, otherwise prompt - note = user_note if user_note else input(" Enter a note for this calibration (e.g., 'desk', 'bike') [none]: ").strip() - run_step("compute_params", calibrator.compute_params, session_dir, PARAMS_FILE, note) - - if not PARAMS_FILE.exists(): - print(f"\n ⚠ calibration_params.json not found at {PARAMS_FILE}") - print(" Run a static_calib session first to generate it.") - print(" Skipping calibration application step.") - else: - run_step("calibrator", calibrator.apply_params, session_dir, PARAMS_FILE) - v = _latest_v(session_dir / "calibrated", "calibration") - calib_json = _load_json_safe(session_dir / "calibrated" / f"calibration_v{v}.json") - steps_run.append("calibrate") - - # ── 5. Plot ─────────────────────────────────────────────────────────────── - if order.index("plot") >= start_idx: - plotter = import_pipeline("plotter") - plots_dir = OUTPUTS_DIR / "plots" / session_dir.name - plots_dir.mkdir(parents=True, exist_ok=True) - # Plot raw, clean, calibrated - raw_csv = session_dir / "raw" / "raw.csv" - sig_csv = sorted((session_dir / "clean").glob("signal_v*.csv")) - cal_csv = sorted((session_dir / "calibrated").glob("calibrated_v*.csv")) - for csv, tag in ([(raw_csv, "raw")] + - [(p, f"clean_v{i+1}") for i, p in enumerate(sig_csv)] + - [(p, f"calibrated_v{i+1}") for i, p in enumerate(cal_csv)]): - if csv.exists(): - run_step(f"plotter ({tag})", plotter.run, - csv, plots_dir / f"{tag}.png") - steps_run.append("plot") - - # ── 6. Metadata + summary ───────────────────────────────────────────────── - print(f"\n\n{'─'*52}") - print(" Finalising metadata & summary") - print(f"\n{'─'*52}") - v_t = _latest_v(session_dir / "diagnostics", "timing") - timing_json = timing_json or _load_json_safe( - session_dir / "diagnostics" / f"timing_v{v_t}.json") - v_c = _latest_v(session_dir / "calibrated", "calibration") - calib_json = calib_json or _load_json_safe( - session_dir / "calibrated" / f"calibration_v{v_c}.json") - meta = write_metadata(session_dir, session_type, steps_run, timing_json, calib_json, calib_state=calib_state, user_note=user_note) - write_summary(session_dir, meta, timing_json, calib_json) - - -# ── entry point ──────────────────────────────────────────────────────────────── def main(): parser = argparse.ArgumentParser(description="Nav-Stack Pipeline") parser.add_argument("--action", choices=["1", "2", "3", "4", "5"], help="Action to perform") - parser.add_argument("--session-type", choices=list(SESSION_TYPES.values()), help="For action 1") + parser.add_argument("--session-type", choices=list(pipeline.SESSION_TYPES.values()), help="For action 1") parser.add_argument("--session-dir", type=str, help="For actions 2, 3, 4") - parser.add_argument("--start-from", choices=list(PIPELINE_STEPS.values()), help="For action 3") + parser.add_argument("--start-from", choices=list(pipeline.PIPELINE_STEPS.values()), help="For action 3") parser.add_argument("--user-note", type=str, default="", help="For calibration") parser.add_argument("--calib-mode", choices=["0", "1"], help="0=abort if no calib, 1=continue") parser.add_argument("--calib-path", type=str, help="Custom path for calibration params") args, _ = parser.parse_known_args() - hr("═") - print(" Nav-Stack Pipeline") - hr("═") - - actions = { - "1": "Start new session (log → trim → diagnose → calibrate → plot)", - "2": "Run pipeline on existing raw data", - "3": "Re-run from a specific step", - "4": "Compute calibration params from existing static session", - "5": "List existing sessions", - } - action = args.action if args.action else ask("\nWhat would you like to do?", actions, default="1") - - if action == "1": - session_type, session_dir, user_note = menu_new_session(args) - cs = enforce_calibration_check(session_type, args) - run_pipeline(session_dir, session_type, start_from="log", args=args, calib_state=cs, user_note=user_note) - - elif action == "2": - session_dir = menu_existing_session(args) - meta_path = session_dir / "metadata.json" - meta = _load_json_safe(meta_path) or {} - session_type = meta.get("session_type", "free_label") - user_note = meta.get("user_note", "") - cs = enforce_calibration_check(session_type, args) - run_pipeline(session_dir, session_type, start_from="trim", args=args, calib_state=cs, user_note=user_note) - - elif action == "3": - session_dir = menu_existing_session(args) - meta_path = session_dir / "metadata.json" - meta = _load_json_safe(meta_path) or {} - session_type = meta.get("session_type", "free_label") - user_note = meta.get("user_note", "") - start_from = menu_from_step(args) - cs = enforce_calibration_check(session_type, args) - run_pipeline(session_dir, session_type, start_from=start_from, args=args, calib_state=cs, user_note=user_note) - - elif action == "4": - session_dir = menu_existing_session(args) - calibrator = import_pipeline("calibrator") - user_note = input("\n Enter a note for this calibration (e.g., 'static (desk)', 'dynamic (bike)') [none]: ").strip() - calibrator.compute_params(session_dir, PARAMS_FILE, user_note) - - elif action == "5": - sessions = sorted([d for d in DATA_DIR.iterdir() if d.is_dir()], reverse=True) - print() - for s in sessions: - meta = _load_json_safe(s / "metadata.json") or {} - dur = f"{float(meta['duration_s'])/60:.1f} min" \ - if "duration_s" in meta else "?" - print(f"\n {s.name:<45} {meta.get('session_type','?'):<15} {dur}") - return - - hr("═") - print(" Pipeline complete.") - hr("═") + opts = pipeline.Options( + session_type=args.session_type, session_dir=args.session_dir, start_from=args.start_from, + user_note=args.user_note, calib_mode=args.calib_mode, calib_path=args.calib_path, + ) + pipeline.wizard(workspace.resolve(ROOT), opts, action=args.action) if __name__ == "__main__": diff --git a/src/navkit/__init__.py b/src/navkit/__init__.py new file mode 100644 index 0000000..f9392ab --- /dev/null +++ b/src/navkit/__init__.py @@ -0,0 +1,7 @@ +"""navkit — host tools for the Multi-Sensor Navigation System. + +Flash the firmware, log sessions over serial, and run the trim → diagnose → +calibrate → plot pipeline. +""" + +__version__ = "0.2.0" diff --git a/src/navkit/__main__.py b/src/navkit/__main__.py new file mode 100644 index 0000000..dd8a8c9 --- /dev/null +++ b/src/navkit/__main__.py @@ -0,0 +1,5 @@ +import sys + +from .cli import main + +sys.exit(main()) diff --git a/pipeline/calibrator.py b/src/navkit/calibrator.py similarity index 97% rename from pipeline/calibrator.py rename to src/navkit/calibrator.py index d4d31cc..610b6c8 100644 --- a/pipeline/calibrator.py +++ b/src/navkit/calibrator.py @@ -10,9 +10,9 @@ --apply Apply saved params to any session, adding corrected and derived columns. Saves calibrated_vi.csv + calibration_vi.json. -Called by run_pipeline.py or standalone: - python pipeline/calibrator.py --compute-params data/static_calib_session - python pipeline/calibrator.py --apply data/mag_rot_session --params calibration_params.json +Called by navkit.pipeline or standalone: + python -m navkit.calibrator --compute-params data/static_calib_session + python -m navkit.calibrator --apply data/mag_rot_session --params calibration_params.json Calibration steps applied: 1. Gyroscope bias subtraction (from static session mean per axis) @@ -232,7 +232,7 @@ def compute_params(session_dir: Path, params_path: Path, user_note: str = ""): }, } - params_path.write_text(json.dumps(params, indent=2)) + params_path.write_text(json.dumps(params, indent=2), encoding="utf-8") print(f"\n Gyro bias : gx={gyro_bias[0]:+.4f} gy={gyro_bias[1]:+.4f} gz={gyro_bias[2]:+.4f} °/s") print(f" Accel bias : {[f'{x:+.4f}' for x in accel_bias]}") print(f" Accel scale : {[f'{x:.4f}' for x in accel_scale]}") @@ -277,7 +277,7 @@ def apply_params(session_dir: Path, params_path: Path): print(f" Input : {sig_path.name}") print(f" Params : {params_path.name}") - params = json.loads(params_path.read_text()) + params = json.loads(params_path.read_text(encoding="utf-8")) df = load_signal(sig_path) df_cal = apply_calibration(df, params) @@ -310,7 +310,7 @@ def apply_params(session_dir: Path, params_path: Path): "post_cal_accel_mean_g": round(accel_after, 4), "post_cal_mag_mean_uT": round(mag_after, 2), } - out_json.write_text(json.dumps(calib_meta, indent=2)) + out_json.write_text(json.dumps(calib_meta, indent=2), encoding="utf-8") print(f" Post-cal |a| = {accel_after:.4f} g (target 1.0000)") print(f" Post-cal |B| = {mag_after:.2f} μT") diff --git a/src/navkit/cli.py b/src/navkit/cli.py new file mode 100644 index 0000000..5fa010b --- /dev/null +++ b/src/navkit/cli.py @@ -0,0 +1,289 @@ +"""The `nav` command.""" + +import argparse +import sys +from datetime import datetime +from pathlib import Path + +from . import __version__, workspace + +SESSION_TYPES = ["static_calib", "accel_6pos", "mag_rotation", "free_label"] +STEPS = ["trim", "diagnose", "calibrate", "plot"] + + +def _add_calib_options(p: argparse.ArgumentParser) -> None: + g = p.add_mutually_exclusive_group() + g.add_argument("--strict", dest="calib_mode", action="store_const", const="0", + help="abort if no calibration parameters exist") + g.add_argument("--allow-uncalibrated", dest="calib_mode", action="store_const", const="1", + help="continue without calibration; the session is flagged not valid for analysis") + p.add_argument("--calib-path", metavar="FILE", help="use this calibration_params.json") + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="nav", + description="Host tools for the Multi-Sensor Navigation System: flash, log, process.", + ) + parser.add_argument("--version", action="version", version=f"navkit {__version__}") + parser.add_argument("-w", "--workspace", metavar="DIR", + help=f"workspace directory (default: ${workspace.ENV_VAR} or ~/navkit)") + sub = parser.add_subparsers(dest="command", metavar="") + + # ── board ──────────────────────────────────────────────────────────────── + p = sub.add_parser("flash", help="download a firmware release and flash it") + p.add_argument("--board", default="auto", + help="board id (default: auto — detect the chip and pick the matching image)") + p.add_argument("--version", dest="fw_version", default="latest", metavar="TAG", + help="firmware release to flash (default: latest)") + p.add_argument("--file", metavar="IMAGE", help="flash this local merged image instead of a release") + p.add_argument("--chip", help="esptool chip id for --file (default: detect)") + p.add_argument("--port", help="serial port (default: auto-detect)") + p.add_argument("--baud", type=int, default=921600) + p.add_argument("-y", "--yes", action="store_true", help="do not ask for confirmation") + + p = sub.add_parser("firmware", help="list or download firmware releases") + fsub = p.add_subparsers(dest="firmware_command", metavar="", required=True) + fsub.add_parser("list", help="list published firmware releases and their boards") + f = fsub.add_parser("fetch", help="download and verify an image without flashing") + f.add_argument("--board", default="esp32dev") + f.add_argument("--version", dest="fw_version", default="latest", metavar="TAG") + + sub.add_parser("ports", help="list serial ports that look like a board") + + p = sub.add_parser("doctor", help="check that this machine can flash and log") + p.add_argument("--online", action="store_true", help="also check that firmware releases are reachable") + + # ── sessions ───────────────────────────────────────────────────────────── + p = sub.add_parser("record", help="log a new session from the board, then process it") + p.add_argument("--type", dest="session_type", choices=SESSION_TYPES, default="free_label") + p.add_argument("--note", default="", help="free-text note stored with the session") + p.add_argument("--port", help="serial port (default: auto-detect)") + _add_calib_options(p) + + p = sub.add_parser("process", help="run the pipeline on an existing session") + p.add_argument("session", help="session name, or path to its directory") + p.add_argument("--from", dest="start_from", choices=STEPS, default="trim", + help="first step to run (default: trim)") + _add_calib_options(p) + + p = sub.add_parser("calibrate", help="compute calibration parameters from a static session") + p.add_argument("session", help="session name, or path to its directory") + p.add_argument("--note", default="") + + sub.add_parser("sessions", help="list sessions in the workspace") + + p = sub.add_parser("log", help="log the serial stream to a CSV file, nothing else") + p.add_argument("-o", "--output", metavar="FILE", help="output CSV (default: ./session_