Skip to main content

frenz_export/
lib.rs

1//! Turns FRENZ recordings into time-aligned, analysis-ready session datasets.
2//!
3//! A session dataset is a folder with one zstd Parquet file per stream (`eeg`, `accel`, `gyro`,
4//! `ppg`, `vitals`, `battery`, `contact`, `status`, `markers`) and a `session.json` describing
5//! sources, units, channel map, timing fits and data-quality counts. Every sample row has `t`, its
6//! estimated acquisition time in Unix seconds on one host clock, so streams align directly.
7//! Values stay in raw device units; nothing is dropped or interpolated. Rows that repeat an earlier
8//! block are flagged `duplicate`, and each uninterrupted stretch has its own `segment` number.
9//!
10//! Source: SQLite recordings written by the `frenz` crate ([`recording`]).
11
12use std::collections::BTreeMap;
13use std::path::Path;
14
15use serde_json::{Map, Value, json};
16
17pub mod recording;
18pub mod table;
19pub mod timing;
20
21/// Format identifier written to `session.json`.
22pub const FORMAT: &str = "openfrenz-session/1";
23
24/// Export errors.
25#[derive(Debug, thiserror::Error)]
26pub enum Error {
27    /// Reading the SQLite recording failed.
28    #[error("recording: {0}")]
29    Sqlite(#[from] rusqlite::Error),
30    /// Filesystem error.
31    #[error("io: {0}")]
32    Io(#[from] std::io::Error),
33    /// Building Arrow data failed.
34    #[error("arrow: {0}")]
35    Arrow(#[from] arrow_schema::ArrowError),
36    /// Writing Parquet failed.
37    #[error("parquet: {0}")]
38    Parquet(#[from] parquet::errors::ParquetError),
39    /// JSON serialization failed.
40    #[error("json: {0}")]
41    Json(#[from] serde_json::Error),
42    /// The input is not in a recognized or consistent form.
43    #[error("invalid input: {0}")]
44    Invalid(String),
45}
46
47/// An in-memory session: metadata plus one table per stream.
48#[derive(Debug, Clone)]
49pub struct Session {
50    /// `session.json` contents.
51    pub meta: Map<String, Value>,
52    /// Stream name → table.
53    pub tables: BTreeMap<&'static str, table::Table>,
54}
55
56impl Session {
57    fn new(source: Value) -> Self {
58        let mut meta = Map::new();
59        meta.insert("format".into(), json!(FORMAT));
60        meta.insert(
61            "exporter".into(),
62            json!(format!("openfrenz frenz-export {}", env!("CARGO_PKG_VERSION"))),
63        );
64        meta.insert("source".into(), source);
65        Self {
66            meta,
67            tables: BTreeMap::new(),
68        }
69    }
70
71    /// Writes the dataset folder (created if needed; existing files with the same names are replaced).
72    pub fn write(&self, dir: &Path) -> Result<(), Error> {
73        std::fs::create_dir_all(dir)?;
74        let mut files = Map::new();
75        for (name, table) in &self.tables {
76            table.write_parquet(&dir.join(format!("{name}.parquet")))?;
77            files.insert(
78                (*name).to_owned(),
79                json!({"file": format!("{name}.parquet"), "rows": table.rows()}),
80            );
81        }
82        let mut meta = self.meta.clone();
83        meta.insert("tables".into(), Value::Object(files));
84        std::fs::write(
85            dir.join("session.json"),
86            serde_json::to_string_pretty(&Value::Object(meta))?,
87        )?;
88        Ok(())
89    }
90}
91
92/// Reads a `.sqlite` recording.
93pub fn read(input: &Path) -> Result<Session, Error> {
94    if input.extension().is_some_and(|e| e == "sqlite") {
95        recording::from_recording(input)
96    } else {
97        Err(Error::Invalid(format!("{}: not a .sqlite recording", input.display())))
98    }
99}
100
101/// EEG channel description shared by all sources (electrode map from the press test).
102pub(crate) fn eeg_channel_json() -> Value {
103    json!({
104        "forehead_right": "slot 0: right forehead pad, beside the optical sensor",
105        "comb_left": "slot 1: left side comb (shows eyes-closed alpha)",
106        "forehead_left": "slot 3: left forehead pad (strongest blink/EMG)",
107        "comb_right": "slot 4: right side comb (shows eyes-closed alpha)",
108        "reference": "centre forehead pad (inferred)",
109    })
110}
111
112/// Accelerometer/gyroscope description.
113pub(crate) fn motion_json(accel: bool) -> Value {
114    json!({
115        "nominal_rate_hz": 50.0,
116        "units": "raw signed 16-bit counts",
117        "frame": "+x down (toward chin when worn), +y wearer's left, +z forward; y/z rotated ~30° about x",
118        "scale": if accel { json!({"counts_per_g_nominal": 16384, "note": "per-unit calibration: see docs/HARDWARE.md"}) } else { json!("unknown") },
119    })
120}