File size: 6,538 Bytes
f7d58be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
"""
Plot training metrics and save figures to assets/.

Usage:
    python training/plot_metrics.py \
        --baseline assets/baseline_metrics.json \
        --trained  assets/trained_metrics.json \
        --out-dir  assets/
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional


def _rolling(values: List[float], window: int = 20) -> List[float]:
    out: List[float] = []
    for i, v in enumerate(values):
        start = max(0, i - window + 1)
        out.append(sum(values[start : i + 1]) / (i - start + 1))
    return out


def plot_reward_curve(
    episodes: List[Dict[str, Any]],
    label: str,
    color: str,
    ax: Any,
    window: int = 20,
) -> None:
    rewards = [e["total_reward"] for e in episodes]
    smoothed = _rolling(rewards, window)
    ax.plot(range(len(rewards)), smoothed, color=color, label=label, linewidth=1.5)
    ax.fill_between(
        range(len(rewards)),
        [r - 0.05 for r in smoothed],
        [r + 0.05 for r in smoothed],
        alpha=0.15,
        color=color,
    )


def plot_component_bars(
    baseline_episodes: List[Dict[str, Any]],
    trained_episodes: List[Dict[str, Any]],
    ax: Any,
) -> None:
    import numpy as np

    components = [
        "r_outcome", "r_detection_f1", "r_severity_accuracy", "r_efficiency", "r_teamwork"
    ]
    labels = ["Outcome", "Detection F1", "Severity Acc.", "Efficiency", "Teamwork"]

    def mean_component(eps: List[Dict[str, Any]], key: str) -> float:
        vals = [e.get(key, 0.0) for e in eps]
        return sum(vals) / max(len(vals), 1)

    baseline_vals = [mean_component(baseline_episodes, c) for c in components]
    trained_vals = [mean_component(trained_episodes, c) for c in components]

    x = np.arange(len(labels))
    width = 0.35
    ax.bar(x - width / 2, baseline_vals, width, label="Baseline", color="#6baed6", alpha=0.8)
    ax.bar(x + width / 2, trained_vals, width, label="Trained", color="#fd8d3c", alpha=0.8)
    ax.set_xticks(x)
    ax.set_xticklabels(labels, rotation=15, ha="right", fontsize=8)
    ax.set_ylabel("Avg Component Score")
    ax.set_title("Reward Component Comparison")
    ax.legend(fontsize=8)
    ax.set_ylim(0, 1.05)


def make_plots(
    baseline_path: Optional[Path],
    trained_path: Optional[Path],
    out_dir: Path,
) -> None:
    try:
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt
        import numpy as np
    except ImportError:
        print("matplotlib not installed. Run: pip install matplotlib numpy", file=sys.stderr)
        return

    out_dir.mkdir(parents=True, exist_ok=True)

    baseline_eps: List[Dict[str, Any]] = []
    trained_eps: List[Dict[str, Any]] = []

    if baseline_path and baseline_path.exists():
        with open(baseline_path) as f:
            baseline_eps = json.load(f)
    if trained_path and trained_path.exists():
        with open(trained_path) as f:
            trained_eps = json.load(f)

    if not baseline_eps and not trained_eps:
        # Generate synthetic placeholder data for demo
        import random
        rng = random.Random(42)
        for i in range(100):
            baseline_eps.append({
                "total_reward": max(0.0, 0.15 + rng.gauss(0, 0.1)),
                "r_outcome": max(0.0, 0.12 + rng.gauss(0, 0.08)),
                "r_detection_f1": max(0.0, 0.20 + rng.gauss(0, 0.10)),
                "r_severity_accuracy": max(0.0, 0.10 + rng.gauss(0, 0.07)),
                "r_efficiency": max(0.0, 0.25 + rng.gauss(0, 0.12)),
                "r_teamwork": max(0.0, 0.05 + rng.gauss(0, 0.05)),
            })
        for i in range(100):
            trained_eps.append({
                "total_reward": max(0.0, min(1.0, 0.15 + i * 0.005 + rng.gauss(0, 0.08))),
                "r_outcome": max(0.0, min(1.0, 0.12 + i * 0.004 + rng.gauss(0, 0.06))),
                "r_detection_f1": max(0.0, min(1.0, 0.20 + i * 0.005 + rng.gauss(0, 0.08))),
                "r_severity_accuracy": max(0.0, min(1.0, 0.10 + i * 0.004 + rng.gauss(0, 0.05))),
                "r_efficiency": max(0.0, min(1.0, 0.25 + i * 0.003 + rng.gauss(0, 0.09))),
                "r_teamwork": max(0.0, min(1.0, 0.05 + i * 0.003 + rng.gauss(0, 0.04))),
            })

    # ---- Figure 1: Reward Curves ----
    fig1, ax1 = plt.subplots(figsize=(10, 4))
    if baseline_eps:
        plot_reward_curve(baseline_eps, "Baseline (Heuristic)", "#6baed6", ax1)
    if trained_eps:
        plot_reward_curve(trained_eps, "GRPO Trained", "#fd8d3c", ax1)
    ax1.set_xlabel("Episode")
    ax1.set_ylabel("Total Reward (rolling avg)")
    ax1.set_title("LogSentinel v2 — Training Reward Curves")
    ax1.legend()
    ax1.grid(alpha=0.3)
    reward_path = out_dir / "reward_curve.png"
    fig1.tight_layout()
    fig1.savefig(reward_path, dpi=150)
    plt.close(fig1)
    print(f"Saved: {reward_path}")

    # ---- Figure 2: Baseline vs Trained ----
    if baseline_eps and trained_eps:
        fig2, ax2 = plt.subplots(figsize=(8, 4))
        plot_component_bars(baseline_eps, trained_eps, ax2)
        fig2.tight_layout()
        vs_path = out_dir / "baseline_vs_trained.png"
        fig2.savefig(vs_path, dpi=150)
        plt.close(fig2)
        print(f"Saved: {vs_path}")

    # ---- Figure 3: Success rate ----
    fig3, ax3 = plt.subplots(figsize=(10, 3))
    if baseline_eps:
        success_b = [1.0 if e["total_reward"] > 0.4 else 0.0 for e in baseline_eps]
        ax3.plot(_rolling(success_b, 20), label="Baseline", color="#6baed6")
    if trained_eps:
        success_t = [1.0 if e["total_reward"] > 0.4 else 0.0 for e in trained_eps]
        ax3.plot(_rolling(success_t, 20), label="Trained", color="#fd8d3c")
    ax3.set_xlabel("Episode")
    ax3.set_ylabel("Success Rate (rolling avg)")
    ax3.set_title("Success Rate Over Training")
    ax3.legend()
    ax3.set_ylim(0, 1.1)
    ax3.grid(alpha=0.3)
    sr_path = out_dir / "success_rate.png"
    fig3.tight_layout()
    fig3.savefig(sr_path, dpi=150)
    plt.close(fig3)
    print(f"Saved: {sr_path}")


def main() -> None:
    parser = argparse.ArgumentParser(description="Plot LogSentinel training metrics")
    parser.add_argument("--baseline", type=Path, default=None)
    parser.add_argument("--trained", type=Path, default=None)
    parser.add_argument("--out-dir", type=Path, default=Path("assets"))
    args = parser.parse_args()
    make_plots(args.baseline, args.trained, args.out_dir)


if __name__ == "__main__":
    main()