Repository navigation
Expand file tree
/
Copy pathvisualization.py
More file actions
4673 lines (3807 loc) · 202 KB
/
Copy pathvisualization.py
File metadata and controls
4673 lines (3807 loc) · 202 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Visualization module for ALT Metrics experiments.
Contains all visualization and analysis functions migrated from new_code.py.
Updated naming (Dec 29, 2025):
- qFALT/qEALT (quadratic) instead of EFALT/EEALT (exponential) - mathematically correct
- ILF/IQF (Inverse Linear/Quadratic Fractional) instead of EFR/EAFR - mathematically correct
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import config
from config import (
COLOR_PALETTE, BASE_EPISODES, EPSILON_DECAY_TARGET, EPSILON_MIN, EPSILON_INITIAL
)
from metrics import (
compute_alt_metrics, compute_rp_metrics,
compute_efficiency, compute_reward_fairness, compute_tt_fairness, compute_fairness,
calculate_coordination_score, calculate_alt_ratio
)
def create_figure_7_altratio_analysis(results_list):
"""
Figure 7: AltRatio Analysis - separate plots for each mode (Type-A/B × ILF/IQF).
Creates 4 separate figures, each with 2 subplots (estimated agents, percentages).
"""
# Define 4 modes
modes = [
('Type-A', 'ILF'),
('Type-A', 'IQF'),
('Type-B', 'ILF'),
('Type-B', 'IQF')
]
for state_type, reward_type in modes:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
# Filter results for this mode
results = [r for r in results_list if r.get('state_type', '') == state_type
and r['reward_type'] == reward_type
and not r.get('is_random_baseline', False)]
results.sort(key=lambda x: x['num_agents'])
if not results:
plt.close()
continue
# Build separate agent lists for each metric (in case some metrics are missing for some agents)
agents_per_metric = {metric: [] for metric in ['FALT', 'EALT', 'qFALT', 'qEALT', 'CALT', 'AALT']}
estimated_agents = {metric: [] for metric in ['FALT', 'EALT', 'qFALT', 'qEALT', 'CALT', 'AALT']}
percentages = {metric: [] for metric in ['FALT', 'EALT', 'qFALT', 'qEALT', 'CALT', 'AALT']}
for r in results:
for metric in estimated_agents.keys():
if 'estimated_agents' in r and metric in r['estimated_agents']:
agents_per_metric[metric].append(r['num_agents'])
estimated_agents[metric].append(r['estimated_agents'][metric])
percentages[metric].append(r['percentages'][metric])
# Get unique agent counts for perfect alternation line
all_agents = sorted(set([r['num_agents'] for r in results]))
# Panel (a): Estimated agents for all ALT metrics
for metric in ['FALT', 'EALT', 'qFALT', 'qEALT', 'CALT', 'AALT']:
if estimated_agents[metric]:
ax1.plot(agents_per_metric[metric], estimated_agents[metric], 'o-',
label=metric, color=COLOR_PALETTE[metric], markersize=5, linewidth=1.5)
# Add perfect alternation line - semi-transparent dashed
if all_agents:
ax1.plot(all_agents, all_agents, 'r--', label='Perfect Alternation',
linewidth=2, alpha=0.5, zorder=5)
ax1.set_xlabel('Number of Agents', fontsize=11)
ax1.set_ylabel('Estimated Alternating Agents', fontsize=11)
ax1.set_title(f'(a) AltRatio Estimation - {state_type} {reward_type}', fontsize=11)
ax1.grid(True, alpha=0.3)
ax1.legend(fontsize=9, loc='upper left', framealpha=0.9)
# Panel (b): Percentages for all ALT metrics (NO 65-70% range)
x = np.arange(len(all_agents))
width = 0.12
metrics_to_show = ['FALT', 'EALT', 'qFALT', 'qEALT', 'CALT', 'AALT']
for i, metric in enumerate(metrics_to_show):
if percentages[metric]:
# Map metric's agent counts to x positions
x_positions = [all_agents.index(agent) for agent in agents_per_metric[metric]]
offset = width * (i - len(metrics_to_show)/2 + 0.5)
ax2.bar(np.array(x_positions) + offset, percentages[metric], width,
label=metric, color=COLOR_PALETTE[metric])
# NO 65-70% range lines
ax2.set_xlabel('Number of Agents', fontsize=11)
ax2.set_ylabel('Alternation Percentage (%)', fontsize=11)
ax2.set_title(f'(b) Achieved Alternation - {state_type} {reward_type}', fontsize=11)
ax2.set_xticks(x)
ax2.set_xticklabels(all_agents)
ax2.legend(fontsize=9, loc='best', framealpha=0.9)
ax2.grid(True, alpha=0.3, axis='y')
ax2.set_ylim([0, 105])
plt.suptitle(f'Figure 7: ALT Ratio Analysis - {state_type} {reward_type}',
fontsize=13, fontweight='bold')
plt.tight_layout()
plt.savefig(os.path.join(config.figure_dirs['main'],
f'figure_7_altratio_{state_type}_{reward_type}.png'), dpi=300)
plt.show()
plt.close()
print(f"[OK] Saved Figure 7 for {state_type} {reward_type}")
def create_figure_6_metric_progression_rate(results_list, metric='CALT'):
"""
Figure 6: Metric progression rate for all 4 modes (Type-A/B × ILF/IQF).
4 subplots in 2×2 grid, normalized 0-1, no slope annotations, with random baselines.
"""
# Create 2x2 grid for all 4 modes
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
axes = axes.flatten()
# Define 4 modes
modes = [
('Type-A', 'ILF', 0),
('Type-A', 'IQF', 1),
('Type-B', 'ILF', 2),
('Type-B', 'IQF', 3)
]
# Import colormap for gradient
import matplotlib.cm as cm
for state_type, reward_type, subplot_idx in modes:
ax = axes[subplot_idx]
# Get Q-learning results for this mode
ql_results = [r for r in results_list if r.get('state_type', '') == state_type
and r['reward_type'] == reward_type
and not r.get('is_random_baseline', False)]
ql_results.sort(key=lambda x: x['num_agents'])
# Get random baseline for this reward type
random_results = [r for r in results_list if r.get('is_random_baseline', False)
and r['reward_type'] == reward_type]
# Generate color gradient for agent counts
n_results = len(ql_results)
if n_results > 0:
colors = cm.get_cmap('viridis')(np.linspace(0.3, 0.9, n_results))
# Plot Q-learning curves with gradient colors
for i, result in enumerate(ql_results):
metric_vals = result['progression_data'][metric]
episodes = result['episode_points']
# Normalize episodes 0-1
norm_episodes = [ep / result['num_episodes'] for ep in episodes]
ax.plot(norm_episodes, metric_vals,
label=f"{result['num_agents']} agents",
linestyle='-', # Solid only
alpha=0.85, linewidth=2.0,
color=colors[i]) # Gradient color
# Add epsilon milestone indicator (vertical line)
if len(ql_results) > 0 and 'Epsilon' in ql_results[0]['progression_data']:
# Get epsilon decay target from global parameters
epsilon_decay_target = ql_results[0].get('q_learning_info', {}).get('epsilon_decay_target', EPSILON_DECAY_TARGET)
# Draw vertical line at epsilon milestone - use metric's palette color
ax.axvline(x=epsilon_decay_target,
color=COLOR_PALETTE.get(metric, 'gray'), linestyle=':',
linewidth=1.5, alpha=0.4,
label=f'ε-min@{epsilon_decay_target:.0%}')
# Add random baseline with text annotation on line
for random_result in random_results:
if metric in random_result['metrics']:
n_agents = random_result['num_agents']
random_value = random_result['metrics'][metric]
# Draw horizontal line
ax.axhline(y=random_value, color='gray', linestyle=':',
linewidth=1.5, alpha=0.4)
# Add small text label ON the line (right side)
ax.text(0.98, random_value, f'random ({n_agents}a)',
transform=ax.get_yaxis_transform(),
fontsize=7, va='center', ha='right',
bbox=dict(boxstyle='round,pad=0.2', fc='white', alpha=0.7))
ax.set_xlabel('Episode Progress (0-1)', fontsize=10)
ax.set_ylabel(f'{metric} Value', fontsize=10)
ax.set_title(f'{state_type} {reward_type}', fontsize=11, fontweight='bold')
legend = ax.legend(fontsize=8, loc='best', ncol=2,
frameon=True, fancybox=True,
framealpha=0.7, edgecolor='gray',
facecolor='white')
legend.get_frame().set_boxstyle('round', pad=0.5)
ax.grid(True, alpha=0.3)
ax.set_xlim([0, 1])
ax.set_ylim([0, 1.05])
plt.suptitle(f'Figure 6: {metric} Progression Rate (All Modes)', fontsize=13, fontweight='bold')
plt.tight_layout()
plt.savefig(os.path.join(config.figure_dirs['main'], f'figure_6_{metric}_progression_rate_all_modes.png'), dpi=300)
plt.show()
plt.close()
def create_figure_2_type_comparison(results_list):
"""
Figure 2: Type-A vs Type-B Progression with ALL metrics (Traditional + ALT).
Creates comprehensive 4x2 plot showing both ILF and IQF for both state types.
4 rows (Type-A ILF, Type-A IQF, Type-B ILF, Type-B IQF) × 2 cols (Traditional, ALT)
"""
# Use only 2 agents for simplicity
selected_agents = [2]
fig, axes = plt.subplots(4, 2, figsize=(14, 16))
# Find all 4 combinations
type_a_efr = next((r for r in results_list if r['num_agents'] == selected_agents[0] and
r.get('state_type', '') == 'Type-A' and r['reward_type'] == 'ILF'), None)
type_a_eafr = next((r for r in results_list if r['num_agents'] == selected_agents[0] and
r.get('state_type', '') == 'Type-A' and r['reward_type'] == 'IQF'), None)
type_b_efr = next((r for r in results_list if r['num_agents'] == selected_agents[0] and
r.get('state_type', '') == 'Type-B' and r['reward_type'] == 'ILF'), None)
type_b_eafr = next((r for r in results_list if r['num_agents'] == selected_agents[0] and
r.get('state_type', '') == 'Type-B' and r['reward_type'] == 'IQF'), None)
results_grid = [
(type_a_efr, 'Type-A ILF', 0),
(type_a_eafr, 'Type-A IQF', 1),
(type_b_efr, 'Type-B ILF', 2),
(type_b_eafr, 'Type-B IQF', 3)
]
for result, label, row_idx in results_grid:
if result:
x_vals = [e/result['num_episodes'] for e in result['episode_points']]
# Left column: Traditional Metrics
for metric in ['Efficiency', 'Reward_Fairness', 'TT_Fairness', 'Fairness']:
axes[row_idx, 0].plot(x_vals, result['progression_data'][metric],
label=metric, alpha=0.8, color=COLOR_PALETTE.get(metric), linewidth=1.5)
axes[row_idx, 0].set_title(f'{label} - Traditional ({selected_agents[0]} agents)', fontsize=10)
axes[row_idx, 0].set_xlabel('Episode Progress', fontsize=9)
axes[row_idx, 0].set_ylabel('Metric Value', fontsize=9)
axes[row_idx, 0].grid(True, alpha=0.3)
axes[row_idx, 0].legend(fontsize=7, loc='best')
axes[row_idx, 0].set_ylim([0, 1.05])
# Right column: ALT Metrics
for metric in ['FALT', 'EALT', 'qFALT', 'qEALT', 'CALT', 'AALT']:
axes[row_idx, 1].plot(x_vals, result['progression_data'][metric],
label=metric, alpha=0.8, color=COLOR_PALETTE.get(metric), linewidth=1.5)
axes[row_idx, 1].set_title(f'{label} - ALT ({selected_agents[0]} agents)', fontsize=10)
axes[row_idx, 1].set_xlabel('Episode Progress', fontsize=9)
axes[row_idx, 1].set_ylabel('Metric Value', fontsize=9)
axes[row_idx, 1].grid(True, alpha=0.3)
axes[row_idx, 1].legend(fontsize=7, loc='best')
axes[row_idx, 1].set_ylim([0, 1.05])
plt.tight_layout()
plt.savefig(os.path.join(config.figure_dirs['main'], 'figure_2_type_comparison_comprehensive.png'), dpi=300)
plt.show()
plt.close()
def create_random_baseline_progression_plots(results_list):
"""Create progression plots for random baselines showing ALL metrics."""
print("\n== Creating Random Baseline Progression Plots ==")
# Filter random baseline results
random_results = [r for r in results_list if r.get('is_random_baseline', False)
and r['reward_type'] == 'ILF' and 'progression_data' in r]
random_results.sort(key=lambda x: x['num_agents'])
for result in random_results:
n_agents = result['num_agents']
n_episodes = result['num_episodes']
progression_data = result['progression_data']
episode_points = result['episode_points']
# Normalize episode points
x_vals = [e / n_episodes for e in episode_points]
# Create 2x2 plot
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 8))
# Panel 1: Traditional Metrics
for metric in ['Efficiency', 'Reward_Fairness', 'TT_Fairness', 'Fairness']:
ax1.plot(x_vals, progression_data[metric],
label=metric, alpha=0.8, color=COLOR_PALETTE.get(metric), linewidth=1.5)
ax1.set_title(f'(a) Traditional Metrics - Random Policy ({n_agents} agents)', fontsize=10)
ax1.set_xlabel('Episode Progress')
ax1.set_ylabel('Metric Value')
ax1.grid(True, alpha=0.3)
ax1.legend(fontsize=8)
# Panel 2: F-based ALT Metrics
for metric in ['FALT', 'qFALT']:
ax2.plot(x_vals, progression_data[metric],
label=metric, alpha=0.8, color=COLOR_PALETTE.get(metric), linewidth=1.5)
ax2.set_title(f'(b) Frequency ALT Metrics - Random Policy ({n_agents} agents)', fontsize=10)
ax2.set_xlabel('Episode Progress')
ax2.set_ylabel('Metric Value')
ax2.grid(True, alpha=0.3)
ax2.legend(fontsize=8)
# Panel 3: E-based ALT Metrics
for metric in ['EALT', 'qEALT']:
ax3.plot(x_vals, progression_data[metric],
label=metric, alpha=0.8, color=COLOR_PALETTE.get(metric), linewidth=1.5)
ax3.set_title(f'(c) Episode ALT Metrics - Random Policy ({n_agents} agents)', fontsize=10)
ax3.set_xlabel('Episode Progress')
ax3.set_ylabel('Metric Value')
ax3.grid(True, alpha=0.3)
ax3.legend(fontsize=8)
# Panel 4: Combined ALT Metrics
for metric in ['CALT', 'AALT']:
ax4.plot(x_vals, progression_data[metric],
label=metric, alpha=0.8, color=COLOR_PALETTE.get(metric), linewidth=1.5)
ax4.set_title(f'(d) Combined ALT Metrics - Random Policy ({n_agents} agents)', fontsize=10)
ax4.set_xlabel('Episode Progress')
ax4.set_ylabel('Metric Value')
ax4.grid(True, alpha=0.3)
ax4.legend(fontsize=8)
plt.tight_layout()
plt.savefig(os.path.join(config.figure_dirs['random'],
f'random_baseline_progression_{n_agents}agents.png'), dpi=300)
plt.show()
plt.close()
print(f"[OK] Saved random baseline progression for {n_agents} agents")
print("[OK] Random baseline progression plots completed")
def create_random_vs_qlearning_comparison(results_list, metric='CALT'):
"""
Create a figure comparing random policies vs Q-learning for a specific metric.
Shows all 4 modes (Type-A/B × ILF/IQF) on the same plot.
"""
fig, ax = plt.subplots(figsize=(10, 6))
# Define 4 modes with colors and line styles
modes = [
('Type-A', 'ILF', 'o-', 0.9, '#1f77b4'), # Blue
('Type-A', 'IQF', 's--', 0.9, '#ff7f0e'), # Orange
('Type-B', 'ILF', 'D-.', 0.9, '#2ca02c'), # Green
('Type-B', 'IQF', '^:', 0.9, '#d62728') # Red
]
# Collect all random baselines first to check if they're identical
random_baselines_by_mode = {}
all_values = []
# First pass: collect random baselines
for state_type, reward_type, _, _, _ in modes:
random_results = [r for r in results_list if r.get('is_random_baseline', False)
and r['reward_type'] == reward_type]
random_results.sort(key=lambda x: x['num_agents'])
if random_results:
random_agents = [r['num_agents'] for r in random_results]
random_values = [r['metrics'][metric] for r in random_results]
mode_key = f'{state_type}_{reward_type}'
random_baselines_by_mode[mode_key] = (random_agents, random_values)
# Check if all random baselines are identical
random_values_lists = [vals for _, vals in random_baselines_by_mode.values()]
all_random_same = len(set(tuple(vals) for vals in random_values_lists)) == 1 if random_values_lists else True
# Second pass: plot Q-learning and random baselines
random_plotted = False
for state_type, reward_type, linestyle_marker, alpha_val, mode_color in modes:
# Get Q-learning results
qlearning_results = [r for r in results_list if r.get('state_type', '') == state_type
and r['reward_type'] == reward_type
and not r.get('is_random_baseline', False)]
qlearning_results.sort(key=lambda x: x['num_agents'])
if not qlearning_results:
continue
# Extract Q-learning data
qlearning_agents = [r['num_agents'] for r in qlearning_results]
qlearning_values = [r['metrics'][metric] for r in qlearning_results]
# Collect values for auto-zoom
all_values.extend(qlearning_values)
# Plot Q-learning
label = f'Q-Learning {state_type} {reward_type}'
ax.plot(qlearning_agents, qlearning_values, linestyle_marker,
label=label, markersize=6, linewidth=2, alpha=alpha_val,
color=mode_color)
# Plot random baseline
mode_key = f'{state_type}_{reward_type}'
if mode_key in random_baselines_by_mode:
random_agents, random_values = random_baselines_by_mode[mode_key]
all_values.extend(random_values)
if all_random_same:
# All random baselines are the same - plot only once
if not random_plotted:
random_plotted = True
ax.plot(random_agents, random_values, 'x--',
label='Random baseline',
markersize=6, linewidth=1.5, alpha=0.4,
color='gray')
else:
# Random baselines differ (shouldn't happen!) - plot each with mode label
ax.plot(random_agents, random_values, 'x--',
label=f'Random {state_type}-{reward_type}',
markersize=6, linewidth=1.5, alpha=0.4,
color=mode_color)
# Auto-zoom based on data range
if all_values:
min_val = min(all_values)
max_val = max(all_values)
ax.set_ylim([min_val * 0.90, max_val * 1.05])
else:
ax.set_ylim([0, 1.05]) # Fallback
ax.set_xlabel('Number of Agents', fontsize=12)
ax.set_ylabel(f'{metric} Value', fontsize=12)
ax.set_title(f'Random vs Q-Learning Comparison: {metric} by Agent Count', fontsize=13, fontweight='bold')
ax.legend(fontsize=9, loc='best', ncol=2, framealpha=0.95)
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(config.figure_dirs['comparison'], f'random_vs_qlearning_{metric}_all_modes.png'), dpi=300)
plt.show()
plt.close()
def create_alt_ratio_benchmark_comparison(results_list, metric='CALT'):
"""Compare Q-learning results with PA benchmark values - 4 bars per agent (all modes)."""
fig, ax = plt.subplots(figsize=(10, 5))
# Define 4 modes
modes = [
('Type-A', 'ILF', COLOR_PALETTE.get(metric, 'blue'), 0.85),
('Type-A', 'IQF', COLOR_PALETTE.get(metric, 'blue'), 0.6),
('Type-B', 'ILF', COLOR_PALETTE.get(metric, 'blue'), 0.35),
('Type-B', 'IQF', COLOR_PALETTE.get(metric, 'blue'), 0.1)
]
# Get all unique agent counts
all_agent_counts = sorted(set([r['num_agents'] for r in results_list
if not r.get('is_random_baseline', False)]))
# Prepare data for each mode
mode_data = []
for state_type, reward_type, color, alpha_adjust in modes:
qlearning_results = [r for r in results_list if r.get('state_type', '') == state_type
and r['reward_type'] == reward_type
and not r.get('is_random_baseline', False)]
qlearning_results.sort(key=lambda x: x['num_agents'])
# Get PA equivalents for this mode
pa_equivalents = []
for n_agents in all_agent_counts:
result = next((r for r in qlearning_results if r['num_agents'] == n_agents), None)
if result:
pa_eq = result['estimated_agents'].get(metric, 0)
pa_equivalents.append(pa_eq)
else:
pa_equivalents.append(0)
mode_data.append({
'label': f'{state_type} {reward_type}',
'pa_equivalents': pa_equivalents,
'color': color,
'alpha': 0.9 - alpha_adjust
})
# Create grouped bar chart
x = np.arange(len(all_agent_counts))
bar_width = 0.2
for i, mode_info in enumerate(mode_data):
offset = (i - 1.5) * bar_width
bars = ax.bar(x + offset, mode_info['pa_equivalents'],
width=bar_width,
label=mode_info['label'],
color=mode_info['color'],
alpha=mode_info['alpha'],
edgecolor='black',
linewidth=0.5)
# Add percentage labels on bars
for j, (pa_eq, n_agents) in enumerate(zip(mode_info['pa_equivalents'], all_agent_counts)):
if pa_eq > 0:
pct = (pa_eq / n_agents) * 100
ax.annotate(f"{pct:.0f}%",
xy=(x[j] + offset, pa_eq),
xytext=(0, 3),
textcoords="offset points",
ha='center',
fontsize=7,
rotation=0)
# Add perfect alternation line
perfect_line = all_agent_counts
ax.plot(x, perfect_line, 'r--', label='Perfect Alternation', linewidth=2.5, alpha=0.7, zorder=10)
# Set labels and formatting
ax.set_xticks(x)
ax.set_xticklabels(all_agent_counts)
ax.set_xlabel('Number of Agents', fontsize=12)
ax.set_ylabel('PA Equivalent Agents', fontsize=12)
ax.set_title(f'Figure 10: Perfect Alternation Equivalent Agents ({metric})', fontsize=13, fontweight='bold')
ax.legend(fontsize=9, loc='upper left', ncol=2, framealpha=0.95)
ax.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(config.figure_dirs['alt_ratio'], f'pa_equivalent_{metric}_all_modes.png'), dpi=300)
plt.show()
plt.close()
def create_alt_ratio_comparison_table(results_list):
"""Create a table comparing ALT ratio estimates across metrics and agent counts."""
# Get Q-learning results for Type-B ILF
qlearning_results = [r for r in results_list if r.get('state_type', '') == 'Type-B'
and r['reward_type'] == 'ILF' and not r.get('is_random_baseline', False)]
qlearning_results.sort(key=lambda x: x['num_agents'])
# Get random results
random_results = [r for r in results_list if r.get('is_random_baseline', False) == True and r['reward_type'] == 'ILF']
random_results.sort(key=lambda x: x['num_agents'])
# Create table data
table_data = []
header = ['Agents', 'Metric', 'Q-Learning PA Equivalent', 'Random PA Equivalent', 'Coordination Score']
metrics = ['FALT', 'EALT', 'qFALT', 'qEALT', 'CALT', 'AALT']
for ql_result in qlearning_results:
n = ql_result['num_agents']
# Find corresponding random result
rand_result = next((r for r in random_results if r['num_agents'] == n), None)
if rand_result:
for metric in metrics:
ql_val = ql_result['estimated_agents'].get(metric, 0)
rand_val = rand_result['estimated_agents'].get(metric, 0)
if ql_val > 0 or rand_val > 0:
coord_score = calculate_coordination_score(
ql_result['metrics'].get(metric, 0),
rand_result['metrics'].get(metric, 0),
1.0 # Perfect value
)
table_data.append([
n,
metric,
f"{ql_val:.2f} ({ql_val/n:.1%})",
f"{rand_val:.2f} ({rand_val/n:.1%})",
f"{coord_score:.2f}"
])
# Create DataFrame
df = pd.DataFrame(table_data, columns=header)
# Save to CSV
csv_path = os.path.join(config.figure_dirs['tables'], 'alt_ratio_comparison.csv')
df.to_csv(csv_path, index=False)
# Display table
display(df)
# Return DataFrame
return df
def create_all_alt_ratio_figures(results_list):
"""Create all ALT ratio benchmark figures and tables."""
metrics = ['FALT', 'EALT', 'CALT'] # Primary metrics for Paper 1
print("\n== ALT Ratio Analysis ==")
# Create PA equivalent comparison figures for each primary metric
for metric in metrics:
create_alt_ratio_benchmark_comparison(results_list, metric)
# Create comparative table
df = create_alt_ratio_comparison_table(results_list)
return df
#===============================================================================
# Main Execution
#===============================================================================
def run_single_experiment_worker(experiment_params):
"""Worker function to run a single experiment (for multiprocessing)."""
num_agents, state_type, reward_type, experiment_type = experiment_params
# Reset seed for reproducibility
random.seed(42 + num_agents) # Different seed per agent count
np.random.seed(42 + num_agents)
try:
if state_type == 'Random':
# Random policy simulation
print(f" [Process {os.getpid()}] Running random baseline: {num_agents} agents, {reward_type}")
num_episodes = 10000
result = simulate_random_policy(num_agents, num_episodes, reward_type=reward_type)
elif experiment_type == 'theory':
# Theory-based episodes calculation
num_episodes = calculate_episodes_theory_based(num_agents, BASE_EPISODES)
print(f" [Process {os.getpid()}] Theory-based: {num_agents} agents, {state_type}, {reward_type} - {num_episodes} episodes")
result = run_q_learning_experiment(num_agents, num_episodes, state_type, reward_type, decay_schedule='exponential')
else:
# Adaptive threshold-based approach
print(f" [Process {os.getpid()}] Adaptive: {num_agents} agents, {state_type}, {reward_type}")
alt_thresholds = {
'CALT': 0.6,
'FALT': 0.7,
'EALT': 0.7,
'qFALT': 0.5,
'qEALT': 0.5,
'AALT': 0.4
}
result = run_adaptive_q_learning_experiment(
num_agents, state_type, reward_type,
alt_thresholds=alt_thresholds,
patience=5000,
max_episodes=150000
)
# Clean up memory
gc.collect()
# Print completion message
if state_type == 'Random':
print(f"[OK] Completed random baseline: {num_agents} agents, {reward_type}")
else:
print(f"[OK] Completed Q-learning: {num_agents} agents, {state_type}, {reward_type}")
return result
except Exception as e:
print(f"ERROR in worker [Process {os.getpid()}]: {num_agents} agents, {state_type}, {reward_type} - {str(e)}")
import traceback
traceback.print_exc()
return None
def run_experiments(experiment_type='theory'):
"""Run experiments with selected approach (with optional multiprocessing)."""
if IN_COLAB:
keep_colab_alive()
results_list = load_results()
# For Paper 1, focus on 2-10 agents
# PRODUCTION CONFIGURATION: Run benchmark_test.py first to determine optimal settings
# Adjust based on benchmark results:
# - Full: [2, 3, 5, 8, 10, 12] if machine can handle (~92 hours)
# - Reduced: [2, 3, 5, 8, 10] if limited time (~67 hours)
# - Minimal: [2, 3, 5, 8] if limited resources (~40 hours)
# Experiment configurations:
# BASE=100: [2,3] ~2min (quick test with fixes) ✅ TESTING
# BASE=1000: [2,3,5,8,10] ~40min-1hr (verification)
# BASE=5000: [2,3,5,8,10] ~3-5hrs (mid-scale)
# BASE=10000: [2,3,5,8,10] ~7-10hrs (production)
agent_counts = [2, 3, 5, 8, 10] # BASE=1000 verification run
state_types = ['Type-A', 'Type-B']
reward_types = ['ILF', 'IQF']
# Generate experiments to run list
experiments_to_run = []
for num_agents in agent_counts:
for state_type in state_types:
for reward_type in reward_types:
if not is_experiment_completed(results_list, num_agents, state_type, reward_type):
experiments_to_run.append((
num_agents, state_type, reward_type, experiment_type
))
# Add random baselines
for num_agents in agent_counts:
for reward_type in reward_types:
if not is_experiment_completed(results_list, num_agents, None, reward_type, is_random=True):
experiments_to_run.append((
num_agents, 'Random', reward_type, experiment_type
))
if not experiments_to_run:
print("All experiments completed!")
return results_list
print(f"Running {len(experiments_to_run)} experiments with {experiment_type} approach...")
# Multiprocessing or sequential
if USE_MULTIPROCESSING and len(experiments_to_run) > 1:
print(f"Using multiprocessing with {NUM_PROCESSES} parallel processes")
print("NOTE: Progress bars may overlap - this is normal")
# Use multiprocessing Pool
with mp.Pool(processes=NUM_PROCESSES) as pool:
new_results = pool.map(run_single_experiment_worker, experiments_to_run)
# Add successful results to list
for result in new_results:
if result is not None:
results_list.append(result)
print(f"Completed {sum(1 for r in new_results if r is not None)}/{len(experiments_to_run)} experiments")
else:
# Sequential execution (original behavior)
print("Running experiments sequentially (multiprocessing disabled)")
for i, exp_params in enumerate(experiments_to_run):
print(f"Progress: {i+1}/{len(experiments_to_run)} ({(i+1)/len(experiments_to_run)*100:.1f}%)")
result = run_single_experiment_worker(exp_params)
if result is not None:
results_list.append(result)
gc.collect()
return results_list
def create_agent_performance_summary(results_list):
"""
Create individual agent performance breakdown figure.
Shows:
1. How many times each individual agent reached terminal position
2. How many exclusive wins each agent got
3. Comprehensive table of ALL metrics (Traditional + ALT)
Purpose: Reveal hidden inequality - even with high aggregate fairness,
individual agents may have very unequal performance.
"""
# Filter Q-learning results (Type-B ILF for consistency)
qlearning_results = [r for r in results_list
if not r.get('is_random_baseline', False)
and r.get('state_type', '') == 'Type-B'
and r['reward_type'] == 'ILF'
and 'agent_stats' in r]
qlearning_results.sort(key=lambda x: x['num_agents'])
if not qlearning_results:
print("No Q-learning results with agent_stats found")
return
# Create figure with 2 bar plots + 1 table
from matplotlib.gridspec import GridSpec
fig = plt.figure(figsize=(18, 10))
gs = GridSpec(2, 1, figure=fig, hspace=0.4, height_ratios=[1, 0.6])
# Top: 2 bar plots side by side
gs_top = gs[0].subgridspec(1, 2, wspace=0.3)
ax1 = fig.add_subplot(gs_top[0]) # Top reaches per agent
ax2 = fig.add_subplot(gs_top[1]) # Exclusive wins per agent
# Bottom: Comprehensive metrics table
ax3 = fig.add_subplot(gs[1])
# === PANEL 1: Top Reaches per Agent ===
# Prepare data - group by agent count
max_agents = max([r['num_agents'] for r in qlearning_results])
agent_counts = sorted(set([r['num_agents'] for r in qlearning_results]))
# For each agent ID, collect reaches across different agent counts
x_positions = np.arange(max_agents)
bar_width = 0.15
colors = plt.cm.tab10(np.linspace(0, 1, len(agent_counts)))
for idx, n_agents in enumerate(agent_counts):
result = next((r for r in qlearning_results if r['num_agents'] == n_agents), None)
if result:
reaches = result['agent_stats']['reaches_per_agent']
# Plot bars for this agent count
positions = x_positions[:n_agents] + (idx - len(agent_counts)/2) * bar_width
ax1.bar(positions, reaches, bar_width,
label=f'{n_agents} agents', color=colors[idx], alpha=0.8, edgecolor='black')
ax1.set_xlabel('Agent ID', fontsize=12, fontweight='bold')
ax1.set_ylabel('Number of Reaches to Terminal', fontsize=12, fontweight='bold')
ax1.set_title('(a) Individual Agent Performance: Top Reaches',
fontsize=12, fontweight='bold')
ax1.set_xticks(x_positions)
ax1.set_xticklabels([f'A{i+1}' for i in range(max_agents)])
# Semi-transparent rounded box legend with enhanced styling and padding
legend1 = ax1.legend(fontsize=10, loc='best', framealpha=0.85, fancybox=True,
shadow=True, borderpad=1.0, labelspacing=0.8)
legend1.get_frame().set_facecolor('#FFFFFF') # White background
legend1.get_frame().set_edgecolor('#2C3E50') # Dark border color
legend1.get_frame().set_linewidth(2.0) # Thicker border for visibility
ax1.grid(True, alpha=0.3, axis='y')
# === PANEL 2: Exclusive Wins per Agent ===
for idx, n_agents in enumerate(agent_counts):
result = next((r for r in qlearning_results if r['num_agents'] == n_agents), None)
if result:
wins = result['agent_stats']['exclusive_wins_per_agent']
# Plot bars for this agent count
positions = x_positions[:n_agents] + (idx - len(agent_counts)/2) * bar_width
ax2.bar(positions, wins, bar_width,
label=f'{n_agents} agents', color=colors[idx], alpha=0.8, edgecolor='black')
ax2.set_xlabel('Agent ID', fontsize=12, fontweight='bold')
ax2.set_ylabel('Number of Exclusive Wins', fontsize=12, fontweight='bold')
ax2.set_title('(b) Individual Agent Performance: Exclusive Wins',
fontsize=12, fontweight='bold')
ax2.set_xticks(x_positions)
ax2.set_xticklabels([f'A{i+1}' for i in range(max_agents)])
# Semi-transparent rounded box legend with enhanced styling and padding
legend2 = ax2.legend(fontsize=10, loc='best', framealpha=0.85, fancybox=True,
shadow=True, borderpad=1.0, labelspacing=0.8)
legend2.get_frame().set_facecolor('#FFFFFF') # White background
legend2.get_frame().set_edgecolor('#2C3E50') # Dark border color
legend2.get_frame().set_linewidth(2.0) # Thicker border for visibility
ax2.grid(True, alpha=0.3, axis='y')
# === PANEL 3: Comprehensive Metrics Table ===
# Extract ALL metrics for each agent count
table_headers = ['Agents', 'Efficiency', 'R_Fair', 'TT_Fair', 'Fairness',
'FALT', 'EALT', 'qFALT', 'qEALT', 'CALT', 'AALT']
table_data = []
cell_colors = []
for result in qlearning_results:
n_agents = result['num_agents']
m = result['metrics']
row = [
f"{n_agents}",
f"{m['Efficiency']:.3f}",
f"{m['Reward_Fairness']:.3f}",
f"{m['TT_Fairness']:.3f}",
f"{m['Fairness']:.3f}",
f"{m['FALT']:.3f}",
f"{m['EALT']:.3f}",
f"{m['qFALT']:.3f}",
f"{m['qEALT']:.3f}",
f"{m['CALT']:.3f}",
f"{m['AALT']:.3f}"
]
table_data.append(row)
# Color code cells: green > 0.7, yellow > 0.5, red <= 0.5
row_colors = ['lightgray'] # Agents column
for metric_val in [m['Efficiency'], m['Reward_Fairness'], m['TT_Fairness'], m['Fairness'],
m['FALT'], m['EALT'], m['qFALT'], m['qEALT'], m['CALT'], m['AALT']]:
if metric_val > 0.7:
row_colors.append('lightgreen')
elif metric_val > 0.5:
row_colors.append('lightyellow')
else:
row_colors.append('lightcoral')
cell_colors.append(row_colors)
ax3.axis('off')
table = ax3.table(cellText=table_data,
colLabels=table_headers,
cellLoc='center',
loc='center',
cellColours=cell_colors,
colWidths=[0.08] + [0.092]*10)
table.auto_set_font_size(False)
table.set_fontsize(9)
table.scale(1, 2.5)
for (i, j), cell in table.get_celld().items():
if i == 0:
cell.set_text_props(weight='bold', fontsize=10)
cell.set_facecolor('lightsteelblue')
ax3.set_title('(c) Comprehensive Metrics Summary (Green > 0.7, Yellow > 0.5, Red ≤ 0.5)',
fontsize=11, fontweight='bold', pad=15)
# Overall title
fig.suptitle('Individual Agent Performance Breakdown',
fontsize=14, fontweight='bold', y=0.98)
plt.tight_layout(rect=[0, 0, 1, 0.96])
# Save
output_path = os.path.join(config.figure_dirs['comparison'], 'agent_performance_breakdown.png')
plt.savefig(output_path, dpi=300, bbox_inches='tight')
print(f"[OK] Saved agent performance breakdown: {output_path}")
plt.show()
plt.close()
def create_all_figures(results_list):
"""Generate all key figures for Paper 1."""
print("\n== Generating Key Figures for Paper 1 ==")
# 1. Epsilon vs Metrics (before progression)
print("\n=== EPSILON VS METRICS ===")
create_epsilon_vs_metrics_analysis(results_list)
# 2. Progression Figures (all 6 ALT metrics with epsilon milestone)
print("\n=== PROGRESSION FIGURES ===")
print("\nFigure 6a: FALT Progression Rate")
create_figure_6_metric_progression_rate(results_list, 'FALT')
print("\nFigure 6b: EALT Progression Rate")
create_figure_6_metric_progression_rate(results_list, 'EALT')
print("\nFigure 6c: qFALT Progression Rate")
create_figure_6_metric_progression_rate(results_list, 'qFALT')
print("\nFigure 6d: qEALT Progression Rate")
create_figure_6_metric_progression_rate(results_list, 'qEALT')
print("\nFigure 6e: CALT Progression Rate")
create_figure_6_metric_progression_rate(results_list, 'CALT')
print("\nFigure 6f: AALT Progression Rate")
create_figure_6_metric_progression_rate(results_list, 'AALT')
# 3. 3D Consolidated Plots
print("\n=== 3D CONSOLIDATED PLOTS ===")
create_3d_metric_progression_plots(results_list)
# 4. Random vs Q-Learning Comparison
print("\n=== RANDOM VS Q-LEARNING COMPARISON ===")
print("\nFigure 8: Random vs Q-Learning Comparison (CALT)")
create_random_vs_qlearning_comparison(results_list, 'CALT')
print("\nFigure 9: Random vs Q-Learning Comparison (FALT)")
create_random_vs_qlearning_comparison(results_list, 'FALT')
print("\nFigure 9b: Random vs Q-Learning Comparison (AALT)")
create_random_vs_qlearning_comparison(results_list, 'AALT')
# 5. Learning Phases Analysis
print("\n=== LEARNING PHASES ANALYSIS ===")
create_learning_phases_analysis(results_list)
# 5.5. Metrics Paradox Summary (NEW - shows traditional metrics fail to capture coordination)
print("\n=== METRICS PARADOX SUMMARY ===")
create_agent_performance_summary(results_list)
# 6. ALT Ratio Analysis (Figure 7 style - all 6 ALT metrics for each mode)
print("\n=== ALT RATIO ANALYSIS ===")
print("\nFigure 7: AltRatio Analysis")
create_figure_7_altratio_analysis(results_list)
# 7. Computational Cost
print("\n=== COMPUTATIONAL COST ===")
create_rp_vs_alt_computation_comparison(results_list)
# 8. Other Figures
print("\n=== OTHER FIGURES ===")
create_random_baseline_progression_plots(results_list)
print("\nAll figures generated successfully!")
# CRITICAL: Save comprehensive analysis data FIRST (creates CSV needed by paper1 figures)
print("\n=== SAVING DATA TABLES ===")
save_comprehensive_analysis(results_list)
print("[OK] Data tables saved (comprehensive_results.csv and others)")
# 9. Paper 1 Figures (NEW - automatic generation)
print("\n=== PAPER 1 FIGURES ===")
# Extract base_dir from config.figure_dirs (go up one level from subdirs)
if hasattr(config, 'figure_dirs') and 'tables' in config.figure_dirs:
base_dir = os.path.dirname(config.figure_dirs['tables'])
paper1_output_dir = os.path.join(base_dir, 'paper1_figures')
print(f"DEBUG: base_dir = {base_dir}")
print(f"DEBUG: paper1_output_dir = {paper1_output_dir}")
print(f"Generating Paper 1 figures in: {paper1_output_dir}")
try:
create_all_paper1_figures(base_dir, paper1_output_dir)
print("[OK] Paper 1 figures generated successfully!")
except Exception as e:
import traceback
print(f"[ERROR] Could not generate Paper 1 figures: {e}")