File size: 3,860 Bytes
82eab55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3

import argparse
import json
from pathlib import Path
from collections import defaultdict

import numpy as np


def find_metrics_files(root_dir: Path):
    """
    Find all files matching:
        */test_metrics/metrics.json
    under root_dir.
    """
    return sorted(root_dir.rglob("test_metrics/metrics.json"))


def load_metrics(metrics_path: Path):
    """
    Load the metrics dictionary from one metrics.json file.
    Expected structure:
        {
            "metrics": {
                "accuracy": ...,
                ...
            }
        }
    """
    with open(metrics_path, "r") as f:
        data = json.load(f)

    if "metrics" not in data:
        raise ValueError(f"No 'metrics' key found in {metrics_path}")

    if not isinstance(data["metrics"], dict):
        raise ValueError(f"'metrics' is not a dictionary in {metrics_path}")

    return data["metrics"]


def aggregate_metrics(metrics_list):
    """
    metrics_list:
        list of dictionaries, one per run.

    Returns:
        dictionary containing mean/std aggregation.
    """
    values_by_metric = defaultdict(list)

    for metrics in metrics_list:
        for metric_name, value in metrics.items():
            if isinstance(value, (int, float)):
                values_by_metric[metric_name].append(float(value))

    aggregated = {}

    for metric_name, values in values_by_metric.items():
        values = np.array(values, dtype=np.float64)

        mean = float(np.mean(values))

        # sample std if more than one run, otherwise 0.0
        std = float(np.std(values, ddof=1)) if len(values) > 1 else 0.0

        aggregated[metric_name] = {
            "mean": mean,
            "std": std,
            "mean_pm_std": f"{mean:.6f} ± {std:.6f}",
            "num_runs": int(len(values)),
            "values": values.tolist(),
        }

    return aggregated


def main():
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--root-dir",
        type=str,
        required=True,
        help="Root folder containing experiment subfolders.",
    )

    parser.add_argument(
        "--output-dir",
        type=str,
        required=True,
        help="Folder where the aggregated JSON will be saved.",
    )

    parser.add_argument(
        "--output-name",
        type=str,
        default="aggregated_metrics.json",
        help="Name of the output JSON file.",
    )

    args = parser.parse_args()

    root_dir = Path(args.root_dir)
    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    metrics_files = find_metrics_files(root_dir)

    if len(metrics_files) == 0:
        raise FileNotFoundError(
            f"No files found matching */test_metrics/metrics.json under {root_dir}"
        )

    all_metrics = []
    used_files = []

    for metrics_path in metrics_files:
        try:
            metrics = load_metrics(metrics_path)
            all_metrics.append(metrics)
            used_files.append(str(metrics_path))
        except Exception as e:
            print(f"Skipping {metrics_path}: {e}")

    if len(all_metrics) == 0:
        raise RuntimeError("No valid metrics files could be loaded.")

    aggregated = aggregate_metrics(all_metrics)

    output = {
        "num_valid_runs": len(all_metrics),
        "num_found_metrics_files": len(metrics_files),
        "source_root": str(root_dir),
        "used_files": used_files,
        "aggregated_metrics": aggregated,
    }

    output_path = output_dir / args.output_name

    with open(output_path, "w") as f:
        json.dump(output, f, indent=4)

    for i in metrics_files:
        print(i)
    print(f"Found metrics files: {len(metrics_files)}")
    print(f"Valid runs used: {len(all_metrics)}")
    print(f"Saved aggregation to: {output_path}")


if __name__ == "__main__":
    main()