-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualize_metrics.py
More file actions
190 lines (159 loc) · 5.83 KB
/
Copy pathvisualize_metrics.py
File metadata and controls
190 lines (159 loc) · 5.83 KB
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
187
188
189
190
"""Run two side-by-side simulations and plot all tracked metrics.
Baseline: moderate_lockin scenario (a2=0.5), lock-in premium off (a4=0).
Treatment: same scenario, lock-in premium on (a4=1.0, K=3).
Usage:
python scripts/visualize_metrics.py
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import pandas as pd
from spatial_market_lockin import ModelConfig, SpatialMarketModel
from spatial_market_lockin.metrics import lifetime_counts, summarize_run
from spatial_market_lockin.scenarios import scenario_overrides
STEPS = 300
SEED = 42
PARTIAL_LOCKIN = scenario_overrides("moderate_lockin")
configs = {
"No lock-in premium (a4=0)": ModelConfig(
seed=SEED,
steps=STEPS,
**{**PARTIAL_LOCKIN, "a4": 0.0},
),
"Lock-in premium (a4=1.0, K=3)": ModelConfig(
seed=SEED,
steps=STEPS,
**{**PARTIAL_LOCKIN, "a4": 1.0, "loyalty_threshold_k": 3},
),
}
COLORS = ["#2166ac", "#d6604d"]
def run(config: ModelConfig) -> SpatialMarketModel:
model = SpatialMarketModel(config)
model.run()
return model
print("Running simulations...")
models: dict[str, SpatialMarketModel] = {}
for label, cfg in configs.items():
print(f" {label} ...")
models[label] = run(cfg)
print("Done.\n")
# --- extract time series ---
def ts(model: SpatialMarketModel) -> pd.DataFrame:
df = model.datacollector.get_model_vars_dataframe().reset_index(drop=True)
df["tick"] = range(len(df))
return df
frames = {label: ts(m) for label, m in models.items()}
# --- summary stats ---
print("=" * 60)
print(f"{'Metric':<30} {'Baseline':>18} {'Lock-in premium':>18}")
print("-" * 60)
summaries = {label: summarize_run(m) for label, m in models.items()}
keys_to_show = [
("switch_rate", "Switch rate"),
("switch_rate_traders", "Switch rate (traders)"),
("revealed_lock_in", "Revealed lock-in"),
("revealed_suboptimal_rate", "Revealed suboptimal"),
("streak_suboptimal_rate", "Streak suboptimal"),
("never_transacted", "Never transacted"),
("avg_lifespan", "Avg buyer lifespan (ticks)"),
("avg_posted_price", "Avg posted price"),
("avg_transaction_price", "Avg transaction price"),
("price_cv", "Price CV"),
("price_spread", "Price spread (max/min)"),
("avg_lock_in_rate", "Avg lock-in rate"),
("completed_lives", "Completed buyer lives"),
]
labels = list(configs.keys())
for key, display in keys_to_show:
v0 = summaries[labels[0]].get(key, float("nan"))
v1 = summaries[labels[1]].get(key, float("nan"))
print(f" {display:<28} {v0:>18.4f} {v1:>18.4f}")
print("=" * 60)
# --- plot ---
fig = plt.figure(figsize=(18, 28))
fig.suptitle(
f"Spatial Market Lock-In ABM | moderate_lockin scenario | {STEPS} ticks | seed={SEED}",
fontsize=13,
fontweight="bold",
y=0.99,
)
gs = gridspec.GridSpec(6, 2, figure=fig, hspace=0.55, wspace=0.35)
# Time series panels
ts_panels = [
(0, 0, "avg_posted_price", "Avg posted price", "Price"),
(0, 1, "price_cv", "Price dispersion (CV)", "CV"),
(1, 0, "lock_in_rate", "Instantaneous lock-in rate", "Fraction"),
(1, 1, "suboptimal_lock_in_rate", "Suboptimal lock-in rate", "Fraction"),
(2, 0, "living_buyers", "Living buyers", "Count"),
(2, 1, "living_sellers", "Living sellers", "Count"),
(3, 0, "num_transactions", "Transactions per tick", "Count"),
(3, 1, "avg_transaction_price", "Avg transaction price", "Price"),
(4, 0, "step_buyer_deaths", "Buyer deaths per tick", "Count"),
(4, 1, "cumulative_seller_deaths", "Cumulative seller deaths", "Count"),
]
for row, col, col_name, title, ylabel in ts_panels:
ax = fig.add_subplot(gs[row, col])
for i, (label, df) in enumerate(frames.items()):
if col_name in df.columns:
ax.plot(
df["tick"],
df[col_name],
label=label,
color=COLORS[i],
linewidth=1.2,
alpha=0.85,
)
ax.set_title(title, fontsize=10, fontweight="bold")
ax.set_xlabel("Tick", fontsize=8)
ax.set_ylabel(ylabel, fontsize=8)
ax.tick_params(labelsize=7)
ax.legend(fontsize=7, framealpha=0.6)
ax.grid(True, linewidth=0.4, alpha=0.5)
# Row 5: welfare metric bar charts (lifetime metrics, not per-tick)
welfare_metrics = [
(
5,
0,
"revealed_suboptimal_rate",
"Revealed-suboptimal rate\n(≤2 sellers, believed cheaper exists)",
),
(
5,
1,
"streak_suboptimal_rate",
"Streak-suboptimal rate\n(streak ≥ k, believed cheaper exists)",
),
]
for row, col, key, title in welfare_metrics:
ax = fig.add_subplot(gs[row, col])
values = [summaries[label].get(key, float("nan")) for label in labels]
bars = ax.bar(labels, values, color=COLORS, alpha=0.85, width=0.5)
for bar, val in zip(bars, values):
if not np.isnan(val):
ax.text(
bar.get_x() + bar.get_width() / 2,
bar.get_height() + 0.005,
f"{val:.1%}",
ha="center",
va="bottom",
fontsize=8,
fontweight="bold",
)
ax.set_title(title, fontsize=10, fontweight="bold")
ax.set_ylabel("Fraction of buyer lives", fontsize=8)
ax.set_ylim(0, max(v for v in values if not np.isnan(v)) * 1.25 + 0.01)
ax.tick_params(axis="x", labelsize=7)
ax.tick_params(axis="y", labelsize=7)
ax.grid(True, axis="y", linewidth=0.4, alpha=0.5)
images_dir = Path(__file__).resolve().parent.parent / "images"
images_dir.mkdir(exist_ok=True)
out = images_dir / "metrics_output.png"
fig.savefig(out, dpi=130, bbox_inches="tight")
print(f"\nSaved chart to {out}")
plt.close(fig)