Repository navigation
Expand file tree
/
Copy pathexperiments.py
More file actions
executable file
·2848 lines (2397 loc) · 96.1 KB
/
Copy pathexperiments.py
File metadata and controls
executable file
·2848 lines (2397 loc) · 96.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
#!/usr/bin/env python3
"""
Master script for reproducing paper tables and figures.
Usage:
python3 experiments.py # Reproduce all tables and figures
python3 experiments.py --task results # Same as above
python3 experiments.py --task rerun # Re-run experiments from scratch (hours)
Individual tables/figures:
python3 experiments.py --task table1 # Table 1: UDF Statistics
python3 experiments.py --task table2 # Table 2: Pushdown Outcomes
python3 experiments.py --task table3 # Table 3: Types of Pushdowns
python3 experiments.py --task table4 # Table 4: Pipeline Runtime Reduction
python3 experiments.py --task table5 # Table 5: Search Space Reduction
python3 experiments.py --task table6 # Table 6: Solution Optimality
python3 experiments.py --task figure5 # Figure 5: CDF Plot
"""
import csv
import os
import re
import subprocess
import sys
import pandas as pd
import numpy as np
from pathlib import Path
from statistics import mean as _mean, median as _median
from typing import Dict, List, Tuple, Optional
import argparse
import matplotlib.pyplot as plt
from matplotlib import rcParams
import matplotlib.lines as mlines
CDF_COLORS = dict(
push="C0",
nob="#f28e00",
sp="green",
eld="red",
noa="purple",
two="brown",
noba="darkslategray",
)
def _make_cdf(rts: np.ndarray, tot: int) -> Tuple[np.ndarray, np.ndarray]:
idx = np.arange(1, len(rts) + 1)
y = idx / tot * 100.0
x = np.concatenate(([0.0], rts))
y = np.concatenate(([0.0], y))
return x, y
def _styled_scatter(ax, xs, ys, marker, colour, edge_w=0.6, size=30):
ax.scatter(
xs,
ys,
marker=marker,
s=size,
facecolors=colour,
edgecolors="white",
linewidths=edge_w,
zorder=3,
)
def _halo_handle(colour: str, marker: str, size: int = 5, edge_w: float = 0.6):
return mlines.Line2D(
[],
[],
lw=1,
color=colour,
marker=marker,
markersize=size,
markerfacecolor=colour,
markeredgecolor="white",
markeredgewidth=edge_w,
)
# ---------------------------------------------------------------------------
# Benchmark runner constants and helpers
# ---------------------------------------------------------------------------
FLOAT_RE = re.compile(r"^(\d+\.\d{2})s?$", re.MULTILINE)
STEM_RE = re.compile(r"^(.+)_([0-9]+)$")
CLASS_STEM_RE = re.compile(r"^(.+)_([0-9]+)$")
DEFAULT_MASTER = "local[4]"
DEFAULT_DRIVER_MEMORY = "6g"
DEFAULT_SPARK_CONF = {
"spark.driver.memoryOverhead": "1g",
"spark.driver.host": "127.0.0.1",
"spark.driver.bindAddress": "127.0.0.1",
"spark.default.parallelism": "8",
"spark.sql.shuffle.partitions": "8",
"spark.sql.files.maxPartitionBytes": "64m",
"spark.sql.adaptive.enabled": "false",
"spark.speculation": "false",
"spark.dynamicAllocation.enabled": "false",
"spark.executor.memory": "6g",
"spark.sql.codegen.wholeStage": "false",
"spark.ui.enabled": "false",
"spark.eventLog.enabled": "false",
"spark.driver.extraJavaOptions": "-XX:+AlwaysPreTouch",
"spark.executor.extraJavaOptions": "-XX:+AlwaysPreTouch -XX:+UseG1GC -XX:ParallelGCThreads=2 -XX:ConcGCThreads=1",
"spark.local.dir": "/tmp/spark_tmp",
}
def parse_runtime(text: str) -> Optional[float]:
"""Extract a float runtime (e.g. '12.34' or '12.34s') from text."""
m = FLOAT_RE.search(text)
return float(m.group(1)) if m else None
def _append_speedup_row(benchmark: str, speedup: str, results_path: Path) -> None:
"""Append a single speedup row to the CSV, writing the header if needed."""
write_header = not results_path.exists() or results_path.stat().st_size == 0
with results_path.open("a", newline="", encoding="utf-8") as f:
w = csv.writer(f)
if write_header:
w.writerow(["benchmark", "speedup"])
w.writerow([benchmark, speedup])
def _load_completed_speedups(results_path: Path) -> set:
"""Return set of benchmark names already present in the speedups CSV."""
if not results_path.exists():
return set()
completed = set()
with results_path.open(newline="", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
if row and row[0] != "benchmark":
completed.add(row[0])
return completed
def _print_speedup_summary(results_path: Path) -> None:
"""Read the speedups CSV and print summary statistics."""
if not results_path.exists():
print(f"No results file found at {results_path}")
return
rows = []
with results_path.open(newline="", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
if row and row[0] != "benchmark":
rows.append(row)
valid = [float(r[1].rstrip("%")) for r in rows if r[1] != "NA"]
if valid:
neg = sum(1 for s in valid if s < 0)
print(f"\n{'=' * 60}")
print(f"Results: {results_path}")
print(f"Benchmarks: {len(valid)}")
print(f"Mean speedup: {sum(valid) / len(valid):.1f}%")
print(f"Median speedup: {sorted(valid)[len(valid) // 2]:.1f}%")
print(f"Negative: {neg}/{len(valid)}")
print(f"Range: {min(valid):+.1f}% .. {max(valid):+.1f}%")
print(f"\nResults written to {results_path}")
# -- pandas runner helpers --------------------------------------------------
def _run_pandas_script(
python_cmd: str, script: Path, extra_env: Optional[dict] = None
) -> Optional[float]:
env = {**os.environ, **(extra_env or {})}
try:
p = subprocess.run(
[python_cmd, script.name],
text=True,
capture_output=True,
check=False,
cwd=str(script.resolve().parent),
env=env,
)
except FileNotFoundError:
print(f"[error] Python not found: {python_cmd}", file=sys.stderr)
raise
if p.returncode != 0:
print(f"[warn] {script.stem}: exit {p.returncode}", file=sys.stderr)
if p.stderr.strip():
print(f" stderr: {p.stderr.strip()[-200:]}", file=sys.stderr)
result = parse_runtime(p.stdout)
if result is None:
result = parse_runtime(p.stderr)
return result
def find_benchmark_scripts(d: Path) -> List[str]:
"""Return sorted list of Name_N stems for .py files in a single directory."""
stems = sorted(
p.stem
for p in d.iterdir()
if p.suffix == ".py" and p.is_file() and STEM_RE.match(p.stem)
)
if not stems:
raise SystemExit(f"No benchmark scripts found in {d}")
return stems
def run_pandas(args: argparse.Namespace) -> None:
"""Run pandas benchmarks and collect percentage speedups from stdout."""
stems = find_benchmark_scripts(args.pandas_dir)
if args.file_regex:
rx = re.compile(args.file_regex)
stems = [s for s in stems if rx.search(s)]
if not stems:
print("No matching scripts after filtering.", file=sys.stderr)
sys.exit(1)
completed = _load_completed_speedups(args.results)
remaining = len([s for s in stems if s not in completed])
print(
f"Writing results incrementally to {args.results} ({len(completed)}/{len(stems)} already completed, {remaining} remaining) ..."
)
n_runs = max(args.runs, 2) # at least 1 warmup + 1 measured
print(
f"Pandas benchmark: {len(stems)} scripts x {n_runs} rounds "
f"(1 warmup + {n_runs - 1} measured)\n"
)
for stem in stems:
if stem in completed:
print(f" Skipping {stem} (already completed)")
continue
script = args.pandas_dir / f"{stem}.py"
pct_values: List[float] = []
for rnd in range(n_runs):
is_warmup = rnd == 0
pct = _run_pandas_script(args.python, script)
tag = " (warmup)" if is_warmup else ""
disp = f"{pct:.2f}%" if pct is not None else "NA"
print(f" {stem} [round {rnd + 1}/{n_runs}]{tag}: {disp}")
if not is_warmup and pct is not None:
pct_values.append(pct)
if not pct_values:
print(f"[warn] {stem}: missing data, recording NA", file=sys.stderr)
_append_speedup_row(stem, "NA", args.results)
else:
med_pct = _median(pct_values)
_append_speedup_row(stem, f"{med_pct:.2f}%", args.results)
print(f" {stem} => speedup={med_pct:.2f}%\n")
_print_speedup_summary(args.results)
# -- Spark runner helpers ---------------------------------------------------
def _build_jar(project_dir: Path, skip: bool) -> Path:
jar_dir = project_dir / "target" / "scala-2.13"
jar_pattern = (
"*enchmarks*.jar" # case-insensitive match for SparkBenchmarks/sparkbenchmarks
)
def _find_jar():
jars = list(jar_dir.glob(jar_pattern))
return jars[0] if jars else None
if skip:
jar = _find_jar()
if not jar:
raise SystemExit(f"JAR not found (--skip-build) in {jar_dir}")
return jar
print(f" Building JAR in {project_dir.name}/ ...")
ret = subprocess.call(
["sbt", "-batch", "-error", "--supershell=false", "package"],
cwd=project_dir,
)
if ret != 0:
raise SystemExit(f"sbt package failed in {project_dir}")
jar = _find_jar()
if not jar:
raise SystemExit(f"JAR not found after build in {jar_dir}")
return jar
def _spark_submit(
class_name: str,
jar: Path,
master: str,
driver_memory: str,
conf: dict,
cwd: Optional[Path] = None,
) -> Optional[float]:
cmd = [
"spark-submit",
"--class",
class_name,
"--master",
master,
"--driver-memory",
driver_memory,
]
for k, v in conf.items():
cmd += ["--conf", f"{k}={v}"]
cmd.append(str(jar))
env = {**os.environ, "SPARK_LOCAL_IP": "127.0.0.1"}
try:
p = subprocess.run(
cmd,
text=True,
capture_output=True,
check=False,
env=env,
cwd=str(cwd) if cwd else None,
)
except FileNotFoundError:
print("[error] spark-submit not found on PATH", file=sys.stderr)
raise
if p.returncode != 0:
print(f"[warn] {class_name}: spark-submit exit {p.returncode}", file=sys.stderr)
if p.stderr.strip():
# Print last 300 chars of stderr for diagnostics
print(f" stderr: ...{p.stderr.strip()[-300:]}", file=sys.stderr)
result = parse_runtime(p.stdout)
if result is None:
result = parse_runtime(p.stderr)
return result
def find_benchmark_classes(d: Path) -> List[str]:
"""Return sorted list of Name_N stems for .scala files in a single directory."""
# Look in src/main/scala/ subdirectory (standard sbt layout)
src_dir = d / "src" / "main" / "scala"
search_dir = src_dir if src_dir.is_dir() else d
classes = sorted(
p.stem
for p in search_dir.iterdir()
if p.suffix == ".scala" and p.is_file() and CLASS_STEM_RE.match(p.stem)
)
if not classes:
raise SystemExit(f"No benchmark classes found in {search_dir}")
return classes
def run_spark(args: argparse.Namespace) -> None:
"""Run Spark benchmarks and collect percentage speedups from stdout."""
# Build JAR
print("Building JAR ...")
jar = _build_jar(args.spark_dir, args.skip_build)
# Discover classes
classes = find_benchmark_classes(args.spark_dir)
if args.class_regex:
rx = re.compile(args.class_regex)
classes = [c for c in classes if rx.search(c)]
if not classes:
print("No matching classes after filtering.", file=sys.stderr)
sys.exit(1)
# Merge conf
conf = dict(DEFAULT_SPARK_CONF)
for kv in args.extra_conf:
if "=" not in kv:
raise SystemExit(f"--extra-conf must be key=value, got: {kv}")
k, v = kv.split("=", 1)
conf[k.strip()] = v.strip()
# Run benchmarks
completed = _load_completed_speedups(args.results)
remaining = len([c for c in classes if c not in completed])
print(
f"Writing results incrementally to {args.results} ({len(completed)}/{len(classes)} already completed, {remaining} remaining) ..."
)
n_runs = max(args.runs, 2) # at least 1 warmup + 1 measured
print(
f"\nSpark benchmark: {len(classes)} classes x {n_runs} rounds "
f"(1 warmup + {n_runs - 1} measured)\n"
)
for cls in classes:
if cls in completed:
print(f" Skipping {cls} (already completed)")
continue
pct_values: List[float] = []
for rnd in range(n_runs):
is_warmup = rnd == 0
pct = _spark_submit(
cls, jar, args.master, args.driver_memory, conf, cwd=args.spark_dir
)
tag = " (warmup)" if is_warmup else ""
disp = f"{pct:.2f}%" if pct is not None else "NA"
print(f" {cls} [round {rnd + 1}/{n_runs}]{tag}: {disp}")
if not is_warmup and pct is not None:
pct_values.append(pct)
if not pct_values:
print(f"[warn] {cls}: missing data, recording NA", file=sys.stderr)
_append_speedup_row(cls, "NA", args.results)
else:
med_pct = _median(pct_values)
_append_speedup_row(cls, f"{med_pct:.2f}%", args.results)
print(f" {cls} => speedup={med_pct:.2f}%\n")
_print_speedup_summary(args.results)
# ---------------------------------------------------------------------------
# run-synth: run pusharoo.exe on every benchmark in a directory (from bench.py)
# ---------------------------------------------------------------------------
_SYNTH_COLUMNS = [
"benchmark",
"status",
"kind",
"runtime",
"|Q*|",
"|P*|",
"|BI|",
"|P|",
"|DP|",
"num_pairs",
"magicpush_exact",
"magicpush_partial",
]
def _load_completed_synth(output_csv: str) -> set:
"""Return set of benchmark names already present in the synth results CSV."""
if not os.path.exists(output_csv):
return set()
completed = set()
try:
df = pd.read_csv(output_csv)
completed = set(df["benchmark"].tolist())
except Exception:
pass
return completed
def _append_synth_row(rec: dict, output_csv: str) -> None:
"""Append a single result row to the synth CSV, writing the header if needed."""
write_header = not os.path.exists(output_csv) or os.path.getsize(output_csv) == 0
with open(output_csv, "a", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=_SYNTH_COLUMNS)
if write_header:
w.writeheader()
w.writerow(rec)
def run_pusharoo_on_directory(
bench_dir, timeout, mode, results_dir, out, expand=None, save_qp=None
):
"""Run pusharoo.exe on every .py file in *bench_dir* and write a results CSV."""
exe = str(
(Path(__file__).resolve().parent / "synthesizer" / "pusharoo.exe").resolve()
)
output_csv = str(Path(results_dir) / f"{out}.csv")
# Load already-completed benchmarks for resumability
completed = _load_completed_synth(output_csv)
total_files = sum(
1 for e in os.listdir(bench_dir) if os.path.isfile(os.path.join(bench_dir, e))
)
remaining = total_files - len(completed)
print(
f"Writing results incrementally to {output_csv} ({len(completed)}/{total_files} already completed, {remaining} remaining) ..."
)
for entry in sorted(os.listdir(bench_dir)):
file_path = os.path.join(bench_dir, entry)
if not os.path.isfile(file_path):
continue
# Check the benchmark name (strip .py extension to match CSV format)
bench_name = os.path.splitext(entry)[0] if entry.endswith(".py") else entry
if bench_name in completed or entry in completed:
print(f" Skipping {entry} (already completed)")
continue
cmd = [exe, file_path, "--timeout", timeout, "--mode", mode]
if expand is not None:
cmd += ["--expand", expand]
if save_qp is not None:
cmd += ["--save-qp", save_qp]
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
except subprocess.CalledProcessError as e:
print(f"Error running pusharoo on {entry}: {e.stderr.strip()}")
continue
line = result.stdout.strip()
if not line:
print(f"No output for {entry}, marking as none.")
status = "none"
parts = [entry, status]
else:
parts = [p.strip() for p in line.split(",")]
if parts[1] in ("unknown", "none", "timeout"):
status = parts[1]
elif len(parts) == 11:
status = "ok"
else:
print(f"Unexpected output format for {entry}: {line}")
continue
rec = {
"benchmark": parts[0],
"status": status,
"kind": None,
"runtime": None,
"|Q*|": None,
"|P*|": None,
"|BI|": None,
"|P|": None,
"|DP|": None,
"num_pairs": None,
"magicpush_exact": None,
"magicpush_partial": None,
}
if status == "ok":
rec.update(
{
"kind": int(parts[1]),
"runtime": float(parts[2]),
"|Q*|": int(parts[3]),
"|P*|": int(parts[4]),
"|BI|": int(parts[5]),
"|P|": int(parts[6]),
"|DP|": int(parts[7]),
"num_pairs": int(parts[8]),
"magicpush_exact": parts[9],
"magicpush_partial": parts[10],
}
)
print(line)
_append_synth_row(rec, output_csv)
# Read back the full CSV for summary statistics
df = pd.read_csv(output_csv)
print(f"Results file: {output_csv}")
num_unknown = (df["status"] == "unknown").sum()
num_none = (df["status"] == "none").sum()
num_timeout = (df["status"] == "timeout").sum()
num_ok = (df["status"] == "ok").sum()
print(f"# benchmarks: {len(df)}")
print(f"# successful: {num_ok}")
print(f"# timeouts: {num_timeout}")
print(f"# no solution: {num_none}")
print(f"# unknown: {num_unknown}")
df_ok = df[df["status"] == "ok"]
if mode == "pusharoo":
k4 = df_ok[df_ok["kind"] == 4]
assert len(k4) == 0, (
f"Unexpected kind=4 in Pusharoo mode for: "
f"{', '.join(k4['benchmark'].tolist())}"
)
df.loc[df["kind"] == 5, "kind"] = 3
# Normalize by subtracting the early-halting check pair from num_pairs,
# as it is irrelevant to the search space reduction experiment.
df.loc[df["num_pairs"].notna(), "num_pairs"] = (
df.loc[df["num_pairs"].notna(), "num_pairs"] - 1
).clip(lower=0)
runtimes = df_ok["runtime"]
print("\n=== Runtime statistics (ok only) ===")
print(f"Avg runtime: {runtimes.mean():.2f}s")
print(f"Min runtime: {runtimes.min():.2f}s")
print(f"Max runtime: {runtimes.max():.2f}s")
print(f"Total runtime: {runtimes.sum():.2f}s")
avg_qstar = df_ok["|Q*|"].mean()
avg_pstar = df_ok["|P*|"].mean()
avg_bi = df_ok["|BI|"].mean()
df_k3 = df_ok[df_ok["kind"].isin([3, 4, 5])]
avg_d_p = df_k3["|P|"].mean()
avg_dp = df_k3["|DP|"].mean()
print(f"Avg |Q*|: {avg_qstar:.2f}")
print(f"Avg |P*|: {avg_pstar:.2f}")
print(f"Avg |BI|: {avg_bi:.2f}")
print(f"Avg |P| (weaker): {avg_d_p:.2f}")
print(f"Avg |DP| (weaker): {avg_dp:.2f}")
# ---------------------------------------------------------------------------
# ablcomp: compare solution quality between Pusharoo and CHC solvers
# ---------------------------------------------------------------------------
def _ablcomp_parse_row(row: List[str]) -> Tuple[str, Optional[str], Optional[str]]:
"""Return (benchmark, p_val, sentinel).
benchmark : COL1 stripped.
p_val : COL3 (stripped) if row is *normal*, else None.
sentinel : 'none' | 'timeout' if present, else None.
"""
if len(row) < 2:
raise ValueError(f"Row {row!r} has fewer than two columns.")
benchmark = row[0].strip()
col2 = row[1].strip().lower()
if col2 in {"none", "timeout"}:
return benchmark, None, col2
if len(row) < 3:
raise ValueError(
f"Row for benchmark {benchmark!r} lacks a third column (COL3)."
)
return benchmark, row[2].strip(), None # normal row
def _ablcomp_run(exe: Path, bench_py: Path, p1: str, p2: str, chc_mode: str) -> str:
"""Return ablcomp.exe's single-line stdout (stripped)."""
cmd: List[str] = [
str(exe),
"--chc-mode",
chc_mode,
"-p1",
p1,
"-p2",
p2,
"-i",
str(bench_py),
]
completed = subprocess.run(cmd, check=True, text=True, capture_output=True)
return completed.stdout.strip()
def _ablcomp_load_csv(path: Path) -> List[List[str]]:
"""Read a header-less CSV into a list of raw rows."""
return list(csv.reader(open(path, newline="", encoding="utf-8")))
def _ablcomp_process_mode(
exe: Path,
bench_dir: Path,
csv1_rows: List[List[str]],
csv2_rows: List[List[str]],
chc_mode: str,
) -> List[str]:
"""Execute one mode (spacer or eld) and return comp values aligned with csv1_rows."""
comps: List[str] = []
for idx, (row1, row2) in enumerate(zip(csv1_rows, csv2_rows), 1):
b1, p1, s1 = _ablcomp_parse_row(row1)
b2, p2, s2 = _ablcomp_parse_row(row2)
if b1 != b2:
sys.exit(f"Error: benchmark mismatch at row {idx}: {b1!r} vs {b2!r}")
benchmark = b1
# Sentinel handling
if s1 or s2:
comps.append("timeout" if "timeout" in (s1, s2) else "none")
continue
# Normal row: run ablcomp
bench_file = bench_dir / f"{benchmark}.py"
try:
full_line = _ablcomp_run(exe, bench_file, p1, p2, chc_mode)
try:
_, comp_field = full_line.split(",", 1)
except ValueError:
raise RuntimeError(
f"Unexpected ablcomp output for {benchmark!r}: {full_line!r}"
)
comps.append(comp_field)
except Exception as e:
sys.stderr.write(f"{chc_mode}: failure on {benchmark}: {e}\n")
comps.append("error")
return comps
def run_ablcomp(results_dir: Path, bench_dir: Path) -> None:
"""Compare solution quality between Pusharoo and CHC solvers."""
base_dir = Path(__file__).resolve().parent
exe = (base_dir / "synthesizer" / "ablcomp.exe").resolve()
push_path = results_dir / "comp_pusharoo_QP.csv"
spacer_path = results_dir / "comp_spacer_QP.csv"
eld_path = results_dir / "comp_eld_QP.csv"
out_path = results_dir / "ablcomp.csv"
print(f"Writing results to {out_path} ...")
# Load CSVs
push_rows = _ablcomp_load_csv(push_path)
spacer_rows = _ablcomp_load_csv(spacer_path)
eld_rows = _ablcomp_load_csv(eld_path)
n_rows = len(push_rows)
if len(spacer_rows) != n_rows or len(eld_rows) != n_rows:
sys.exit(
"Error: input CSVs do not have the same number of rows:\n"
f" pusharoo: {n_rows}\n"
f" spacer : {len(spacer_rows)}\n"
f" eld : {len(eld_rows)}"
)
# Run both modes
comp_spacer = _ablcomp_process_mode(
exe, bench_dir, push_rows, spacer_rows, "spacer"
)
comp_eld = _ablcomp_process_mode(exe, bench_dir, push_rows, eld_rows, "eld")
# Write merged output
out_path.parent.mkdir(parents=True, exist_ok=True)
with open(out_path, "w", encoding="utf-8", newline="") as fp_out:
fp_out.write("benchmark,comp_spacer,comp_eld\n")
for row_push, cs, ce in zip(push_rows, comp_spacer, comp_eld):
benchmark = row_push[0].strip()
fp_out.write(f"{benchmark},{cs},{ce}\n")
# Count results
spacer_twos = sum(1 for x in comp_spacer if x == "2")
eld_twos = sum(1 for x in comp_eld if x == "2")
spacer_valid = sum(1 for x in comp_spacer if x not in {"none", "timeout"})
eld_valid = sum(1 for x in comp_eld if x not in {"none", "timeout"})
print(
f"comp_spacer: {spacer_twos} occurrences of 2, "
f"{spacer_valid} non-sentinel values"
)
print(f"comp_eld : {eld_twos} occurrences of 2, {eld_valid} non-sentinel values")
# ---------------------------------------------------------------------------
# udf-props: collect UDF boolean properties for Table 1 (from props.py)
# ---------------------------------------------------------------------------
def compute_udf_props(bench_dir: str) -> None:
"""For each unique prefix, run pusharoo.exe --props and write udf_props.csv."""
exe_path = str(
(Path(__file__).resolve().parent / "synthesizer" / "pusharoo.exe").resolve()
)
results_dir = Path(__file__).resolve().parent / "results"
output_csv = results_dir / "udf_props.csv"
# from manual inspection of the original source code
_HAS_COLLECTION = {
"Ada1",
"Basket",
"Flaredown1",
"MinPooling",
"PreprocCSVTable",
"RoaringBitmapUDAF",
"Top2",
"UDAF2",
}
bool_names = [
"has_conditional",
"has_tuple_accum",
"has_indep",
"has_crossdep",
"has_collection",
]
rows = [] # (prefix, b1, b2, b3, b4, b5)
for fname in sorted(os.listdir(bench_dir)):
full = os.path.join(bench_dir, fname)
if not os.path.isfile(full) or "_" not in fname:
continue
prefix = fname.split("_", 1)[0]
if any(r[0] == prefix for r in rows):
continue # already processed
try:
proc = subprocess.run(
[exe_path, "--udf-props", full],
capture_output=True,
text=True,
check=True,
)
except subprocess.CalledProcessError as e:
print(f"Error running on {fname}: {e.stderr.strip()}")
continue
parts = proc.stdout.strip().split(",")
if len(parts) < 5:
print(f"Unexpected output for {fname}: {proc.stdout.strip()!r}")
continue
bools = [parts[i].strip().lower() == "true" for i in range(1, 5)]
bools.append(prefix in _HAS_COLLECTION)
rows.append((prefix, *bools))
# Write udf_props.csv
print(f"Writing results to {output_csv} ...")
with open(output_csv, "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["prefix"] + bool_names)
for row in rows:
w.writerow([row[0]] + [str(b).lower() for b in row[1:]])
print(f"Processed {len(rows)} UDFs; results written to {output_csv}")
print("Statistics:")
for name in bool_names:
count = sum(1 for row in rows if row[1 + bool_names.index(name)])
print(f" {name}: {count}")
# ---------------------------------------------------------------------------
# ast-sizes: compute AST size statistics for Table 1 (from size.py)
# ---------------------------------------------------------------------------
def compute_ast_sizes(bench_dir: str, results_dir: Path) -> None:
"""For each benchmark .py file, run pusharoo.exe --ast-size and collect sizes."""
exe_path = str(
(Path(__file__).resolve().parent / "synthesizer" / "pusharoo.exe").resolve()
)
output_csv = str(results_dir / "ast_sizes.csv")
print(f"Writing results to {output_csv} ...")
sizes = [] # list of integer AST sizes, one per benchmark file
for fname in sorted(os.listdir(bench_dir)):
full_path = os.path.join(bench_dir, fname)
if not os.path.isfile(full_path) or "_" not in fname:
continue
try:
proc = subprocess.run(
[exe_path, "--ast-size", full_path],
capture_output=True,
text=True,
check=True,
)
except subprocess.CalledProcessError as e:
print(f"Error on {fname}: {e.stderr.strip()}")
continue
line = proc.stdout.strip()
parts = line.split(",")
if len(parts) < 2:
print(f"Unexpected output for {fname}: {line!r}")
continue
try:
value = int(parts[1])
except ValueError:
print(f"Non-integer value for {fname}: {parts[1]!r}")
continue
sizes.append(value)
# ensure output directory exists
os.makedirs(os.path.dirname(output_csv), exist_ok=True)
# write to CSV: single column "size", one row per benchmark
with open(output_csv, "w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["size"])
for size in sizes:
writer.writerow([size])
if not sizes:
print("No valid records collected.")
return
mn = min(sizes)
mx = max(sizes)
avg = _mean(sizes)
med = _median(sizes)
print(f"Processed {len(sizes)} benchmarks; results written to {output_csv}")
print("Statistics for 'size':")
print(f" Min : {mn}")
print(f" Max : {mx}")
print(f" Avg : {avg:.2f}")
print(f" Median: {med}")
class ResultsAnalyzer:
"""Analyzer for benchmark results.
This class provides extensible analysis capabilities for benchmark results.
To add new analyses, simply add new methods and call them from main().
Example extension:
def analyze_timeout_rate(self, files: List[str]) -> pd.DataFrame:
'''Compute timeout rates across different configurations.'''
stats = []
for filename in files:
df = self.load_csv(filename)
total = len(df)
timeouts = len(df[df['status'] == 'timeout'])
stats.append({
'File': filename,
'Timeout Rate': timeouts / total * 100
})
return pd.DataFrame(stats)
"""
def __init__(self, results_dir: Path):
"""Initialize the analyzer with a results directory.
Args:
results_dir: Path to the directory containing results CSV files
"""
self.results_dir = Path(results_dir)
def load_csv(self, filename: str) -> pd.DataFrame:
"""Load a CSV file from the results directory.
Args:
filename: Name of the CSV file to load
Returns:
DataFrame containing the CSV data
"""
filepath = self.results_dir / filename
if not filepath.exists():
raise FileNotFoundError(f"File not found: {filepath}")
return pd.read_csv(filepath)
def compute_speedup_stats_by_type(
self,
speedups_file: str = "results_speedups.csv",
status_file: str = "results.csv",
) -> pd.DataFrame:
"""Compute median, average, and max speedups by pushdown type.
Args:
speedups_file: Name of the speedups CSV file
status_files: Dictionary mapping status file labels to filenames.
If None, uses default files.
Returns:
DataFrame with speedup statistics by type
"""
speedups = self.load_csv(speedups_file)
status_df = self.load_csv(status_file)
merged = speedups.merge(
status_df[["benchmark", "status", "kind"]], on="benchmark"
)
# Convert speedup percentage to float (remove % and convert)
merged["speedup_val"] = merged["speedup"].str.rstrip("%").astype(float)
# Group by pushdown type
type_mapping = {1: "Exact", 2: "Partial", 3: "Split", 5: "Split"}
merged["type_category"] = merged["kind"].map(type_mapping)
# Compute statistics for each type
stats = []
for type_name in ["Exact", "Partial", "Split"]:
type_data = merged[merged["type_category"] == type_name]["speedup_val"]
if len(type_data) > 0:
stats.append(
{
"Type": type_name,
"Min": type_data.min(),
"Median": type_data.median(),
"Avg": type_data.mean(),
"Max": type_data.max(),
}
)
else:
stats.append(
{
"Type": type_name,
"Min": np.nan,
"Median": np.nan,
"Avg": np.nan,
"Max": np.nan,
}
)
# Compute overall statistics across all types
if len(merged) > 0:
stats.append(
{