-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot.py
More file actions
1783 lines (1429 loc) · 66.1 KB
/
plot.py
File metadata and controls
1783 lines (1429 loc) · 66.1 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
import os
import json
import glob
import argparse
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from typing import List, Optional
import matplotlib.patches as mpatches
# --- Global Lookup Dictionaries ---
# Modify these dictionaries to rename metrics (columns) and scenarios (values)
# Keys should match the raw JSON keys/values, Values are the display names.
METRIC_LABELS = {
# CPU Metrics
"cpu_time_seconds": "Total CPU Time (s)",
"cpu_percent_avg": "Avg CPU Load (%)",
"cpu_percent_max": "Peak CPU Load (%)",
# Memory Metrics
"memory_usage_avg_bytes": "Avg RAM Usage (Bytes)",
"memory_usage_max_bytes": "Peak RAM Usage (Bytes)",
"memory_percent_avg": "Avg RAM Utilization (%)",
# Network Metrics (TX = Sent, RX = Received)
"network_tx_total_bytes": "Total Data Sent (Bytes)",
"network_rx_total_bytes": "Total Data Received (Bytes)",
"network_tx_avg": "Avg Upload Rate (Bytes/iter)",
"network_rx_avg": "Avg Download Rate (Bytes/iter)",
"network_tx_max": "Peak Upload Rate (Bytes/iter)",
"network_rx_max": "Peak Download Rate (Bytes/iter)",
# Time Metrics
"total_time_in_seconds": "Total Execution Time (s)"
}
SCENARIO_LABELS = {
"local-async": "Local Async",
"local-multithread": "Local Multi-threading",
"mqtt": "MQTT",
"orbitalis-local": "Orbitalis Local",
"orbitalis-local-ff": "Orbitalis Local (Fire-and-Forget)",
"orbitalis-mqtt": "Orbitalis MQTT",
"orbitalis-mqtt-ff": "Orbitalis MQTT (Fire-and-Forget)",
}
NORMALIZE_TO_ITERATIONS = 1_000_000
def value_modifier(record, key, value):
# Normalize certain metrics to a per-iteration basis
if key in ["cpu_time_seconds", "memory_usage_max_bytes", "network_tx_total_bytes", "network_rx_total_bytes", "total_time_in_seconds", "memory_usage_avg_bytes"]:
n_iterations = record.get("n_iterations", 1)
value = value / n_iterations * NORMALIZE_TO_ITERATIONS
return value
def load_experiments(directory: str) -> pd.DataFrame:
"""
Loads all JSON files from the specified directory and flattens them
into a Pandas DataFrame. Applies global renames for scenarios.
"""
data_records = []
if not os.path.exists(directory):
print(f"Error: The directory '{directory}' does not exist.")
return pd.DataFrame()
json_pattern = os.path.join(directory, "*.json")
json_files = glob.glob(json_pattern)
if not json_files:
print(f"No JSON files found in {directory}")
return pd.DataFrame()
print(f"Found {len(json_files)} experiment files in '{directory}'. Processing...")
for file_path in json_files:
try:
with open(file_path, 'r') as f:
content = json.load(f)
# Extract configuration parameters
raw_scenario = content.get("scenario")
# Apply Scenario Rename
scenario_name = SCENARIO_LABELS.get(raw_scenario, raw_scenario)
record = {
"n_workers": content.get("n_workers"),
"n_primes": content.get("n_primes"),
"n_iterations": content.get("n_iterations"),
"scenario": scenario_name,
}
# Flatten the 'outcome' dictionary
outcome = content.get("outcome", {})
for key, value in outcome.items():
record[key] = value_modifier(record, key, value)
if record["total_time_in_seconds"] < 1:
print(f"Warning: Skipping file {file_path} due to unrealistically low total_time_in_seconds.")
continue
data_records.append(record)
except Exception as e:
print(f"Warning: Error reading file {file_path}: {e}")
df = pd.DataFrame(data_records)
if not df.empty:
# Create a unique readable label for the configuration
df['configuration_label'] = df.apply(
lambda row: f"{row['scenario']}\nWorker: {row['n_workers']}\nPrimes: {row['n_primes']}\nIterations: {row['n_iterations']}",
axis=1
)
# Apply Metric Rename to columns
df.rename(columns=METRIC_LABELS, inplace=True)
return df
def generate_stacked_metrics_plot_horizontal_legend(
df: pd.DataFrame,
output_folder: str,
output_format: str,
metrics_to_stack: list[str],
y_log: bool = False,
show_pct_diff: bool = True,
width: int = 6,
height: int = 8,
):
"""
Generates a stacked bar chart with a horizontal legend at the bottom.
"""
if df.empty:
print("DataFrame is empty. Skipping plot generation.")
return
# 1. Validation
missing = [m for m in metrics_to_stack if m not in df.columns]
if missing:
print(f"Error: The following columns are missing: {missing}")
return
os.makedirs(output_folder, exist_ok=True)
print(f"Generating stacked plot for {metrics_to_stack} in '{output_folder}'...")
# 2. Data Preparation
df_temp = df.copy()
cumulative_cols = []
current_sum_col = None
for i, metric in enumerate(metrics_to_stack):
new_col_name = f"__cum_{i}_{metric}"
if current_sum_col is None:
df_temp[new_col_name] = df_temp[metric]
else:
df_temp[new_col_name] = df_temp[current_sum_col] + df_temp[metric]
cumulative_cols.append(new_col_name)
current_sum_col = new_col_name
available_hatches = ['', '///', '...', 'xxx', '+++', '|||']
# Setup Plot
unique_workers = sorted(df['n_workers'].unique())
n_subplots = len(unique_workers)
sns.set_theme(style="whitegrid")
fig, axes = plt.subplots(
nrows=1,
ncols=n_subplots,
figsize=(width * n_subplots, height),
sharey=False,
constrained_layout=True
)
if n_subplots == 1: axes = [axes]
# --- Prepare Colors Manually ---
unique_scenarios = sorted(df['scenario'].unique())
palette_colors = sns.color_palette("viridis", n_colors=len(unique_scenarios))
scenario_color_map = dict(zip(unique_scenarios, palette_colors))
for i, worker_count in enumerate(unique_workers):
ax = axes[i]
subplot_data = df_temp[df_temp['n_workers'] == worker_count].sort_values(by=['n_primes', 'scenario'])
if subplot_data.empty: continue
# 3. Plotting Loop
for idx in range(len(cumulative_cols) - 1, -1, -1):
col_name = cumulative_cols[idx]
hatch_pattern = available_hatches[idx % len(available_hatches)]
sns.barplot(
data=subplot_data,
x='n_primes',
y=col_name,
hue='scenario',
palette=scenario_color_map,
ax=ax,
dodge=True,
hatch=hatch_pattern,
edgecolor='black',
linewidth=0.5,
alpha=1.0,
legend=False
)
# 4. Annotations
if show_pct_diff:
max_y_limit = 0
bar_tops = {}
for p in ax.patches:
h = p.get_height()
if pd.isna(h) or h <= 0: continue
mx = p.get_x() + p.get_width() / 2.
x_idx = int(round(mx))
key = (x_idx, round(mx, 3))
if key not in bar_tops: bar_tops[key] = h
else:
if h > bar_tops[key]: bar_tops[key] = h
group_baselines = {}
for (x_idx, mx), h in bar_tops.items():
if x_idx not in group_baselines: group_baselines[x_idx] = h
else:
if h < group_baselines[x_idx]: group_baselines[x_idx] = h
for (x_idx, mx), h in bar_tops.items():
if x_idx in group_baselines:
baseline = group_baselines[x_idx]
if h > (baseline + 0.0001):
pct_diff = ((h - baseline) / baseline) * 100
label_text = f"+{pct_diff:.1f}%"
text_y = h
max_y_limit = max(max_y_limit, text_y)
ax.annotate(label_text, (mx, text_y), ha='center', va='bottom', xytext=(0, 5), textcoords='offset points', fontsize=9, color="black", weight="bold")
if max_y_limit > 0:
mult = 1.5 if y_log else 1.15
ax.set_ylim(top=max_y_limit * mult)
# 5. Formatting
if y_log: ax.set_yscale('log')
ax.set_title(f"Workers: {worker_count}", fontsize=14)
ax.set_xlabel("Number of Primes", fontsize=11)
if i == 0: ax.set_ylabel("Stacked Metric Sum", fontsize=12)
else: ax.set_ylabel("")
# --- 6. MANUAL HORIZONTAL LEGEND (Bottom) ---
# A. Scenarios (Colors)
scenario_handles = []
for sc_name, sc_color in scenario_color_map.items():
patch = mpatches.Patch(facecolor=sc_color, edgecolor='black', label=sc_name)
scenario_handles.append(patch)
# B. Metrics (Patterns)
metric_handles = []
for m_idx, m_name in enumerate(metrics_to_stack):
hatch = available_hatches[m_idx % len(available_hatches)]
patch = mpatches.Patch(facecolor='white', edgecolor='black', hatch=hatch, label=m_name)
metric_handles.append(patch)
# Combine: No spacers, just list them all.
final_handles = scenario_handles + metric_handles
# Calculate number of columns to fit them horizontally
# We want as many columns as there are items (to be in 1 row),
# but let's cap it at 6 or 8 to allow wrapping if there are too many items.
n_items = len(final_handles)
n_cols = min(n_items, 8)
fig.legend(
handles=final_handles,
loc='upper center', # The point of the legend to anchor...
bbox_to_anchor=(0.5, -0.02), # ...to this point (x=center, y=just below bottom)
ncol=n_cols, # Number of columns (Horizontal layout)
frameon=True,
borderaxespad=0.5,
title="Scenarios (Colors) & Metrics (Patterns)"
)
safe_name = "stacked_" + "_".join([m[:4] for m in metrics_to_stack]) + f".{output_format}"
plt.suptitle(f"Stacked Sum: {', '.join(metrics_to_stack)}", fontsize=16, y=1.05)
# 'bbox_inches="tight"' is CRITICAL here.
# Since the legend is at negative coordinates (outside the plot area),
# this ensures the saved image expands to include the legend.
plt.savefig(os.path.join(output_folder, safe_name), bbox_inches='tight')
plt.close()
print(f" -> Saved: {safe_name}")
def generate_stacked_metrics_plot(
df: pd.DataFrame,
output_folder: str,
output_format: str,
metrics_to_stack: list[str],
y_log: bool = False,
show_pct_diff: bool = True,
width: int = 6,
height: int = 8,
):
"""
Generates a stacked bar chart.
Fixes the legend by manually creating handles for both Colors (Scenarios) and Patterns (Metrics).
"""
if df.empty:
print("DataFrame is empty. Skipping plot generation.")
return
# 1. Validation
missing = [m for m in metrics_to_stack if m not in df.columns]
if missing:
print(f"Error: The following columns are missing: {missing}")
return
os.makedirs(output_folder, exist_ok=True)
print(f"Generating stacked plot for {metrics_to_stack} in '{output_folder}'...")
# 2. Data Preparation
df_temp = df.copy()
cumulative_cols = []
current_sum_col = None
for i, metric in enumerate(metrics_to_stack):
new_col_name = f"__cum_{i}_{metric}"
if current_sum_col is None:
df_temp[new_col_name] = df_temp[metric]
else:
df_temp[new_col_name] = df_temp[current_sum_col] + df_temp[metric]
cumulative_cols.append(new_col_name)
current_sum_col = new_col_name
available_hatches = ['', '///', '...', 'xxx', '+++', '|||']
# Setup Plot
unique_workers = sorted(df['n_workers'].unique())
n_subplots = len(unique_workers)
sns.set_theme(style="whitegrid")
fig, axes = plt.subplots(
nrows=1,
ncols=n_subplots,
figsize=(width * n_subplots, height),
sharey=False,
constrained_layout=True
)
if n_subplots == 1: axes = [axes]
# --- Prepare Colors Manually ---
# We define the palette here so we can use it for both plotting and the legend
unique_scenarios = sorted(df['scenario'].unique())
# You can change "viridis" to any other palette (e.g., "deep", "muted", "Set2")
palette_colors = sns.color_palette("viridis", n_colors=len(unique_scenarios))
scenario_color_map = dict(zip(unique_scenarios, palette_colors))
for i, worker_count in enumerate(unique_workers):
ax = axes[i]
subplot_data = df_temp[df_temp['n_workers'] == worker_count].sort_values(by=['n_primes', 'scenario'])
if subplot_data.empty: continue
# 3. Plotting Loop
for idx in range(len(cumulative_cols) - 1, -1, -1):
col_name = cumulative_cols[idx]
hatch_pattern = available_hatches[idx % len(available_hatches)]
sns.barplot(
data=subplot_data,
x='n_primes',
y=col_name,
hue='scenario',
palette=scenario_color_map, # Use the manual map ensures consistency
ax=ax,
dodge=True,
hatch=hatch_pattern,
edgecolor='black',
linewidth=0.5,
alpha=1.0,
legend=False
)
# 4. Annotations (PCT Diff)
if show_pct_diff:
max_y_limit = 0
bar_tops = {}
for p in ax.patches:
h = p.get_height()
if pd.isna(h) or h <= 0: continue
mx = p.get_x() + p.get_width() / 2.
x_idx = int(round(mx))
key = (x_idx, round(mx, 3))
if key not in bar_tops: bar_tops[key] = h
else:
if h > bar_tops[key]: bar_tops[key] = h
group_baselines = {}
for (x_idx, mx), h in bar_tops.items():
if x_idx not in group_baselines: group_baselines[x_idx] = h
else:
if h < group_baselines[x_idx]: group_baselines[x_idx] = h
for (x_idx, mx), h in bar_tops.items():
if x_idx in group_baselines:
baseline = group_baselines[x_idx]
if h > (baseline + 0.0001):
pct_diff = ((h - baseline) / baseline) * 100
label_text = f"+{pct_diff:.1f}%"
text_y = h
max_y_limit = max(max_y_limit, text_y)
ax.annotate(label_text, (mx, text_y), ha='center', va='bottom', xytext=(0, 5), textcoords='offset points', fontsize=9, color="black", weight="bold")
if max_y_limit > 0:
mult = 1.5 if y_log else 1.15
ax.set_ylim(top=max_y_limit * mult)
# 5. Formatting
if y_log: ax.set_yscale('log')
ax.set_title(f"Workers: {worker_count}", fontsize=14)
ax.set_xlabel("Number of Primes", fontsize=11)
if i == 0: ax.set_ylabel("Stacked Metric Sum", fontsize=12)
else: ax.set_ylabel("")
# --- 6. MANUAL UNIFIED LEGEND ---
# Instead of extracting from the plot, we build it from our data.
# A. Create handles for Scenarios (Colors)
scenario_handles = []
for sc_name, sc_color in scenario_color_map.items():
# Create a solid patch with the specific color
patch = mpatches.Patch(facecolor=sc_color, edgecolor='black', label=sc_name)
scenario_handles.append(patch)
# B. Create handles for Metrics (Patterns)
metric_handles = []
for m_idx, m_name in enumerate(metrics_to_stack):
hatch = available_hatches[m_idx % len(available_hatches)]
# White background, black pattern
patch = mpatches.Patch(facecolor='white', edgecolor='black', hatch=hatch, label=m_name)
metric_handles.append(patch)
# C. Combine: Scenarios first, then a spacer, then Metrics
# We add a generic label for the sections
final_handles = (
[mpatches.Patch(alpha=0, label="Scenarios")] +
scenario_handles +
[mpatches.Patch(alpha=0, label="")] + # Empty spacer
[mpatches.Patch(alpha=0, label="Metrics")] +
metric_handles
)
fig.legend(
handles=final_handles,
loc='center left',
bbox_to_anchor=(1.0, 0.5),
frameon=True,
title="Legend"
)
safe_name = "stacked_" + "_".join([m[:4] for m in metrics_to_stack]) + f".{output_format}"
plt.suptitle(f"Stacked Sum: {', '.join(metrics_to_stack)}", fontsize=16, y=1.05)
plt.savefig(os.path.join(output_folder, safe_name), bbox_inches='tight')
plt.close()
print(f" -> Saved: {safe_name}")
def generate_plots(df: pd.DataFrame, output_folder: str, output_format: str):
"""
Generates bar charts for every numeric metric. Each bar is annotated with the percentage difference
"""
if df.empty:
print("DataFrame is empty. Skipping plot generation.")
return
os.makedirs(output_folder, exist_ok=True)
print(f"Generating plots in '{output_folder}'...")
config_cols = ['n_workers', 'n_primes', 'n_iterations', 'scenario', 'configuration_label']
metric_cols = [c for c in df.columns if c not in config_cols and pd.api.types.is_numeric_dtype(df[c])]
sns.set_theme(style="whitegrid")
for metric in metric_cols:
plt.figure(figsize=(12, 8))
plot_data = df.sort_values(by=['scenario', 'n_workers', 'n_primes'])
# Create the bar plot (Seaborn calculates the Means here)
ax = sns.barplot(
data=plot_data,
x='configuration_label',
y=metric,
hue='scenario',
palette='viridis'
)
# --- STEP 1: Find the Minimum Bar Height (The Baseline Mean) ---
# We look at the actual plotted bars to find the lowest average.
valid_heights = [p.get_height() for p in ax.patches if not pd.isna(p.get_height()) and p.get_height() > 0]
if not valid_heights:
plt.close()
continue
min_bar_height = min(valid_heights)
# --- STEP 2: Map Error Bar Heights ---
# (Same logic as before to avoid text overlap)
error_bar_tops = {}
for line in ax.lines:
x_data = line.get_xdata()
y_data = line.get_ydata()
if len(x_data) > 0:
x_pos = x_data[0]
y_max = max(y_data)
error_bar_tops[round(x_pos, 4)] = y_max
# --- STEP 3: Annotate ---
max_y_limit = 0
for p in ax.patches:
bar_height = p.get_height()
if pd.isna(bar_height) or bar_height <= 0:
continue
bar_x = p.get_x() + p.get_width() / 2.
# Determine vertical anchor (Bar vs Error Line)
text_y_anchor = bar_height
if round(bar_x, 4) in error_bar_tops:
error_top = error_bar_tops[round(bar_x, 4)]
if error_top > text_y_anchor:
text_y_anchor = error_top
# Calculate Percentage Difference based on MIN_BAR_HEIGHT (Means)
# Use a small epsilon for float comparison safety
if abs(bar_height - min_bar_height) < 0.0001:
# This is the baseline bar
label_text = "Best" # Or leave empty "" if you prefer no label
color = "green"
weight = "bold"
else:
pct_diff = ((bar_height - min_bar_height) / min_bar_height) * 100
label_text = f"+{pct_diff:.1f}%"
color = "black"
weight = "normal"
ax.annotate(
label_text,
(bar_x, text_y_anchor),
ha='center',
va='bottom',
xytext=(0, 5),
textcoords='offset points',
fontsize=10,
color=color,
weight=weight
)
max_y_limit = max(max_y_limit, text_y_anchor)
plt.title(f"Comparison: {metric}", fontsize=16)
plt.xlabel("Configuration", fontsize=12)
plt.ylabel(metric, fontsize=12)
if max_y_limit > 0:
plt.ylim(top=max_y_limit * 1.15)
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
safe_filename = "".join([c if c.isalnum() else "_" for c in metric]) + f".{output_format}"
save_path = os.path.join(output_folder, safe_filename)
plt.savefig(save_path)
plt.close()
print(f" -> Saved: {safe_filename}")
def generate_plots_by_worker(df: pd.DataFrame, output_folder: str, output_format: str, y_log: bool = False, show_pct_diff: bool = True, width: int = 6, height: int = 8):
"""
Generates bar charts for every numeric metric using subplots.
Fix implemented:
- Calculates the baseline strictly from the PLOTTED bars (visual mean),
not the raw dataframe data. This ensures the lowest bar in the chart
is always treated as the baseline (0% diff) and is NOT annotated.
"""
if df.empty:
print("DataFrame is empty. Skipping plot generation.")
return
os.makedirs(output_folder, exist_ok=True)
print(f"Generating plots in '{output_folder}' (Annotations: {show_pct_diff})...")
# 1. Setup Columns
config_cols = ['n_workers', 'n_primes', 'n_iterations', 'scenario', 'configuration_label']
metric_cols = [c for c in df.columns if c not in config_cols and pd.api.types.is_numeric_dtype(df[c])]
unique_workers = sorted(df['n_workers'].unique())
n_subplots = len(unique_workers)
sns.set_theme(style="whitegrid")
for metric in metric_cols:
# Dynamic figure size
fig, axes = plt.subplots(nrows=1, ncols=n_subplots, figsize=(width * n_subplots, height), sharey=False, constrained_layout=True)
if n_subplots == 1:
axes = [axes]
for i, worker_count in enumerate(unique_workers):
ax = axes[i]
# Filter Data
subplot_data = df[df['n_workers'] == worker_count].sort_values(by=['n_primes', 'scenario'])
if subplot_data.empty:
continue
# Create Bar Plot
sns.barplot(
data=subplot_data,
x='n_primes',
y=metric,
hue='scenario',
palette='viridis',
ax=ax
)
if y_log:
ax.set_yscale('log')
ax.set_title(f"Workers: {worker_count}", fontsize=14)
ax.set_xlabel("Number of Primes", fontsize=11)
if i == 0:
ax.set_ylabel(metric, fontsize=12)
else:
ax.set_ylabel("")
# =========================================================
# ANNOTATION LOGIC (Two-Pass Approach)
# =========================================================
if show_pct_diff:
max_y_limit = 0
# --- PASS 1: Map Error Bars & Find Visual Baselines ---
# We need to find the minimum height PLOTTED for each X-tick (0, 1, 2...)
error_bar_tops = {} # To avoid text overlap
group_visual_min = {} # Key: x_coord (int), Value: min_height (float)
# A. Get Error Bar Tops
for line in ax.lines:
x_data = line.get_xdata()
y_data = line.get_ydata()
if len(x_data) > 0:
x_pos = x_data[0]
y_max = max(y_data)
error_bar_tops[round(x_pos, 4)] = y_max
# B. Find the Minimum Bar Height per X-Group strictly from the patches
for p in ax.patches:
h = p.get_height()
if pd.isna(h) or h <= 0:
continue
# Identify the X group (0, 1, 2...)
# p.get_x() returns the left edge. We add width/2 to find center, then round to nearest integer.
x_idx = int(round(p.get_x() + p.get_width() / 2.))
if x_idx not in group_visual_min:
group_visual_min[x_idx] = h
else:
if h < group_visual_min[x_idx]:
group_visual_min[x_idx] = h
# --- PASS 2: Annotate based on Visual Baselines ---
for p in ax.patches:
bar_height = p.get_height()
if pd.isna(bar_height) or bar_height <= 0:
continue
bar_x = p.get_x() + p.get_width() / 2.
x_idx = int(round(bar_x))
# Calculate Y position for text
text_y_anchor = bar_height
if round(bar_x, 4) in error_bar_tops:
error_top = error_bar_tops[round(bar_x, 4)]
if error_top > text_y_anchor:
text_y_anchor = error_top
max_y_limit = max(max_y_limit, text_y_anchor)
# Compare against the VISUAL baseline found in Pass 1
if x_idx in group_visual_min:
baseline = group_visual_min[x_idx]
# Apply Epsilon to handle float precision (e.g. 100.0 vs 100.000001)
# We ONLY annotate if the bar is clearly taller than the baseline
if bar_height > (baseline + 0.0001):
pct_diff = ((bar_height - baseline) / baseline) * 100
label_text = f"+{pct_diff:.1f}%"
ax.annotate(
label_text,
(bar_x, text_y_anchor),
ha='center',
va='bottom',
xytext=(0, 5),
textcoords='offset points',
fontsize=9,
color="black",
weight="normal"
)
# Else: It is the baseline bar (or equal to it), so NO label.
if max_y_limit > 0:
ax.set_ylim(top=max_y_limit * 1.15)
# Legend management
if i < n_subplots - 1:
if ax.get_legend():
ax.get_legend().remove()
else:
ax.legend(title='Scenario', bbox_to_anchor=(1.05, 1), loc='upper left')
plt.suptitle(f"Metric Comparison: {metric}", fontsize=16, y=1.02)
plt.tight_layout()
safe_filename = "".join([c if c.isalnum() else "_" for c in metric]) + f".{output_format}"
save_path = os.path.join(output_folder, safe_filename)
plt.savefig(save_path, bbox_inches='tight')
plt.close()
print(f" -> Saved: {safe_filename}")
def generate_plots_by_worker_horizontal_legend(df: pd.DataFrame, output_folder: str, output_format: str, y_log: bool = False, show_pct_diff: bool = True, width: int = 6, height: int = 8):
"""
Generates bar charts for every numeric metric using subplots.
Fix implemented:
- Calculates the baseline strictly from the PLOTTED bars (visual mean).
- Places the legend horizontally at the bottom of the figure.
"""
if df.empty:
print("DataFrame is empty. Skipping plot generation.")
return
os.makedirs(output_folder, exist_ok=True)
print(f"Generating plots in '{output_folder}' (Annotations: {show_pct_diff})...")
# 1. Setup Columns
config_cols = ['n_workers', 'n_primes', 'n_iterations', 'scenario', 'configuration_label']
metric_cols = [c for c in df.columns if c not in config_cols and pd.api.types.is_numeric_dtype(df[c])]
unique_workers = sorted(df['n_workers'].unique())
n_subplots = len(unique_workers)
sns.set_theme(style="whitegrid")
for metric in metric_cols:
# Dynamic figure size
# Removed constrained_layout=True to allow manual adjustment for the bottom legend
fig, axes = plt.subplots(nrows=1, ncols=n_subplots, figsize=(width * n_subplots, height), sharey=False)
if n_subplots == 1:
axes = [axes]
# Variables to store legend handles and labels
handles, labels = None, None
for i, worker_count in enumerate(unique_workers):
ax = axes[i]
# Filter Data
subplot_data = df[df['n_workers'] == worker_count].sort_values(by=['n_primes', 'scenario'])
if subplot_data.empty:
continue
# Create Bar Plot
sns.barplot(
data=subplot_data,
x='n_primes',
y=metric,
hue='scenario',
palette='viridis',
ax=ax
)
if y_log:
ax.set_yscale('log')
ax.set_title(f"Workers: {worker_count}", fontsize=14)
ax.set_xlabel("Number of Primes", fontsize=11)
if i == 0:
ax.set_ylabel(metric, fontsize=12)
else:
ax.set_ylabel("")
# =========================================================
# ANNOTATION LOGIC (Two-Pass Approach)
# =========================================================
if show_pct_diff:
max_y_limit = 0
error_bar_tops = {}
group_visual_min = {}
# A. Get Error Bar Tops
for line in ax.lines:
x_data = line.get_xdata()
y_data = line.get_ydata()
if len(x_data) > 0:
x_pos = x_data[0]
y_max = max(y_data)
error_bar_tops[round(x_pos, 4)] = y_max
# B. Find the Minimum Bar Height per X-Group strictly from the patches
for p in ax.patches:
h = p.get_height()
if pd.isna(h) or h <= 0:
continue
x_idx = int(round(p.get_x() + p.get_width() / 2.))
if x_idx not in group_visual_min:
group_visual_min[x_idx] = h
else:
if h < group_visual_min[x_idx]:
group_visual_min[x_idx] = h
# --- PASS 2: Annotate based on Visual Baselines ---
for p in ax.patches:
bar_height = p.get_height()
if pd.isna(bar_height) or bar_height <= 0:
continue
bar_x = p.get_x() + p.get_width() / 2.
x_idx = int(round(bar_x))
text_y_anchor = bar_height
if round(bar_x, 4) in error_bar_tops:
error_top = error_bar_tops[round(bar_x, 4)]
if error_top > text_y_anchor:
text_y_anchor = error_top
max_y_limit = max(max_y_limit, text_y_anchor)
if x_idx in group_visual_min:
baseline = group_visual_min[x_idx]
if bar_height > (baseline + 0.0001):
pct_diff = ((bar_height - baseline) / baseline) * 100
label_text = f"+{pct_diff:.1f}%"
ax.annotate(
label_text,
(bar_x, text_y_anchor),
ha='center',
va='bottom',
xytext=(0, 5),
textcoords='offset points',
fontsize=9,
color="black",
weight="normal"
)
if max_y_limit > 0:
ax.set_ylim(top=max_y_limit * 1.15)
# =========================================================
# LEGEND EXTRACTION
# =========================================================
# Capture handles/labels from the first plot, then remove axis-level legend
if ax.get_legend():
if handles is None:
handles, labels = ax.get_legend_handles_labels()
ax.get_legend().remove()
# =========================================================
# GLOBAL LEGEND (Bottom Horizontal)
# =========================================================
if handles and labels:
# ncol=len(labels) forces all items into a single row
fig.legend(
handles,
labels,
loc='lower center',
bbox_to_anchor=(0.5, -0.1), # Adjust Y to move up/down
ncol=len(labels),
frameon=False,
fontsize=11
)
plt.suptitle(f"Metric Comparison: {metric}", fontsize=16, y=0.98)
# Adjust layout to make room for the legend at the bottom
plt.tight_layout()
plt.subplots_adjust(bottom=0.15) # Reserve bottom 15% for legend
safe_filename = "".join([c if c.isalnum() else "_" for c in metric]) + f".{output_format}"
save_path = os.path.join(output_folder, safe_filename)
plt.savefig(save_path, bbox_inches='tight')
plt.close()
print(f" -> Saved: {safe_filename}")
def generate_time_split_plot(
df: pd.DataFrame,
output_folder: str,
output_format: str,
total_time_col: str,
cpu_time_col: str,
y_log: bool = False, # <--- Added back
show_pct_diff: bool = True,
width: int = 6,
height: int = 8
):
"""
Generates a single plot file focusing ONLY on the time composition.
Visual Logic:
- Creates a stacked-like effect by overlaying bars:
1. 'Total Time' (semi-transparent). Top portion = 'Other/Overhead'.
2. 'CPU Time' (solid) on top.
Args:
y_log: If True, sets the Y-axis to logarithmic scale.
"""
if df.empty:
print("DataFrame is empty. Skipping plot generation.")
return
# Validate columns exist
if total_time_col not in df.columns or cpu_time_col not in df.columns:
print(f"Error: Columns '{total_time_col}' or '{cpu_time_col}' not found in DataFrame.")
return
os.makedirs(output_folder, exist_ok=True)
print(f"Generating time split plot in '{output_folder}' (Log Scale: {y_log})...")
# Setup
unique_workers = sorted(df['n_workers'].unique())
n_subplots = len(unique_workers)
sns.set_theme(style="whitegrid")
# Dynamic figure size
fig, axes = plt.subplots(nrows=1, ncols=n_subplots, figsize=(width * n_subplots, height), sharey=False, constrained_layout=True)
if n_subplots == 1:
axes = [axes]
for i, worker_count in enumerate(unique_workers):
ax = axes[i]
# Filter Data
subplot_data = df[df['n_workers'] == worker_count].sort_values(by=['n_primes', 'scenario'])
if subplot_data.empty:
continue
# =========================================================
# PLOT LAYER 1: TOTAL TIME (The container)
# =========================================================
sns.barplot(
data=subplot_data,
x='n_primes',
y=total_time_col,
hue='scenario',
palette='viridis',
alpha=0.4, # Semi-transparent
ax=ax,
dodge=True,
edgecolor=None
)
# =========================================================
# ANNOTATION LOGIC (Calculated on Total Time)
# =========================================================
max_y_limit = 0
if show_pct_diff:
# --- PASS 1: Find Visual Baselines ---
error_bar_tops = {}
group_visual_min = {}