File size: 30,482 Bytes
1c57dd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
#!/usr/bin/env python3
"""Build the publication-ready AIDLAB-HAR package from the immutable v2 ZIP."""

from __future__ import annotations

import argparse
import csv
import hashlib
import html
import json
import re
import shutil
import tempfile
import urllib.request
import zipfile
from collections import Counter, OrderedDict, defaultdict
from datetime import datetime
from pathlib import Path

import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pyedflib


SOURCE_URL = "https://aidlab-production-datasets.s3.eu-central-1.amazonaws.com/AIDLAB-HAR-DATASET_v2.zip"
SOURCE_SHA256 = "bc501d73ad636d9db29ca65525811b9d3a76f7257d1a0f5d9143ccb8bbbd63d7"
DISTRIBUTION_URL = "https://aidlab-production-datasets.s3.eu-central-1.amazonaws.com/AIDLAB-HAR-DATASET_v3.zip"
SAMPLING_RATE_HZ = 50.0
ARCHIVE_ROOT = "AIDLAB-HAR-DATASET-v3"
EXPECTED_SIGNALS = [
    "acceleration_x",
    "acceleration_y",
    "acceleration_z",
    "quaternion_x",
    "quaternion_y",
    "quaternion_z",
    "quaternion_w",
]
ACTIVITIES = OrderedDict(
    [
        ("ABDOMINALTENSE", "abdominal_tense"),
        ("BEND", "bend"),
        ("BROADJUMP", "broad_jump"),
        ("BURPEES", "burpee"),
        ("CHAIRSTANDANDSIT", "chair_stand_and_sit"),
        ("CRUNCHES", "crunch"),
        ("DOWNWARDDOG", "downward_dog"),
        ("LUNGES", "lunge"),
        ("LYINGHIPRISES", "lying_hip_rise"),
        ("PLANK", "plank"),
        ("PUSHUPS", "push_up"),
        ("ROTATINGTOETOUCHES", "rotating_toe_touch"),
        ("RUNNINGPLANK", "running_plank"),
        ("SIDELUNGES", "side_lunge"),
        ("SQUATS", "squat"),
        ("WALK", "walk"),
    ]
)
ACTIVITY_IDS = {source: index for index, source in enumerate(ACTIVITIES)}
FILENAME_PATTERN = re.compile(r"^(SUB\d{2})_(.+)_S(\d+)$")


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def resolve_source(source: Path | None, work_dir: Path) -> Path:
    if source is None:
        source = work_dir / "AIDLAB-HAR-DATASET_v2.zip"
        urllib.request.urlretrieve(SOURCE_URL, source)
    if not source.is_file():
        raise FileNotFoundError(source)
    actual = sha256(source)
    if actual != SOURCE_SHA256:
        raise ValueError(f"Source checksum mismatch: expected {SOURCE_SHA256}, got {actual}")
    with zipfile.ZipFile(source) as archive:
        if archive.testzip() is not None:
            raise ValueError("Source ZIP failed CRC validation")
    return source


def parse_recording_id(recording_id: str) -> tuple[str, str, int]:
    match = FILENAME_PATTERN.match(recording_id)
    if not match:
        raise ValueError(f"Unexpected recording filename: {recording_id}")
    subject_code, source_activity, series = match.groups()
    if source_activity not in ACTIVITIES:
        raise ValueError(f"Unknown activity label: {source_activity}")
    return subject_code, source_activity, int(series)


def normalize_event(source_event: str) -> str:
    normalized = source_event.strip().lower().replace(" ", "_")
    if normalized.startswith("repetition_"):
        normalized = normalized.replace("repetition_", "repetition_marker_", 1)
    allowed = {
        "series_onset",
        "series_offset",
        "repetition_marker_onset",
        "repetition_marker_offset",
    }
    if normalized not in allowed:
        raise ValueError(f"Unknown annotation event: {source_event}")
    return normalized


def contiguous_invalid_intervals(mask: np.ndarray) -> list[tuple[int, int]]:
    padded = np.concatenate(([False], mask, [False])).astype(np.int8)
    transitions = np.diff(padded)
    starts = np.flatnonzero(transitions == 1)
    ends = np.flatnonzero(transitions == -1)
    return list(zip(starts.tolist(), ends.tolist(), strict=True))


def write_corrected_edf(
    source_path: Path,
    target_path: Path,
    physical_samples: np.ndarray,
    signal_headers: list[dict],
    source_subject_code: str,
) -> dict[str, float]:
    corrected_headers = []
    for index, header in enumerate(signal_headers):
        corrected = dict(header)
        if index < 3:
            corrected.update(dimension="g", physical_min=-8.0, physical_max=8.0)
        else:
            corrected.update(dimension="1", physical_min=-1.0, physical_max=1.0)
        corrected_headers.append(corrected)

    file_header = {
        "technician": "",
        "recording_additional": "DATE PLACEHOLDER; REL TIME",
        "patientname": source_subject_code,
        "patient_additional": "PSEUDONYM; NOT GLOBAL PARTICIPANT ID",
        "patientcode": "",
        "equipment": "Aidlab IMU",
        "admincode": "",
        "sex": "",
        "startdate": datetime(1985, 1, 1),
        "birthdate": "",
    }
    with pyedflib.EdfWriter(
        str(target_path), len(corrected_headers), file_type=pyedflib.FILETYPE_EDFPLUS
    ) as writer:
        writer.setHeader(file_header)
        writer.setSignalHeaders(corrected_headers)
        writer.writeSamples(physical_samples.T, digital=False)

    with pyedflib.EdfReader(str(target_path)) as reader:
        roundtrip = np.vstack([reader.readSignal(i) for i in range(7)]).T
        dimensions = [reader.getPhysicalDimension(i) for i in range(7)]
        ranges = [
            (reader.getPhysicalMinimum(i), reader.getPhysicalMaximum(i)) for i in range(7)
        ]
    if dimensions != ["g", "g", "g", "1", "1", "1", "1"]:
        raise ValueError(f"Incorrect corrected dimensions in {target_path.name}: {dimensions}")
    if ranges != [(-8.0, 8.0)] * 3 + [(-1.0, 1.0)] * 4:
        raise ValueError(f"Incorrect corrected ranges in {target_path.name}: {ranges}")
    differences = np.abs(roundtrip - physical_samples)
    acceleration_error = float(differences[:, :3].max(initial=0.0))
    quaternion_error = float(differences[:, 3:].max(initial=0.0))
    if acceleration_error > 0.00013 or quaternion_error > 0.000016:
        raise ValueError(
            f"EDF round-trip error too large in {target_path.name}: "
            f"acc={acceleration_error}, quat={quaternion_error}"
        )
    return {
        "acceleration_max_abs_error_g": acceleration_error,
        "quaternion_max_abs_error": quaternion_error,
    }


def write_deterministic_zip(source_root: Path, target_zip: Path) -> None:
    with zipfile.ZipFile(
        target_zip, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9
    ) as archive:
        for path in sorted(source_root.rglob("*")):
            if not path.is_file():
                continue
            relative = Path(ARCHIVE_ROOT) / path.relative_to(source_root)
            info = zipfile.ZipInfo(str(relative), date_time=(1985, 1, 1, 0, 0, 0))
            info.compress_type = zipfile.ZIP_DEFLATED
            info.external_attr = 0o100644 << 16
            archive.writestr(info, path.read_bytes(), compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)


def write_preview_svg(signals: pd.DataFrame, annotations: pd.DataFrame, target: Path) -> None:
    recording_id = "SUB58_SQUATS_S1"
    frame = signals.loc[signals.recording_id == recording_id].reset_index(drop=True)
    events = annotations.loc[annotations.recording_id == recording_id]
    if frame.empty:
        raise ValueError(f"Preview recording not found: {recording_id}")

    width, height = 1200, 460
    left, right, top, bottom = 70, 30, 70, 55
    plot_width = width - left - right
    plot_height = height - top - bottom
    duration = float(frame.timestamp_s.max())
    values = frame[["acceleration_x_g", "acceleration_y_g", "acceleration_z_g"]].to_numpy()
    valid_values = values[np.isfinite(values)]
    y_limit = max(2.0, float(np.max(np.abs(valid_values))) * 1.1)

    def x_coord(timestamp: float) -> float:
        return left + timestamp / duration * plot_width

    def y_coord(value: float) -> float:
        return top + (y_limit - value) / (2 * y_limit) * plot_height

    colors = ["#ff5a5f", "#2aa876", "#4169e1"]
    labels = ["acceleration_x_g", "acceleration_y_g", "acceleration_z_g"]
    lines = [
        f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">',
        '<rect width="100%" height="100%" fill="#07131f"/>',
        f'<text x="{left}" y="32" fill="#f4f7fb" font-family="system-ui" font-size="22" font-weight="700">AIDLAB-HAR sample · squat · chest acceleration</text>',
        f'<text x="{left}" y="54" fill="#9bb0c5" font-family="system-ui" font-size="13">{html.escape(recording_id)} · 50 Hz · shaded markers are annotation windows</text>',
    ]

    for row in events.itertuples():
        if row.event != "repetition_marker_onset":
            continue
        later = events[(events.timestamp_s > row.timestamp_s) & (events.event == "repetition_marker_offset")]
        if later.empty:
            continue
        end = float(later.iloc[0].timestamp_s)
        start_x, end_x = x_coord(float(row.timestamp_s)), x_coord(end)
        lines.append(
            f'<rect x="{start_x:.2f}" y="{top}" width="{max(1.0, end_x-start_x):.2f}" height="{plot_height}" fill="#ffd166" opacity="0.15"/>'
        )

    for tick in range(int(duration) + 1):
        if tick % 5 != 0:
            continue
        x = x_coord(float(tick))
        lines.append(f'<line x1="{x:.2f}" y1="{top}" x2="{x:.2f}" y2="{top+plot_height}" stroke="#23384c"/>')
        lines.append(f'<text x="{x:.2f}" y="{height-25}" text-anchor="middle" fill="#9bb0c5" font-family="system-ui" font-size="12">{tick}s</text>')
    for value in np.linspace(-y_limit, y_limit, 5):
        y = y_coord(float(value))
        lines.append(f'<line x1="{left}" y1="{y:.2f}" x2="{left+plot_width}" y2="{y:.2f}" stroke="#23384c"/>')
        lines.append(f'<text x="{left-10}" y="{y+4:.2f}" text-anchor="end" fill="#9bb0c5" font-family="system-ui" font-size="12">{value:.1f}g</text>')

    stride = max(1, len(frame) // 1000)
    sampled = frame.iloc[::stride]
    for column, color, label in zip(labels, colors, labels, strict=True):
        points = []
        for row in sampled.itertuples():
            value = getattr(row, column)
            if pd.isna(value):
                continue
            points.append(f"{x_coord(float(row.timestamp_s)):.2f},{y_coord(float(value)):.2f}")
        lines.append(f'<polyline points="{" ".join(points)}" fill="none" stroke="{color}" stroke-width="1.8"/>')
        legend_x = left + labels.index(label) * 190
        lines.append(f'<line x1="{legend_x}" y1="{height-8}" x2="{legend_x+25}" y2="{height-8}" stroke="{color}" stroke-width="3"/>')
        lines.append(f'<text x="{legend_x+32}" y="{height-4}" fill="#dbe6f0" font-family="system-ui" font-size="12">{label}</text>')
    lines.append("</svg>")
    target.write_text("\n".join(lines) + "\n", encoding="utf-8")


def build(source_zip: Path, output: Path) -> dict:
    data_dir = output / "data"
    raw_dir = output / "raw"
    metadata_dir = output / "metadata"
    assets_dir = output / "assets"
    scripts_dir = output / "scripts"
    for directory in (data_dir, raw_dir, metadata_dir, assets_dir, scripts_dir):
        directory.mkdir(parents=True, exist_ok=True)

    for required in ("README.md", "RAW_DATA_README.md", "CLEANING_NOTES.md", "LICENSE"):
        if not (output / required).is_file():
            raise FileNotFoundError(output / required)

    recordings: list[dict] = []
    annotations: list[dict] = []
    signal_frames: list[pd.DataFrame] = []
    quality_intervals: list[dict] = []
    activity_counts = Counter()
    activity_seconds = defaultdict(float)
    total_acceleration_invalid = 0
    total_quaternion_invalid = 0
    max_acceleration_roundtrip_error = 0.0
    max_quaternion_roundtrip_error = 0.0

    with tempfile.TemporaryDirectory(prefix="aidlab-har-build-") as temporary:
        temporary_path = Path(temporary)
        extracted = temporary_path / "source"
        clean_root = temporary_path / "clean"
        clean_data = clean_root / "data"
        clean_data.mkdir(parents=True)
        with zipfile.ZipFile(source_zip) as archive:
            archive.extractall(extracted)
        source_data = extracted / "AIDLAB-HAR-DATASET-v2" / "data"

        edf_files = sorted(source_data.glob("*.edf"))
        csv_files = sorted(source_data.glob("*.csv"))
        if len(edf_files) != 180 or len(csv_files) != 130:
            raise ValueError(
                f"Unexpected source contents: {len(edf_files)} EDF, {len(csv_files)} CSV"
            )

        for edf_path in edf_files:
            recording_id = edf_path.stem
            source_subject_code, source_activity, series_index = parse_recording_id(recording_id)
            activity_id = ACTIVITY_IDS[source_activity]
            activity_label = ACTIVITIES[source_activity]
            annotation_path = edf_path.with_suffix(".csv")

            with pyedflib.EdfReader(str(edf_path)) as reader:
                labels = reader.getSignalLabels()
                rates = [float(reader.getSampleFrequency(i)) for i in range(7)]
                physical_samples = np.vstack([reader.readSignal(i) for i in range(7)]).T
                duration_s = float(reader.getFileDuration())
                signal_headers = reader.getSignalHeaders()
            if labels != EXPECTED_SIGNALS:
                raise ValueError(f"Unexpected channels in {edf_path.name}: {labels}")
            if rates != [SAMPLING_RATE_HZ] * 7:
                raise ValueError(f"Unexpected sample rate in {edf_path.name}: {rates}")

            n_samples = len(physical_samples)
            if n_samples != round(duration_s * SAMPLING_RATE_HZ):
                raise ValueError(f"Duration/sample mismatch in {edf_path.name}")
            timestamps = np.arange(n_samples, dtype=np.float64) / SAMPLING_RATE_HZ

            event_rows: list[tuple[float, str, str]] = []
            if annotation_path.exists():
                with annotation_path.open(newline="", encoding="utf-8-sig") as handle:
                    for row in csv.DictReader(handle):
                        timestamp_s = float(row["TIMESTAMP"])
                        source_event = row["EVENT"].strip()
                        event = normalize_event(source_event)
                        if not 0 <= timestamp_s <= duration_s:
                            raise ValueError(f"Out-of-range event in {annotation_path.name}")
                        event_rows.append((timestamp_s, event, source_event))
                        annotations.append(
                            {
                                "recording_id": recording_id,
                                "source_subject_code": source_subject_code,
                                "activity_id": np.int8(activity_id),
                                "activity_label": activity_label,
                                "source_activity": source_activity,
                                "series_index": np.int8(series_index),
                                "timestamp_s": timestamp_s,
                                "event": event,
                                "source_event": source_event,
                            }
                        )

            series_active = np.zeros(n_samples, dtype=bool)
            marker_active = np.zeros(n_samples, dtype=bool)
            marker_index = np.full(n_samples, -1, dtype=np.int16)
            open_series: int | None = None
            open_marker: int | None = None
            n_markers = 0
            for timestamp_s, event, _ in event_rows:
                index = min(int(np.searchsorted(timestamps, timestamp_s, side="left")), n_samples)
                if event == "series_onset":
                    if open_series is not None:
                        raise ValueError(f"Nested series in {recording_id}")
                    open_series = index
                elif event == "series_offset":
                    if open_series is None:
                        raise ValueError(f"Series offset without onset in {recording_id}")
                    series_active[open_series:index] = True
                    open_series = None
                elif event == "repetition_marker_onset":
                    if open_marker is not None:
                        raise ValueError(f"Nested marker in {recording_id}")
                    open_marker = index
                elif event == "repetition_marker_offset":
                    if open_marker is None:
                        raise ValueError(f"Marker offset without onset in {recording_id}")
                    n_markers += 1
                    marker_active[open_marker:index] = True
                    marker_index[open_marker:index] = n_markers
                    open_marker = None
            if open_series is not None or open_marker is not None:
                raise ValueError(f"Unclosed annotation interval in {recording_id}")

            acceleration = physical_samples[:, :3]
            quaternion = physical_samples[:, 3:]
            acceleration_norm = np.linalg.norm(acceleration, axis=1)
            quaternion_norm = np.linalg.norm(quaternion, axis=1)
            quaternion_valid = (
                np.isfinite(quaternion).all(axis=1)
                & (quaternion_norm >= 0.9)
                & (quaternion_norm <= 1.1)
            )
            # Near-zero acceleration can be real during an airborne phase. Treat it
            # as missing only with the simultaneous invalid-quaternion packet pattern.
            acceleration_valid = np.isfinite(acceleration).all(axis=1) & ~(
                (acceleration_norm < 0.1) & ~quaternion_valid
            )
            sample_valid = acceleration_valid & quaternion_valid
            total_acceleration_invalid += int((~acceleration_valid).sum())
            total_quaternion_invalid += int((~quaternion_valid).sum())

            for signal_name, invalid_mask in (
                ("acceleration", ~acceleration_valid),
                ("quaternion", ~quaternion_valid),
            ):
                for start, end in contiguous_invalid_intervals(invalid_mask):
                    quality_intervals.append(
                        {
                            "recording_id": recording_id,
                            "signal": signal_name,
                            "start_sample": start,
                            "end_sample_exclusive": end,
                            "start_s": start / SAMPLING_RATE_HZ,
                            "end_s": end / SAMPLING_RATE_HZ,
                        }
                    )

            parquet_values = physical_samples.astype(np.float32)
            parquet_values[~acceleration_valid, :3] = np.nan
            parquet_values[~quaternion_valid, 3:] = np.nan
            has_annotations = annotation_path.exists()
            sample_activity_ids = [
                activity_id if (not has_annotations or active) else None for active in series_active
            ]
            sample_activity_labels = [
                activity_label if value is not None else None for value in sample_activity_ids
            ]
            sample_frame = pd.DataFrame(
                {
                    "recording_id": recording_id,
                    "source_subject_code": source_subject_code,
                    "recording_activity_id": np.int8(activity_id),
                    "recording_activity_label": activity_label,
                    "source_activity": source_activity,
                    "series_index": np.int8(series_index),
                    "sample_index": np.arange(n_samples, dtype=np.int32),
                    "timestamp_s": timestamps,
                    "activity_id": pd.array(sample_activity_ids, dtype="Int8"),
                    "activity_label": sample_activity_labels,
                    "acceleration_x_g": parquet_values[:, 0],
                    "acceleration_y_g": parquet_values[:, 1],
                    "acceleration_z_g": parquet_values[:, 2],
                    "quaternion_x": parquet_values[:, 3],
                    "quaternion_y": parquet_values[:, 4],
                    "quaternion_z": parquet_values[:, 5],
                    "quaternion_w": parquet_values[:, 6],
                    "acceleration_valid": acceleration_valid,
                    "quaternion_valid": quaternion_valid,
                    "sample_valid": sample_valid,
                    "series_active": pd.array(
                        series_active if has_annotations else [None] * n_samples,
                        dtype="boolean",
                    ),
                    "repetition_marker_active": pd.array(
                        marker_active if has_annotations else [None] * n_samples,
                        dtype="boolean",
                    ),
                    "repetition_marker_index": pd.array(
                        [int(value) if value >= 0 else None for value in marker_index],
                        dtype="Int16",
                    ),
                }
            )
            signal_frames.append(sample_frame)

            archive_edf_path = f"{ARCHIVE_ROOT}/data/{edf_path.name}"
            archive_annotation_path = (
                f"{ARCHIVE_ROOT}/data/{annotation_path.name}" if has_annotations else None
            )
            recordings.append(
                {
                    "recording_id": recording_id,
                    "source_subject_code": source_subject_code,
                    "activity_id": np.int8(activity_id),
                    "activity_label": activity_label,
                    "source_activity": source_activity,
                    "series_index": np.int8(series_index),
                    "sampling_rate_hz": np.float32(SAMPLING_RATE_HZ),
                    "duration_s": duration_s,
                    "n_samples": np.int32(n_samples),
                    "n_annotations": np.int16(len(event_rows)),
                    "n_repetition_markers": np.int16(n_markers),
                    "has_annotations": has_annotations,
                    "n_acceleration_invalid": np.int32((~acceleration_valid).sum()),
                    "n_quaternion_invalid": np.int32((~quaternion_valid).sum()),
                    "n_samples_valid": np.int32(sample_valid.sum()),
                    "valid_fraction": np.float32(sample_valid.mean()),
                    "absolute_time_available": False,
                    "archive_edf_path": archive_edf_path,
                    "archive_annotation_path": archive_annotation_path,
                }
            )
            activity_counts[activity_label] += 1
            activity_seconds[activity_label] += duration_s

            corrected_path = clean_data / edf_path.name
            errors = write_corrected_edf(
                edf_path,
                corrected_path,
                physical_samples,
                signal_headers,
                source_subject_code,
            )
            max_acceleration_roundtrip_error = max(
                max_acceleration_roundtrip_error, errors["acceleration_max_abs_error_g"]
            )
            max_quaternion_roundtrip_error = max(
                max_quaternion_roundtrip_error, errors["quaternion_max_abs_error"]
            )

            if has_annotations:
                with (clean_data / annotation_path.name).open(
                    "w", newline="", encoding="utf-8"
                ) as handle:
                    writer = csv.DictWriter(handle, fieldnames=["timestamp_s", "event"])
                    writer.writeheader()
                    for timestamp_s, event, _ in event_rows:
                        writer.writerow({"timestamp_s": f"{timestamp_s:.9g}", "event": event})

        recordings_frame = pd.DataFrame(recordings).sort_values("recording_id").reset_index(drop=True)
        annotations_frame = (
            pd.DataFrame(annotations)
            .sort_values(["recording_id", "timestamp_s"])
            .reset_index(drop=True)
        )
        signals_frame = pd.concat(signal_frames, ignore_index=True)

        pq.write_table(
            pa.Table.from_pandas(recordings_frame, preserve_index=False),
            data_dir / "recordings.parquet",
            compression="zstd",
            row_group_size=180,
            write_page_index=True,
        )
        pq.write_table(
            pa.Table.from_pandas(signals_frame, preserve_index=False),
            data_dir / "signals.parquet",
            compression="zstd",
            row_group_size=50_000,
            write_page_index=True,
        )
        pq.write_table(
            pa.Table.from_pandas(annotations_frame, preserve_index=False),
            data_dir / "annotations.parquet",
            compression="zstd",
            row_group_size=5_000,
            write_page_index=True,
        )

        with (clean_root / "quality_intervals.csv").open(
            "w", newline="", encoding="utf-8"
        ) as handle:
            fieldnames = [
                "recording_id",
                "signal",
                "start_sample",
                "end_sample_exclusive",
                "start_s",
                "end_s",
            ]
            writer = csv.DictWriter(handle, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(quality_intervals)
        shutil.copy2(output / "RAW_DATA_README.md", clean_root / "README.md")
        shutil.copy2(output / "CLEANING_NOTES.md", clean_root / "CLEANING_NOTES.md")
        shutil.copy2(output / "LICENSE", clean_root / "LICENSE")

        distribution_archive = raw_dir / "AIDLAB-HAR-DATASET_v3.zip"
        write_deterministic_zip(clean_root, distribution_archive)
        with zipfile.ZipFile(distribution_archive) as archive:
            if archive.testzip() is not None:
                raise ValueError("Cleaned distribution ZIP failed CRC validation")

        write_preview_svg(signals_frame, annotations_frame, assets_dir / "sample-squat.svg")

    artifact_paths = [
        data_dir / "recordings.parquet",
        data_dir / "signals.parquet",
        data_dir / "annotations.parquet",
        raw_dir / "AIDLAB-HAR-DATASET_v3.zip",
        assets_dir / "sample-squat.svg",
    ]
    manifest = {
        "dataset": "AIDLAB-HAR v3 corrected distribution",
        "distribution_url": DISTRIBUTION_URL,
        "source_archive_url": SOURCE_URL,
        "source_archive_sha256": SOURCE_SHA256,
        "sampling_rate_hz": SAMPLING_RATE_HZ,
        "recordings": len(recordings),
        "signal_samples": int(sum(item["n_samples"] for item in recordings)),
        "annotations": len(annotations),
        "repetition_marker_intervals": int(
            sum(item["n_repetition_markers"] for item in recordings)
        ),
        "duration_seconds": float(sum(item["duration_s"] for item in recordings)),
        "activity_labels": list(ACTIVITIES.values()),
        "activity_mapping": [
            {
                "activity_id": ACTIVITY_IDS[source],
                "activity_label": label,
                "source_activity": source,
            }
            for source, label in ACTIVITIES.items()
        ],
        "activity_summary": {
            label: {
                "recordings": activity_counts[label],
                "duration_seconds": activity_seconds[label],
            }
            for label in ACTIVITIES.values()
        },
        "quality": {
            "acceleration_invalid_samples": total_acceleration_invalid,
            "quaternion_invalid_samples": total_quaternion_invalid,
            "quality_intervals": len(quality_intervals),
            "acceleration_valid_definition": (
                "finite values; a vector norm < 0.1 g is invalid only when the "
                "simultaneous quaternion is invalid"
            ),
            "quaternion_valid_definition": "finite values and vector norm in [0.9, 1.1]",
        },
        "edf_corrections": {
            "acceleration_dimension": "g",
            "acceleration_physical_range": [-8.0, 8.0],
            "quaternion_dimension": "1",
            "quaternion_physical_range": [-1.0, 1.0],
            "absolute_time_available": False,
            "placeholder_start_date": "1985-01-01T00:00:00",
            "max_acceleration_roundtrip_error_g": max_acceleration_roundtrip_error,
            "max_quaternion_roundtrip_error": max_quaternion_roundtrip_error,
        },
        "transformation_notes": [
            "Activity labels are canonical snake_case; source labels are preserved separately.",
            "Samples outside annotated exercise series have null sample-level activity labels.",
            "Invalid signal values are null in Parquet and represented as intervals in the cleaned archive.",
            "Repetition annotations are marker/fiducial windows, not complete movement cycles.",
            "No synthetic train/validation/test split was created; every configuration uses the full split.",
        ],
        "artifacts": {
            str(path.relative_to(output)): {"bytes": path.stat().st_size, "sha256": sha256(path)}
            for path in artifact_paths
        },
        "build_environment": {
            "numpy": np.__version__,
            "pandas": pd.__version__,
            "pyarrow": pa.__version__,
            "pyedflib": pyedflib.__version__,
        },
    }
    (metadata_dir / "manifest.json").write_text(
        json.dumps(manifest, indent=2) + "\n", encoding="utf-8"
    )
    return manifest


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source", type=Path, help="Path to the immutable AIDLAB-HAR v2 ZIP")
    parser.add_argument(
        "--output",
        type=Path,
        default=Path(__file__).resolve().parents[1],
        help="Publication package root (default: repository root)",
    )
    args = parser.parse_args()
    output = args.output.resolve()
    with tempfile.TemporaryDirectory(prefix="aidlab-har-source-") as temporary:
        source = resolve_source(args.source, Path(temporary))
        manifest = build(source, output)
    print(
        json.dumps(
            {
                "recordings": manifest["recordings"],
                "signal_samples": manifest["signal_samples"],
                "annotations": manifest["annotations"],
                "quality": manifest["quality"],
                "artifacts": manifest["artifacts"],
            },
            indent=2,
        )
    )


if __name__ == "__main__":
    main()