Download Calculate_TM_RM_Stats.py from OPTIMlab/mmf-tm-rm-experimental: direct link, hf CLI and curl.
- Browser
- Download file 3.17 kB
-
https://huggingface.co/datasets/OPTIMlab/mmf-tm-rm-experimental/resolve/main/Calculate_TM_RM_Stats.py
- Command line
-
hf download hf://datasets/OPTIMlab/mmf-tm-rm-experimental/Calculate_TM_RM_Stats.py
-
curl -L -o Calculate_TM_RM_Stats.py https://huggingface.co/datasets/OPTIMlab/mmf-tm-rm-experimental/resolve/main/Calculate_TM_RM_Stats.py
3.17 kB
| """ | |
| Calculate statistics and singular values for all TMs and RMs, and save in their resepctive analysis/ subdirectories. | |
| Usage: | |
| python Calculate_TM_RM_Stats.py | |
| Expects: | |
| processed_dataset.npz in the working directory, containing standardised TM and RM stacks, and paths to the original data directories. | |
| Outputs: | |
| metrics.json in <bend subdir>/analysis/, containing: | |
| cond_TM: single float | |
| cond_RM: single float | |
| num_modes: single integer | |
| rank_90_TM: single integer | |
| rank_90_RM: single integer | |
| singular_values_TM.csv in <bend subdir>/analysis, containing: | |
| tm_singular_values: unnormalized singular values of the TM, one per row (145,) | |
| singular_values_RM.csv in <bend subdir>/analysis, containing: | |
| rm_singular_values: unnormalized singular values of the RM, one per row (145,) | |
| singular_values_overlay.png in <bend subdir>/analysis, containing: | |
| plot of tm_singular_values_norm and rm_singular_values_norm | |
| """ | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import os | |
| import pandas as pd | |
| import json | |
| dataset = np.load('processed_dataset.npz', allow_pickle=True) | |
| with open('processed_dataset_paths.txt', 'r') as f: | |
| paths = [line.strip() for line in f] | |
| TM_stack = dataset['TM'] | |
| RM_stack = dataset['RM'] | |
| for TM, RM, path in zip(TM_stack, RM_stack, paths): | |
| try: | |
| save_dir = os.path.join(path, "analysis/") | |
| os.makedirs(save_dir, exist_ok=True) | |
| S_tm = np.linalg.svd(TM, full_matrices=False, compute_uv=False) | |
| cond_TM = float(S_tm[0]) / float(S_tm[-1] + 1e-12) # used instead of np.linalg.cond() to save doing 2x SVD | |
| cum_TM = np.cumsum(S_tm**2) / np.sum(S_tm**2) | |
| rank_90_TM = int(np.searchsorted(cum_TM, 0.9)) + 1 | |
| S_rm = np.linalg.svd(RM, full_matrices=False, compute_uv=False) | |
| cond_RM = float(S_rm[0]) / float(S_rm[-1] + 1e-12) | |
| cum_RM = np.cumsum(S_rm**2) / np.sum(S_rm**2) | |
| rank_90_RM = int(np.searchsorted(cum_RM, 0.9)) + 1 | |
| assert np.isclose(S_tm[0], 1.0, atol=1e-3), f"TM not normalised: S[0]={S_tm[0]:.4f} in {path}" | |
| assert np.isclose(S_rm[0], 1.0, atol=1e-3), f"RM not normalised: S[0]={S_rm[0]:.4f} in {path}" | |
| fig, ax = plt.subplots() | |
| ax.set_ylim(1e-4, 1.1) | |
| ax.semilogy(S_tm/(S_tm[0] + 1e-12), label="TM") | |
| ax.semilogy(S_rm/(S_rm[0] + 1e-12), label="RM") | |
| ax.set_xlabel("Index") | |
| ax.set_ylabel("Singular value") | |
| ax.legend() | |
| fig.tight_layout() | |
| fig.savefig(f"{save_dir}singular_values_overlay.png", dpi=300) | |
| plt.close(fig) | |
| pd.DataFrame({"tm_singular_values": S_tm}).to_csv(f"{save_dir}/singular_values_TM.csv", index=False) | |
| pd.DataFrame({"rm_singular_values": S_rm}).to_csv(f"{save_dir}/singular_values_RM.csv", index=False) | |
| metrics = {"cond_TM": float(cond_TM), "cond_RM": float(cond_RM), | |
| "num_modes": int(TM.shape[1]), "rank_90_TM": rank_90_TM, "rank_90_RM": rank_90_RM} | |
| with open(f"{save_dir}/metrics.json", "w") as f: | |
| json.dump(metrics, f, indent=4) | |
| except Exception as e: | |
| print(f"Error in {path}: {e}") |