Repository navigation
Expand file tree
/
Copy pathcadquery_ops.py
More file actions
2491 lines (2065 loc) · 108 KB
/
Copy pathcadquery_ops.py
File metadata and controls
2491 lines (2065 loc) · 108 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
"""CadQuery operation evaluation and greedy IoU-based pruning.
Each candidate operation (extrusion or revolve) is materialized via CadQuery,
its IoU against the ground-truth mesh is computed with CPU mesh booleans,
and a greedy pass keeps the subset that maximizes union IoU.
"""
from __future__ import annotations
import os
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["VECLIB_MAXIMUM_THREADS"] = "1"
import argparse
import json
import pickle
import glob
import time
import signal
import subprocess
import tempfile
import multiprocessing as mp
from typing import List, Dict, Any, Optional, Tuple
import tqdm
import numpy as np
import trimesh
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from fit_primitives import build_action_instances_from_entry
from iou import mesh_iou_cpu_boolean, normalize_mesh
def project_3d_to_2d(points_3d, origin, normal, xdir):
"""
Project 3D points onto a 2D plane coordinate system.
Args:
points_3d: Nx3 array of 3D points
origin: Origin of the plane
normal: Normal vector of the plane
xdir: X-direction vector of the plane
Returns:
Nx2 array of 2D points
"""
points_3d = np.array(points_3d)
origin = np.array(origin)
normal = np.array(normal)
xdir = np.array(xdir)
# Normalize vectors
normal = normal / np.linalg.norm(normal)
xdir = xdir / np.linalg.norm(xdir)
# Compute y-direction (perpendicular to both normal and xdir)
ydir = np.cross(normal, xdir)
ydir = ydir / np.linalg.norm(ydir)
# Project points onto plane
points_2d = []
for point in points_3d:
relative = point - origin
x = np.dot(relative, xdir)
y = np.dot(relative, ydir)
points_2d.append([x, y])
return np.array(points_2d)
def check_symmetry_axis(points_2d, axis_angle_deg, tolerance=0.03):
"""
Check if 2D points are symmetric about an axis through their centroid.
Args:
points_2d: Nx2 array of 2D points
axis_angle_deg: Angle of axis in degrees (0 = x-axis)
tolerance: Distance tolerance for symmetry (as fraction of point cloud size)
Returns:
(is_symmetric, axis_unit_vector, symmetry_ratio)
"""
if len(points_2d) < 4:
return False, None, 0.0
# Compute centroid
centroid = np.mean(points_2d, axis=0)
centered = points_2d - centroid
# Check if points form a circle - skip symmetry check for circles
# A circle has uniform distance from centroid
distances_from_centroid = np.linalg.norm(centered, axis=1)
if np.allclose(distances_from_centroid, distances_from_centroid[0], rtol=0.01):
# This is likely a circle, skip symmetry axis check
return False, None, 0.0
# Axis direction
axis_rad = np.radians(axis_angle_deg)
axis_dir = np.array([np.cos(axis_rad), np.sin(axis_rad)])
# Perpendicular to axis
perp_dir = np.array([-np.sin(axis_rad), np.cos(axis_rad)])
# Project points onto perpendicular direction (distance from axis)
perp_distances = centered @ perp_dir
# Flip points across axis
flipped_centered = centered - 2 * np.outer(perp_distances, perp_dir)
flipped = flipped_centered + centroid
# Check if flipped points match original points
# For each flipped point, find closest original point
from scipy.spatial.distance import cdist
distances = cdist(flipped, points_2d)
min_distances = np.min(distances, axis=1)
# Compute characteristic size
bbox_size = np.max(np.ptp(points_2d, axis=0))
threshold = tolerance * bbox_size
# Check if most points have a close match
symmetric_points = np.sum(min_distances < threshold)
symmetry_ratio = symmetric_points / len(points_2d)
is_symmetric = symmetry_ratio > 0.95 # 95% of points should match
return is_symmetric, axis_dir, symmetry_ratio
def plot_symmetry_2d(loops_2d, sketch_idx, axis_angle_deg, axis_dir_2d, symmetry_ratio, output_folder):
"""
Plot 2D sketch with symmetry axis.
Args:
loops_2d: List of 2D loops (each loop is Nx2 array)
sketch_idx: Sketch index
axis_angle_deg: Angle of symmetry axis in degrees
axis_dir_2d: 2D direction vector of axis
symmetry_ratio: Symmetry match ratio
output_folder: Output folder for plots
"""
try:
import matplotlib.pyplot as plt
os.makedirs(f'{output_folder}/symmetry_plots', exist_ok=True)
fig, ax = plt.subplots(figsize=(10, 10))
# Plot all loops
all_points = []
for i, loop in enumerate(loops_2d):
loop_array = np.array(loop)
all_points.extend(loop)
# Plot loop
ax.plot(loop_array[:, 0], loop_array[:, 1], 'b-', linewidth=2, label=f'Loop {i}' if i < 3 else '')
# Mark start point
ax.plot(loop_array[0, 0], loop_array[0, 1], 'go', markersize=8)
all_points = np.array(all_points)
# Compute centroid and extent for axis
centroid = np.mean(all_points, axis=0)
bbox_range = np.max(np.ptp(all_points, axis=0))
extent = bbox_range * 0.7
# Plot symmetry axis
axis_start = centroid - extent * axis_dir_2d
axis_end = centroid + extent * axis_dir_2d
ax.plot([axis_start[0], axis_end[0]], [axis_start[1], axis_end[1]],
'r--', linewidth=3, alpha=1.0, label=f'Symmetry Axis {axis_angle_deg}° (ratio={symmetry_ratio:.2%})')
# Plot centroid
ax.plot(centroid[0], centroid[1], 'r*', markersize=15, label='Centroid', zorder=10)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title(f'Sketch {sketch_idx} - SYMMETRIC (axis={axis_angle_deg}°, ratio={symmetry_ratio:.2%})')
ax.grid(True, alpha=0.3)
ax.axis('equal')
ax.legend(loc='best', fontsize=10)
plt.tight_layout()
output_path = f'{output_folder}/symmetry_plots/sketch_{sketch_idx}_symmetric_{axis_angle_deg}deg.png'
plt.savefig(output_path, dpi=150, bbox_inches='tight')
plt.close()
print(f" Saved symmetry plot: {output_path}")
except Exception as e:
print(f" Failed to save symmetry plot: {e}")
def find_symmetry_axis(entry, sketch_idx=None, output_folder=None):
"""
Find axis of symmetry for a sketch by testing 4 axes (0°, 45°, 90°, 135°).
Projects 3D loops to 2D before testing.
Returns ALL symmetric axes found, not just the first one.
Args:
entry: Sketch entry with loops_3d or loops
sketch_idx: Sketch index (for plotting)
output_folder: Output folder (for plotting)
Returns:
List of dicts with 'angle', 'ratio', 'axis_3d_start', 'axis_3d_end' for each symmetric axis,
or empty list if no symmetry found
"""
# Get 3D loops
loops_3d = entry.get('loops_3d', entry.get('loops', []))
if not loops_3d:
return []
# Get plane information
origin = entry.get('origin', [0, 0, 0])
normal = entry.get('normal', [0, 0, 1])
xdir = entry.get('xdir', [1, 0, 0])
# Project 3D loops to 2D
all_points_2d = []
loops_2d = []
for loop_3d in loops_3d:
loop_2d = project_3d_to_2d(loop_3d, origin, normal, xdir)
all_points_2d.extend(loop_2d)
loops_2d.append(loop_2d)
if len(all_points_2d) < 4:
return []
all_points_2d = np.array(all_points_2d)
# Remove duplicates
unique_points = np.unique(all_points_2d, axis=0)
# Compute principal axes using PCA
centered_points = unique_points - np.mean(unique_points, axis=0)
cov_matrix = np.cov(centered_points.T)
eigenvalues, eigenvectors = np.linalg.eig(cov_matrix)
# Sort by eigenvalue (descending)
sorted_indices = np.argsort(eigenvalues)[::-1]
principal_axes = eigenvectors[:, sorted_indices]
# Convert principal axes to angles (in degrees)
pca_angles = []
for i in range(2): # First two principal axes
axis_vec = principal_axes[:, i]
angle_rad = np.arctan2(axis_vec[1], axis_vec[0])
angle_deg = np.degrees(angle_rad) % 180 # Normalize to [0, 180)
pca_angles.append(angle_deg)
# Test 4 fixed axes plus 2 PCA axes and collect ALL symmetric ones
test_angles = [0, 45, 90, 135] + pca_angles
symmetric_axes = []
symmetric_axes_2d = []
for angle in test_angles:
is_sym, axis_dir_2d, ratio = check_symmetry_axis(unique_points, angle, tolerance=0.05)
if is_sym:
symmetric_axes_2d.append({
'angle': int(angle),
'axis_dir_2d': axis_dir_2d,
'ratio': float(ratio)
})
if not symmetric_axes_2d:
return []
# Convert all symmetric axes to 3D
origin_arr = np.array(origin)
normal_arr = np.array(normal)
xdir_arr = np.array(xdir)
# Normalize vectors
normal_arr = normal_arr / np.linalg.norm(normal_arr)
xdir_arr = xdir_arr / np.linalg.norm(xdir_arr)
# Compute y-direction (perpendicular to both normal and xdir)
ydir_arr = np.cross(normal_arr, xdir_arr)
ydir_arr = ydir_arr / np.linalg.norm(ydir_arr)
# Centroid in 2D
centroid_2d = np.mean(unique_points, axis=0)
# Centroid in 3D (fixed: swap xdir and ydir components)
centroid_3d = origin_arr + centroid_2d[0] * ydir_arr + centroid_2d[1] * xdir_arr
# Convert each symmetric axis to 3D
for sym_axis in symmetric_axes_2d:
axis_dir_2d = sym_axis['axis_dir_2d']
angle = sym_axis['angle']
ratio = sym_axis['ratio']
print(f" Found symmetry at {angle}° axis (ratio={ratio:.2%})")
# Save plot if requested (plot for first/best axis)
if sketch_idx is not None and output_folder is not None and len(symmetric_axes) == 0:
plot_symmetry_2d(loops_2d, sketch_idx, angle, axis_dir_2d, ratio, output_folder)
# Convert axis direction to 3D (fixed: swap xdir and ydir components)
axis_3d_dir = axis_dir_2d[0] * ydir_arr + axis_dir_2d[1] * xdir_arr
axis_3d_dir = axis_3d_dir / np.linalg.norm(axis_3d_dir)
# Axis endpoints (extend 10 units in each direction)
axis_3d_start = tuple(centroid_3d - 10 * axis_3d_dir)
axis_3d_end = tuple(centroid_3d + 10 * axis_3d_dir)
symmetric_axes.append({
'angle': angle,
'ratio': ratio,
'axis_3d_start': axis_3d_start,
'axis_3d_end': axis_3d_end
})
return symmetric_axes
def cut_loop_at_symmetry_axis(loop_2d, axis_angle_deg):
"""
Cut a 2D loop along a symmetry axis and close it with a line segment.
Removes ALL points on the negative side of the axis.
Args:
loop_2d: List of [x, y] points forming a closed loop
axis_angle_deg: Angle of symmetry axis in degrees
Returns:
Modified loop with cut and closure
"""
points = np.array(loop_2d)
# Remove closing duplicate if present
if len(points) > 0 and np.allclose(points[0], points[-1]):
points = points[:-1]
if len(points) < 3:
return loop_2d
# Centroid
centroid = np.mean(points, axis=0)
# Axis direction
axis_rad = np.radians(axis_angle_deg)
axis_dir = np.array([np.cos(axis_rad), np.sin(axis_rad)])
perp_dir = np.array([-np.sin(axis_rad), np.cos(axis_rad)])
# Project points onto perpendicular direction
centered = points - centroid
perp_distances = centered @ perp_dir
# Find points on or near the axis (within small threshold)
threshold = 0.01 * np.max(np.abs(perp_distances))
on_axis = np.abs(perp_distances) < threshold
# Keep only points on positive side OR on axis (remove ALL negative side points)
positive_side = perp_distances >= -threshold # Changed to >= to keep axis and positive side only
if not np.any(positive_side):
# All points on negative side, return empty
return []
# Keep only points on positive side and points on axis
keep_mask = positive_side
cut_points = points[keep_mask]
if len(cut_points) < 2:
return []
# Add closing line segment if needed
if not np.allclose(cut_points[0], cut_points[-1]):
cut_points = np.vstack([cut_points, cut_points[0]])
return cut_points.tolist()
def generate_cadquery_revolve_script(sketch_actions: List[str], axis_start: Tuple[float, float, float],
axis_end: Tuple[float, float, float], angle_degrees: float,
output_stl_path: str, origin=None, normal=None, xdir=None) -> str:
"""
Generate CadQuery script for revolve operation.
Args:
sketch_actions: List of sketch action strings
axis_start: (x, y, z) start point of revolution axis
axis_end: (x, y, z) end point of revolution axis
angle_degrees: Angle to revolve in degrees
output_stl_path: Path to save output STL
origin: 3D origin of the plane (optional, if None will use existing plane definition)
normal: 3D normal vector of the plane (optional)
xdir: 3D x-direction of the plane (optional)
Returns:
Python script content
"""
script_lines = ["import cadquery as cq", "import math", ""]
plane_name = "plane_1"
sketch_name = "sketch_1"
# Use plane information from arguments if provided
if origin is not None and normal is not None and xdir is not None:
script_lines.append(f"# Plane definition from JSON")
script_lines.append(f"origin = ({round(origin[0], 3)}, {round(origin[1], 3)}, {round(origin[2], 3)})")
script_lines.append(f"normal = ({round(normal[0], 3)}, {round(normal[1], 3)}, {round(normal[2], 3)})")
script_lines.append(f"xdir = ({round(xdir[0], 3)}, {round(xdir[1], 3)}, {round(xdir[2], 3)})")
script_lines.append(f"{plane_name} = cq.Plane(origin=origin, normal=normal, xDir=xdir)")
script_lines.append(f"{sketch_name} = cq.Workplane({plane_name})")
script_lines.append("")
else:
# Find plane definition from sketch actions
plane_def_line = None
workplane_def_line = None
for action in sketch_actions:
action_lines = action.split('\n')
for line in action_lines:
line = line.strip()
if line.startswith("plane = "):
plane_def_line = line.replace("plane = ", f"{plane_name} = ")
elif line.startswith("sketch = cq.Workplane("):
if "cq.Workplane(plane)" in line:
workplane_def_line = f"{sketch_name} = cq.Workplane({plane_name})"
else:
workplane_def_line = line.replace("sketch = ", f"{sketch_name} = ")
if plane_def_line:
script_lines.append(plane_def_line)
if workplane_def_line:
script_lines.append(workplane_def_line)
# Process sketch actions
for action in sketch_actions:
action_lines = action.split('\n')
for line in action_lines:
line = line.strip()
if not line or line.startswith("plane = ") or line.startswith("sketch = cq.Workplane("):
continue
if line.startswith("sketch."):
operation = line.replace("sketch.", "")
script_lines.append(f"{sketch_name} = {sketch_name}.{operation}")
elif line.startswith("sketch = sketch."):
operation = line.replace("sketch = sketch.", "")
script_lines.append(f"{sketch_name} = {sketch_name}.{operation}")
# Add revolve operation
axis_start_str = f"({round(axis_start[0], 3)+1e-3}, {round(axis_start[1], 3)+1e-3}, {round(axis_start[2], 3)+1e-3})"
axis_end_str = f"({round(axis_end[0], 3)+1e-3}, {round(axis_end[1], 3)+1e-3}, {round(axis_end[2], 3)+1e-3})"
script_lines.append(f"result = {sketch_name}.revolve(angleDegrees={round(angle_degrees, 3)}, axisStart={axis_start_str}, axisEnd={axis_end_str})")
script_lines.append(f"cq.exporters.export(result, '{output_stl_path}')")
script_lines.append(f"print('Successfully revolved and exported to {output_stl_path}')")
return "\n".join(script_lines)
def test_revolve_operation_multi_axis(axis_to_insts, symmetric_axes, gt_mesh, output_folder, sketch_idx, origin, normal, xdir, alpha=0.01, normalize=True, points=None, inside_a=None):
"""
Test revolve operation at different angles (90°, 180°, 270°, 360°) for ALL symmetric axes and return best IoU.
Each axis uses its own cut loops.
Args:
axis_to_insts: Dict mapping axis angle to cut sketch action instances
symmetric_axes: List of dicts with 'angle', 'axis_3d_start', 'axis_3d_end' for each symmetric axis
gt_mesh: Ground truth mesh
output_folder: Output folder
sketch_idx: Sketch index
origin: 3D origin of the plane
normal: 3D normal vector of the plane
xdir: 3D x-direction of the plane
alpha: Alpha for IoU computation
normalize: Whether to normalize meshes before IoU computation
points: Precomputed sample points
inside_a: Precomputed inside ground truth mask
Returns:
(best_iou, best_angle, best_axis_angle) or (0.0, None, None) if all fail
"""
test_angles = [360]
results = []
print(f" Testing revolve operation for sketch {sketch_idx} with {len(symmetric_axes)} symmetric axes at angles {test_angles}")
# Ensure best_extrusions folder exists
os.makedirs(f'{output_folder}/best_extrusions', exist_ok=True)
for sym_axis in symmetric_axes:
axis_angle_deg = sym_axis['angle']
axis_start = sym_axis['axis_3d_start']
axis_end = sym_axis['axis_3d_end']
# Get the cut instructions for this specific axis
insts = axis_to_insts.get(axis_angle_deg)
if insts is None:
print(f" Axis {axis_angle_deg}°: No cut loops available, skipping")
continue
for angle in test_angles:
try:
worker_id = os.getpid()
timestamp = int(time.time() * 1000000)
unique_suffix = f"worker_{worker_id}_{timestamp}"
# Use temporary files for revolve operations
temp_stl_path = f'{output_folder}/temp_revolve_{unique_suffix}.stl'
temp_script_path = f'{output_folder}/temp_revolve_{unique_suffix}.py'
# Generate script with plane information
script_content = generate_cadquery_revolve_script(insts, axis_start, axis_end, angle, temp_stl_path,
origin=origin, normal=normal, xdir=xdir)
success = execute_cadquery_script(script_content, temp_stl_path, temp_script_path)
if success:
# Save GT mesh to a stable path so the IoU cache stays warm
# across the inner-loop calls.
gt_cache = os.path.join(output_folder, '_revolve_gt_cached.stl')
if not os.path.exists(gt_cache):
gt_mesh.export(gt_cache)
iou = compute_iou(gt_cache, temp_stl_path)
results.append((iou, angle, axis_angle_deg))
print(f" Axis {axis_angle_deg}° Revolve {angle}°: IoU = {iou:.6f}")
# Clean up temporary files
try:
os.unlink(temp_stl_path)
os.unlink(temp_script_path)
except:
pass
else:
print(f" Axis {axis_angle_deg}° Revolve {angle}°: Failed to execute")
# Clean up on failure too
try:
os.unlink(temp_stl_path)
os.unlink(temp_script_path)
except:
pass
except Exception as e:
print(f" Axis {axis_angle_deg}° Revolve {angle}°: Error - {e}")
if results:
best_iou, best_angle, best_axis_angle = max(results, key=lambda x: x[0])
return best_iou, best_angle, best_axis_angle
return 0.0, None, None
class TimeoutError(Exception):
"""Custom timeout exception"""
pass
def timeout_handler(signum, frame):
"""Signal handler for timeout"""
raise TimeoutError("Operation timed out")
def execute_cadquery_script(script_content: str, output_stl_path: str, save_script_path: str = None) -> bool:
"""
Execute a CadQuery script and export STL file.
Args:
script_content: Python script content with CadQuery operations
output_stl_path: Path where to save the resulting STL file
save_script_path: Optional path to save the script file permanently
Returns:
True if successful, False otherwise
"""
try:
# Determine script path
if save_script_path:
script_path = save_script_path
# Ensure directory exists
os.makedirs(os.path.dirname(script_path), exist_ok=True)
else:
# Create temporary Python script
tmp_script = tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False)
script_path = tmp_script.name
tmp_script.close()
# Write script content
with open(script_path, 'w') as f:
f.write(script_content)
print(f"Executing CadQuery script: {script_path}")
print(f"Expected output: {output_stl_path}")
# Execute the script in the parent's Python interpreter.
import sys as _sys
result = subprocess.run([_sys.executable, script_path],
capture_output=True, text=True, timeout=60)
# Clean up temporary script if it was temporary
if not save_script_path:
try:
os.unlink(script_path)
except:
pass
if result.returncode == 0:
if os.path.exists(output_stl_path):
print(f"✓ Successfully generated STL: {output_stl_path}")
return True
else:
print(f"✗ Script executed but STL not found: {output_stl_path}")
print(f"Script stdout: {result.stdout}")
print(f"Script stderr: {result.stderr}")
return False
else:
print(f"✗ CadQuery script execution failed:")
print(f"Return code: {result.returncode}")
print(f"Stdout: {result.stdout}")
print(f"Stderr: {result.stderr}")
return False
except subprocess.TimeoutExpired:
print(f"✗ CadQuery script execution timed out after 60 seconds")
return False
except Exception as e:
print(f"✗ Error executing CadQuery script: {e}")
return False
def compute_iou(gt_path: str, gen_path: str, normalize: bool = True) -> float:
"""CPU mesh-boolean IoU: vol(A ∩ B) / vol(A ∪ B) via trimesh + manifold3d.
Returns 0.0 if either file is missing/empty or the boolean op fails.
`normalize` rescales the ground-truth mesh to a [-1, 1] cube first.
"""
try:
if not os.path.exists(gt_path) or not os.path.exists(gen_path):
print(f"Missing files: gt={os.path.exists(gt_path)}, gen={os.path.exists(gen_path)}")
return 0.0
if os.path.getsize(gt_path) == 0 or os.path.getsize(gen_path) == 0:
print(f"Empty files: gt={os.path.getsize(gt_path)}, gen={os.path.getsize(gen_path)}")
return 0.0
return mesh_iou_cpu_boolean(gt_path, gen_path, normalize=normalize)
except Exception as e:
print(f"IoU computation failed: {e}")
return 0.0
def generate_cadquery_script_multi_height(sketch_actions_list: List[List[str]], heights: List[float], output_stl_path: str) -> str:
"""
Generate a complete CadQuery script from sketch actions and extrusion heights.
Args:
sketch_actions_list: List of sketch action lists (each sketch is a list of strings)
heights: List of extrusion heights (one per sketch)
output_stl_path: Path where to save the STL file
Returns:
Complete Python script content
"""
script_lines = ["import cadquery as cq", "import math", ""]
solid_names = []
for i, (sketch_actions, height) in enumerate(zip(sketch_actions_list, heights)):
if not sketch_actions:
continue
# Add index suffix to plane and sketch names
plane_name = f"plane_{i+1}"
sketch_name = f"sketch_{i+1}"
solid_name = f"solid_{i+1}"
# Find plane definition and close statements to identify loops
plane_def_line = None
workplane_def_line = None
close_indices = []
for idx, action in enumerate(sketch_actions):
action_lines = action.split('\n')
for line in action_lines:
line = line.strip()
if line.startswith("plane = "):
plane_def_line = line.replace("plane = ", f"{plane_name} = ")
elif line.startswith("sketch = cq.Workplane("):
if "cq.Workplane(plane)" in line:
workplane_def_line = f"{sketch_name} = cq.Workplane({plane_name})"
else:
workplane_def_line = line.replace("sketch = ", f"{sketch_name} = ")
elif "close" in line or "circle" in line:
close_indices.append(idx)
# Add plane and sketch definitions
if plane_def_line:
script_lines.append(plane_def_line)
if workplane_def_line:
script_lines.append(workplane_def_line)
# Process loops
loop_names = []
current_loop_idx = 0
current_action_idx = 0
while current_action_idx < len(sketch_actions):
# Find next close statement
next_close_idx = None
for close_idx in close_indices:
if close_idx >= current_action_idx:
next_close_idx = close_idx
break
if next_close_idx is None:
break
# Process actions until close
loop_name = f"loop_{current_loop_idx + 1}"
loop_names.append(loop_name)
first_action_in_loop = True
for action_idx in range(current_action_idx, next_close_idx + 1):
if action_idx >= len(sketch_actions):
break
action = sketch_actions[action_idx]
action_lines = action.split('\n')
for line in action_lines:
line = line.strip()
if not line:
continue
# Skip plane and workplane definitions (already handled)
if line.startswith("plane = ") or line.startswith("sketch = cq.Workplane("):
continue
if line.startswith("sketch.moveTo("):
# First action in loop - create loop variable
coords = line.replace("sketch.moveTo(", "").replace(")", "")
modified_line = f"{loop_name} = {sketch_name}.moveTo({coords})"
script_lines.append(modified_line)
first_action_in_loop = False
elif line.startswith("sketch."):
# Chain loop operations
operation = line.replace("sketch.", "")
modified_line = f"{loop_name} = {loop_name}.{operation}"
script_lines.append(modified_line)
elif line.startswith("sketch = sketch."):
# Chained operations like "sketch = sketch.threePointArc(...)"
operation = line.replace("sketch = sketch.", "")
modified_line = f"{loop_name} = {loop_name}.{operation}"
script_lines.append(modified_line)
elif "close" in line:
# Close the loop
script_lines.append(f"{loop_name} = {loop_name}.close()")
current_loop_idx += 1
current_action_idx = next_close_idx + 1
# Add all loops to sketch
if loop_names:
add_chain = f"{sketch_name}={sketch_name}.add({loop_names[0]})"
for loop_name in loop_names[1:]:
add_chain += f".add({loop_name})"
script_lines.append(add_chain)
# Add extrusion with specific height
script_lines.append(f"{solid_name} = {sketch_name}.extrude({round(height, 3)})")
solid_names.append(solid_name)
script_lines.append("")
# Union all solids if there are multiple
if len(solid_names) > 1:
# Start with first solid
union_script = f"result = {solid_names[0]}"
script_lines.append(union_script)
# Combine remaining solids via `.add()` — produces a Compound that
# exports correct geometry without invoking OCC's brittle/expensive
# boolean union. Downstream uses manifold3d to clean the STL.
for solid_name in solid_names[1:]:
script_lines.append(f"result = result.add({solid_name})")
# Export the result
script_lines.append(f"cq.exporters.export(result, '{output_stl_path}')")
script_lines.append("print(f'Successfully exported {0} solids to {1}')".format(len(solid_names), output_stl_path))
elif len(solid_names) == 1:
# Just one solid, export directly
script_lines.append(f"result = {solid_names[0]}")
script_lines.append(f"cq.exporters.export(result, '{output_stl_path}')")
script_lines.append(f"print('Successfully exported 1 solid to {output_stl_path}')")
else:
# No solids, create empty script that just creates an empty file
script_lines.append(f"# No solids to export")
script_lines.append(f"print('No solids to export - creating empty file')")
script_lines.append(f"open('{output_stl_path}', 'w').close()")
return "\n".join(script_lines)
def generate_cadquery_script(sketch_actions_list: List[List[str]], height: float, output_stl_path: str) -> str:
"""
Generate a complete CadQuery script from sketch actions and single extrusion height.
Args:
sketch_actions_list: List of sketch action lists (each sketch is a list of strings)
height: Extrusion height (applied to all sketches)
output_stl_path: Path where to save the STL file
Returns:
Complete Python script content
"""
heights = [height] * len(sketch_actions_list)
return generate_cadquery_script_multi_height(sketch_actions_list, heights, output_stl_path)
def with_timeout(timeout_seconds):
"""Decorator to enforce timeout on function execution"""
def decorator(func):
def wrapper(*args, **kwargs):
# Set up signal handler
old_handler = signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(int(timeout_seconds))
try:
result = func(*args, **kwargs)
signal.alarm(0) # Cancel alarm
return result
except TimeoutError:
signal.alarm(0) # Cancel alarm
print(f" TIMEOUT: Function {func.__name__} exceeded {timeout_seconds}s")
return None
except Exception as e:
signal.alarm(0) # Cancel alarm
print(f" ERROR in {func.__name__}: {e}")
return None
finally:
signal.signal(signal.SIGALRM, old_handler)
return wrapper
return decorator
def adaptive_height_search(insts, faces_idx, gt_mesh, h_min, h_max, max_iterations=7, sketch_idx=None, height_type="pos", timeout_seconds=100, max_height_eval_time=300, output_folder="search", alpha=0.01, normalize=True, points=None, inside_a=None):
"""
Adaptive height search exploiting the linear/quadratic nature of IoU curves.
Uses golden section search with intelligent sampling.
Args:
timeout_seconds: Maximum time to spend on this search before giving up
max_height_eval_time: Maximum time to spend on a single height evaluation
normalize: Whether to normalize meshes before IoU computation
points: Precomputed sample points
inside_a: Precomputed inside ground truth mask
"""
search_start_time = time.time()
height_iou_pairs = []
@with_timeout(max_height_eval_time)
def evaluate_height_with_timeout(h):
"""Helper to evaluate a single height with hard timeout"""
# Check if already evaluated
for cached_h, cached_iou in height_iou_pairs:
if abs(cached_h - h) < 1e-6:
return cached_iou
eval_start_time = time.time()
# Convert insts to sketch actions list format
sketch_actions_list = [insts] # Assuming insts is already a list of sketch actions
# Generate and execute CadQuery script with unique worker naming
worker_id = os.getpid()
timestamp = int(time.time() * 1000000) # microsecond timestamp
unique_suffix = f"worker_{worker_id}_{timestamp}"
output_path = f'{output_folder}/adaptive_{sketch_idx}_{height_type}_{unique_suffix}'
script_content = generate_cadquery_script(sketch_actions_list, h, f'{output_path}.stl')
script_path = f'{output_path}_h{h}.py'
success = execute_cadquery_script(script_content, f'{output_path}.stl', script_path)
print(f" Worker {worker_id}: Height {h}: Script saved to {script_path}, Success={success}")
if not success:
return 0.0
mesh = trimesh.load(f'{output_path}.stl', force='mesh')
if mesh is None:
iou = 0.0
else:
try:
iou_start = time.time()
# Save GT to a stable path so the IoU cache stays warm.
gt_path = os.path.join(output_folder, '_height_gt_cached.stl')
if not os.path.exists(gt_path):
gt_mesh.copy().export(gt_path)
iou = compute_iou(gt_path, f'{output_path}.stl')
iou_duration = time.time() - iou_start
print(f"IoU computed for height {h}: {iou:.6f} (IoU took {iou_duration:.2f}s)")
except Exception as e:
iou = 0.0
print(f"IoU computation failed for height {h}: {e}")
# Clean up generated files to save space
try:
if os.path.exists(f'{output_path}.stl'):
os.unlink(f'{output_path}.stl')
if os.path.exists(script_path):
os.unlink(script_path)
except:
pass # Ignore cleanup errors
eval_duration = time.time() - eval_start_time
print(f" Height {h} evaluation completed in {eval_duration:.2f}s")
return iou
def evaluate_height(h):
"""Wrapper for evaluate_height_with_timeout with fallback handling"""
# Check timeout before starting evaluation
if time.time() - search_start_time > timeout_seconds:
print(f" Timeout reached ({timeout_seconds}s), stopping height search")
return 0.0
# Check if already evaluated
for cached_h, cached_iou in height_iou_pairs:
if abs(cached_h - h) < 1e-6:
return cached_iou
try:
result = evaluate_height_with_timeout(h)
if result is None: # Timeout occurred
height_iou_pairs.append((h, 0.0))
return 0.0
else:
height_iou_pairs.append((h, result))
return result
except Exception as e:
print(f"Exception during height {h} evaluation: {e}")
height_iou_pairs.append((h, 0.0))
return 0.0
# Initial 5-point sampling with fallback strategy
initial_ious = [0 for _ in range(5)]
checks = 0
while all(iou == 0.0 for iou in initial_ious) and checks < 4:
# Progressively smaller heights on retry to avoid issues
scale_factor = 5**checks if checks > 0 else 1
initial_heights = [(h_min + j * (h_max - h_min) / 4)/scale_factor for j in range(5)]
initial_ious = [0 for _ in range(len(initial_heights))]
checks += 1
print(f" Check {checks}: Trying heights {initial_heights}")
for i, h in enumerate(initial_heights):
if time.time() - search_start_time > timeout_seconds:
print(f" Timeout reached during initial sampling, stopping")
break
initial_ious[i] = evaluate_height(h)
if not initial_ious or all(iou == 0.0 for iou in initial_ious):
print(f" No valid IoU values found or timeout reached, returning empty results")
return [], []
print(f"Initial sampling: {list(zip(initial_heights[:len(initial_ious)], initial_ious))}")
# Find the best initial point
best_idx = np.argmax(initial_ious)
# Adaptive refinement iterations
for iteration in range(max_iterations):
# Check timeout before each iteration
# break
# Sort points by height
sorted_pairs = sorted(height_iou_pairs, key=lambda x: x[0])
heights_sorted = [pair[0] for pair in sorted_pairs]
ious_sorted = [pair[1] for pair in sorted_pairs]
if len(heights_sorted) < 3:
break
# Find current best
current_best_idx = np.argmax(ious_sorted)
current_best_h = heights_sorted[current_best_idx]
current_best_iou = ious_sorted[current_best_idx]
# Determine search intervals around the best point
search_intervals = []
# Left interval
if current_best_idx > 0: