File size: 4,235 Bytes
e7a6bab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import csv
import argparse
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

K = 1.0
BOUNDARY_EPS = 0.02


def load_csv(path):
    with open(path, newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def index_by_id(rows):
    index = {}
    for row in rows:
        sid = str(row.get("scenario_id", "")).strip()
        if not sid:
            raise ValueError("Blank or missing scenario_id detected")
        if sid in index:
            raise ValueError(f"Duplicate scenario_id detected: {sid}")
        index[sid] = row
    return index


def parse_binary(value, field_name, sid):
    try:
        parsed = int(value)
    except ValueError as e:
        raise ValueError(f"Invalid {field_name} for {sid}: {value}") from e
    if parsed not in (0, 1):
        raise ValueError(f"Invalid {field_name} for {sid}: {parsed}")
    return parsed


def compute_surfaces(pressure, buffer, lag, coupling):
    s1 = buffer - (pressure * coupling) - (K * lag)
    s2 = buffer - (pressure * (coupling ** 2)) - (K * lag)
    s3 = buffer - (pressure * coupling) - (K * (lag ** 2))
    return {
        "baseline_surface": s1,
        "coupling_surface": s2,
        "lag_surface": s3,
    }


def plot_projection(pred_path, truth_path):
    preds = load_csv(pred_path)
    truth = load_csv(truth_path)

    pred_map = index_by_id(preds)
    truth_map = index_by_id(truth)

    if set(pred_map.keys()) != set(truth_map.keys()):
        raise ValueError("scenario_id mismatch between prediction and truth files")

    plt.figure(figsize=(10, 8))

    for sid in sorted(truth_map):
        truth_row = truth_map[sid]
        pred_row = pred_map[sid]

        pressure = float(truth_row["pressure"])
        buffer = float(truth_row["buffer"])
        lag = float(truth_row["lag"])
        coupling = float(truth_row["coupling"])

        pred = parse_binary(pred_row["prediction"], "prediction", sid)
        label = parse_binary(truth_row["label_stable"], "label_stable", sid)

        surfaces = compute_surfaces(pressure, buffer, lag, coupling)
        manifold_margin = min(surfaces.values())
        active_surface = min(surfaces, key=surfaces.get)

        x = pressure * coupling
        y = buffer

        if abs(manifold_margin) <= BOUNDARY_EPS:
            color = "orange"
            marker = "s"
        elif manifold_margin < 0:
            color = "red"
            marker = "x"
        else:
            color = "green"
            marker = "o"

        if label == 0 and pred == 1:
            color = "purple"
            marker = "*"
        elif label == 1 and pred == 0:
            color = "blue"
            marker = "D"

        size = 110
        edgecolor = "black" if active_surface == "coupling_surface" else "none"
        linewidth = 1.2 if active_surface == "coupling_surface" else 0.0

        plt.scatter(
            x,
            y,
            c=color,
            marker=marker,
            s=size,
            edgecolors=edgecolor,
            linewidths=linewidth,
        )

    plt.xlabel("Pressure × Coupling")
    plt.ylabel("Buffer Capacity")
    plt.title("Clarus Stability Manifold Projection (2D View)")
    plt.grid(True)
    plt.tight_layout()

    legend_elements = [
        Line2D([0], [0], marker="o", color="w", label="Stable region", markerfacecolor="green", markersize=10),
        Line2D([0], [0], marker="x", color="red", label="Collapse region", linestyle="None", markersize=10),
        Line2D([0], [0], marker="s", color="w", label="Near boundary", markerfacecolor="orange", markersize=10),
        Line2D([0], [0], marker="*", color="w", label="False rescue", markerfacecolor="purple", markersize=12),
        Line2D([0], [0], marker="D", color="w", label="False collapse", markerfacecolor="blue", markersize=10),
        Line2D([0], [0], marker="o", color="black", label="Coupling surface active", markerfacecolor="white", markersize=9),
    ]
    plt.legend(handles=legend_elements)
    plt.show()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--pred", required=True)
    parser.add_argument("--truth", required=True)
    args = parser.parse_args()

    plot_projection(args.pred, args.truth)