File size: 6,014 Bytes
0f81796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Reprocess P1-P21 force CSVs using participant-specific ignore rules."""

from __future__ import annotations

import argparse
import csv
import importlib.util
import shutil
from pathlib import Path

import pandas as pd


DEFAULT_PROCESSOR = Path("/media/lab/Seagate Portable Drive/ECCV_dataset/zero_correct.py")


def load_processor(path: Path):
    spec = importlib.util.spec_from_file_location("feel_zero_correct", path)
    if spec is None or spec.loader is None:
        raise RuntimeError(f"Cannot import processor: {path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def enabled(value: str):
    return value.strip().lower() in {"1", "true", "yes", "y"}


def parse_ignore_before(value: str, side: str = "right"):
    """Parse a global cutoff or sensor-specific cutoffs such as ``4r@2050``."""
    value = value.strip().lower()
    if not value:
        return None, {}
    if value.isdigit():
        return int(value), {}

    rules = {}
    for token in value.split(","):
        token = token.strip()
        if token.count("@") != 1:
            raise ValueError(
                f"invalid ignore_before rule {token!r}; expected SENSORr@ROW, e.g. 4r@2050"
            )
        base, end_text = token.split("@")
        if len(base) < 2 or base[-1] not in {"l", "r"} or not base[:-1].isdigit():
            raise ValueError(
                f"invalid ignore_before sensor {base!r}; expected e.g. 4r"
            )
        if not end_text.isdigit():
            raise ValueError(
                f"invalid ignore_before row {end_text!r}; expected a non-negative integer"
            )
        hand = base[-1]
        if (hand == "l" and side == "left") or (hand == "r" and side == "right"):
            rules.setdefault(int(base[:-1]), []).append((0, int(end_text)))
    return None, rules


def raw_input_from_existing(path: Path):
    df = pd.read_csv(path)
    sensor_cols = sorted(
        (column for column in df.columns if column.startswith("sensor") and column[6:].isdigit()),
        key=lambda column: int(column[6:]),
    )
    if not sensor_cols:
        raise RuntimeError(f"No sensorN columns in {path}")
    for column in sensor_cols:
        raw_column = f"raw_{column}"
        if raw_column not in df.columns:
            raise RuntimeError(f"{path} lacks {raw_column}; cannot reconstruct original sensor data")
        df[column] = df[raw_column]
    # The correction routine recreates these columns from reconstructed input.
    drop = [f"raw_{column}" for column in sensor_cols] + ["raw_force", "force"]
    return df.drop(columns=[column for column in drop if column in df.columns])


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--config", type=Path, default=Path(__file__).with_name("non_named_ignore_rules.csv"))
    parser.add_argument("--feel-root", type=Path, default=Path(__file__).resolve().parent)
    parser.add_argument("--processor", type=Path, default=DEFAULT_PROCESSOR)
    parser.add_argument("--apply", action="store_true", help="Write results; otherwise only validate and report")
    parser.add_argument("--only", nargs="*", help="Optional participant subset, for example --only P1 P4")
    args = parser.parse_args()
    processor = load_processor(args.processor)
    selected = set(args.only or [])

    with args.config.open(newline="") as handle:
        rules = list(csv.DictReader(handle))
    failures = []
    for row in rules:
        participant = row["participant"].strip()
        if not enabled(row.get("enabled", "true")) or (selected and participant not in selected):
            continue
        destination = args.feel_root / participant / "force_aligned_.csv"
        ignore = (row.get("ignore") or "").strip()
        before_text = (row.get("ignore_before") or "").strip()
        try:
            raw_df = raw_input_from_existing(destination)
            parsed = processor.parse_ignore(ignore, "right")
            ignore_before, before_rules = parse_ignore_before(before_text, "right")
            for sensor, spans in before_rules.items():
                parsed.setdefault(sensor, []).extend(spans)
            if not args.apply:
                if ignore_before is not None and not 0 <= ignore_before <= len(raw_df):
                    raise ValueError(f"ignore_before must be between 0 and {len(raw_df)}")
                for sensor, spans in before_rules.items():
                    for _, end in spans:
                        if not 0 <= end <= len(raw_df):
                            raise ValueError(
                                f"ignore_before cutoff for sensor {sensor} must be between "
                                f"0 and {len(raw_df)}"
                            )
                print(f"VALID {participant}: rows={len(raw_df)}, ignore={ignore or '(none)'}, "
                      f"ignore_before={before_text or '(none)'}")
                continue
            corrected = processor.apply_piecewise_zero_correction(
                raw_df, parsed, ignore_before=ignore_before
            )
            if len(corrected) != len(raw_df):
                raise RuntimeError("correction changed row count")
            backup = destination.with_name("force_aligned_.before_reprocess.csv")
            if not backup.exists():
                shutil.copy2(destination, backup)
            temporary = destination.with_suffix(".csv.tmp")
            corrected.to_csv(temporary, index=False)
            temporary.replace(destination)
            print(f"WROTE {participant}: {len(corrected)} rows, ignore={ignore or '(none)'}, "
                  f"ignore_before={before_text or '(none)'}")
        except Exception as error:
            failures.append((participant, str(error)))
            print(f"ERROR {participant}: {error}")
    if failures:
        raise SystemExit(f"Failed participants: {', '.join(name for name, _ in failures)}")


if __name__ == "__main__":
    main()