Datasets:
Download extract_example.py from ml303/vector-high-speed-running-motion-force: direct link, hf CLI and curl.
- Browser
- Download file 6.75 kB
-
https://huggingface.co/datasets/ml303/vector-high-speed-running-motion-force/resolve/main/extract_example.py
- Command line
-
hf download hf://datasets/ml303/vector-high-speed-running-motion-force/extract_example.py
-
curl -L -o extract_example.py https://huggingface.co/datasets/ml303/vector-high-speed-running-motion-force/resolve/main/extract_example.py
6.75 kB
| """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) | |