Repository navigation
Expand file tree
/
Copy pathbench.py
More file actions
182 lines (159 loc) · 6.98 KB
/
Copy pathbench.py
File metadata and controls
182 lines (159 loc) · 6.98 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
"""Shared Python CDT benchmark driver and postcondition validator."""
from __future__ import annotations
import argparse
import csv
import json
import statistics
import time
from pathlib import Path
import numpy as np
from scipy.spatial import cKDTree
import common
HEADER = [
"case_id", "n", "param", "time_ms", "valid", "note",
"out_points", "out_faces", "crossings_resolved", "recovery_checked",
"samples_ms",
]
MAGIC = b"PSLG0001"
def load_pslg(path: Path):
raw = path.read_bytes()
if raw[:8] != MAGIC or len(raw) < 24:
raise ValueError(f"{path}: invalid PSLG header")
n_points, n_segments, expected_crossings, flags = np.frombuffer(
raw, dtype="<u4", count=4, offset=8
)
offset = 24
points = np.frombuffer(
raw, dtype="<f8", count=int(n_points) * 2, offset=offset
).reshape(-1, 2)
offset += int(n_points) * 16
segments = np.frombuffer(
raw, dtype="<i4", count=int(n_segments) * 2, offset=offset
).reshape(-1, 2)
# The public cross-language benchmark uses one canonical float32 input.
return (
np.ascontiguousarray(points, dtype=np.float32),
np.ascontiguousarray(segments, dtype=np.int32),
int(expected_crossings),
int(flags),
)
def load_list(path: Path, limit: int | None):
rows = []
for line in path.read_text().splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
item = Path(line)
if not item.is_absolute():
item = (path.parent / item).resolve()
rows.append(item)
return rows if limit is None else rows[:limit]
def _edge_keys(faces: np.ndarray):
edges = np.concatenate((faces[:, :2], faces[:, 1:], faces[:, (2, 0)]))
edges.sort(axis=1)
keys = (edges[:, 0].astype(np.uint64) << np.uint64(32)) | edges[:, 1].astype(np.uint64)
return np.unique(keys, return_counts=True)
def validate(points, segments, expected_crossings, flags, out):
faces, out_points = out
faces = np.ascontiguousarray(np.asarray(faces, dtype=np.int32)).reshape(-1, 3)
out_points = np.ascontiguousarray(np.asarray(out_points, dtype=np.float32)).reshape(-1, 2)
extras = {
"out_points": len(out_points),
"out_faces": len(faces),
"crossings_resolved": len(out_points) - len(points),
"recovery_checked": 0,
}
if not len(faces) or not len(out_points):
return 0, "empty_result", extras
if not np.isfinite(out_points).all():
return 0, "nonfinite_coords", extras
if faces.min(initial=0) < 0 or faces.max(initial=-1) >= len(out_points):
return 0, "invalid_face_index", extras
tri = out_points[faces]
area2 = ((tri[:, 1, 0] - tri[:, 0, 0]) * (tri[:, 2, 1] - tri[:, 0, 1])
- (tri[:, 1, 1] - tri[:, 0, 1]) * (tri[:, 2, 0] - tri[:, 0, 0]))
if np.any(area2 == 0):
return 0, "degenerate_triangle", extras
keys, counts = _edge_keys(faces)
if np.any(counts > 2):
return 0, "nonmanifold_topology", extras
used = np.unique(faces)
if len(used) != len(out_points) or len(used) - len(keys) + len(faces) != 1:
return 0, "incomplete_topology", extras
crossings_unknown = bool(flags & 1)
if expected_crossings and not crossings_unknown:
actual = len(out_points) - len(points)
if actual != expected_crossings:
note = "constraint_dropped" if actual < expected_crossings else "crossing_count_mismatch"
return 0, note, extras
if len(segments) and not expected_crossings and not crossings_unknown:
span = np.ptp(points.astype(np.float64), axis=0)
tolerance = 1e-6 * (float(np.linalg.norm(span)) or 1.0)
distance, mapping = cKDTree(out_points.astype(np.float64)).query(
points.astype(np.float64), k=1
)
if np.any(distance > tolerance):
return 0, "input_vertex_missing", extras
a = mapping[segments[:, 0]].astype(np.uint64)
b = mapping[segments[:, 1]].astype(np.uint64)
lo, hi = np.minimum(a, b), np.maximum(a, b)
wanted = (lo << np.uint64(32)) | hi
positions = np.searchsorted(keys, wanted)
found = positions < len(keys)
found[found] &= keys[positions[found]] == wanted[found]
if not np.all(found):
return 0, "constraint_dropped", extras
extras["recovery_checked"] = 1
return 1, "", extras
def run_harness(library, version, solve, *, supports_constraints=True):
parser = argparse.ArgumentParser(description=f"Python CDT benchmark: {library}")
parser.add_argument("operands", type=Path)
parser.add_argument("--samples", type=int, default=5)
parser.add_argument("--limit", type=int)
parser.add_argument("--param", help=argparse.SUPPRESS)
parser.add_argument("--corpus", default="pslg-public-api")
args = parser.parse_args()
rows = []
for path in load_list(args.operands, args.limit):
case_id = path.stem
try:
points, segments, expected_crossings, flags = load_pslg(path)
if len(segments) and not supports_constraints:
rows.append([case_id, len(points), "constraints", "", 0,
"rejected:no_constraint_support", "", "", "", 0, ""])
continue
samples = []
output = None
for _ in range(args.samples):
start = time.perf_counter()
output = solve(points, segments)
samples.append((time.perf_counter() - start) * 1000.0)
valid, note, extras = validate(
points, segments, expected_crossings, flags, output
)
rows.append([
case_id, len(points), "constraints" if len(segments) else "points",
f"{statistics.median(samples):.6f}", valid, note,
extras["out_points"], extras["out_faces"],
extras["crossings_resolved"], extras["recovery_checked"],
";".join(f"{sample:.6f}" for sample in samples),
])
except Exception as exc:
rows.append([case_id, "", "", "", 0,
f"error:{type(exc).__name__}:{exc}", "", "", "", 0, ""])
out_dir = common.results_dir("cdt")
csv_path = out_dir / f"{library}.csv"
with csv_path.open("w", newline="") as stream:
writer = csv.writer(stream)
writer.writerow(HEADER)
writer.writerows(rows)
meta_path = common.write_meta("cdt", library, version, args.corpus, args.samples)
meta = json.loads(meta_path.read_text())
meta.update({
"track": "Python",
"timing_boundary": "float32 points/int32 constraints in -> triangle arrays out",
"contract": "public interior CDT for constrained closed boundaries; convex-hull Delaunay without constraints",
"validation": "nondegenerate manifold disk, Euler completeness, direct recovery of every non-crossing constraint",
})
meta_path.write_text(json.dumps(meta, indent=2) + "\n")
print(f"done cdt/{library}: {len(rows)} cases -> {csv_path}")