File size: 6,747 Bytes
577d696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Extract the two SimTK running trials. Requires ezc3d, numpy and matplotlib."""
import argparse
import csv
from pathlib import Path
from tempfile import TemporaryDirectory
from zipfile import ZipFile

import ezc3d
import matplotlib

matplotlib.use("Agg")

import matplotlib.pyplot as plt
import numpy as np


TRIALS = (
    ("run520", 5.20, "Run5ms/JA1Gait27.c3d"),
    ("run700", 7.00, "Run7ms/JA1Gait33.c3d"),
)


def load_trial(path):
    source = ezc3d.c3d(str(path), extract_forceplat_data=True)
    points = source["data"]["points"]
    residuals = source["data"]["meta_points"]["residuals"][0]
    labels = source["parameters"]["POINT"]["LABELS"]["value"]
    platforms = source["data"]["platform"]
    point_header = source["header"]["points"]
    analog_header = source["header"]["analogs"]
    point_rate = int(point_header["frame_rate"])
    force_rate = int(analog_header["frame_rate"])
    step = force_rate // point_rate
    force = np.sum([np.asarray(plate["force"]) for plate in platforms], axis=0).T
    assert source["parameters"]["POINT"]["UNITS"]["value"] == ["mm"]
    assert all(plate["unit_force"] == "N" for plate in platforms)
    assert force_rate == point_rate * step and len(force) == points.shape[2] * step
    assert analog_header["first_frame"] == point_header["first_frame"] * step
    assert np.isfinite(force).all() and force[:, 2].max() > 1000
    return points, residuals, labels, force, point_rate, force_rate, int(point_header["first_frame"])


def export(archive_path, output):
    output.mkdir(parents=True, exist_ok=True)
    point_rows, force_rows, aligned_rows, metadata = [], [], [], []
    plot = []

    with ZipFile(archive_path) as archive, TemporaryDirectory() as tmp:
        for trial, speed, member in TRIALS:
            path = Path(archive.extract(member, tmp))
            points, residuals, labels, force, point_rate, force_rate, first_frame = load_trial(path)
            n = points.shape[2]
            stride = force_rate // point_rate
            aligned = force[::stride]
            coords = np.transpose(points[:3], (2, 1, 0)) / 1000
            valid = residuals.T >= 0
            valid &= np.isfinite(coords).all(axis=2)
            anatomy = [i for i, label in enumerate(labels) if not label.startswith("*")]
            sacrum = labels.index("SACR")
            left = labels.index("LHEEL")
            right = labels.index("RHEEL")
            assert valid[:, [sacrum, left, right]].all()
            plot.append((speed, np.arange(n) / point_rate, coords[:, sacrum, 1], aligned[:, 2]))

            for k in range(n):
                frame = first_frame + k
                time_s = round(k / point_rate, 9)
                grf = aligned[k].round(6).tolist()
                aligned_rows.append([
                    trial, speed, frame, time_s, *coords[k, sacrum].round(6).tolist(),
                    round(float(coords[k, left, 2]), 6), round(float(coords[k, right, 2]), 6),
                    *grf, int(aligned[k, 2] >= 20),
                ])
                for i in anatomy:
                    marker = coords[k, i].round(6).tolist() if valid[k, i] else ["", "", ""]
                    point_rows.append([trial, frame, time_s, labels[i], *marker, int(valid[k, i])])

            for j, sample in enumerate(force):
                force_rows.append([trial, j, round(j / force_rate, 9), *sample.round(6).tolist()])

            metadata.append([
                trial, "JA1", speed, member, point_rate, force_rate, first_frame, n,
                len(force), len(anatomy), "overground",
            ])

    files = (
        ("motion_force.csv", [
            "trial_id", "source_speed_mps", "source_frame", "time_s", "sacrum_x_m",
            "sacrum_y_m", "sacrum_z_m", "left_heel_z_m", "right_heel_z_m",
            "grf_x_n", "grf_y_n", "grf_z_n", "plate_loaded_20n",
        ], aligned_rows),
        ("markers.csv", ["trial_id", "source_frame", "time_s", "marker", "x_m", "y_m", "z_m", "valid"], point_rows),
        ("forces.csv", ["trial_id", "sample_index", "time_s", "grf_x_n", "grf_y_n", "grf_z_n"], force_rows),
        ("trials.csv", [
            "trial_id", "source_subject_code", "source_speed_mps", "source_c3d",
            "motion_hz", "force_hz", "first_source_frame", "motion_frames",
            "force_samples", "named_markers", "surface",
        ], metadata),
    )
    for name, fields, rows in files:
        with (output / name).open("w", newline="", encoding="utf-8") as file:
            writer = csv.writer(file, lineterminator="\n")
            writer.writerow(fields)
            writer.writerows(rows)
    make_plot(plot, output / "running-motion-force.png")


def make_plot(data, path):
    navy, blue, slate, tint = "#152743", "#185bd6", "#40536f", "#e1e9f5"
    fig, panels = plt.subplots(2, 1, figsize=(10.6, 6.7), layout="constrained")
    fig.suptitle("High-speed running: motion and measured ground reaction force", x=0.02, ha="left",
                 fontsize=17, fontweight="bold", color=navy)
    for ax, (speed, time, sacrum_y, force_z) in zip(panels, data):
        motion = ax.twinx()
        a, = ax.plot(time, force_z, color=blue, linewidth=1.9, label="Vertical GRF")
        ax.fill_between(time, 0, force_z, color=blue, alpha=0.12)
        b, = motion.plot(time, sacrum_y - sacrum_y[0], color=slate, linewidth=1.5,
                         linestyle="--", label="Sacrum travel")
        ax.set_title(f"{speed:.2f} m/s  ·  overground trial", loc="left", fontsize=12,
                     color=navy, fontweight="bold")
        ax.set(ylabel="Vertical GRF (N)", ylim=(0, 2500), xlim=(0, 2.28))
        motion.set(ylabel="Sacrum travel (m)", ylim=(0, 12.5))
        ax.set_yticks([0, 1000, 2000])
        ax.grid(axis="y", color=tint, linewidth=0.75)
        ax.set_axisbelow(True)
        ax.tick_params(axis="y", colors=blue)
        motion.tick_params(axis="y", colors=slate)
        ax.yaxis.label.set_color(blue)
        motion.yaxis.label.set_color(slate)
        for side in ("top", "right"):
            ax.spines[side].set_visible(False)
        motion.spines["top"].set_visible(False)
        motion.spines["right"].set_color(tint)
        if ax is panels[0]:
            ax.legend([a, b], [a.get_label(), b.get_label()], loc="upper left",
                      frameon=False, fontsize=9)
    panels[-1].set_xlabel("Seconds from first C3D frame")
    fig.savefig(path, dpi=155, facecolor="white")
    plt.close(fig)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("archive", type=Path, help="Original SimTK RunningDataModels.zip")
    parser.add_argument("output", type=Path)
    args = parser.parse_args()
    export(args.archive, args.output)