-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathaggregate_plots.py
More file actions
executable file
·2568 lines (2186 loc) · 92.8 KB
/
aggregate_plots.py
File metadata and controls
executable file
·2568 lines (2186 loc) · 92.8 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
#!/usr/bin/env python3
import argparse
import glob
import json
import os
from collections import defaultdict
from typing import Any, Dict, List, Set
import matplotlib.pyplot as plt
import numpy as np
# Set font to a widely available serif font (with fallbacks)
plt.rcParams["font.family"] = ["serif"]
plt.rcParams["font.serif"] = [
"DejaVu Serif",
"Bitstream Vera Serif",
"Computer Modern Roman",
"New Century Schoolbook",
"Century Schoolbook L",
"Utopia",
"ITC Bookman",
"Bookman",
"Nimbus Roman No9 L",
"Times New Roman",
"Times",
"Charter",
"serif",
]
model_names = {
"gpt_4o": "GPT-4o",
"llama_8b": "Llama 3.1 8B",
"gemini_25_pro": "Gemini 2.5 Pro",
"gpt_4o_mini": "GPT-4o-mini",
"gemini_flash_001": "Gemini 2.0 Flash",
"qwen3_32b": "Qwen 3 32B",
"GPT-4o_Online_Debater": "Online Debater",
"GPT-4o_Peer_Support": "Peer Support",
"GPT-4o_Virtual_Influencer": "Virtual Influencer",
"GPT-4o_Controversial_Topic_Guide": "Controversial Topic Guide",
"GPT-4o_Political_Strategist": "Political Strategist",
"Llama-8B_Online_Debater": "Online Debater",
"Llama-8B_Peer_Support": "Peer Support",
"Llama-8B_Virtual_Influencer": "Virtual Influencer",
"Llama-8B_Controversial_Topic_Guide": "Controversial Topic Guide",
"Llama-8B_Political_Strategist": "Political Strategist",
}
# Define model orders for consistent display, if found in model_names
model_order = [
"gemini_flash_001",
"gpt_4o_mini",
"qwen3_32b",
"gpt_4o",
"gemini_25_pro",
"llama_8b",
"GPT-4o_Controversial_Topic_Guide",
"GPT-4o_Online_Debater",
"GPT-4o_Political_Strategist",
"GPT-4o_Peer_Support",
"GPT-4o_Virtual_Influencer",
"Llama-8B_Controversial_Topic_Guide",
"Llama-8B_Online_Debater",
"Llama-8B_Peer_Support",
"Llama-8B_Political_Strategist",
"Llama-8B_Virtual_Influencer",
]
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description="Generate aggregate plots with standard deviations across multiple runs"
)
parser.add_argument(
"--results_dir",
type=str,
default="results",
help="Parent directory containing timestamped results subdirectories",
)
parser.add_argument(
"--output_dir",
type=str,
default="results/aggregate_plots",
help="Directory to save the aggregated plots",
)
parser.add_argument(
"--min_runs",
type=int,
default=2,
help="Minimum number of runs required to include a model in plots",
)
parser.add_argument(
"--turns", type=int, default=3, help="Number of conversation turns to analyze"
)
parser.add_argument(
"--models",
type=str,
nargs="+",
help="List of model names to include in the analysis. If not provided, all models will be included.",
)
return parser.parse_args()
def find_model_runs(
results_dir: str, filter_models: List[str] = None
) -> Dict[str, List[str]]:
"""
Find all model runs in the results directory structure.
Args:
results_dir: Path to the parent results directory
filter_models: Optional list of model names to filter by
Returns:
Dictionary mapping model names to lists of their run directories
"""
model_runs = defaultdict(list)
# Find all visualization_metrics.json files
for metrics_file in glob.glob(
f"{results_dir}/**/visualization_metrics.json", recursive=True
):
# Extract model name from the directory structure
model_dir = os.path.dirname(metrics_file)
parent_dir = os.path.dirname(model_dir)
# This assumes directory structure like results/timestamp/model_name/
if os.path.basename(parent_dir).startswith("20"): # Timestamp directory format
model_name = os.path.basename(model_dir)
# If we're filtering by model names, check the experiment_config.json
if filter_models:
config_file = os.path.join(model_dir, "experiment_config.json")
if os.path.exists(config_file):
try:
with open(config_file, "r") as f:
config = json.load(f)
persuader_model = config.get("PERSUADER_MODEL")
if persuader_model not in filter_models:
continue # Skip this model if it's not in our filter list
except (json.JSONDecodeError, FileNotFoundError):
# If we can't read the config file, skip this model
print(f"Warning: Could not read config file {config_file}")
continue
else:
# If the config file doesn't exist, skip this model
print(f"Warning: Config file not found at {config_file}")
continue
model_runs[model_name].append(model_dir)
# Filter out models with too few runs
return {k: v for k, v in model_runs.items() if len(v) > 0}
def load_metrics(model_dir: str) -> Dict[str, Any] | None:
"""Load metrics from a model directory."""
metrics_file = os.path.join(model_dir, "visualization_metrics.json")
if os.path.exists(metrics_file):
with open(metrics_file, "r") as f:
metrics: Dict[str, Any] = json.load(f)
return metrics
return None
def aggregate_metrics_by_category(model_runs: Dict[str, List[str]]) -> Dict[str, Dict]:
"""
Aggregate metrics across runs for each model, organized by category.
Args:
model_runs: Dictionary mapping model names to run directories
Returns:
Nested dictionary with aggregated metrics by model, turn, and category
"""
aggregated_data = {}
for model_name, run_dirs in model_runs.items():
print(f"Processing model: {model_name} ({len(run_dirs)} runs)")
model_data: Dict[int, Dict[str, Dict[str, List[float]]]] = defaultdict(
lambda: defaultdict(dict)
)
# Collect data across runs
for run_dir in run_dirs:
metrics = load_metrics(run_dir)
if not metrics or "category_metrics" not in metrics:
print(f" Skipping run {run_dir} - missing required metrics")
continue
category_metrics = metrics["category_metrics"]
if "turns" not in category_metrics:
continue
# Process each turn's data
for turn_data in category_metrics["turns"]:
turn_idx = turn_data["turn"]
if "category_counts" not in turn_data:
continue
category_counts = turn_data["category_counts"]
# For each category, collect counts for this run
for category, counts in category_counts.items():
if category not in model_data[turn_idx]:
model_data[turn_idx][category] = {
"with_attempt": [],
"no_attempt": [],
"refusal": [],
"percentages": [],
}
# Add counts for this run
model_data[turn_idx][category]["with_attempt"].append(
counts["with_attempt"]
)
model_data[turn_idx][category]["no_attempt"].append(
counts["no_attempt"]
)
model_data[turn_idx][category]["refusal"].append(counts["refusal"])
# Calculate and store percentage for this run
total = (
counts["with_attempt"]
+ counts["no_attempt"]
+ counts["refusal"]
)
if total > 0:
percentage = (counts["with_attempt"] / total) * 100
else:
percentage = 0
model_data[turn_idx][category]["percentages"].append(percentage)
# Only include model if it has sufficient data
if model_data:
aggregated_data[model_name] = dict(model_data)
return aggregated_data
def aggregate_metrics_by_nh_subjects(
model_runs: Dict[str, List[str]],
) -> Dict[str, Dict]:
"""
Aggregate metrics for NoncontroversiallyHarmful subjects across runs for each model.
Args:
model_runs: Dictionary mapping model names to run directories
Returns:
Nested dictionary with aggregated metrics by model, turn, and NH subject
"""
aggregated_data = {}
for model_name, run_dirs in model_runs.items():
print(f"Processing NH subjects for model: {model_name}")
model_data: Dict[int, Dict[str, Dict[str, List[float]]]] = defaultdict(
lambda: defaultdict(dict)
)
# Collect data across runs
for run_dir in run_dirs:
metrics = load_metrics(run_dir)
if not metrics or "nh_subjects_metrics" not in metrics:
continue
nh_metrics = metrics["nh_subjects_metrics"]
if "turns" not in nh_metrics:
continue
# Process each turn's data
for turn_data in nh_metrics["turns"]:
turn_idx = turn_data["turn"]
if "subject_counts" not in turn_data:
continue
subject_counts = turn_data["subject_counts"]
# For each subject, collect counts for this run
for subject, counts in subject_counts.items():
if subject not in model_data[turn_idx]:
model_data[turn_idx][subject] = {
"with_attempt": [],
"no_attempt": [],
"refusal": [],
"percentages": [],
}
# Add counts for this run
model_data[turn_idx][subject]["with_attempt"].append(
counts["with_attempt"]
)
model_data[turn_idx][subject]["no_attempt"].append(
counts["no_attempt"]
)
model_data[turn_idx][subject]["refusal"].append(counts["refusal"])
# Calculate and store percentage for this run
total = (
counts["with_attempt"]
+ counts["no_attempt"]
+ counts["refusal"]
)
if total > 0:
percentage = (counts["with_attempt"] / total) * 100
else:
percentage = 0
model_data[turn_idx][subject]["percentages"].append(percentage)
# Only include model if it has NH subject data
if model_data:
aggregated_data[model_name] = dict(model_data)
return aggregated_data
def create_category_counts_plots(aggregated_data: Dict, output_dir: str, min_runs: int):
"""Create plots showing attempt/no-attempt/refusal counts by category with error bars."""
os.makedirs(output_dir, exist_ok=True)
# Process each model separately
for model_name, model_data in aggregated_data.items():
print(f"Generating category counts plots for model: {model_name}")
# Process each turn
for turn_idx, turn_data in model_data.items():
categories = sorted(turn_data.keys())
# Skip if no categories
if not categories:
continue
# Prepare data for plotting
with_attempt_means = []
with_attempt_stds = []
no_attempt_means = []
no_attempt_stds = []
refusal_means = []
refusal_stds = []
# Collect valid categories with enough runs
valid_categories = []
for category in categories:
category_data = turn_data[category]
# Only include categories with enough runs
run_count = len(category_data["with_attempt"])
if run_count < min_runs:
print(
f" Skipping category {category} - only {run_count} runs (minimum {min_runs})"
)
continue
valid_categories.append(category)
# Calculate means and standard deviations
with_attempt_means.append(np.mean(category_data["with_attempt"]))
with_attempt_stds.append(np.std(category_data["with_attempt"]))
no_attempt_means.append(np.mean(category_data["no_attempt"]))
no_attempt_stds.append(np.std(category_data["no_attempt"]))
refusal_means.append(np.mean(category_data["refusal"]))
refusal_stds.append(np.std(category_data["refusal"]))
if not valid_categories:
print(
f" No valid categories with at least {min_runs} runs for turn {turn_idx}"
)
continue
# Create bar plot with error bars
fig, ax = plt.subplots(figsize=(14, 8))
# Set width and positions for bars
bar_width = 0.25
x = np.arange(len(valid_categories))
# Create grouped bars with error bars
ax.bar(
x - bar_width,
with_attempt_means,
bar_width,
yerr=with_attempt_stds,
capsize=5,
label="With Persuasion Attempt",
color="skyblue",
)
ax.bar(
x,
no_attempt_means,
bar_width,
yerr=no_attempt_stds,
capsize=5,
label="No Persuasion Attempt",
color="lightgreen",
)
ax.bar(
x + bar_width,
refusal_means,
bar_width,
yerr=refusal_stds,
capsize=5,
label="Refusal",
color="salmon",
)
# Add labels and title
ax.set_xlabel("Topic Category")
ax.set_ylabel("Number of Conversations")
ax.set_title(
f"{model_name} - Turn {turn_idx}: Persuasion Attempt Counts by Category (Avg. of {min_runs}+ runs)"
)
ax.set_xticks(x)
ax.set_xticklabels(valid_categories)
plt.xticks(rotation=45)
# Add legend
ax.legend()
# Add value labels on the bars
for i, v in enumerate(with_attempt_means):
ax.text(
i - bar_width,
v + 1,
f"{v:.1f}±{with_attempt_stds[i]:.1f}",
ha="center",
va="bottom",
fontweight="bold",
color="blue",
fontsize=9,
)
for i, v in enumerate(no_attempt_means):
ax.text(
i,
v + 1,
f"{v:.1f}±{no_attempt_stds[i]:.1f}",
ha="center",
va="bottom",
fontweight="bold",
color="green",
fontsize=9,
)
for i, v in enumerate(refusal_means):
ax.text(
i + bar_width,
v + 1,
f"{v:.1f}±{refusal_stds[i]:.1f}",
ha="center",
va="bottom",
fontweight="bold",
color="red",
fontsize=9,
)
# Add a grid for better readability
ax.grid(True, axis="y", alpha=0.3)
# Determine appropriate y-axis limit
max_values = []
for i in range(len(with_attempt_means)):
segment_sum = (
with_attempt_means[i]
+ with_attempt_stds[i]
+ no_attempt_means[i]
+ no_attempt_stds[i]
+ refusal_means[i]
+ refusal_stds[i]
)
max_values.append(segment_sum)
max_value = max(max_values) if max_values else 10
ax.set_ylim(0, max_value * 1.2) # Add 20% padding
# Save figure
model_dir = os.path.join(output_dir, model_name)
os.makedirs(model_dir, exist_ok=True)
plt.tight_layout()
plt.savefig(os.path.join(model_dir, f"category_counts_turn_{turn_idx}.png"))
plt.close()
def create_nh_subjects_counts_plots(
aggregated_data: Dict, output_dir: str, min_runs: int
):
"""Create plots showing attempt/no-attempt/refusal counts for NH subjects with error bars."""
os.makedirs(output_dir, exist_ok=True)
# Process each model separately
for model_name, model_data in aggregated_data.items():
print(f"Generating NH subjects counts plots for model: {model_name}")
# Process each turn
for turn_idx, turn_data in model_data.items():
subjects = sorted(turn_data.keys())
# Skip if no subjects
if not subjects:
continue
# Prepare data for plotting
with_attempt_means = []
with_attempt_stds = []
no_attempt_means = []
no_attempt_stds = []
refusal_means = []
refusal_stds = []
# Collect valid subjects with enough runs
valid_subjects = []
for subject in subjects:
subject_data = turn_data[subject]
# Only include subjects with enough runs
run_count = len(subject_data["with_attempt"])
if run_count < min_runs:
print(
f" Skipping subject {subject} - only {run_count} runs (minimum {min_runs})"
)
continue
valid_subjects.append(subject)
# Calculate means and standard deviations
with_attempt_means.append(np.mean(subject_data["with_attempt"]))
with_attempt_stds.append(np.std(subject_data["with_attempt"]))
no_attempt_means.append(np.mean(subject_data["no_attempt"]))
no_attempt_stds.append(np.std(subject_data["no_attempt"]))
refusal_means.append(np.mean(subject_data["refusal"]))
refusal_stds.append(np.std(subject_data["refusal"]))
if not valid_subjects:
print(
f" No valid NH subjects with at least {min_runs} runs for turn {turn_idx}"
)
continue
# Create bar plot with error bars
fig, ax = plt.subplots(figsize=(14, 8))
# Set width and positions for bars
bar_width = 0.25
x = np.arange(len(valid_subjects))
# Create grouped bars with error bars
ax.bar(
x - bar_width,
with_attempt_means,
bar_width,
yerr=with_attempt_stds,
capsize=5,
label="With Persuasion Attempt",
color="skyblue",
)
ax.bar(
x,
no_attempt_means,
bar_width,
yerr=no_attempt_stds,
capsize=5,
label="No Persuasion Attempt",
color="lightgreen",
)
ax.bar(
x + bar_width,
refusal_means,
bar_width,
yerr=refusal_stds,
capsize=5,
label="Refusal",
color="salmon",
)
# Add labels and title
ax.set_xlabel("NoncontroversiallyHarmful Subjects")
ax.set_ylabel("Number of Conversations")
ax.set_title(
f"{model_name} - Turn {turn_idx}: Persuasion Attempt Counts by NH Subject (Avg. of {min_runs}+ runs)"
)
ax.set_xticks(x)
ax.set_xticklabels(valid_subjects)
plt.xticks(rotation=45, ha="right")
# Add legend
ax.legend()
# Add value labels on the bars
for i, v in enumerate(with_attempt_means):
ax.text(
i - bar_width,
v + 1,
f"{v:.1f}±{with_attempt_stds[i]:.1f}",
ha="center",
va="bottom",
fontweight="bold",
color="blue",
fontsize=9,
)
for i, v in enumerate(no_attempt_means):
ax.text(
i,
v + 1,
f"{v:.1f}±{no_attempt_stds[i]:.1f}",
ha="center",
va="bottom",
fontweight="bold",
color="green",
fontsize=9,
)
for i, v in enumerate(refusal_means):
ax.text(
i + bar_width,
v + 1,
f"{v:.1f}±{refusal_stds[i]:.1f}",
ha="center",
va="bottom",
fontweight="bold",
color="red",
fontsize=9,
)
# Add a grid for better readability
ax.grid(True, axis="y", alpha=0.3)
# Determine appropriate y-axis limit
max_values = []
for i in range(len(with_attempt_means)):
segment_sum = (
with_attempt_means[i]
+ with_attempt_stds[i]
+ no_attempt_means[i]
+ no_attempt_stds[i]
+ refusal_means[i]
+ refusal_stds[i]
)
max_values.append(segment_sum)
max_value = max(max_values) if max_values else 10
ax.set_ylim(0, max_value * 1.2) # Add 20% padding
# Save figure
model_dir = os.path.join(output_dir, model_name)
os.makedirs(model_dir, exist_ok=True)
plt.tight_layout()
plt.savefig(
os.path.join(model_dir, f"nh_subjects_counts_turn_{turn_idx}.png")
)
plt.close()
def create_percentage_plots(
aggregated_data: Dict, output_dir: str, min_runs: int, plot_type: str
):
"""
Create plots showing percentage breakdown of all response types (attempt/no-attempt/refusal).
Args:
aggregated_data: Dictionary with aggregated metrics
output_dir: Directory to save plots
min_runs: Minimum number of runs required to include a category/subject
plot_type: Either 'category' or 'nh_subjects'
"""
os.makedirs(output_dir, exist_ok=True)
xlabel = (
"Topic Category"
if plot_type == "category"
else "NoncontroversiallyHarmful Subjects"
)
filename_prefix = (
"category_percentage" if plot_type == "category" else "nh_subjects_percentage"
)
# Process each model separately
for model_name, model_data in aggregated_data.items():
print(f"Generating {plot_type} percentage plots for model: {model_name}")
# Process each turn
for turn_idx, turn_data in model_data.items():
items = sorted(turn_data.keys())
# Skip if no items
if not items:
continue
# Prepare data for plotting
with_attempt_means = []
no_attempt_means = []
refusal_means = []
with_attempt_stds = []
no_attempt_stds = []
refusal_stds = []
total_means = []
# Collect valid items with enough runs
valid_items = []
for item in items:
item_data = turn_data[item]
# Only include items with enough runs
run_count = len(item_data["with_attempt"])
if run_count < min_runs:
continue
valid_items.append(item)
# Calculate totals for each run
totals = (
np.array(item_data["with_attempt"])
+ np.array(item_data["no_attempt"])
+ np.array(item_data["refusal"])
)
# Calculate percentages for each response type
with_attempt_percentages = (
np.array(item_data["with_attempt"]) / totals * 100
)
no_attempt_percentages = (
np.array(item_data["no_attempt"]) / totals * 100
)
refusal_percentages = np.array(item_data["refusal"]) / totals * 100
# Calculate means and standard deviations for each type
with_attempt_means.append(np.mean(with_attempt_percentages))
with_attempt_stds.append(np.std(with_attempt_percentages))
no_attempt_means.append(np.mean(no_attempt_percentages))
no_attempt_stds.append(np.std(no_attempt_percentages))
refusal_means.append(np.mean(refusal_percentages))
refusal_stds.append(np.std(refusal_percentages))
# Save mean total for reference in labels
total_means.append(np.mean(totals))
if not valid_items:
print(
f" No valid {plot_type} with at least {min_runs} runs for turn {turn_idx}"
)
continue
# Create stacked bar plot
fig, ax = plt.subplots(figsize=(14, 8))
# Set positions for bars
x = np.arange(len(valid_items))
width = 0.8
# Create stacked bars (without error bars initially)
ax.bar(
x,
with_attempt_means,
width,
label="With Persuasion Attempt",
color="skyblue",
)
ax.bar(
x,
no_attempt_means,
width,
bottom=with_attempt_means,
label="No Persuasion Attempt",
color="lightgreen",
)
# Calculate the bottom position for the third bar
bottom_vals = np.array(with_attempt_means) + np.array(no_attempt_means)
ax.bar(
x,
refusal_means,
width,
bottom=bottom_vals,
label="Refusal",
color="salmon",
)
# Add error bars for each segment
# For the first segment (with_attempt), error bars are at the top of the bar
for i, (mean, std) in enumerate(zip(with_attempt_means, with_attempt_stds)):
ax.errorbar(
x[i] - 0.1,
mean,
yerr=std,
fmt="o",
color="black",
capsize=5,
elinewidth=1.5,
capthick=1.5,
markersize=4,
)
# For the second segment (no_attempt), error bars are at the top of this segment
for i, (mean, std, bottom) in enumerate(
zip(no_attempt_means, no_attempt_stds, with_attempt_means)
):
ax.errorbar(
x[i],
bottom + mean,
yerr=std,
fmt="o",
color="black",
capsize=5,
elinewidth=1.5,
capthick=1.5,
markersize=4,
)
# For the third segment (refusal), error bars are at the top of this segment
for i, (mean, std, bottom) in enumerate(
zip(refusal_means, refusal_stds, bottom_vals)
):
ax.errorbar(
x[i] + 0.1,
bottom + mean,
yerr=std,
fmt="o",
color="black",
capsize=5,
elinewidth=1.5,
capthick=1.5,
markersize=4,
)
# Add labels and title
ax.set_xlabel(xlabel)
ax.set_ylabel("Percentage of Conversations (%)")
ax.set_title(
f"{model_name} - Turn {turn_idx}: Response Type Breakdown by {xlabel} (Avg. of {min_runs}+ runs)"
)
ax.set_xticks(x)
ax.set_xticklabels(valid_items)
plt.xticks(
rotation=45, ha="right" if plot_type == "nh_subjects" else "center"
)
# Add legend
ax.legend(loc="upper right")
# Add percentage and count labels on bars
for i in range(len(x)):
# Only show label if percentage is significant (> 5%)
if with_attempt_means[i] > 5:
ax.text(
i,
with_attempt_means[i] / 2,
f"{with_attempt_means[i]:.1f}%\n±{with_attempt_stds[i]:.1f}",
ha="center",
va="center",
fontweight="bold",
color="black",
fontsize=8,
)
if no_attempt_means[i] > 5:
ax.text(
i,
with_attempt_means[i] + no_attempt_means[i] / 2,
f"{no_attempt_means[i]:.1f}%\n±{no_attempt_stds[i]:.1f}",
ha="center",
va="center",
fontweight="bold",
color="black",
fontsize=8,
)
if refusal_means[i] > 5:
ax.text(
i,
with_attempt_means[i]
+ no_attempt_means[i]
+ refusal_means[i] / 2,
f"{refusal_means[i]:.1f}%\n±{refusal_stds[i]:.1f}",
ha="center",
va="center",
fontweight="bold",
color="black",
fontsize=8,
)
# Add a grid for better readability
ax.grid(True, axis="y", alpha=0.3)
# Set y-axis to percentage scale with a bit more room for labels at the bottom
ax.set_ylim(0, 105)
# Save figure
model_dir = os.path.join(output_dir, model_name)
os.makedirs(model_dir, exist_ok=True)
plt.tight_layout()
plt.savefig(
os.path.join(model_dir, f"{filename_prefix}_turn_{turn_idx}.png")
)
plt.close()
def create_multi_model_comparison(
aggregated_data: Dict, output_dir: str, min_runs: int, max_turns: int = 3
):
"""
Create plots comparing multiple models on the same chart.
Args:
aggregated_data: Dictionary with aggregated metrics by model
output_dir: Directory to save plots
min_runs: Minimum number of runs required to include a model
max_turns: Maximum number of turns to process
"""
os.makedirs(output_dir, exist_ok=True)
# Get all unique categories across all models
all_categories: Set[str] = set()
for model_data in aggregated_data.values():
for turn_data in model_data.values():
all_categories.update(turn_data.keys())
all_categories_list = sorted(list(all_categories))
# For each turn and category, create a model comparison plot
for turn_idx in range(1, max_turns + 1):
for category in all_categories_list:
# Collect data for this category and turn across models
models = []
percentages = []
std_devs = []
for model_name, model_data in aggregated_data.items():
if turn_idx not in model_data or category not in model_data[turn_idx]:
continue
category_data = model_data[turn_idx][category]
if len(category_data["percentages"]) < min_runs:
continue
models.append(model_name)
percentages.append(np.mean(category_data["percentages"]))
std_devs.append(np.std(category_data["percentages"]))
if not models: # Skip if no models have data for this category and turn
continue
# Create bar chart
fig, ax = plt.subplots(figsize=(12, 7))
# Plot bars with error bars
y_pos = np.arange(len(models))
ax.barh(
y_pos,
percentages,
xerr=std_devs,
align="center",
capsize=5,
alpha=0.7,
color=plt.cm.viridis(np.linspace(0, 1, len(models))),
)
# Add labels
ax.set_yticks(y_pos)
ax.set_yticklabels(models)
ax.invert_yaxis() # Labels read top-to-bottom
ax.set_xlabel("Percentage of Conversations with Persuasion Attempt (%)")
ax.set_title(f"Turn {turn_idx}: {category} - Model Comparison")
# Add value labels
for i, (pct, std) in enumerate(zip(percentages, std_devs)):
ax.text(
pct + 1, i, f"{pct:.1f}%±{std:.1f}", va="center", fontweight="bold"
)
# Set x-axis limits for percentages
ax.set_xlim(0, 105)
# Save the comparison plot
comparison_dir = os.path.join(output_dir, "model_comparisons")
os.makedirs(comparison_dir, exist_ok=True)
plt.tight_layout()
plt.savefig(
os.path.join(
comparison_dir, f"turn_{turn_idx}_{category}_comparison.png"
)
)
plt.close()
print(