-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
188 lines (156 loc) · 6.67 KB
/
Copy pathmain.py
File metadata and controls
188 lines (156 loc) · 6.67 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
import os
from Environment.SimEnv import SimEnv
from Utils.config import setup_perser, set_params
from Utils.utils import (
display_simulation_config,
simulation_init,
read_from_file,
plot_performance_graph,
_avg_mismatch_series,
_avg_collision_series,
_avg_phase_series,
_avg_accuracy_series,
append_metrics_to_csv,
append_reached_timeseries, # NEW
plot_figures_from_csv, # direction mismatch
plot_collision_figures_from_csv, # collisions
plot_phase_figures_from_csv, # kuramoto-only phase
plot_reached_figures_from_csv, # NEW: agents reached per time step
_ensure_data_dir,
)
from Model.CollectiveDecisionModel import MajorityRuleModel, VoterModel, KuramotoModel
def _run_one(params, model_key, max_steps=0):
"""
Run one model configuration and return averaged metric series + per-step reached counts.
"""
# (Re)generate initial conditions for this run
simulation_init(params)
data_list = read_from_file()
agent_pos = [tuple(e) for e in data_list[0]]
targets = [tuple(e) for e in data_list[1]]
hurdles = [tuple(e) for e in data_list[2]]
simEnv = SimEnv(params, targets)
if model_key == 'majority':
simEnv.model = MajorityRuleModel(agent_pos, targets, params)
pretty = 'Majority Model'
elif model_key == 'voter':
simEnv.model = VoterModel(agent_pos, targets, params)
pretty = 'Voter Model'
elif model_key == 'kuramoto':
simEnv.model = KuramotoModel(agent_pos, targets, params)
pretty = 'Kuramoto Model'
else:
raise ValueError(f'Unknown model_key: {model_key}')
perf = simEnv.run_simulation(hurdles, targets, max_steps=max_steps)
# Grab per-timestep reached counts BEFORE closing
reached_counts = list(simEnv.reached_counts)
simEnv.close_sim()
# Average series per checkpoint for the legacy CSV
return (pretty,
_avg_mismatch_series(perf),
_avg_collision_series(perf),
_avg_phase_series(perf),
_avg_accuracy_series(perf),
reached_counts)
def _batch_sweep(args):
"""
Sweep: agents {10,20,30,40} × targets {2,10} × models {majority,voter,kuramoto}
Save per-checkpoint averages to the main CSV, and per-time-step agents-reached
to Data/reached_timeseries.csv.
"""
env0, sw0 = set_params()
agent_sizes = [10, 20, 30, 40]
target_sizes = [2, 10]
model_keys = ['majority', 'voter', 'kuramoto']
# Headless display/audio for batch runs
os.environ.setdefault('SDL_VIDEODRIVER', 'dummy')
os.environ.setdefault('SDL_AUDIODRIVER', 'dummy')
_ensure_data_dir()
from Utils.utils import _ensure_csv_with_header
_ensure_csv_with_header(args.csv_out)
for A in agent_sizes:
for T in target_sizes:
# Fresh params for this (A, T)
env = dict(env0)
swarm = dict(sw0)
swarm['NUM_AGENTS'] = A
env['NUM_TARGET'] = T
params = [env, swarm]
for mk in model_keys:
name, mis, col, phs, acc, reached = _run_one(params, mk, max_steps=args.max_steps)
# Legacy checkpoint CSV (unchanged)
append_metrics_to_csv(args.csv_out, A, T, name, mis, col, phs, acc)
# NEW: per-time-step agents reached CSV
append_reached_timeseries(A, T, name, reached)
print(f"Saved: A={A}, T={T}, model={name}, checkpoints={len(mis)}, steps={len(reached)}")
print(f"\nSweep complete. CSV: {args.csv_out}")
print("Agents-reached timeseries: Data/reached_timeseries.csv")
print(f"Direction mismatch figs:\n python main.py --plot-only --csv-in {args.csv_out}")
print(f"Collision figs:\n python main.py --plot-collision --csv-in {args.csv_out}")
print(f"Phase-sync figs (Kuramoto):\n python main.py --plot-phase --csv-in {args.csv_out}")
print(f"Agents-reached figs:\n python main.py --plot-accuracy") # reuse flag to avoid new CLI param
def main():
args = setup_perser()
# --- Plot-only branches (no simulation) ---
if getattr(args, 'plot_only', False):
plot_figures_from_csv(args.csv_in) # direction mismatch
print("Figures written to Data/DirectionMismatch_*A_2T_vs_10T.png")
return
if getattr(args, 'plot_collision', False):
plot_collision_figures_from_csv(args.csv_in) # collision
print("Figures written to Data/Collision_*A_2T_vs_10T.png")
return
if getattr(args, 'plot_phase', False):
plot_phase_figures_from_csv(args.csv_in) # phase sync (Kuramoto)
print("Figures written to Data/PhaseSync_*A_2T_vs_10T.png")
return
# Reuse --plot-accuracy to plot the *new* per-time-step counts
if getattr(args, 'plot_accuracy', False):
plot_reached_figures_from_csv('Data/reached_timeseries.csv')
print("Figures written to Data/AgentsReached_*A_2T_vs_10T.png")
return
# --- Batch sweep ---
if getattr(args, 'batch', False):
_batch_sweep(args)
return
# --- Single-run (interactive window) ---
params = set_params()
print('\n')
print('%' * 60)
if getattr(args, 'newdata', False):
is_new_data = True
print('Simulation has been started with New Data')
else:
is_new_data = False
print('Simulation has been started with Old Data')
display_simulation_config(params)
if is_new_data:
simulation_init(params)
data_list = read_from_file()
agent_pos = [tuple(element) for element in data_list[0]]
targets = [tuple(element) for element in data_list[1]]
hurdles = [tuple(element) for element in data_list[2]]
simEnv = SimEnv(params, targets)
# Choose model by flags; default to Majority to avoid None crash
if getattr(args, 'majority', False):
simEnv.model = MajorityRuleModel(agent_pos, targets, params)
print('Model Select :', simEnv.model.Name)
elif getattr(args, 'voter', False):
simEnv.model = VoterModel(agent_pos, targets, params)
print('Model Select :', simEnv.model.Name)
elif getattr(args, 'kuramoto', False):
simEnv.model = KuramotoModel(agent_pos, targets, params)
print('Model Select :', simEnv.model.Name)
else:
print('No model selected via CLI, defaulting to Majority Model (-m).')
simEnv.model = MajorityRuleModel(agent_pos, targets, params)
print('Model Select :', simEnv.model.Name)
performance_data = simEnv.run_simulation(
hurdles,
targets,
max_steps=getattr(args, 'max_steps', 0)
)
plot_performance_graph(simEnv.model.Name, performance_data, params)
simEnv.close_sim()
if __name__ == "__main__":
main()