feat: add build123d to FTC conversion tools

Capture Builder and algebra programs into portable feature traces, emit native FTC sources, and validate geometry in isolated processes.

Include the API inventory, six real trace fixtures, inferred constraint recovery, and the 50-model benchmark. All models build; the tea-cup STEP reference-kernel failure remains explicit.
This commit is contained in:
yuliuse
2026-10-07 17:05:30 +08:00
parent 367262f499
commit 6a63494978
33 changed files with 26983 additions and 0 deletions
+1
View File
@@ -55,6 +55,7 @@ tools/research/out/
tools/research/histjson/out/
tools/research/whucad/out/
tools/research/cadqueryftc/out/
tools/research/build123dftc/out/
.venv-cq/
# Source screen recordings stay local; compressed MP4/GIF derivatives are tracked
+18
View File
@@ -0,0 +1,18 @@
# Portable build123d feature traces
These fixtures contain the actual operation inputs captured from six of the
50 build123d examples supplied for the converter: lines and arcs, a selected
circular fillet, a mirrored profile, one closed font glyph with a hole, and a
nonplanar spring sweep, and a spherical cut/fillet followed by nonuniform scale.
The glyph is feature `s3` of the text example; the affine case retains the first
eight features of the keycap example. Other traces retain their entire history.
The tests require SimpleCADAPI but do not import build123d, download source
programs, load result BReps, or use paths outside the repository. Curve data
contains exact analytic geometry or B-spline poles, knots, multiplicities,
and weights; it is not a mesh or a fitted final-body snapshot.
Reference volumes use OCCT's adaptive Gauss–Kronrod integration with
`eps=1e-9` and B-spline span splitting. Original non-adaptive volumes remain
as diagnostic data because they differ materially on closed rational curves.
Each fixture records its build123d and source-kernel versions.
@@ -0,0 +1,820 @@
{
"schema_version": "1.0",
"steps": [
{
"id": "s1",
"op": "extrude_taper",
"inputs": [],
"parameters": {
"direction": [
0.0,
0.0,
10.0
],
"taper": 15,
"flip_inner": true
},
"source": "Solid.extrude_taper",
"result": {
"volume": 2371.1119335472795,
"volume_gk": 2371.1119335472795,
"area": 1118.2335726410245,
"default_volume": 2371.11193354728,
"bbox": [
-9.0,
-9.0,
0.0,
9.0,
9.0,
10.000000000000005
],
"solid_count": 1
},
"profile": {
"kind": "face",
"origin": [
-2.0816681711721685e-17,
-2.4671622769447924e-16,
0.0
],
"x_dir": [
1.0,
0.0,
-0.0
],
"y_dir": [
-0.0,
1.0,
0.0
],
"normal": [
0.0,
0.0,
1.0
],
"wires": [
{
"edges": [
{
"kind": "line",
"start": [
-9.0,
9.0,
0.0
],
"end": [
-9.0,
-9.0,
0.0
],
"parameter_range": [
-9.0,
9.0
],
"reversed": true
},
{
"kind": "line",
"start": [
-9.0,
-9.0,
0.0
],
"end": [
9.0,
-9.0,
0.0
],
"parameter_range": [
-9.0,
9.0
],
"reversed": false
},
{
"kind": "line",
"start": [
9.0,
-9.0,
0.0
],
"end": [
9.0,
9.0,
0.0
],
"parameter_range": [
-9.0,
9.0
],
"reversed": false
},
{
"kind": "line",
"start": [
9.0,
9.0,
0.0
],
"end": [
-9.0,
9.0,
0.0
],
"parameter_range": [
-9.0,
9.0
],
"reversed": true
}
],
"closed": true
}
]
}
},
{
"id": "s2",
"op": "sphere",
"inputs": [],
"parameters": {
"radius": 40,
"plane": {
"origin": [
0.0,
0.0,
0.0
],
"x_dir": [
1.0,
0.0,
-0.0
],
"y_dir": [
-0.0,
1.0,
0.0
],
"normal": [
0.0,
0.0,
1.0
]
},
"angle1": -90,
"angle2": 90,
"angle3": 360
},
"source": "Solid.make_sphere",
"result": {
"volume": 268082.57310632826,
"volume_gk": 268082.57310632826,
"area": 20106.192982974666,
"default_volume": 268082.5731063291,
"bbox": [
-40.0,
-40.0,
-40.0,
40.0,
40.0,
40.0
],
"solid_count": 1
}
},
{
"id": "s3",
"op": "transform",
"inputs": [
"s2"
],
"parameters": {
"loc": {
"matrix": [
[
1.0,
0.0,
0.0,
-0.0
],
[
0.0,
1.0,
0.0,
-0.0
],
[
0.0,
0.0,
1.0,
-0.0
],
[
0.0,
0.0,
0.0,
1.0
]
]
},
"method": "move",
"matrix": [
[
1.0,
0.0,
0.0,
-0.0
],
[
0.0,
1.0,
0.0,
-0.0
],
[
0.0,
0.0,
1.0,
-0.0
],
[
0.0,
0.0,
0.0,
1.0
]
]
},
"source": "Shape.move",
"result": {
"volume": 268082.57310632826,
"volume_gk": 268082.57310632826,
"area": 20106.192982974666,
"default_volume": 268082.5731063291,
"bbox": [
-40.0,
-40.0,
-40.0,
40.0,
40.0,
40.0
],
"solid_count": 1
}
},
{
"id": "s4",
"op": "transform",
"inputs": [
"s3"
],
"parameters": {
"loc": {
"matrix": [
[
1.0,
-0.0,
0.0,
0.0
],
[
0.0,
2.220446049250313e-16,
-1.0,
0.0
],
[
0.0,
1.0,
2.220446049250313e-16,
0.0
],
[
0.0,
0.0,
0.0,
1.0
]
]
},
"method": "moved",
"matrix": [
[
1.0,
-0.0,
0.0,
0.0
],
[
0.0,
2.220446049250313e-16,
-1.0,
0.0
],
[
0.0,
1.0,
2.220446049250313e-16,
0.0
],
[
0.0,
0.0,
0.0,
1.0
]
]
},
"source": "Shape.moved",
"result": {
"volume": 268082.5731063284,
"volume_gk": 268082.5731063284,
"area": 20106.192982974666,
"default_volume": 268082.5731063291,
"bbox": [
-40.0,
-40.0,
-40.0,
40.0,
40.0,
40.0
],
"solid_count": 1
}
},
{
"id": "s5",
"op": "transform",
"inputs": [
"s4"
],
"parameters": {
"loc": {
"matrix": [
[
1.0,
0.0,
0.0,
0.0
],
[
0.0,
1.0,
0.0,
-3.0
],
[
0.0,
0.0,
1.0,
47.0
],
[
0.0,
0.0,
0.0,
1.0
]
]
},
"method": "moved",
"matrix": [
[
1.0,
0.0,
0.0,
0.0
],
[
0.0,
1.0,
0.0,
-3.0
],
[
0.0,
0.0,
1.0,
47.0
],
[
0.0,
0.0,
0.0,
1.0
]
]
},
"source": "Shape.moved",
"result": {
"volume": 268082.5731063284,
"volume_gk": 268082.5731063284,
"area": 20106.192982974666,
"default_volume": 268082.5731063291,
"bbox": [
-40.0,
-43.0,
7.0,
40.0,
37.0,
87.0
],
"solid_count": 1
}
},
{
"id": "s6",
"op": "cut",
"inputs": [
"s1",
"s5"
],
"parameters": {},
"source": "Shape.cut",
"result": {
"volume": 1929.8444343829303,
"volume_gk": 1929.8444343829303,
"area": 1035.6152278365398,
"default_volume": 1929.844434382934,
"bbox": [
-9.0,
-9.0,
0.0,
9.0,
9.0,
8.756864140153603
],
"solid_count": 1
}
},
{
"id": "s7",
"op": "fillet",
"inputs": [
"s6"
],
"parameters": {
"radius": 1
},
"source": "Mixin3D.fillet",
"result": {
"volume": 1914.6009359753375,
"volume_gk": 1914.6009359753375,
"area": 1002.7137487227009,
"default_volume": 1914.6009359753382,
"bbox": [
-9.000000100000001,
-9.000000100000001,
-1e-07,
9.000000100000001,
9.000000100000001,
8.441500309937386
],
"solid_count": 1
},
"selection": [
{
"kind": "edge",
"geom_type": "LINE",
"center": [
-7.955513473192318,
-7.955513473192318,
3.898076785867421
],
"bbox": [
-9.0,
-9.0,
0.0,
-6.911026946384637,
-6.911026946384637,
7.796153571734842
],
"length": 8.337123445861655,
"start": [
-6.911026946384637,
-6.911026946384637,
7.796153571734842
],
"mid": [
-7.955513473192318,
-7.955513473192318,
3.898076785867421
],
"end": [
-9.0,
-9.0,
0.0
],
"index": 4
},
{
"kind": "edge",
"geom_type": "LINE",
"center": [
7.955513473192318,
-7.955513473192318,
3.898076785867421
],
"bbox": [
6.911026946384637,
-9.0,
0.0,
9.0,
-6.911026946384637,
7.796153571734842
],
"length": 8.337123445861655,
"start": [
6.911026946384637,
-6.911026946384637,
7.796153571734842
],
"mid": [
7.955513473192318,
-7.955513473192318,
3.898076785867421
],
"end": [
9.0,
-9.0,
0.0
],
"index": 7
},
{
"kind": "edge",
"geom_type": "LINE",
"center": [
-7.826802662708394,
7.826802662708394,
4.378432070076798
],
"bbox": [
-9.0,
6.653605325416787,
0.0,
-6.653605325416787,
9.0,
8.756864140153596
],
"length": 9.364497077095645,
"start": [
-9.0,
9.0,
0.0
],
"mid": [
-7.826802662708394,
7.826802662708394,
4.378432070076798
],
"end": [
-6.653605325416787,
6.653605325416787,
8.756864140153596
],
"index": 6
},
{
"kind": "edge",
"geom_type": "LINE",
"center": [
7.826802662708394,
7.826802662708394,
4.378432070076798
],
"bbox": [
6.653605325416787,
6.653605325416787,
0.0,
9.0,
9.0,
8.756864140153596
],
"length": 9.364497077095645,
"start": [
6.653605325416787,
6.653605325416787,
8.756864140153596
],
"mid": [
7.826802662708394,
7.826802662708394,
4.378432070076798
],
"end": [
9.0,
9.0,
0.0
],
"index": 9
},
{
"kind": "edge",
"geom_type": "CIRCLE",
"center": [
2.2364273360068107e-14,
-7.016130216452036,
7.40390282780167
],
"bbox": [
-6.911026946384598,
-7.068763296161196,
7.207473500168263,
6.911026946384642,
-6.911026946384634,
7.796153571734848
],
"length": 13.893601237415288,
"start": [
-6.911026946384598,
-6.911026946384636,
7.796153571734841
],
"mid": [
2.2373044540339126e-14,
-7.068763296161196,
7.207473500168263
],
"end": [
6.911026946384642,
-6.911026946384634,
7.796153571734848
],
"index": 8
},
{
"kind": "edge",
"geom_type": "CIRCLE",
"center": [
-6.882861213849936,
-0.10022652368490893,
7.9012695165867335
],
"bbox": [
-6.960821167729055,
-6.911026946384645,
7.610319007754136,
-6.653605325416786,
6.6536053254167875,
8.756864140153603
],
"length": 13.667946481986268,
"start": [
-6.653605325416786,
6.6536053254167875,
8.756864140153603
],
"mid": [
-6.933207795109661,
-0.08596340420454629,
7.713373517338049
],
"end": [
-6.911026946384634,
-6.911026946384645,
7.796153571734848
],
"index": 5
},
{
"kind": "edge",
"geom_type": "CIRCLE",
"center": [
6.882861213849936,
-0.10022652368489449,
7.901269516586735
],
"bbox": [
6.653605325416786,
-6.911026946384631,
7.610319007754136,
6.960821167729055,
6.653605325416802,
8.756864140153603
],
"length": 13.667946481986268,
"start": [
6.911026946384634,
-6.911026946384631,
7.796153571734848
],
"mid": [
6.933207795109661,
-0.08596340420453208,
7.713373517338049
],
"end": [
6.653605325416786,
6.653605325416802,
8.756864140153603
],
"index": 10
},
{
"kind": "edge",
"geom_type": "CIRCLE",
"center": [
-4.503045217372866e-14,
6.74972397417161,
8.398144459445728
],
"bbox": [
-6.653605325416833,
6.653605325416785,
8.218533741391056,
6.653605325416744,
6.7978505210263345,
8.756864140153603
],
"length": 13.369366777347004,
"start": [
6.653605325416744,
6.653605325416788,
8.756864140153588
],
"mid": [
-4.531965428549345e-14,
6.7978505210263345,
8.218533741391056
],
"end": [
-6.653605325416833,
6.653605325416785,
8.756864140153603
],
"index": 11
}
]
},
{
"id": "s8",
"op": "transform",
"inputs": [
"s7"
],
"parameters": {
"factor": [
0.925,
0.925,
0.85
],
"about": [
0.0,
0.0,
0.0
],
"method": "scale"
},
"source": "Shape.scale",
"result": {
"volume": 1392.4533674204192,
"volume_gk": 1392.4533674204192,
"area": 826.3818860013073,
"default_volume": 1392.4533674401873,
"bbox": [
-8.325000100000002,
-8.325000100000002,
-1e-07,
8.325000100000002,
8.325000100000002,
7.175275363446779
],
"solid_count": 1
}
}
],
"result_refs": [
"s8"
],
"b3d_status": "ok",
"b3d_volume": 1392.4533674204192,
"b3d_bbox": [
-8.325000100000002,
-8.325000100000002,
-1e-07,
8.325000100000002,
8.325000100000002,
7.175275363446779
],
"solid_count": 1,
"unsupported": [],
"error": "",
"b3d_default_volume": 1392.4533674401873,
"b3d_volume_gk": 1392.4533674204192,
"b3d_valid": true,
"b3d_area": 826.3818860013073,
"source_file": "models/45_key_cap.py",
"source_sha256": "3e3683ba02aff7a4d0baca83532875541030b095d2e46b4de7307437e384a6b4",
"build123d_version": "0.13.0",
"stem": "affine_trimmed_sphere",
"source_metadata": {
"source_url": "https://github.com/gumyr/build123d/blob/38effd343e1508964673faf59300a5cc68fbedc1/examples/key_cap.py",
"source_sha256": "0e3b3e77b88e488ef093b308415072dddded3e971e72081bf1c0a51ad9ce2e73",
"export_options": {
"precision_mode": "AVERAGE",
"write_pcurves": true
}
},
"extraction_note": "First eight real feature operations of model 45, through affine scale; source provenance retained."
}
@@ -0,0 +1,311 @@
{
"schema_version": "1.0",
"steps": [
{
"id": "s3",
"op": "extrude",
"inputs": [],
"parameters": {
"direction": [
0.0,
0.0,
4.0
]
},
"source": "Solid.extrude",
"result": {
"volume": 289.73641490428105,
"volume_gk": 289.73641490428105,
"default_volume": 290.6612252204212,
"bbox": [
14.874267428125,
-7.713174450168028e-15,
4.9999999,
27.020263721875,
13.549804887499992,
9.0000001
],
"solid_count": 1
},
"profile": {
"kind": "face",
"origin": [
20.952972409981427,
6.772877390140605,
5.0
],
"x_dir": [
1.0,
0.0,
-0.0
],
"y_dir": [
-0.0,
1.0,
0.0
],
"normal": [
0.0,
0.0,
1.0
],
"wires": [
{
"edges": [
{
"kind": "bspline",
"start": [
16.876220653125,
12.109375099999992,
5.0
],
"end": [
16.876220653125,
12.109375099999992,
5.0
],
"parameter_range": [
0.0,
6.5628065631728365
],
"reversed": false,
"degree": 2,
"poles": [
[
16.876220653125,
12.109375099999992,
5.0
],
[
14.874267528125,
10.375976662499992,
5.0
],
[
14.874267528125,
3.4912110374999923,
5.0
],
[
18.231201121875,
9.999999228682555e-08,
5.0
],
[
22.650146434375,
9.999999228682555e-08,
5.0
],
[
25.518798778125,
1.5869141624999923,
5.0
],
[
27.020263621875,
4.455566506249992,
5.0
],
[
27.020263621875,
10.046386818749992,
5.0
],
[
23.626708934375,
13.549804787499992,
5.0
],
[
18.548583934375,
13.549804787499992,
5.0
],
[
16.876220653125,
12.109375099999992,
5.0
]
],
"weights": [
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0
],
"knots": [
0.0,
1.0,
1.911864406779661,
2.823728813559322,
3.39211066352512,
3.9604925134909177,
4.5288743634567155,
5.230340744146212,
5.931807124835709,
6.5628065631728365
],
"multiplicities": [
3,
1,
1,
1,
1,
1,
1,
1,
1,
3
],
"periodic": false
}
],
"closed": true
},
{
"edges": [
{
"kind": "bspline",
"start": [
17.132568309375,
6.774902443749992,
5.0
],
"end": [
17.132568309375,
6.774902443749992,
5.0
],
"parameter_range": [
0.0,
8.16675617962079
],
"reversed": false,
"degree": 2,
"poles": [
[
17.132568309375,
6.774902443749992,
5.0
],
[
17.132568309375,
9.265136818749992,
5.0
],
[
19.305419871875,
11.730957131249992,
5.0
],
[
22.576904246875,
11.730957131249992,
5.0
],
[
24.761962840625,
9.252929787499992,
5.0
],
[
24.761962840625,
4.296875099999992,
5.0
],
[
22.589111278125,
1.8066407249999923,
5.0
],
[
19.305419871875,
1.8066407249999923,
5.0
],
[
17.132568309375,
4.284668068749992,
5.0
],
[
17.132568309375,
6.774902443749992,
5.0
]
],
"weights": [
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0
],
"knots": [
0.0,
1.0,
2.0,
2.985185185185185,
3.97037037037037,
5.015566835871404,
6.060763301372438,
7.113759740496614,
8.16675617962079
],
"multiplicities": [
3,
1,
1,
1,
1,
1,
1,
1,
3
],
"periodic": false
}
],
"closed": true
}
]
}
}
],
"result_refs": [
"s3"
],
"b3d_status": "ok",
"b3d_volume": 289.73641490428105,
"b3d_volume_gk": 289.73641490428105,
"b3d_default_volume": 290.6612252204212,
"b3d_bbox": [
14.874267428125,
-7.713174450168028e-15,
4.9999999,
27.020263721875,
13.549804887499992,
9.0000001
],
"solid_count": 1,
"unsupported": [],
"fixture_provenance": {
"source_stem": "34_embossed_debossed_text",
"source_feature": "s3",
"build123d_version": "0.13.0",
"source_kernel": "8.0.1.1",
"reference_volume_method": "Gauss-Kronrod, eps=1e-9, use_span=True"
}
}
@@ -0,0 +1,249 @@
{
"schema_version": "1.0",
"steps": [
{
"id": "s1",
"op": "extrude",
"inputs": [],
"parameters": {
"direction": [
0.0,
0.0,
20.0
]
},
"source": "Solid.extrude",
"result": {
"volume": 42797.5432332819,
"volume_gk": 42797.5432332819,
"default_volume": 42797.54323328191,
"bbox": [
-24.270509831248425,
-28.53169548885461,
0.0,
30.0,
28.531695488854606,
20.0
],
"solid_count": 1
},
"profile": {
"kind": "face",
"origin": [
-9.23053696217674e-16,
0.0,
0.0
],
"x_dir": [
1.0,
0.0,
-0.0
],
"y_dir": [
-0.0,
1.0,
0.0
],
"normal": [
0.0,
0.0,
1.0
],
"wires": [
{
"edges": [
{
"kind": "line",
"start": [
30.0,
0.0,
0.0
],
"end": [
9.270509831248427,
28.531695488854602,
0.0
],
"parameter_range": [
0.0,
35.26711513754839
],
"reversed": false
},
{
"kind": "line",
"start": [
9.270509831248424,
28.531695488854606,
0.0
],
"end": [
-24.27050983124842,
17.633557568774197,
0.0
],
"parameter_range": [
0.0,
35.26711513754839
],
"reversed": false
},
{
"kind": "line",
"start": [
-24.27050983124842,
17.633557568774197,
0.0
],
"end": [
-24.270509831248425,
-17.63355756877419,
0.0
],
"parameter_range": [
0.0,
35.26711513754839
],
"reversed": false
},
{
"kind": "line",
"start": [
-24.270509831248425,
-17.63355756877419,
0.0
],
"end": [
9.270509831248418,
-28.53169548885461,
0.0
],
"parameter_range": [
0.0,
35.26711513754839
],
"reversed": false
},
{
"kind": "line",
"start": [
9.270509831248416,
-28.53169548885461,
0.0
],
"end": [
29.999999999999996,
3.548257364643738e-16,
0.0
],
"parameter_range": [
0.0,
35.267115137548394
],
"reversed": false
}
],
"closed": true
}
]
}
},
{
"id": "s2",
"op": "transform",
"inputs": [
"s1"
],
"parameters": {
"mirror_plane": {
"origin": [
-7.500000000000003,
-23.0826265288144,
10.0
],
"x_dir": [
0.9510565162951525,
-0.30901699437495084,
0.0
],
"y_dir": [
-0.0,
0.0,
1.0
],
"normal": [
-0.30901699437495084,
-0.9510565162951525,
-0.0
]
},
"method": "mirror"
},
"source": "Shape.mirror",
"result": {
"volume": 42797.54323328192,
"volume_gk": 42797.54323328192,
"default_volume": 42797.54323328192,
"bbox": [
-45.00000000000017,
-74.69694854648331,
0.0,
9.270509831248383,
-17.633557568774084,
20.0
],
"solid_count": 1
}
},
{
"id": "s3",
"op": "union",
"inputs": [
"s1",
"s2"
],
"parameters": {
"glue": false,
"tol": null
},
"source": "Shape.fuse",
"result": {
"volume": 85595.08646656375,
"volume_gk": 85595.08646656375,
"default_volume": 85595.08646656378,
"bbox": [
-45.00000000000017,
-74.69694854648331,
0.0,
30.0,
28.531695488854606,
20.0
],
"solid_count": 1
}
}
],
"result_refs": [
"s3"
],
"b3d_volume": 85595.08646656375,
"b3d_volume_gk": 85595.08646656375,
"b3d_default_volume": 85595.08646656378,
"b3d_bbox": [
-45.00000000000017,
-74.69694854648331,
0.0,
30.0,
28.531695488854606,
20.0
],
"solid_count": 1,
"b3d_status": "ok",
"unsupported": [],
"fixture_provenance": {
"source_stem": "17_face_mirror",
"build123d_version": "0.13.0",
"source_kernel": "8.0.1.1",
"reference_volume_method": "Gauss-Kronrod, eps=1e-9, use_span=True"
}
}
@@ -0,0 +1,365 @@
{
"schema_version": "1.0",
"steps": [
{
"id": "s1",
"op": "box",
"inputs": [],
"parameters": {
"length": 80.0,
"width": 60.0,
"height": 10.0,
"plane": {
"origin": [
0.0,
0.0,
0.0
],
"x_dir": [
1.0,
0.0,
-0.0
],
"y_dir": [
-0.0,
1.0,
0.0
],
"normal": [
0.0,
0.0,
1.0
]
}
},
"source": "Solid.make_box",
"result": {
"volume": 47999.99999999999,
"volume_gk": 47999.99999999999,
"default_volume": 48000.0,
"bbox": [
0.0,
0.0,
0.0,
80.0,
60.0,
10.0
],
"solid_count": 1
}
},
{
"id": "s2",
"op": "transform",
"inputs": [
"s1"
],
"parameters": {
"loc": {
"matrix": [
[
1.0,
0.0,
0.0,
-40.0
],
[
0.0,
1.0,
0.0,
-30.0
],
[
0.0,
0.0,
1.0,
-5.0
],
[
0.0,
0.0,
0.0,
1.0
]
]
},
"method": "move",
"matrix": [
[
1.0,
0.0,
0.0,
-40.0
],
[
0.0,
1.0,
0.0,
-30.0
],
[
0.0,
0.0,
1.0,
-5.0
],
[
0.0,
0.0,
0.0,
1.0
]
]
},
"source": "Shape.move",
"result": {
"volume": 47999.99999999999,
"volume_gk": 47999.99999999999,
"default_volume": 48000.0,
"bbox": [
-40.0,
-30.0,
-5.0,
40.0,
30.0,
5.0
],
"solid_count": 1
}
},
{
"id": "s3",
"op": "cylinder",
"inputs": [],
"parameters": {
"radius": 15.0,
"height": 200.9975124224178,
"plane": {
"origin": [
0.0,
0.0,
100.4987562112089
],
"x_dir": [
-1.0,
0.0,
-0.0
],
"y_dir": [
0.0,
1.0,
0.0
],
"normal": [
0.0,
0.0,
-1.0
]
},
"angle": 360
},
"source": "Solid.make_cylinder",
"result": {
"volume": 142076.76939362014,
"volume_gk": 142076.76939362014,
"default_volume": 142076.76939362046,
"bbox": [
-15.0,
-15.0,
-100.4987562112089,
15.0,
15.0,
100.4987562112089
],
"solid_count": 1
}
},
{
"id": "s4",
"op": "transform",
"inputs": [
"s3"
],
"parameters": {
"loc": {
"matrix": [
[
1.0,
0.0,
0.0,
-0.0
],
[
0.0,
1.0,
0.0,
-0.0
],
[
0.0,
0.0,
1.0,
-0.0
],
[
0.0,
0.0,
0.0,
1.0
]
]
},
"method": "move",
"matrix": [
[
1.0,
0.0,
0.0,
-0.0
],
[
0.0,
1.0,
0.0,
-0.0
],
[
0.0,
0.0,
1.0,
-0.0
],
[
0.0,
0.0,
0.0,
1.0
]
]
},
"source": "Shape.move",
"result": {
"volume": 142076.76939362014,
"volume_gk": 142076.76939362014,
"default_volume": 142076.76939362046,
"bbox": [
-15.0,
-15.0,
-100.4987562112089,
15.0,
15.0,
100.4987562112089
],
"solid_count": 1
}
},
{
"id": "s5",
"op": "cut",
"inputs": [
"s2",
"s4"
],
"parameters": {},
"source": "Shape.cut",
"result": {
"volume": 40931.41652942296,
"volume_gk": 40931.41652942296,
"default_volume": 40931.41652942296,
"bbox": [
-40.0,
-30.0,
-5.0,
40.0,
30.0,
5.0
],
"solid_count": 1
}
},
{
"id": "s6",
"op": "fillet",
"inputs": [
"s5"
],
"parameters": {
"radius": 2
},
"source": "Mixin3D.fillet",
"result": {
"volume": 40848.104058581375,
"volume_gk": 40848.104058581375,
"default_volume": 40848.10405858136,
"bbox": [
-40.0,
-30.0,
-5.0,
40.0,
30.0,
5.0
],
"solid_count": 1
},
"selection": [
{
"kind": "edge",
"geom_type": "CIRCLE",
"center": [
-7.0682404105834e-14,
-4.637201104937301e-16,
4.999999999999999
],
"bbox": [
-15.0,
-15.0,
5.0,
15.0,
15.0,
5.0
],
"length": 94.2477796076938,
"start": [
-15.0,
-1.699661669294394e-14,
5.0
],
"mid": [
15.0,
8.49830834647197e-15,
5.0
],
"end": [
-15.0,
0.0,
5.0
],
"index": 9
}
]
}
],
"result_refs": [
"s6"
],
"b3d_volume": 40848.104058581375,
"b3d_volume_gk": 40848.104058581375,
"b3d_default_volume": 40848.10405858136,
"b3d_bbox": [
-40.0,
-30.0,
-5.0,
40.0,
30.0,
5.0
],
"solid_count": 1,
"b3d_status": "ok",
"unsupported": [],
"fixture_provenance": {
"source_stem": "10_filleted_hole",
"build123d_version": "0.13.0",
"source_kernel": "8.0.1.1",
"reference_volume_method": "Gauss-Kronrod, eps=1e-9, use_span=True"
}
}
@@ -0,0 +1,178 @@
{
"schema_version": "1.0",
"steps": [
{
"id": "s1",
"op": "extrude",
"inputs": [],
"parameters": {
"direction": [
0.0,
0.0,
10.0
]
},
"source": "Solid.extrude",
"result": {
"volume": 69504.67164903213,
"volume_gk": 69504.67164903213,
"default_volume": 69504.6716490322,
"bbox": [
0.0,
0.0,
0.0,
80.0,
95.31128874149275,
10.0
],
"solid_count": 1
},
"profile": {
"kind": "face",
"origin": [
40.0,
43.87364956936529,
0.0
],
"x_dir": [
1.0,
0.0,
-0.0
],
"y_dir": [
-0.0,
1.0,
0.0
],
"normal": [
0.0,
0.0,
1.0
],
"wires": [
{
"edges": [
{
"kind": "line",
"start": [
0.0,
0.0,
0.0
],
"end": [
80.0,
0.0,
0.0
],
"parameter_range": [
0.0,
80.0
],
"reversed": false
},
{
"kind": "line",
"start": [
80.0,
0.0,
0.0
],
"end": [
80.0,
60.0,
0.0
],
"parameter_range": [
0.0,
60.0
],
"reversed": false
},
{
"kind": "arc",
"mid": [
40.00000000000001,
95.31128874149275,
0.0
],
"start": [
80.0,
60.0,
0.0
],
"end": [
0.0,
60.00000000000001,
0.0
],
"parameter_range": [
0.0,
2.89288266449627
],
"reversed": false,
"center": [
40.0,
55.0,
0.0
],
"radius": 40.311288741492746,
"normal": [
0.0,
0.0,
1.0
],
"x_dir": [
0.9922778767136677,
0.12403473458920847,
-0.0
]
},
{
"kind": "line",
"start": [
0.0,
60.0,
0.0
],
"end": [
0.0,
0.0,
0.0
],
"parameter_range": [
0.0,
60.0
],
"reversed": false
}
],
"closed": true
}
]
}
}
],
"result_refs": [
"s1"
],
"b3d_volume": 69504.67164903213,
"b3d_volume_gk": 69504.67164903213,
"b3d_default_volume": 69504.6716490322,
"b3d_bbox": [
0.0,
0.0,
0.0,
80.0,
95.31128874149275,
10.0
],
"solid_count": 1,
"b3d_status": "ok",
"unsupported": [],
"fixture_provenance": {
"source_stem": "04_lines_and_arcs_profile",
"build123d_version": "0.13.0",
"source_kernel": "8.0.1.1",
"reference_volume_method": "Gauss-Kronrod, eps=1e-9, use_span=True"
}
}
File diff suppressed because it is too large Load Diff
+25
View File
@@ -0,0 +1,25 @@
"""Complex shared fillet geometry must survive nonuniform scale without a crash."""
import json
from pathlib import Path
import sys
import pytest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tools/research/build123dftc"))
from b3ftc.replay import replay_trace_to_ftc
from b3ftc.validation import _worker
def test_nonuniform_scale_after_spherical_cut_and_fillet(tmp_path):
trace = json.loads((ROOT / "test/build123d_traces/affine_trimmed_sphere.trace.json").read_text())
source, meta = replay_trace_to_ftc(trace, stem="affine-shared-geometry")
assert meta["status"] == "ok"
path = tmp_path / "affine.ftc.py"
path.write_text(source)
# A native kernel regression can segfault. Keep the test runner alive and
# report it as a failing feature, exactly like the external acceptance tool.
metrics = _worker(path, tmp_path / "work", 30, None, sys.executable, None)
assert metrics["status"] == "ok", metrics
assert metrics["is_valid"] is True
assert metrics["volume"] == pytest.approx(trace["b3d_volume"], rel=1e-6)
+88
View File
@@ -0,0 +1,88 @@
"""The pure stage-2 boundary and batch input discovery contracts."""
import importlib.util
import json
import sys
from pathlib import Path
import pytest
TOOLS = Path(__file__).resolve().parents[1] / "tools/research/build123dftc"
sys.path.insert(0, str(TOOLS))
def _script(name):
spec = importlib.util.spec_from_file_location(name, TOOLS / f"{name}.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_translate_writes_reviewable_source_and_sidecars(tmp_path):
payload = {"schema_version": "1.0", "stem": "box", "b3d_status": "ok",
"unsupported": [], "steps": [{"id": "base", "op": "box", "inputs": [],
"parameters": {"length": 10, "width": 8, "height": 4}}],
"result_refs": ["base"], "b3d_volume": 320,
"b3d_bbox": [0, 0, 0, 10, 8, 4], "solid_count": 1}
trace = tmp_path / "box.trace.json"
trace.write_text(json.dumps(payload))
stem, source, meta = _script("build123d_to_ftc").translate_trace_file(trace, tmp_path / "out")
assert stem == "box"
assert meta["status"] == "ok"
assert "feature:" in source and "make_box_rsolid" in source
assert (tmp_path / "out/box.ftc.py").exists()
assert (tmp_path / "out/box.meta.json").exists()
assert (tmp_path / "out/box.sketches.json").exists()
@pytest.mark.parametrize("stem", ["../escape", "/absolute", "..", "nested/file"])
def test_trace_cannot_write_outside_output_directory(tmp_path, stem):
trace = tmp_path / "bad.trace.json"
trace.write_text(json.dumps({"schema_version": "1.0", "stem": stem, "steps": []}))
with pytest.raises(ValueError):
_script("build123d_to_ftc").translate_trace_file(trace, tmp_path / "out")
assert not (tmp_path / "out").exists()
def test_future_schema_is_not_silently_reinterpreted(tmp_path):
trace = tmp_path / "bad.trace.json"
trace.write_text(json.dumps({"schema_version": "999", "steps": []}))
with pytest.raises(ValueError, match="schema"):
_script("build123d_to_ftc").translate_trace_file(trace, tmp_path / "out")
def test_manifest_resolves_only_declared_models(tmp_path):
models = tmp_path / "models"
models.mkdir()
for name in ("one.py", "two.py", "extra.py"):
(models / name).write_text("")
manifest = tmp_path / "manifest.json"
manifest.write_text(json.dumps({"examples": [{"file": "models/one.py"}, {"file": "models/two.py"}]}))
actual = _script("build123d_trace").discover_inputs(manifest=manifest)
assert [p.name for p in actual] == ["one.py", "two.py"]
@pytest.mark.parametrize("timeout", ["nan", "inf", "0", "-1"])
def test_capture_rejects_unbounded_or_invalid_timeouts(timeout):
with pytest.raises(SystemExit) as error:
_script("build123d_trace").main(["--input", "unused.py", "--timeout", timeout])
assert error.value.code == 2
def test_validator_cli_reports_failure_with_nonzero_exit(tmp_path, monkeypatch):
module = _script("build123d_validate")
report = {"rows": [{"stem": "broken", "quality": "rejected", "build": "build_error",
"reasons": ["build_failed"]}],
"counts": {"accepted": 0, "partial": 0, "rejected": 1}}
monkeypatch.setattr(module, "validate_directory", lambda *a, **kw: report)
output = tmp_path / "report.json"
assert module.main(["--ftc-dir", str(tmp_path), "--traces-dir", str(tmp_path),
"--report", str(output)]) == 1
assert json.loads(output.read_text())["counts"]["rejected"] == 1
@pytest.mark.parametrize("timeout", ["nan", "inf", "-1", "0"])
def test_validator_cli_rejects_nonfinite_or_nonpositive_timeout(tmp_path, timeout):
with pytest.raises(SystemExit) as exc:
_script("build123d_validate").main(["--ftc-dir", str(tmp_path), "--traces-dir", str(tmp_path),
"--timeout", timeout])
assert exc.value.code == 2
+229
View File
@@ -0,0 +1,229 @@
"""Feature tracing regressions, independent of the SimpleCAD runtime."""
from pathlib import Path
import copy
import json
import sys
import pytest
b = pytest.importorskip("build123d")
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools/research/build123dftc"))
from b3ftc.geometry import edge as transcribe_edge
from b3ftc.geometry import fingerprint
from b3ftc.tracer import trace_source
def checked(source):
trace = trace_source(source)
assert trace["b3d_status"] == "ok", trace["error"]
assert trace["unsupported"] == []
known = set()
for step in trace["steps"]:
assert set(step["inputs"]) <= known
known.add(step["id"])
assert set(trace["result_refs"]) <= known
json.dumps(trace, allow_nan=False)
return trace
def test_builder_profile_is_actual_placed_face_with_hole():
trace = checked("""from build123d import *
with BuildPart() as bp:
with BuildSketch(Plane.XY.offset(7)):
Rectangle(10, 8)
Circle(2, mode=Mode.SUBTRACT)
extrude(amount=3)
result = bp.part
""")
feature = next(s for s in trace["steps"] if s["op"] == "extrude")
assert len(feature["profile"]["wires"]) == 2
assert feature["profile"]["origin"][2] == pytest.approx(7)
assert trace["b3d_bbox"][2::3] == pytest.approx([7, 10])
assert trace["b3d_volume"] == pytest.approx((80 - 4 * 3.141592653589793) * 3)
def test_algebra_has_boolean_dependencies_and_transform_snapshots():
trace = checked("""from build123d import *
base = Box(10, 10, 10)
base.move(Location((3, 0, 0)))
result = base - Pos(3, 0, 0) * Cylinder(2, 20)
""")
assert trace["steps"][-1]["op"] == "cut"
assert len(trace["steps"][-1]["inputs"]) == 2
transform = [s for s in trace["steps"] if s["op"] == "transform"]
assert transform[0]["result"]["bbox"][0] == -5
assert transform[1]["result"]["bbox"][0] == -2
assert trace["b3d_volume"] == pytest.approx(1000 - 40 * 3.141592653589793)
def test_nested_builder_publication_is_captured_once():
trace = checked("""from build123d import *
with BuildPart(Plane.XY.offset(10)) as bp:
with Locations((4, 0, 0)):
Box(2, 2, 2)
result = bp.part
""")
assert len([s for s in trace["steps"] if s["op"] == "box"]) == 1
assert trace["b3d_bbox"] == pytest.approx([3, -1, 9, 5, 1, 11])
def test_deepcopy_mirror_preserves_feature_reference():
trace = checked("""from build123d import *
import copy
original = Solid.make_box(2, 3, 4)
result = copy.deepcopy(original).mirror(Plane.YZ)
""")
assert [s["op"] for s in trace["steps"]] == ["box", "transform"]
assert trace["b3d_bbox"] == pytest.approx([-2, 0, 0, 0, 3, 4])
def test_multiple_solid_components_and_union_groups():
trace = checked("""from build123d import *
a = Solid.make_box(1, 1, 1)
b = Solid.make_box(1, 1, 1).moved(Location((3, 0, 0)))
group = a.fuse(b).moved(Location((0, 0, 2)))
result = group.solids()[0].moved(Location((0, 2, 0)))
""")
union = next(s for s in trace["steps"] if s["op"] == "union")
assert union["result"]["solid_count"] == 2
assert len(union["result_groups"]) == 2
assert all(group for group in union["result_groups"])
assert any(s["op"] == "component" for s in trace["steps"])
assert trace["b3d_volume"] == pytest.approx(1)
def test_selection_fingerprints_for_fillet_and_shell():
trace = checked("""from build123d import *
with BuildPart() as bp:
Box(10, 10, 10)
fillet(bp.edges().filter_by(Axis.Z), 1)
offset(amount=-.5, openings=bp.faces().sort_by(Axis.Z)[-1])
result=bp.part
""")
fillet = next(s for s in trace["steps"] if s["op"] == "fillet")
shell = next(s for s in trace["steps"] if s["op"] == "offset")
assert len(fillet["selection"]) == 4
assert shell["selection"][0]["kind"] == "face"
assert "normal" in shell["selection"][0]
def test_trimmed_spline_retains_exact_control_points():
original = b.Edge.make_spline([(0, 0), (1, 2), (3, 1), (4, 0)])
trimmed = original.trim(.2, .8)
encoded = transcribe_edge(trimmed)
assert encoded["kind"] == "bspline"
assert encoded["start"] == pytest.approx(tuple(trimmed.position_at(0)))
assert encoded["end"] == pytest.approx(tuple(trimmed.position_at(1)))
assert encoded["poles"][0] == pytest.approx(encoded["end"] if encoded["reversed"] else encoded["start"])
def test_absolute_location_assignment_and_exact_conic_trim():
trace = checked("""from build123d import *
result = Solid.make_box(2,3,4).moved(Location((2,0,0)))
result.location = Location((5,0,0))
""")
assert trace["b3d_bbox"][0] == pytest.approx(5)
assert trace["steps"][-1]["parameters"]["matrix"][0][3] == pytest.approx(3)
conic = b.Edge.make_ellipse(3, 2, start_angle=10, end_angle=150)
data = transcribe_edge(conic)
assert data["kind"] == "bspline"
assert data["degree"] == 2
assert any(weight != 1 for weight in data["weights"])
def test_curved_selection_center_is_mass_center_and_no_arbitrary_surface_normal():
arc = b.Edge.make_three_point_arc((1, 0), (0, 1), (-1, 0))
data = fingerprint(arc)
assert data["center"] == pytest.approx(tuple(arc.center(b.CenterOf.MASS)))
assert data["center"] != pytest.approx(tuple(arc.center()))
sphere = b.Solid.make_sphere(2)
curved = fingerprint(sphere.faces()[0])
assert "normal" not in curved
def test_scaling_resolves_actual_default_location_center():
trace = checked("""from build123d import *
placed = Solid.make_box(2,3,4).moved(Location((10,0,0)))
result = placed.scale(2)
""")
assert trace["steps"][-1]["parameters"]["about"] == pytest.approx([10, 0, 0])
assert trace["b3d_bbox"] == pytest.approx([10, 0, 0, 14, 6, 8])
def test_factory_parameters_partial_angles_and_generator_inputs_are_preserved():
trace = checked("""from build123d import *
a = Solid.make_cylinder(2,3,angle=120)
b = Solid.make_cone(3,1,4,angle=180).moved(Location((10,0,0)))
c = Solid.make_torus(5,1,start_angle=-30,end_angle=80,major_angle=140).moved(Location((20,0,0)))
result = a.fuse(b,c)
""")
assert next(s for s in trace["steps"] if s["op"] == "cylinder")["parameters"]["angle"] == 120
torus = next(s for s in trace["steps"] if s["op"] == "torus")
assert torus["parameters"]["major_angle"] == 140
trace = checked("""from build123d import *
wires = (Wire.make_circle(r, plane=Plane.XY.offset(z)) for r,z in [(2,0),(3,5)])
result = Solid.make_loft(wires)
""")
assert len(trace["steps"][-1]["profiles"]) == 2
def test_draft_is_transcribed_and_nonplanar_thicken_reports_surface_boundary():
trace = checked("""from build123d import *
body = Solid.make_box(5,5,5)
side = body.faces().filter_by(Plane.YZ)[-1]
result = body.draft([side], Plane.XY, 5)
""")
draft = trace["steps"][-1]
assert draft["op"] == "draft"
assert len(draft["selection"]) == 1
assert draft["parameters"]["neutral_plane"]["normal"] == [0, 0, 1]
trace = trace_source("""from build123d import *
face = Solid.make_sphere(2).faces()[0]
result = Solid.thicken(face, .2)
""")
assert trace["unsupported"]
assert any(s["op"] == "thicken" and "geometry_error" in s for s in trace["steps"])
def test_unknown_kernel_solid_is_reported_and_errors_restore_patches():
original = b.Solid.make_box.__func__
owned_attributes = set(b.Solid.__dict__)
trace = trace_source("""from build123d import Solid
from OCP.BRepPrimAPI import BRepPrimAPI_MakeBox
result = Solid(BRepPrimAPI_MakeBox(2, 3, 4).Solid())
""")
assert trace["unsupported"]
assert trace["steps"][-1]["op"] == "unsupported"
assert b.Solid.make_box.__func__ is original
trace = trace_source("from build123d import *\nresult=Box(1,2,3)\nraise RuntimeError('expected')")
assert trace["b3d_status"] == "error"
assert "expected" in trace["error"]
assert b.Solid.make_box.__func__ is original
assert set(b.Solid.__dict__) == owned_attributes
def test_rational_circle_volume_uses_span_aware_adaptive_integration():
trace = checked("""from build123d import *
from math import sqrt
points = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1),(1,0)]
weights = [1,sqrt(.5),1,sqrt(.5),1,sqrt(.5),1,sqrt(.5),1]
curve = Edge.make_bspline(points,[0,0,0,1,1,2,2,3,3,4,4,4],2,weights)
result = Solid.extrude(Face(Wire([curve])), (0,0,1))
""")
assert trace["b3d_volume"] == pytest.approx(3.141592653589793, rel=1e-9)
assert trace["b3d_area"] == pytest.approx(4 * 3.141592653589793, rel=1e-9)
assert "b3d_default_volume" in trace
assert trace["steps"][-1]["profile"]["wires"][0]["edges"][0]["kind"] == "bspline"
def test_multiple_intersection_results_reference_individual_components():
trace = checked("""from build123d import *
base = Solid.make_box(10,2,2)
left = Solid.make_box(2,4,4)
right = Solid.make_box(2,4,4).moved(Location((8,0,0)))
intersection = base.intersect(left.fuse(right))
result = intersection[0].moved(Location((0,10,0)))
""")
assert any(s["op"] == "component" for s in trace["steps"])
assert trace["solid_count"] == 1
assert trace["b3d_volume"] == pytest.approx(8)
+271
View File
@@ -0,0 +1,271 @@
"""Format and executable geometry tests for build123d FTC translation.
Fixtures model the trace protocol without depending on build123d itself.
"""
from __future__ import annotations
import importlib.util
import math
import re
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/research/build123dftc'))
from b3ftc.replay import replay_trace_to_ftc
def rectangle(x=10, y=6, z=0):
points = [(0, 0, z), (x, 0, z), (x, y, z), (0, y, z)]
return {'origin': (0, 0, z), 'u': (1, 0, 0), 'v': (0, 1, 0),
'normal': (0, 0, 1), 'wires': [{'edges': [
{'kind': 'line', 'start': a, 'end': b}
for a, b in zip(points, points[1:] + points[:1])]}]}
def circle(radius, z=0):
return {'origin': (0, 0, z), 'u': (1, 0, 0), 'v': (0, 1, 0),
'normal': (0, 0, 1), 'wires': [{'edges': [
{'kind': 'circle', 'center': (0, 0, z), 'radius': radius,
'normal': (0, 0, 1), 'x_dir': (1, 0, 0)}]}]}
def trace(*steps):
return {'schema_version': '1.0', 'steps': list(steps),
'result_refs': [steps[-1]['id']], 'unsupported': []}
class FormatTests(unittest.TestCase):
def test_vertex_loft_sections_use_keyword_arguments(self):
source, meta = replay_trace_to_ftc(trace({'id': 's1', 'op': 'loft',
'profiles': [circle(2), {'kind': 'vertex', 'point': (0, 0, 5)}],
'parameters': {'ruled': True}}), stem='pointed')
self.assertEqual(meta['status'], 'ok', meta)
self.assertIn('scad.make_point_rvertex(x=0, y=0, z=5)', source)
def test_real_recorded_fixtures_need_no_build123d_dependency(self):
for path in sorted((ROOT / 'test/build123d_traces').glob('*.trace.json')):
with self.subTest(fixture=path.name):
import json
source, meta = replay_trace_to_ftc(json.loads(path.read_text()), stem=path.stem)
self.assertEqual(meta['status'], 'ok', meta['unsupported'])
compile(source, str(path), 'exec')
self.assertNotIn('import build123d', source)
self.assertNotIn('load_brep', source)
def test_sketch_extrusion_and_explicit_module_contract(self):
source, meta = replay_trace_to_ftc(trace({'id': 's1', 'op': 'extrude',
'profile': rectangle(), 'parameters': {'direction': (0, 0, 1), 'distance': 4}}), stem='plate')
self.assertEqual(meta['status'], 'ok', meta)
self.assertIn('scad.make_sketch_rsketch(', source)
self.assertIn('scad.make_face_from_sketch_rface(', source)
self.assertIn('scad.extrude_rsolid(', source)
self.assertIn("project_root=Path(__file__).parent", source)
self.assertIn('BODIES = list(bodies)', source)
self.assertRegex(source, r'feature: extrude \(build, profile=geometry\)')
for text in ('import build123d', 'import OCP', 'load_brep', '.get_edges()', '.get_faces()'):
self.assertNotIn(text, source)
compile(source, '<FTC>', 'exec')
def test_unknown_feature_blocks_dependents(self):
source, meta = replay_trace_to_ftc(trace({'id': 's1', 'op': 'unknown'},
{'id': 's2', 'op': 'translate', 'inputs': ['s1'], 'parameters': {'vector': (1, 0, 0)}}), stem='unknown')
self.assertEqual(meta['status'], 'partial')
self.assertTrue(any('unknown' in str(x) for x in meta['unsupported']))
self.assertIn('feature tree produced no solid', source)
def test_modifiers_use_individual_fingerprints(self):
payload = trace({'id': 's1', 'op': 'box', 'parameters': {'length': 10, 'width': 10, 'height': 10}},
{'id': 's2', 'op': 'fillet', 'inputs': ['s1'], 'parameters': {'radius': 1},
'selection': [{'kind': 'edge', 'geom_type': 'LINE', 'center': [0, 0, 5], 'length': 10, 'area': 0}]})
source, meta = replay_trace_to_ftc(payload, stem='filleted')
self.assertEqual(meta['status'], 'ok', meta)
self.assertIn('ql.edges()', source)
self.assertIn('.take(1).exactly(1)', source)
self.assertIn("ql.prop('geom.length'", source)
self.assertIn('scad.fillet_rsolid(', source)
self.assertNotIn('geom.area', source)
def test_no_final_snapshot_fallback(self):
source, meta = replay_trace_to_ftc({'steps': [], 'final_brep': 'ignored'}, stem='empty')
self.assertEqual(meta['status'], 'partial')
self.assertNotIn('ignored', source)
self.assertNotIn('load_brep', source)
def test_explicit_empty_results_do_not_promote_unused_tool(self):
payload = trace({'id': 's1', 'op': 'box', 'parameters': {'length': 1, 'width': 2, 'height': 3}})
payload['result_refs'] = []
source, meta = replay_trace_to_ftc(payload)
self.assertEqual(meta['status'], 'partial')
self.assertIn('feature tree produced no solid', source)
def test_draft_uses_face_predicate_and_neutral_plane(self):
payload = trace({'id': 's1', 'op': 'box', 'parameters': {'length': 2, 'width': 2, 'height': 3}},
{'id': 's2', 'op': 'draft', 'inputs': ['s1'], 'parameters': {'angle': 5,
'neutral_plane': {'origin': (0, 0, 0), 'normal': (0, 0, 1)}},
'selection': [{'kind': 'face', 'geom_type': 'PLANE', 'center': (2, 1, 1.5), 'area': 6, 'length': 0}]})
source, meta = replay_trace_to_ftc(payload)
self.assertEqual(meta['status'], 'ok', meta)
self.assertIn('scad.draft_rsolid(', source)
self.assertIn('faces_to_draft=ql.faces()', source)
self.assertNotIn('geom.length', source)
compile(source, '<FTC>', 'exec')
class GeometryTests(unittest.TestCase):
def test_real_recorded_fixtures_reconcile(self):
import json
for path in sorted((ROOT / 'test/build123d_traces').glob('*.trace.json')):
with self.subTest(fixture=path.name):
payload = json.loads(path.read_text())
self.build(payload, payload['b3d_volume'])
def build(self, payload, expected, *, constraints_mode=False):
source, meta = replay_trace_to_ftc(payload, stem='geometry', constraints_mode=constraints_mode)
self.assertEqual(meta['status'], 'ok', meta)
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / 'model.ftc.py'
path.write_text(source)
spec = importlib.util.spec_from_file_location('ftc_geometry_' + path.parent.name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
module.build()
self.assertEqual(len(module.BODIES), payload.get('solid_count', 1))
from OCP.BRepCheck import BRepCheck_Analyzer
self.assertTrue(all(BRepCheck_Analyzer(body.wrapped).IsValid() for body in module.BODIES))
from OCP.BRepGProp import BRepGProp
from OCP.GProp import GProp_GProps
def accurate_volume(body):
props = GProp_GProps()
BRepGProp.VolumePropertiesGK_s(body.wrapped, props, 1e-9, True, True)
return float(props.Mass())
volume = sum(accurate_volume(body) for body in module.BODIES)
self.assertAlmostEqual(volume, expected, delta=max(abs(expected), 1) * 1e-6)
def test_extruded_rectangle(self):
self.build(trace({'id': 's1', 'op': 'extrude', 'profile': rectangle(),
'parameters': {'direction': (0, 0, 1), 'distance': 4}}), 240)
def test_recovered_constraints_preserve_rectangle_geometry(self):
payload = trace({'id': 's1', 'op': 'extrude', 'profile': rectangle(),
'parameters': {'direction': (0, 0, 1), 'distance': 4}})
self.build(payload, 240, constraints_mode=True)
source, meta = replay_trace_to_ftc(payload, constraints_mode=True)
self.assertTrue(meta['sketches'])
self.assertEqual(meta['constraint_recovery'][0]['status'], 'riveted')
self.assertIn('scad.constrain_', source)
def test_face_with_circle_hole(self):
profile = circle(5)
profile['wires'].extend(circle(2)['wires'])
self.build(trace({'id': 's1', 'op': 'extrude', 'profile': profile,
'parameters': {'direction': (0, 0, -1), 'distance': 3}}), math.pi * 21 * 3)
def test_clockwise_polygon_hole_is_subtractive(self):
profile = circle(5)
points = [(2, -1, 0), (-2, -1, 0), (-2, 1, 0), (2, 1, 0)]
profile['wires'].append({'edges': [{'kind': 'line', 'start': a, 'end': b}
for a, b in zip(points, points[1:] + points[:1])]})
self.build(trace({'id': 's1', 'op': 'extrude', 'profile': profile,
'parameters': {'direction': (0, 0, 1), 'distance': 3}}), (math.pi * 25 - 8) * 3)
def test_explicit_boolean_cut(self):
self.build(trace({'id': 's1', 'op': 'box', 'parameters': {'length': 10, 'width': 10, 'height': 5}},
{'id': 's2', 'op': 'cylinder', 'parameters': {'radius': 2, 'height': 5, 'origin': (5, 5, 0)}},
{'id': 's3', 'op': 'cut', 'inputs': ['s1', 's2']}), 500 - math.pi * 20)
def test_loft_circle_sections(self):
self.build(trace({'id': 's1', 'op': 'loft', 'profiles': [circle(2), circle(4, 6)],
'parameters': {'ruled': True}}), math.pi * 6 * (4 + 8 + 16) / 3)
def test_native_multisection_sweep(self):
self.build(trace({'id': 's1', 'op': 'sweep_multi', 'profiles': [circle(2), circle(4, 6)],
'path': {'edges': [{'kind': 'line', 'start': (0, 0, 0), 'end': (0, 0, 6)}]},
'parameters': {'is_frenet': False}}), 56 * math.pi)
def test_native_tapered_extrusion(self):
top_radius = 4 - 6 * math.tan(math.radians(15))
self.build(trace({'id': 's1', 'op': 'extrude_taper', 'profile': circle(4),
'parameters': {'direction': (0, 0, 6), 'taper': 15}}),
math.pi * 6 * (16 + 4 * top_radius + top_radius ** 2) / 3)
def test_native_until_extrusion(self):
self.build(trace({'id': 's1', 'op': 'box',
'parameters': {'length': 10, 'width': 10, 'height': 3, 'origin': (-5, -5, 5)}},
{'id': 's2', 'op': 'extrude_until', 'inputs': ['s1'], 'profile': circle(1),
'parameters': {'direction': (0, 0, 1), 'until': 'NEXT'}}), 5 * math.pi)
def test_native_twisted_extrusion(self):
self.build(trace({'id': 's1', 'op': 'extrude_twist', 'profile': rectangle(),
'parameters': {'normal': (0, 0, 4), 'center': (0, 0, 0), 'angle': 90}}), 240)
def test_affine_shear_preserves_volume(self):
self.build(trace({'id': 's1', 'op': 'box', 'parameters': {'length': 10, 'width': 6, 'height': 4}},
{'id': 's2', 'op': 'transform', 'inputs': ['s1'], 'parameters': {'matrix': [
[1, .5, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]}}), 240)
def test_both_split_preserves_original_component_order(self):
self.build(trace({'id': 's1', 'op': 'box',
'parameters': {'length': 2, 'width': 3, 'height': 8},
'result': {'bbox': [0, 0, 0, 2, 3, 8], 'solid_count': 1}},
{'id': 's2', 'op': 'split', 'inputs': ['s1'],
'parameters': {'tool': {'origin': (0, 0, 2), 'normal': (0, 0, 1)}, 'keep': 'BOTH'},
'result_component_sides': ['BOTTOM', 'TOP']},
{'id': 's3', 'op': 'component', 'inputs': ['s2'], 'parameters': {'index': 0}}), 12)
def test_exact_ellipse_sketch(self):
profile = circle(2)
profile['wires'][0]['edges'] = [{'kind': 'ellipse', 'center': (0, 0, 0),
'major_radius': 4, 'minor_radius': 2, 'x_dir': (1, 0, 0), 'y_dir': (0, 1, 0)}]
self.build(trace({'id': 's1', 'op': 'extrude', 'profile': profile,
'parameters': {'direction': (0, 0, 1), 'distance': 3}}), math.pi * 8 * 3)
def test_translate_preserves_volume(self):
self.build(trace({'id': 's1', 'op': 'sphere', 'parameters': {'radius': 3}},
{'id': 's2', 'op': 'translate', 'inputs': ['s1'], 'parameters': {'vector': (5, -8, 2)}}), 36 * math.pi)
def test_partial_cylinder(self):
self.build(trace({'id': 's1', 'op': 'cylinder',
'parameters': {'radius': 3, 'height': 4, 'angle': 180}}), 18 * math.pi)
def test_partial_cone(self):
self.build(trace({'id': 's1', 'op': 'cone',
'parameters': {'base_radius': 3, 'top_radius': 0, 'height': 4, 'angle': 90}}), 3 * math.pi)
def test_partial_sphere(self):
self.build(trace({'id': 's1', 'op': 'sphere',
'parameters': {'radius': 3, 'angle1': 0, 'angle2': 90, 'angle3': 360}}), 18 * math.pi)
def test_closed_rational_spline_profile(self):
profile = circle(1)
poles = [(1, 0, 0), (1, 1, 0), (0, 1, 0), (-1, 1, 0), (-1, 0, 0),
(-1, -1, 0), (0, -1, 0), (1, -1, 0), (1, 0, 0)]
profile['wires'][0]['edges'] = [{'kind': 'bspline', 'poles': poles, 'degree': 2,
'knots': [0, .25, .5, .75, 1], 'multiplicities': [3, 2, 2, 2, 3],
'weights': [1, math.sqrt(.5), 1, math.sqrt(.5), 1, math.sqrt(.5), 1, math.sqrt(.5), 1],
'start': poles[0], 'end': poles[-1]}]
self.build(trace({'id': 's1', 'op': 'extrude', 'profile': profile,
'parameters': {'direction': [0, 0, 1], 'distance': 2}}), 2 * math.pi)
def test_reversed_cubic_basis_preserves_entire_curve(self):
profile = circle(1)
poles = [(0, 0, 0), (0, 3, 0), (2, 4, 0), (4, 0, 0)]
profile['wires'][0]['edges'] = [{'kind': 'bezier', 'poles': poles, 'degree': 3,
'start': poles[-1], 'end': poles[0], 'reversed': True},
{'kind': 'line', 'start': poles[0], 'end': poles[-1]}]
# Exact Green-integral area of this cubic and its closing chord is 7.5.
self.build(trace({'id': 's1', 'op': 'extrude', 'profile': profile,
'parameters': {'direction': [0, 0, 1], 'distance': 2}}), 15)
def test_multi_body_is_complete_assembly(self):
payload = trace({'id': 's1', 'op': 'box', 'parameters': {'length': 2, 'width': 3, 'height': 4}},
{'id': 's2', 'op': 'box', 'parameters': {'length': 4, 'width': 2, 'height': 3, 'origin': [20, 0, 0]}},
{'id': 's3', 'op': 'compound', 'inputs': ['s1', 's2']})
payload['solid_count'] = 2
self.build(payload, 48)
source, meta = replay_trace_to_ftc(payload)
self.assertEqual(meta['artifact_type'], 'assembly')
self.assertIn('@scad.assemble(', source)
if __name__ == '__main__':
unittest.main()
+40
View File
@@ -0,0 +1,40 @@
"""Unknown construction must remain visible instead of aliasing an old solid."""
from pathlib import Path
import sys
import pytest
pytest.importorskip("build123d")
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tools/research/build123dftc"))
from b3ftc.replay import replay_trace_to_ftc
from b3ftc.tracer import trace_source
from b3ftc.validation import compare_metrics
@pytest.mark.parametrize("statement", [
"result = ConvexPolyhedron([(0,0,0),(1,0,0),(0,1,0),(0,0,1)])",
"result = Box(2,3,4).to_splines()",
"from OCP.BRepPrimAPI import BRepPrimAPI_MakeBox\nresult = Solid(BRepPrimAPI_MakeBox(2,3,4).Solid())",
])
def test_uninstrumented_api_cannot_silently_accept(statement):
trace = trace_source("from build123d import *\n" + statement)
assert trace["b3d_status"] == "ok", trace["error"]
assert trace["unsupported"], trace
assert any(step["op"] == "unsupported" for step in trace["steps"])
_, metadata = replay_trace_to_ftc(trace)
assert metadata["status"] == "partial", metadata
actual = {"status": "ok", "volume": trace["b3d_volume"],
"bbox": trace["b3d_bbox"], "solid_count": trace["solid_count"],
"body_count": trace["solid_count"], "is_valid": True}
assert compare_metrics(trace, actual, metadata)["quality"] == "rejected"
def test_failed_source_rejects_even_after_valid_feature_was_created():
trace = trace_source("from build123d import *\nresult=Box(2,3,4)\nraise RuntimeError('unknown operation')")
_, metadata = replay_trace_to_ftc(trace)
actual = {"status": "ok", "volume": 24, "bbox": [-1,-1.5,-2,1,1.5,2],
"solid_count": 1, "body_count": 1, "is_valid": True}
result = compare_metrics(trace, actual, metadata)
assert result["quality"] == "rejected"
assert "source_failed" in result["reasons"]
+215
View File
@@ -0,0 +1,215 @@
"""Acceptance must reject missing evidence and geometric false positives."""
from __future__ import annotations
import json
import math
from pathlib import Path
import sys
import pytest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tools/research/build123dftc"))
from b3ftc.validation import compare_metrics, validate_directory, validate_row
def expected(**changes):
trace = {"b3d_status": "ok", "b3d_volume": 1000.0,
"b3d_bbox": [-5, -5, 0, 5, 5, 10], "solid_count": 1,
"result_refs": ["s1"], "unsupported": []}
trace.update(changes)
return trace
def actual(**changes):
metrics = {"status": "ok", "volume": 1000.0,
"bbox": [-5, -5, 0, 5, 5, 10], "solid_count": 1,
"body_count": 1, "is_valid": True}
metrics.update(changes)
return metrics
META = {"status": "ok", "unsupported": []}
def test_matching_metrics_accepted():
result = compare_metrics(expected(), actual(), META)
assert result["quality"] == "accepted", result
assert result["bbox_error"] == 0
def test_reference_failure_reports_basic_geometry_separately(tmp_path, monkeypatch):
import b3ftc.validation as validation
ftc = tmp_path / "sample.ftc.py"
ftc.write_text("# worker is isolated by this test")
trace = tmp_path / "sample.trace.json"
trace.write_text(json.dumps(expected()))
ftc.with_name("sample.meta.json").write_text(json.dumps(META))
monkeypatch.setattr(validation, "_worker", lambda *args, **kwargs:
actual(reference_status="error", reference_error="kernel comparison failed"))
row = validate_row(ftc, trace, reference_step=tmp_path / "reference.step")
assert row["quality"] == "rejected"
assert row["metrics_quality"] == "accepted"
assert row["metrics_reasons"] == []
assert row["reasons"] == ["reference_error"]
def test_rational_circle_cylinder_has_mathematical_area_four_pi():
from OCP.BRepBuilderAPI import BRepBuilderAPI_MakeEdge, BRepBuilderAPI_MakeWire, BRepBuilderAPI_MakeFace
from OCP.BRepPrimAPI import BRepPrimAPI_MakePrism
from OCP.Geom import Geom_Circle
from OCP.GeomConvert import GeomConvert
from OCP.gp import gp_Ax2, gp_Pnt, gp_Dir, gp_Vec
from b3ftc._validate_worker import _area, _volume
circle = Geom_Circle(gp_Ax2(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)), 1)
spline = GeomConvert.CurveToBSplineCurve_s(circle)
assert spline.IsRational()
edge = BRepBuilderAPI_MakeEdge(spline).Edge()
wire = BRepBuilderAPI_MakeWire(edge).Wire()
face = BRepBuilderAPI_MakeFace(wire, True).Face()
solid = BRepPrimAPI_MakePrism(face, gp_Vec(0, 0, 1)).Shape()
# OCCT 7.9's continuity split adds about 7.7e-9 relative integration
# error here; this precision still detects the original 0.0028 error.
assert _area(solid) == pytest.approx(4 * math.pi, rel=1e-8)
assert _volume(solid) == pytest.approx(math.pi, rel=1e-9)
def test_reference_export_cannot_change_geometry_to_obtain_acceptance():
metrics = actual(reference_status="ok", reference_volume=1000,
symmetric_difference_volume=0, roundtrip_actual_volume=900,
roundtrip_actual_bbox=[-5, -5, 0, 5, 5, 10],
roundtrip_actual_solid_count=1, roundtrip_actual_valid=True)
row = compare_metrics(expected(), metrics, META, require_reference=True)
assert row["quality"] == "rejected"
assert "reference_roundtrip_changed_geometry" in row["reasons"]
@pytest.mark.parametrize("changes", [
{"b3d_status": "error"}, {"b3d_volume": None}, {"b3d_bbox": None},
{"solid_count": None}, {"result_refs": []}, {"b3d_volume": math.nan},
{"b3d_bbox": [0, 0, 0]}, {"unsupported": ["unsupported sweep"]},
])
def test_source_failure_or_missing_evidence_rejected(changes):
assert compare_metrics(expected(**changes), actual(), META)["quality"] == "rejected"
@pytest.mark.parametrize("metadata", [None, {}, {"status": "partial"},
{"status": "ok", "unsupported": ["torus"]},
{"status": "ok", "unknown": ["operation"]},
{"status": "ok", "unknown_operations": 1}])
def test_incomplete_conversion_never_accepted(metadata):
assert compare_metrics(expected(), actual(), metadata)["quality"] == "rejected"
@pytest.mark.parametrize("changes", [
{"body_count": 0}, {"solid_count": 2}, {"is_valid": False},
{"volume": None}, {"bbox": None}, {"volume": math.inf},
{"bbox": [0, -5, 0, 10, 5, 10]},
])
def test_actual_failure_including_rigid_translation_rejected(changes):
assert compare_metrics(expected(), actual(**changes), META)["quality"] == "rejected"
def write_case(root: Path, stem: str, source: str, trace=None, metadata=None):
ftc_dir, traces_dir = root / "ftc", root / "traces"
ftc_dir.mkdir(exist_ok=True)
traces_dir.mkdir(exist_ok=True)
ftc = ftc_dir / (stem + ".ftc.py")
ftc.write_text(source)
trace_path = traces_dir / (stem + ".trace.json")
trace_path.write_text(json.dumps(trace or expected()))
ftc.with_name(stem + ".meta.json").write_text(json.dumps(metadata or META))
return ftc, trace_path
def box_source(center_x=0):
return f'''from pathlib import Path
import simplecadapi as scad
BODIES = None
@scad.part(id='validation-box', project_root=Path(__file__).parent)
def build():
global BODIES
body = scad.make_box_rsolid(10, 10, 10, bottom_face_center=({center_x}, 0, 0))
BODIES = [body]
return body
'''
def test_worker_builds_real_topology_and_checks_position(tmp_path):
ftc, trace = write_case(tmp_path, "box", box_source())
row = validate_row(ftc, trace, timeout=30)
assert row["quality"] == "accepted", row
assert row["ftc_solid_count"] == 1
ftc.write_text(box_source(10))
row = validate_row(ftc, trace, timeout=30)
assert row["quality"] == "rejected", row
assert "bbox_mismatch" in row["reasons"]
def test_no_bodies_cannot_fall_back_to_returned_part(tmp_path):
source = box_source().replace("BODIES = [body]", "BODIES = []")
ftc, trace = write_case(tmp_path, "empty", source)
row = validate_row(ftc, trace, timeout=30)
assert row["quality"] == "rejected", row
assert "empty_bodies" in row["reasons"]
def test_timeout_and_build_failure_do_not_stop_batch(tmp_path):
write_case(tmp_path, "a_timeout", "import time\ntime.sleep(100)\n")
write_case(tmp_path, "b_failure", "raise RuntimeError('model failure')\n")
write_case(tmp_path, "c_good", box_source())
report = validate_directory(tmp_path / "ftc", tmp_path / "traces", timeout=8)
assert [row["quality"] for row in report["rows"]] == ["rejected", "rejected", "accepted"], report
assert report["rows"][0]["build"] == "timeout"
assert "model failure" in report["rows"][1]["error"]
def test_missing_trace_rejected_but_other_cases_continue(tmp_path):
ftc, trace = write_case(tmp_path, "a_missing", box_source())
trace.unlink()
write_case(tmp_path, "b_good", box_source())
report = validate_directory(ftc.parent, tmp_path / "traces", timeout=30)
assert report["counts"] == {"accepted": 1, "partial": 0, "rejected": 1}
def test_reference_step_detects_equal_volume_equal_bbox_different_holes(tmp_path):
from OCP.BRepAlgoAPI import BRepAlgoAPI_Cut
from OCP.BRepPrimAPI import BRepPrimAPI_MakeBox, BRepPrimAPI_MakeCylinder
from OCP.gp import gp_Pnt, gp_Ax2, gp_Dir
from OCP.STEPControl import STEPControl_Writer, STEPControl_AsIs
from OCP.IFSelect import IFSelect_RetDone
box = BRepPrimAPI_MakeBox(gp_Pnt(-5, -5, 0), 10, 10, 10).Shape()
hole = BRepPrimAPI_MakeCylinder(gp_Ax2(gp_Pnt(2, 0, 0), gp_Dir(0, 0, 1)), 1, 10).Shape()
reference = BRepAlgoAPI_Cut(box, hole).Shape()
step = tmp_path / "reference.step"
writer = STEPControl_Writer()
assert writer.Transfer(reference, STEPControl_AsIs) == IFSelect_RetDone
assert writer.Write(str(step)) == IFSelect_RetDone
source = box_source().replace("BODIES = [body]", "body = scad.cut_rsolid(body, scad.make_cylinder_rsolid(1, 10, bottom_face_center=(-2, 0, 0)))\n BODIES = [body]")
ftc, trace = write_case(tmp_path, "wrong_hole", source,
expected(b3d_volume=1000 - math.pi * 10))
coarse = validate_row(ftc, trace, timeout=30)
assert coarse["quality"] == "accepted", coarse
strict = validate_row(ftc, trace, timeout=30, reference_step=step)
assert strict["quality"] == "rejected", strict
assert "symmetric_difference_mismatch" in strict["reasons"]
assert strict["symmetric_difference_volume"] > 60
independent = validate_row(ftc, trace, timeout=30, reference_step=step,
reference_python=sys.executable)
assert independent["quality"] == "rejected", independent
assert independent["reference_kernel"]
assert "symmetric_difference_mismatch" in independent["reasons"]
ftc.write_text(source.replace("bottom_face_center=(-2, 0, 0)", "bottom_face_center=(2, 0, 0)"))
identical = validate_row(ftc, trace, timeout=30, reference_step=step,
reference_python=sys.executable)
assert identical["quality"] == "accepted", identical
assert identical["symmetric_difference_volume"] == pytest.approx(0)
def test_requested_missing_reference_rejected(tmp_path):
ftc, trace = write_case(tmp_path, "box", box_source())
row = validate_row(ftc, trace, timeout=30, reference_step=tmp_path / "absent.step")
assert row["quality"] == "rejected", row
assert "reference_error" in row["reasons"]
+124
View File
@@ -0,0 +1,124 @@
# build123d 0.13 API 与测试集调研
本调研针对工作区 `.venv` 中实际安装的 build123d 0.13.0,以及上层 `tests/manifest.json` 固定的 `v0.13.0`、提交 `38effd343e1508964673faf59300a5cc68fbedc1`。2026 年 10 月 7 日已联网核查对应版本的官方文档。清单是测试范围和实现检查表,不能当作已通过转换的声明。
## 完整公开入口清单
`api_coverage.json` 从实际安装包生成,包含以下范围:
| 范围 | 数量 | 含义 |
| --- | ---: | --- |
| 包 `__all__` 导出 | 203 | 官方顶层公开入口 |
| 公开成员定义 | 540 | 按定义所属类去重,含可达继承方法、属性与建模运算符 |
| 类接口 | 138 | 导出类,加上 Shape、几何维度 mixin、Builder、BaseObjectMeta |
| 工作区模型 | 50 | manifest 中全部模型,逐项记录调用位置统计 |
| 模型使用的顶层调用 | 50 种 | 已排除 `__main__` 导出代码和恒为 False 的文档生成分支 |
| 顶层调用位置 | 454 | 源码静态位置数量,循环次数和运行时内部调用未展开 |
顶层入口分类:32 个枚举,15 个常量或类型别名,3 个 builder,4 个位置阵列上下文,27 个曲线对象入口、15 个草图对象入口、11 个实体对象入口(均包含 Base 类),6 个图纸对象入口,23 个建模操作,12 个几何类入口,20 个直接拓扑入口,5 个装配关节,9 个导出入口,6 个导入入口,以及 15 个其他工具入口。
成员分类:40 个 `make_*` 等工厂、68 个直接特征方法、18 个变换方法、41 个代数运算符定义、4 个上下文生命周期方法、122 个属性,以及 247 个查询或工具方法。分类采用方法名和所属模块,不能替代逐方法的行为测试。底层 OCP/Python 标准类型的成员和下划线内部实现不算公开 API;专门列入了建模运算符。
重新生成:
```bash
.venv/bin/python simplecadapi/tools/research/build123dftc/research/inspect_api.py \
--manifest tests/manifest.json \
--output simplecadapi/tools/research/build123dftc/api_coverage.json
```
清单内每条入口有签名、定义文件与行号,类接口指向去重后的成员定义。`conversion_status: unverified` 表示尚未通过该接口的转换验证。后续覆盖报告应区分“识别入口”“真正生成 SimpleCAD 特征”“几何验证通过”,不要把成功执行源脚本等同于转换成功。
生成器也接受 `--validation-report` 和 `--traces-dir`。指定严格验收报告后,`verified_sampled_usage` 仅表示列出的模型中执行过该入口且模型验收通过。矩阵保留模型名单与报告 SHA256;其他参数、模式和未执行分支仍未验证。方法证据使用 trace 的实际 `source`,不会仅凭同名方法就把整个继承接口标为通过。最终验收报告更新后需重新生成矩阵。
## 捕获结构与可行的扩展方案
builder 与 algebra 是建模方式,Direct API 是两者共用的拓扑层;顶层入口捕获和底层特征捕获可以互补。[官方 Direct API 说明](https://build123d.readthedocs.io/en/v0.13.0/direct_api_reference.html)
当前实现选择 Direct API 层记录实体构造图,并在实体特征的输入边界转录草图轮廓。这覆盖两种建模方式,不需要改变 builder 的 Python frame。下文第一层是未来扩展原始对象/草图操作记录的方案,不是当前已实现的声明。`project / offset / make_hull` 等草图变化目前进入求解后的精确轮廓;不会逐项保留原草图操作。非平面 Face/Shell 曲面工厂、Vertex 终点放样以及清单中其他未验证 API 仍需单独检查,未支持构造必须显式报告。
### 第一层:可读的原建模操作
安装源码中 `build_common.BaseObjectMeta.__call__` 是全部内置 `BaseObject` 子类的统一入口。它能保留 `Box`、`Circle`、`Spline`、`Hole` 等原参数,也能接收自定义继承类;外层调用期间,内部建模需要防止被重复计入。23 个公开 operations 应全部登记。记录原参数以后,应展开 locations、默认参数以及隐式 pending faces/edges。
### 第二层:Direct API 特征与几何
工厂需要覆盖以下定义;方法会被继承,不能只包装 `Solid` 一种类:
- `Edge.make_bezier / make_circle / make_constrained_arcs / make_constrained_lines / make_ellipse / make_parabola / make_hyperbola / make_helix / make_line / make_mid_way / make_spline / make_bspline / make_spline_approx / make_tangent_arc / make_three_point_arc`。
- `Wire.make_circle / make_convex_hull / make_ellipse / make_polygon / make_rect`。
- `Face.make_bezier_surface / make_gordon_surface / make_rect / make_surface / make_surface_from_array_of_points / make_surface_from_curves / make_surface_patch / make_holes`。
- `Shell.make_loft`。
- `Solid.make_box / make_cone / make_cylinder / make_loft / make_sphere / make_torus / make_wedge`。
- `Compound.make_text / make_triad`。
- `Shape / Mixin1D / Mixin2D / Mixin3D / Edge / Wire / Face / Shell / Solid / Compound` 各自声明的 `extrude`;其中部分重载返回不同维度,不能假定都是 Solid。
- 3D 的 `extrude_taper / extrude_until / extrude_linear_with_rotation / revolve / sweep / sweep_multi / thicken / draft / fillet / chamfer / hollow / offset_3d / dprism`。
- 2D/1D 的 `offset / offset_2d / fillet_2d / chamfer_2d / trim* / project* / split* / close / stitch / combine / wrap*`。
对于没有 SimpleCAD 同名原语的曲线构造(如受约束圆弧、Airfoil、BlendCurve),可把求解后的单条曲线分解为解析参数或精确 BSpline 定义,再以 SimpleCAD 曲线原语重建。需保留 poles、degree、weights、knots、multiplicities、periodic,以及区间/方向。这个方法保留草图和后续特征,而不是把最终实体导入当作转换。
### 第三层:组合、位置与查询
布尔定义分布在 `Shape`、`Compound` 与 `Mixin1D`。1D 的加法可能得到 Wire/Curve,不能按 3D union 发射。`Shape` 的 `fuse / cut / intersect` 是 builder 和 algebra 实际共用的接口,应按几何维度分派。
`Location.__mul__` 对 Shape 实际调用 `other.moved(self)`,`Plane.__mul__` 也进入位置变换。因此包装 `Shape.moved` 后已经能捕获大多数 algebra placement 和 builder 发布,不必再重复包装 `*`。`move / locate / location.setter` 是原位变更;`moved / located` 返回副本。原位变更应建立新节点,保留变更前的输入节点。`translate / rotate / scale / mirror / transformed / transform_shape / transform_geometry` 也需覆盖。
查询 API 大多数不用发射新的 FTC 操作,但查询结果必须用于源脚本继续执行。边/面选择器的结果应关联已有特征,再记录指纹或索引;不能把选中边的 repr 当作可重放参数。曲线的 `@ / % / ^` 分别参与求值和位置计算,记录最终 Vector/Location 参数即可。枚举、单位、字体和颜色也应有稳定的序列化。
## 0.13 builder 语义的两个关键陷阱
所有 builder 先在自身 XY 局部坐标中构造。`output_placements` 只在输出或退出后统一应用。对象构造时使用的 `Locations` 属于局部位置;builder 发布时另有外层 `publication_locations`。两种位置不能重复应用,尤其是嵌套 BuildPart、BuildSketch、BuildLine 和多个 face placement。[官方 builder 位置说明](https://build123d.readthedocs.io/en/v0.13.0/key_concepts_builder.html)
本地源码 `Builder.__enter__` 用 Python frame 判断当前 builder 与父 builder 是否同一作用域。直接加 `__enter__` 或 `__init__` 包装函数会改变 frame,可能把嵌套 builder 误判为无父级。优先捕获 `_add_to_context`、`_PublicationService.place/publish`;如必须包装 enter/init,要保持原同作用域判定的含义,并测试函数内返回私有草图这种有意隔离的情况。
`Builder._add_to_context` 中拿到的 shapes 是 builder 的局部坐标,不能称为全局坐标。此处同时维护累计几何、pending faces/edges 和 Select.LAST/NEW 的变化历史。对截面依赖引用、用于扫掠的独立路径、多个离散实体,需要保留输入依赖图。
## 50 个模型真正考验的能力
最常出现的静态调用:BuildSketch 57,BuildPart 55,extrude 40,Circle 29,Rectangle 25,Locations 23,Box/Line 各 18,BuildLine 16,fillet 15,RegularPolygon 14,GridLocations 11,Plane 10。完整逐模型统计见 JSON。
以下模型需要独立回归,避免简单盒子通过造成覆盖错觉:
| 模型 | 关键行为 |
| --- | --- |
| 09、10、11、18、29、45、46、47 | 边/面选择、3D 圆角与倒角、修改后的选择指纹 |
| 12、30、40、46、47 | 样条、Bezier、端点切向量、非直线轮廓及扫掠 |
| 13、41、49 | 普通孔、沉孔、锥孔、负向深度、自动贯穿深度、多位置 |
| 14、39、40、46、50 | pending 路径/截面、扫掠参数、曲线起点坐标系 |
| 16、17、20、21、22、24、27、37、38、43 | 不同 workplane、嵌套位置、旋转、偏移与 builder 发布 |
| 19、31、32、33、42、48 | 循环/函数生成阵列,以及源查询决定下一操作参数 |
| 23、29、44、46、47 | 旋转、放样、壁厚偏置、开口选择、多截面 |
| 34 | Text 的字体形状与字内孔,不能只重建外轮廓 |
| 36 | `extrude(until=Until.*)`,限界对象与方向 |
| 45 | section、面内孔与比例缩放 |
| 49 | 四个彼此独立的 BuildPart 输出组合为 Compound |
| 50 | 完全 algebra 模型:Helix、`path ^ 0`、位置相乘、显式 sweep 参数 |
源码中被禁用的 SVG 文档导出和 `__main__` STEP 输出不属于建模转换测试,但导入/导出公开入口仍列在 API 清单。清单中的矩阵、关节、图纸类和未被这 50 个模型使用的几何操作,应通过额外小型行为用例逐项验证;50 个模型不等于全部 API 覆盖。
## SimpleCAD 对应关系与几何验证
现有目标原语已提供:线/圆/椭圆/三点圆弧/角度圆弧/精确样条/插值样条/螺旋、wire/face 构造、草图 2D 布尔、3D 原语、3D 布尔、拉伸/旋转/放样/扫掠、圆角/倒角/抽壳,以及曲面构造。可优先复用 `operators/geometry.py`、`features.py`、`boolean.py`、`transform.py` 和 cqftc 的选择指纹与重放模式。
每个测试应同时检查操作结构与几何:FTC 内必须存在实际构造特征和输入依赖,执行生成脚本时不依赖 build123d;体积、包围盒、实体数量和有效性应该与源模型一致。只有体积相同无法证明孔位置和姿态正确,建议再比较差集体积或对称差集,并在拓扑变化时用几何指纹选择。基准来源是执行源脚本所得结果或 manifest 的 STEP,不能把待检 FTC 的结果本身作为基准。
验收工具已实现独立进程与超时隔离,缺少指标、源执行失败、空 BODIES、无效实体、转换元数据中的 unsupported/unknown 都会拒绝。包围盒比较六个世界坐标而非仅比较尺寸。体积与 STEP 差集使用 `VolumePropertiesGK_s(..., Eps=1e-9, OnlyClosed=True, IsUseSpan=True)`;有理 BSpline 使用默认积分或普通自适应积分可能产生明显误差,所以源与目标必须用同一定义。
模型 28 揭示了内核差异:OCP 7.9 对实际形状与基准 STEP 的共同内部点判为 IN,却把 Common 计算为空、双向 Cut 留下全部体积。标准 ShapeFix 和微小 fuzzy 未解决。实际形状重新导出 STEP 后,独立 OCP 8.0.1.1 求得 Common 等于完整体积、双向 Cut 都为空。可选 `--reference-python` 因此让 FTC 在 SimpleCAD 环境中构建,同时在指定独立内核进程中对 STEP 做差集。实际 STEP 的读回体积、包围盒、有效性与实体数量也必须与 FTC 真实 BODIES 一致,验收门槛不变,报告记录两个内核与积分方法。
面积计算在独立的几何深拷贝上先按 C1 连续性切分积分区间,再用明确 `Eps` keyword 的自适应积分;不修改实际 FTC 或 STEP。半径 1、高度 1 的精确有理 BSpline 圆柱有面积 `4π`、体积 `π` 的独立数学测试。OCP 7.9 的测量区间切分在该例有约 `7.7e-9` 相对误差,数学测试精度为 `1e-8`,整模型验收门槛保持原值。
参考 STEP 的临时实际导出使用 trace `source_metadata.export_options` 中声明的参数曲线与精度模式;没有声明时用标准 `True / AVERAGE`。差集布尔在首次 Build 前统一使用输入实际 BRep 顶点/边容差与内核 `Precision.Confusion` 的最大值,记录该值,不逐级尝试容差。差集必须有效并通过原体积门槛。模型 46 的当前记录表明即使匹配 `False / GREATEST` 并使用该固定规则,跨内核差集仍可能无效;这种情况会报告 `reference_error`,不会将基础指标通过冒充严格 STEP 匹配通过。
验收 CLI 有任何 rejected/partial 或没有可验收案例时返回退出码 1,所有案例 accepted 才返回 0;NaN、Inf 与非正 timeout 会作为参数错误拒绝,报告仍保存每例拒绝原因。
确实不能转换的入口应报出明确 API 名、源位置与原因。允许用户显式选择近似曲线时,应报告近似误差并保持后续特征可修改。最终 BRep/STEP 导入只能作为明确标记的外部几何来源,不能用它把未覆盖操作伪装成成功 FTC 转换。
## 官方核查来源
- [Objects](https://build123d.readthedocs.io/en/v0.13.0/objects.html)
- [Operations](https://build123d.readthedocs.io/en/v0.13.0/operations.html)
- [Builder concepts](https://build123d.readthedocs.io/en/v0.13.0/key_concepts_builder.html)
- [Algebra concepts](https://build123d.readthedocs.io/en/v0.13.0/key_concepts_algebra.html)
- [Direct API reference](https://build123d.readthedocs.io/en/v0.13.0/direct_api_reference.html)
- [固定测试集上游提交](https://github.com/gumyr/build123d/tree/38effd343e1508964673faf59300a5cc68fbedc1)
+35
View File
@@ -0,0 +1,35 @@
# 工作区 50 个模型实测
日期:2026-10-07。输入为相邻工作区 `tests/manifest.json` 中的 50 个官方
build123d 模型,版本 0.13.0,源内核 OCP 8.0.1.1;FTC 在
SimpleCADAPI 2.2.0b1 / OCP 7.9.3.1 中构建,参考 STEP 在独立 OCP 8 环境对账。
运行命令见 [README.md](README.md)。
| 检查 | 结果 |
| --- | --- |
| 源模型执行、特征图捕获 | 50 / 50,未识别实体操作 0 |
| FTC 源码生成 | 50 / 50,410 个特征,无未翻译记录 |
| FTC 实际构建、内核有效性、实体数量 | 50 / 50 |
| 体积、表面积、世界包围盒 | 50 / 50 |
| 加入参考 STEP 双向差集的严格验收 | 49 / 50 |
所有模型的最大相对体积误差为 `1.492e-6`,最大面积误差为 `1.092e-6`,
最大包围盒误差(相对于对应轴跨度)为 `2.778e-9`。均远低于 `1e-3` 的
验收阈值。原始报告在本机 `out/validate.json`,逐模型源码在 `out/ftc`,
输入特征图在 `out/traces`。这些运行产物被 Git 忽略。
模型 `46_tea_cup` 构建成功且全部基础几何检查通过,体积相对误差约
`1.45e-9`、世界包围盒一致。独立参考内核的 STEP 双向差集计算仍生成无效
拓扑,因此保留 `reference_error`,严格验收判为拒绝。没有跳过该模型、
改变差集门槛或把无效差集当作零。报告同时给出 `metrics_quality=accepted`
与 `quality=rejected`,批量 CLI 在这次严格验收中返回 1。
测试按先写断言再实现的方式推进,相关回归包括真实捕获、格式、几何、未知
API、孤立进程崩溃、超时、同体积/同包围盒但孔位不同的反例、图重放以及
既有 CQ / WHUCAD、草图、QL 测试。295 项相关用例通过,另有 35 个子测试。
六个真实图 fixture 保存在 `test/build123d_traces`,普通 CI 不需要 build123d。
203 个顶层导出、540 个去重公开成员的清单与样例证据在 `api_coverage.json`。
标为 `verified_sampled_usage` 的条目仅说明相应已验收样例使用过该 API,
不代表其全部参数组合或全部公开 API 都已通过转换。复杂曲面构造等未接入
边界在 [API_RESEARCH.md](API_RESEARCH.md) 和转换 meta 中明确列出。
+147
View File
@@ -0,0 +1,147 @@
# build123d → FTC 转换工具
把真实执行的 build123d 模型转换成本仓库现行 FTC Python:显式草图、实体
特征、布尔和 QL 修改选择。组织方式沿用 `tools/research/cadqueryftc`,转换
与验收分开。支持 Builder、代数写法及已接入的底层实体 API。
```text
trusted model.py → build123d_trace.py → trace.json
trace.json → build123d_to_ftc.py → ftc.py + meta.json + sketches.json
ftc.py + trace.json [+ reference STEP] → build123d_validate.py → validate.json
trace.json → build123d_profile.py → profile.json
```
捕获执行模型的 Python;只对可信源文件运行。模型的 `__main__` 分支不会运行,
可在顶层将最终形状绑定为 `result`。捕获和验收分别在隔离子进程执行,设置
超时,一例失败仍处理后续文件。
## 环境
本次实测为 Python 3.12、build123d 0.13.0 / OCP 8.0.1.1,以及
SimpleCADAPI 2.2.0b1 / OCP 7.9.3.1。两个内核的绑定不能混装在同一环境:
```bash
# 在 SimpleCADAPI 仓库根目录运行。环境放在相邻工作区。
uv venv ../.venv --python 3.12
uv pip install --python ../.venv/bin/python 'build123d==0.13.0'
uv venv ../.venv-sca --python 3.12
uv pip install --python ../.venv-sca/bin/python -e . 'cadquery-ocp==7.9.3.1' pytest
```
已有环境无需重建。翻译阶段是纯 Python,不导入 build123d 或 CAD 内核;启用
约束恢复时才加载现有 CQ 的求解器。
## 单模型
```bash
../.venv/bin/python tools/research/build123dftc/build123d_trace.py \
--input ../tests/models/01_rectangular_plate.py \
--out tools/research/build123dftc/out/traces
../.venv-sca/bin/python tools/research/build123dftc/build123d_to_ftc.py \
--trace tools/research/build123dftc/out/traces/01_rectangular_plate.trace.json \
--out tools/research/build123dftc/out/ftc
../.venv-sca/bin/python tools/research/build123dftc/build123d_validate.py \
--ftc-dir tools/research/build123dftc/out/ftc \
--traces-dir tools/research/build123dftc/out/traces \
--report tools/research/build123dftc/out/validate.json
```
`--constraints on` 从实际草图恢复推断约束,复用 `cqftc.constraints`。只有生产
求解器确认坐标复现才插入约束;约束 ID 标记推断出处。椭圆、样条及耗时超限
的草图在 `constraint_recovery` 中明确记录状态,其精确几何仍保留。
## 工作区 50 个模型
```bash
../.venv/bin/python tools/research/build123dftc/build123d_trace.py \
--manifest ../tests/manifest.json \
--out tools/research/build123dftc/out/traces --timeout 180
../.venv-sca/bin/python tools/research/build123dftc/build123d_to_ftc.py \
--traces-dir tools/research/build123dftc/out/traces \
--out tools/research/build123dftc/out/ftc
../.venv-sca/bin/python tools/research/build123dftc/build123d_validate.py \
--ftc-dir tools/research/build123dftc/out/ftc \
--traces-dir tools/research/build123dftc/out/traces \
--reference-step-dir ../tests/step --reference-python ../.venv/bin/python \
--report tools/research/build123dftc/out/validate.json --timeout 180
../.venv-sca/bin/python tools/research/build123dftc/build123d_profile.py \
--traces-dir tools/research/build123dftc/out/traces \
--report tools/research/build123dftc/out/profile.json
```
也可用 `--inputs-dir` 处理目录中的 `.py` 文件,或用 `--input` 指定一个模型。
每个模型产生 `.trace.json`、执行日志、`.ftc.py`、`.meta.json` 和
`.sketches.json`。批量验收报告保留所有模型,缺少转换结果也计入失败。
## 验收依据
- 实际执行 FTC,检查非空实体、内核有效性、体积、表面积和实体数量。
- 比较世界坐标中的六个包围盒边界;同尺寸但位置错误会失败。
- 指定参考 STEP 时,要求两个方向几何差集的总体积通过检查。
- `--reference-python` 让参考几何对账在指定内核执行,FTC 仍在
SimpleCADAPI 环境构建。报告记录两个内核版本,并检查 STEP 导出往返的
体积、包围盒、有效性和实体数。
- 体积使用按样条节点区间计算的 Gauss–Kronrod 积分。普通固定阶积分对有理
样条有明显误差,还会在某些非均匀缩放后的裁剪曲面上崩溃。
面积只在独立副本上切开不连续的曲面参数区间,再做自适应积分;原始模型和
拓扑保持不变。参考导出沿用 manifest 声明的参数曲线与精度选项,布尔对账
采用输入已有的内核容差,报告保留这些设置。
阈值为体积、面积和包围盒相对误差 `1e-3`,另有绝对误差保护;STEP 双向
差集体积相对误差 `1e-3`。源执行失败、缺指标、未知操作、翻译不完整和空实体
都不会判为通过。验收通过是给定输入在这些阈值下的结果。`metrics_quality`
单独报告基础几何检查;要求 STEP 对账时,任何参考计算失败仍会使
`quality` 为拒绝,且 CLI 返回非零。工作区实测结果见 [BENCHMARK.md](BENCHMARK.md)。
模型 28 的重合球面在 OCP 7.9 中出现错误的空交集;相同几何在 OCP 8 的
严格双向差集为零。因此上述工作区命令使用独立的 OCP 8 参考环境。
## 转换结构和覆盖
`b3ftc/tracer.py` 在真实底层实体构造、布尔、修改和变换边界捕获操作图。
所有已执行的草图对象与查询仍由 build123d 计算,在实体特征的输入处转录
实际轮廓。JSON 保存参数、世界坐标、精确曲线控制数据和拓扑指纹,不保存
最终实体 BRep。`profiles.py`、`emit.py`、`replay.py` 分别负责轮廓、格式和
实体数据流;外部验收位于 `validation.py` 及独立 worker。
当前支持盒、圆柱、圆锥、球、完整圆环及部分原语;拉伸、带拔模角拉伸、
限界拉伸、扭转拉伸、旋转、放样、单/多截面扫掠;布尔、圆角、倒角、拔模、
双向实体偏移与抽壳、平面分割、刚体与一般仿射变换、多实体组合。
草图支持直线、圆弧、圆、椭圆、精确有理 B 样条与闭合/周期样条;曲线型
文字及三维路径使用实际曲线控制数据。多实体输出为完整 `@scad.assemble`。
生成代码使用现行 FTC 块头、几何档标注、keyword 实参、QL 谓词和基数。
数字来源于实际调用,不虚构参数名。动态追踪只描述执行到的路径;输出不会
保留未执行的分支,也不承诺恢复源草图的约束或全部表达式。
**API 清单不等于全部 API 转换已通过验证。** `api_coverage.json` 和
`API_RESEARCH.md` 梳理了 203 个顶层导出、540 个去重公开成员和 138 个类。
查询、布局和多数草图 API 通过实际求值再转录轮廓覆盖;非平面曲面构造、
原生内核直接包装等未接入的实体构造、部分圆环截面、特殊扫掠模式、复杂孔
拓扑变化等仍有明确边界。未知节点会阻断依赖它的后续特征,并写入 meta,
不会导入最终模型作为替代。完整清单可重生:
```bash
../.venv/bin/python tools/research/build123dftc/research/inspect_api.py --help
```
## 回归测试
`test/build123d_traces` 保留真实捕获的轮廓、修改、镜像、文字和螺旋扫掠
fixture,并带出处。普通 FTC 测试不依赖 build123d;执行捕获测试在其专用
环境运行。
```bash
../.venv/bin/python -m pytest test/test_build123d_trace.py test/test_build123d_unknown_api.py -q
../.venv-sca/bin/python -m pytest \
test/test_build123d_cli.py test/test_build123d_translation_output.py \
test/test_build123d_validation.py test/test_deformation_features.py \
test/test_section_features.py test/test_limited_extrusion.py \
test/test_rational_volume_precision.py test/test_sketch_closed_bspline.py -q
```
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,44 @@
"""Compare two STEP files in an independently selected OCCT environment."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from _validate_worker import _compare_reference, _read_step, _solid_count, _volume
def run(actual_step, reference_step):
import OCP
from OCP.Bnd import Bnd_Box
from OCP.BRepBndLib import BRepBndLib
actual = _read_step(actual_step)
bounds = Bnd_Box()
BRepBndLib.AddOptimal_s(actual, bounds, False, False)
low, high = bounds.CornerMin(), bounds.CornerMax()
bbox = [float(getattr(point, axis)()) for point in (low, high) for axis in "XYZ"]
return {"status": "ok", **_compare_reference([actual], reference_step),
"reference_kernel": getattr(OCP, "__version__", "unknown"),
"roundtrip_actual_volume": _volume(actual),
"roundtrip_actual_bbox": bbox,
"roundtrip_actual_solid_count": _solid_count(actual),
"roundtrip_actual_valid": True}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--actual-step", type=Path, required=True)
parser.add_argument("--reference-step", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
try:
result = run(args.actual_step, args.reference_step)
except Exception as exc:
result = {"status": "reference_error", "reference_status": "error",
"reference_error": f"{type(exc).__name__}: {exc}"}
args.output.write_text(json.dumps(result, ensure_ascii=False, allow_nan=False) + "\n")
return 0 if result["status"] == "ok" else 1
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,13 @@
"""Private process boundary. Model output goes to the parent's log, not JSON."""
import json
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from b3ftc.tracer import trace_file
if __name__ == "__main__":
source, output = map(Path, sys.argv[1:])
payload = trace_file(source)
output.write_text(json.dumps(payload, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8")
@@ -0,0 +1,260 @@
"""Isolated CAD worker; communicates only through an explicit JSON file."""
from __future__ import annotations
import argparse
import importlib.util
import json
import math
from pathlib import Path
import shutil
import traceback
import uuid
def _volume(shape):
if not _solid_count(shape):
from OCP.TopAbs import TopAbs_FACE
from OCP.TopExp import TopExp_Explorer
if TopExp_Explorer(shape, TopAbs_FACE).More():
raise ValueError("volume result has faces but no closed solid")
return 0.0
from OCP.BRepGProp import BRepGProp
from OCP.GProp import GProp_GProps
properties = GProp_GProps()
error = BRepGProp.VolumePropertiesGK_s(shape, properties, 1e-9, True, True)
if error < 0:
raise ValueError("Gauss-Kronrod volume integration failed")
return float(properties.Mass())
def _area(shape):
from OCP.BRepGProp import BRepGProp
from OCP.BRepBuilderAPI import BRepBuilderAPI_Copy
from OCP.GeomAbs import GeomAbs_C1
from OCP.GProp import GProp_GProps
from OCP.ShapeUpgrade import ShapeUpgrade_ShapeDivideContinuity
# Integration must respect C0 knot boundaries. Work on independent geometry
# so this numerical conditioning never changes the FTC or exported STEP.
copied = BRepBuilderAPI_Copy(shape, True, False).Shape()
divide = ShapeUpgrade_ShapeDivideContinuity(copied)
divide.SetSurfaceCriterion(GeomAbs_C1)
divide.SetBoundaryCriterion(GeomAbs_C1)
divide.SetPCurveCriterion(GeomAbs_C1)
divide.Perform()
measurement = divide.Result()
if measurement.IsNull():
raise ValueError("surface integration continuity split produced no shape")
properties = GProp_GProps()
BRepGProp.SurfaceProperties_s(S=measurement, SProps=properties, Eps=1e-10, SkipShared=False)
return float(properties.Mass())
def _solid_count(shape):
from OCP.TopAbs import TopAbs_SOLID
from OCP.TopExp import TopExp_Explorer
explorer = TopExp_Explorer(shape, TopAbs_SOLID)
count = 0
while explorer.More():
count += 1
explorer.Next()
return count
def _read_step(step):
from OCP.BRepCheck import BRepCheck_Analyzer
from OCP.IFSelect import IFSelect_RetDone
from OCP.STEPControl import STEPControl_Reader
if not step.is_file():
raise FileNotFoundError(f"reference STEP does not exist: {step}")
reader = STEPControl_Reader()
if reader.ReadFile(str(step)) != IFSelect_RetDone or reader.TransferRoots() == 0:
raise ValueError("reference STEP could not be read")
reference = reader.OneShape()
if reference.IsNull() or not BRepCheck_Analyzer(reference).IsValid() or not _solid_count(reference):
raise ValueError("reference STEP contains no valid solids")
from OCP.BRepClass3d import BRepClass3d_SolidClassifier
from OCP.TopAbs import TopAbs_SOLID, TopAbs_OUT
from OCP.TopExp import TopExp_Explorer
explorer = TopExp_Explorer(reference, TopAbs_SOLID)
while explorer.More():
classifier = BRepClass3d_SolidClassifier(explorer.Current())
classifier.PerformInfinitePoint(1e-7)
if classifier.State() != TopAbs_OUT:
raise ValueError("reference STEP solid orientation includes the infinite exterior")
explorer.Next()
return reference
def _compare_reference(shapes, step):
from OCP.BRepAlgoAPI import BRepAlgoAPI_Cut, BRepAlgoAPI_Fuse
from OCP.BRepCheck import BRepCheck_Analyzer
reference = _read_step(step)
# Treat BODIES as a geometric set. Fuse disjoint bodies too, avoiding double
# counting overlap when comparing a multi-body result to STEP assemblies.
actual = shapes[0]
for shape in shapes[1:]:
fusion = BRepAlgoAPI_Fuse(actual, shape)
fusion.Build()
if not fusion.IsDone():
raise ValueError("could not combine actual bodies for comparison")
actual = fusion.Shape()
tolerance = _kernel_tolerance(actual, reference)
# Configure before the first Build: the two-shape constructor would already
# run the intersection and retain a pave filler computed at default tolerance.
missing = _cut(reference, actual, tolerance)
extra = _cut(actual, reference, tolerance)
for operation in (missing, extra):
if not operation.IsDone() or operation.Shape().IsNull():
return {"reference_status": "error", "reference_error": "STEP symmetric difference failed",
"reference_boolean_fuzzy_tolerance": tolerance}
if not BRepCheck_Analyzer(operation.Shape()).IsValid():
return {"reference_status": "error", "reference_error": "STEP symmetric difference produced invalid topology",
"reference_boolean_fuzzy_tolerance": tolerance}
return {"reference_status": "ok", "reference_volume": _volume(reference),
"reference_boolean_fuzzy_tolerance": tolerance,
"symmetric_difference_volume": abs(_volume(missing.Shape())) + abs(_volume(extra.Shape()))}
def _cut(left, right, tolerance):
from OCP.BRepAlgoAPI import BRepAlgoAPI_Cut
try:
from OCP.TopTools import TopTools_ListOfShape as ShapeList
except ImportError:
from OCP.collections import List_TopoDS_Shape as ShapeList
arguments, tools = ShapeList(), ShapeList()
arguments.Append(left)
tools.Append(right)
operation = BRepAlgoAPI_Cut()
operation.SetArguments(arguments)
operation.SetTools(tools)
operation.SetNonDestructive(True)
operation.SetFuzzyValue(tolerance)
operation.Build()
return operation
def _kernel_tolerance(*shapes):
from OCP.BRep import BRep_Tool
from OCP.Precision import Precision
from OCP.TopAbs import TopAbs_VERTEX, TopAbs_EDGE
from OCP.TopExp import TopExp_Explorer
from OCP.TopoDS import TopoDS
tolerance = float(Precision.Confusion_s())
for shape in shapes:
for kind, name in ((TopAbs_VERTEX, "Vertex"), (TopAbs_EDGE, "Edge")):
cast = getattr(TopoDS, name + "_s", None) or getattr(TopoDS, name)
explorer = TopExp_Explorer(shape, kind)
while explorer.More():
value = float(BRep_Tool.Tolerance_s(cast(explorer.Current())))
if not math.isfinite(value) or value < 0:
raise ValueError("invalid reference geometry tolerance")
tolerance = max(tolerance, value)
explorer.Next()
return tolerance
def _export_step(shapes, path, options=None):
from OCP.STEPControl import STEPControl_Writer, STEPControl_AsIs
from OCP.Interface import Interface_Static
from OCP.IFSelect import IFSelect_RetDone
writer = STEPControl_Writer()
options = options or {}
pcurves = options.get("write_pcurves", True)
precision = options.get("precision_mode", "AVERAGE")
modes = {"AVERAGE": 0, "GREATEST": 1, "LEAST": -1, "SESSION": 2}
if not isinstance(pcurves, bool) or precision not in modes:
raise ValueError("invalid source STEP export options")
# Honor the declared corpus export contract: spherical seams retain their
# UV curves; freeform sweeps can explicitly request rebuilding on import.
if not Interface_Static.SetIVal_s("write.surfacecurve.mode", int(pcurves)):
raise ValueError("could not configure STEP parameter-curve export")
if not Interface_Static.SetIVal_s("write.precision.mode", modes[precision]):
raise ValueError("could not configure STEP precision mode")
for shape in shapes:
if writer.Transfer(shape, STEPControl_AsIs) != IFSelect_RetDone:
raise ValueError("could not transfer actual geometry for external comparison")
if writer.Write(str(path)) != IFSelect_RetDone:
raise ValueError("could not export actual geometry for external comparison")
return {"write_pcurves": pcurves, "precision_mode": precision,
"rebuild_pcurves_on_import": not pcurves}
def run(ftc_path, staging_dir, reference_step=None, export_step=None, export_options=None):
import OCP
from OCP.Bnd import Bnd_Box
from OCP.BRepBndLib import BRepBndLib
from OCP.BRepCheck import BRepCheck_Analyzer
from OCP.TopoDS import TopoDS_Shape
# An isolated path keeps imports/artifacts away from original outputs and
# provides a fresh module/global BODIES namespace on every validation.
staged = staging_dir / (ftc_path.stem + "_" + uuid.uuid4().hex + ".py")
shutil.copyfile(ftc_path, staged)
spec = importlib.util.spec_from_file_location("ftc_validation_" + uuid.uuid4().hex, staged)
if spec is None or spec.loader is None:
raise ValueError("cannot import FTC module")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
build = getattr(module, "build", None)
if not callable(build):
raise ValueError("FTC module must define callable build()")
build()
bodies = getattr(module, "BODIES", None)
if not isinstance(bodies, (list, tuple)) or not bodies:
return {"status": "ok", "body_count": 0, "solid_count": 0,
"is_valid": False, "volume": None, "bbox": None}
shapes = []
for index, body in enumerate(bodies):
wrapped = getattr(body, "wrapped", None)
if not isinstance(wrapped, TopoDS_Shape) or wrapped.IsNull():
raise ValueError(f"BODIES[{index}] is not actual nonempty CAD topology")
if _solid_count(wrapped) < 1:
raise ValueError(f"BODIES[{index}] contains no solid")
shapes.append(wrapped)
bounds = Bnd_Box()
for shape in shapes:
BRepBndLib.AddOptimal_s(shape, bounds, False, False)
volume = sum(_volume(shape) for shape in shapes)
low, high = bounds.CornerMin(), bounds.CornerMax()
bbox = [float(getattr(point, axis)()) for point in (low, high) for axis in "XYZ"]
if not math.isfinite(volume) or not all(map(math.isfinite, bbox)):
raise ValueError("nonfinite actual geometry metrics")
result = {"status": "ok", "body_count": len(bodies),
"solid_count": sum(_solid_count(shape) for shape in shapes),
"is_valid": all(BRepCheck_Analyzer(shape).IsValid() for shape in shapes),
"volume": volume, "area": sum(_area(shape) for shape in shapes), "bbox": bbox,
"build_kernel": getattr(OCP, "__version__", "unknown"),
"volume_method": "Gauss-Kronrod, epsilon=1e-9, closed shells, BSpline spans",
"area_method": "Independent geometry copy, C1 continuity spans, adaptive epsilon=1e-10"}
if reference_step is not None:
try:
result.update(_compare_reference(shapes, reference_step))
except Exception as exc:
result.update(reference_status="error", reference_error=f"{type(exc).__name__}: {exc}")
if export_step is not None:
try:
result["reference_export_options"] = _export_step(shapes, export_step, export_options)
except Exception as exc:
result.update(reference_status="error", reference_error=f"{type(exc).__name__}: {exc}")
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--ftc", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--staging-dir", type=Path, required=True)
parser.add_argument("--reference-step", type=Path)
parser.add_argument("--export-step", type=Path)
parser.add_argument("--export-options", type=json.loads)
args = parser.parse_args()
try:
result = run(args.ftc, args.staging_dir, args.reference_step, args.export_step, args.export_options)
except BaseException as exc:
result = {"status": "build_error", "error": f"{type(exc).__name__}: {exc}",
"traceback": traceback.format_exc(limit=5)}
args.output.write_text(json.dumps(result, ensure_ascii=False, allow_nan=False) + "\n")
return 0 if result.get("status") == "ok" else 1
if __name__ == "__main__":
raise SystemExit(main())
+140
View File
@@ -0,0 +1,140 @@
"""Deterministic FTC formatting and topology-fingerprint QL selectors.
This module has no CAD dependency: generated programs use only SimpleCADAPI.
"""
from __future__ import annotations
import math
import re
from typing import Any, Mapping, Sequence
ROLES = frozenset({'build', 'add', 'subtract', 'intersect', 'modify', 'pattern', 'annotate'})
def fmt_num(value: float) -> str:
number = float(value)
if not math.isfinite(number):
raise ValueError('non-finite geometry parameter')
if abs(number) < 1e-12:
number = 0.0
return format(number, '.15g')
def fmt_vec(vector: Sequence[float]) -> str:
return '(' + ', '.join(fmt_num(v) for v in vector) + (',' if len(vector) == 1 else '') + ')'
def fmt_literal(value: Any) -> str:
if value is None or isinstance(value, (bool, str)):
return repr(value)
if isinstance(value, (int, float)):
return fmt_num(value)
if isinstance(value, (list, tuple)):
return '[' + ', '.join(fmt_literal(v) for v in value) + ']'
if isinstance(value, Mapping):
return '{' + ', '.join(repr(k) + ': ' + fmt_literal(v) for k, v in value.items()) + '}'
raise ValueError(f'unsupported literal type: {type(value).__name__}')
class SlugAllocator:
def __init__(self) -> None:
self.counts: dict[str, int] = {}
def allocate(self, name: str) -> str:
slug = re.sub('[^a-z0-9]+', '-', str(name).lower()).strip('-') or 'feature'
count = self.counts.get(slug, 0) + 1
self.counts[slug] = count
return slug if count == 1 else f'{slug}-{count}'
def block_header(slug: str, role: str, tiers: Sequence[str] = ()) -> str:
if role not in ROLES:
raise ValueError(f'invalid FTC role: {role}')
return f" # ---- feature: {slug} ({', '.join([role, *tiers])}) ----"
def fingerprint_selector(fingerprints: Sequence[Mapping[str, Any]], kind: str, tolerance: float = 1e-4) -> str:
"""Union individual fingerprint predicates; never select a wide bounding band.
Each traced edge/face gets its own conjunction. This preserves a disjoint
selected set whose bounding box could otherwise include unrelated topology.
"""
predicates = []
seen = set()
for fp in fingerprints:
if fp.get('kind', kind) != kind:
continue
terms = []
geom_type = fp.get('geom_type') or fp.get('type')
if geom_type:
terms.append(f"ql.prop('geom.type', '==', {str(geom_type).upper()!r})")
for name in ('center', 'normal'):
values = fp.get(name)
if values is not None:
for axis, value in zip('xyz', values):
tolerance_here = 1e-5 if name == 'normal' else tolerance
value = round(float(value), 10)
terms.extend([
f"ql.prop('geom.{name}.{axis}', '>=', {fmt_num(value - tolerance_here)})",
f"ql.prop('geom.{name}.{axis}', '<=', {fmt_num(value + tolerance_here)})",
])
for name in ('length', 'area', 'radius'):
if (kind == 'edge' and name == 'area') or (kind == 'face' and name == 'length'):
continue
if fp.get(name) is not None:
value = float(fp[name])
delta = max(tolerance, abs(value) * 1e-8)
terms.extend([
f"ql.prop('geom.{name}', '>=', {fmt_num(value - delta)})",
f"ql.prop('geom.{name}', '<=', {fmt_num(value + delta)})",
])
if not terms:
raise ValueError(f'{kind} selection lacks geometric fingerprints')
predicate = 'ql.and_(' + ', '.join(terms) + ')'
if predicate not in seen:
seen.add(predicate)
predicates.append(predicate)
if not predicates:
raise ValueError(f'{kind} selection is empty')
combined = predicates[0] if len(predicates) == 1 else 'ql.or_(' + ', '.join(predicates) + ')'
count = len([fp for fp in fingerprints if fp.get('kind', kind) == kind])
return f'ql.{kind}s().where({combined}).take({count}).exactly({count})'
def emit_module(stem: str, lines: Sequence[str], refs: Sequence[str], unsupported: Sequence[str], uses_ql: bool, solid_count: int = 1) -> str:
part_id = 'b3d-' + (re.sub('[^A-Za-z0-9._-]+', '-', stem).strip('-.') or 'part')
result = [f'"""FTC generated from build123d feature trace: {stem.replace(chr(34), chr(39))}."""',
'', 'from pathlib import Path', '', 'import simplecadapi as scad']
if uses_ql:
result.append('from simplecadapi import ql')
result.extend(['', 'BODIES = None', '', ''])
if solid_count <= 1:
result.extend([f"@scad.part(id={part_id!r}, revision='1.0.0', project_root=Path(__file__).parent)",
'def build() -> scad.Part:'])
else:
result.append('def _build_bodies():')
result.extend(lines)
for note in unsupported:
result.append(' # untranslated: ' + str(note).replace('\n', ' '))
if refs:
result.extend([f' bodies = [_b for _group in [{", ".join(refs)}] for _b in _group]',
' global BODIES', ' BODIES = list(bodies)',
' return bodies[0]' if solid_count <= 1 else ' return bodies'])
else:
result.append(" raise RuntimeError('feature tree produced no solid')")
if solid_count > 1:
for index in range(solid_count):
result.extend(['', '', f"@scad.part(id={f'{part_id}-body-{index + 1}'!r}, revision='1.0.0', project_root=Path(__file__).parent)",
f'def _build_body_{index + 1}() -> scad.Part:',
f' return _build_bodies()[{index}]'])
result.extend(['', '', 'def build():',
' parts = [' + ', '.join(f'_build_body_{i + 1}()' for i in range(solid_count)) + ']',
f" @scad.assemble(id={part_id!r}, revision='1.0.0', definitions=parts, project_root=Path(__file__).parent)",
' def _build_assembly():',
' # ---- feature: body-components (build) ----',
f' assembly = scad.make_assembly_rassembly(assembly_id={part_id!r})',
' for index, item in enumerate(parts):',
" component_id = f'body-{index + 1}'",
' assembly = scad.add_component_rassembly(assembly=assembly, item=item.value, component_id=component_id, placement=scad.identity_placement_rplacement())',
' assembly = scad.ground_component_rassembly(assembly=assembly, component_id=component_id)',
' return assembly', ' return _build_assembly()'])
return '\n'.join(result) + '\n'
@@ -0,0 +1,224 @@
"""Kernel-independent JSON descriptions of build123d profile geometry.
The trace contains analytic curves and NURBS control data, never a saved BRep.
Coordinates are in the coordinate system of the actual feature input.
"""
from __future__ import annotations
from enum import Enum
import math
from typing import Any
def vector(value: Any) -> list[float]:
if hasattr(value, "X"):
return [float(getattr(value, n)() if callable(getattr(value, n)) else getattr(value, n)) for n in "XYZ"]
if hasattr(value, "x"):
return [float(value.x), float(value.y), float(value.z)]
return [float(value.X()), float(value.Y()), float(value.Z())]
def plane(value: Any) -> dict[str, Any]:
return {"origin": vector(value.origin), "x_dir": vector(value.x_dir),
"y_dir": vector(value.y_dir), "normal": vector(value.z_dir)}
def location_matrix(value: Any) -> list[list[float]]:
trsf = value.wrapped.Transformation()
return [[float(trsf.Value(i, j)) for j in range(1, 5)] for i in range(1, 4)] + [[0., 0., 0., 1.]]
def serialize(value: Any) -> Any:
if value is None or isinstance(value, (str, bool, int, float)):
return value
if isinstance(value, Enum):
return value.name
if isinstance(value, dict):
return {str(k): serialize(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [serialize(v) for v in value]
name = type(value).__name__
if name == "Plane":
return plane(value)
if name == "Axis":
return {"origin": vector(value.position), "direction": vector(value.direction)}
if name in {"Location", "Rotation", "Pos", "Rot"} or hasattr(value, "wrapped") and hasattr(value.wrapped, "Transformation"):
return {"matrix": location_matrix(value)}
if name == "Matrix":
return {"matrix": [[float(value.wrapped.Value(i, j)) for j in range(1, 5)] for i in range(1, 4)] + [[0., 0., 0., 1.]]}
if name == "Vector":
return vector(value)
if hasattr(value, "wrapped"):
return {"shape_type": name}
return {"type": name, "repr": repr(value)}
def metrics(shape: Any) -> dict[str, Any]:
from OCP.BRepGProp import BRepGProp
from OCP.GProp import GProp_GProps
shapes = shape if isinstance(shape, (list, tuple)) else [shape]
solids = [s for item in shapes if item is not None for s in item.solids()]
if not solids:
return {"volume": 0., "bbox": None, "solid_count": 0}
boxes = [s.bounding_box() for s in solids]
low = [min(vector(box.min)[i] for box in boxes) for i in range(3)]
high = [max(vector(box.max)[i] for box in boxes) for i in range(3)]
volumes, areas = [], []
for solid in solids:
properties = GProp_GProps()
BRepGProp.VolumePropertiesGK_s(solid.wrapped, properties, 1e-9, True, True)
volumes.append(float(properties.Mass()))
areas.append(surface_area(solid.wrapped))
return {"volume": sum(volumes), "volume_gk": sum(volumes), "area": sum(areas), "default_volume": sum(float(s.volume) for s in solids), "bbox": low + high,
"solid_count": len(solids)}
def surface_area(wrapped: Any) -> float:
"""Integrate per smooth span on a geometry copy, preserving the source model.
OCCT's adaptive surface integrator can miss rational spline knot breaks.
Splitting C0 boundaries/surfaces into C1 spans resolves those breaks before
integration. This temporary topology is used only for the numeric metric.
"""
from OCP.BRepBuilderAPI import BRepBuilderAPI_Copy
from OCP.ShapeUpgrade import ShapeUpgrade_ShapeDivideContinuity
from OCP.GeomAbs import GeomAbs_C1
from OCP.BRepGProp import BRepGProp
from OCP.GProp import GProp_GProps
copied = BRepBuilderAPI_Copy(wrapped, True, False).Shape()
divider = ShapeUpgrade_ShapeDivideContinuity(copied)
divider.SetSurfaceCriterion(GeomAbs_C1)
divider.SetBoundaryCriterion(GeomAbs_C1)
divider.SetPCurveCriterion(GeomAbs_C1)
divider.Perform()
properties = GProp_GProps()
BRepGProp.SurfaceProperties_s(S=divider.Result(), SProps=properties, Eps=1e-10, SkipShared=False)
return float(properties.Mass())
def fingerprint(shape: Any, parent: Any = None) -> dict[str, Any]:
from build123d import CenterOf
kind = type(shape).__name__.lower()
payload = {"kind": kind, "geom_type": shape.geom_type.name,
"center": vector(shape.center(CenterOf.MASS)) if kind in {"edge", "face"} else vector(shape.center()),
"bbox": vector(shape.bounding_box().min) + vector(shape.bounding_box().max)}
if kind in {"edge", "wire"}:
payload["length"] = float(shape.length)
payload["start"] = vector(shape.position_at(0))
payload["mid"] = vector(shape.position_at(.5))
payload["end"] = vector(shape.position_at(1))
if kind == "face":
payload["area"] = float(shape.area)
if shape.geom_type.name == "PLANE":
try:
payload["normal"] = vector(shape.normal_at())
except Exception:
pass
if parent is not None:
children = parent.edges() if kind == "edge" else parent.faces() if kind == "face" else parent.vertices()
for index, child in enumerate(children):
if child.wrapped.IsSame(shape.wrapped):
payload["index"] = index
break
return payload
def edge(value: Any) -> dict[str, Any]:
from OCP.BRepAdaptor import BRepAdaptor_Curve
adaptor = BRepAdaptor_Curve(value.wrapped)
kind = value.geom_type.name.lower()
first, last = adaptor.FirstParameter(), adaptor.LastParameter()
common = {"start": vector(value.position_at(0)), "end": vector(value.position_at(1)),
"parameter_range": [float(first), float(last)], "reversed": not value.is_forward}
if kind == "line":
return {"kind": "line", **common}
if kind == "circle":
circle = adaptor.Circle()
data = {"center": vector(circle.Location()), "radius": float(circle.Radius()),
"normal": vector(circle.Axis().Direction()), "x_dir": vector(circle.XAxis().Direction())}
if abs(last - first - 2 * math.pi) < 1e-7:
return {"kind": "circle", **common, **data}
return {"kind": "arc", "mid": vector(value.position_at(.5)), **common, **data}
if kind == "ellipse" and abs(last - first - 2 * math.pi) < 1e-7:
ellipse = adaptor.Ellipse()
return {"kind": "ellipse", **common, "center": vector(ellipse.Location()),
"major_radius": float(ellipse.MajorRadius()), "minor_radius": float(ellipse.MinorRadius()),
"x_dir": vector(ellipse.XAxis().Direction()), "y_dir": vector(ellipse.YAxis().Direction()),
"normal": vector(ellipse.Axis().Direction())}
if kind in {"bspline", "bezier", "ellipse", "parabola", "hyperbola"}:
# Segmentation preserves the exact trimmed curve, including NURBS weights.
# Conic arcs become exact rational BSplines rather than sampled polylines.
if kind not in {"bspline", "bezier"}:
from OCP.Geom import Geom_TrimmedCurve
from OCP.GeomConvert import GeomConvert
from OCP.BRep import BRep_Tool
curve = BRep_Tool.Curve_s(value.wrapped, first, last)
spline = GeomConvert.CurveToBSplineCurve_s(Geom_TrimmedCurve(curve, first, last))
kind = "bspline"
else:
spline = adaptor.BSpline() if kind == "bspline" else adaptor.Bezier()
unclamped = kind == "bspline" and not spline.IsPeriodic() and (spline.Multiplicity(1) < spline.Degree()+1 or spline.Multiplicity(spline.NbKnots()) < spline.Degree()+1)
if unclamped or abs(first - spline.FirstParameter()) > 1e-9 or abs(last - spline.LastParameter()) > 1e-9:
spline = spline.Copy()
spline.Segment(first, last)
# Converted/segmented poles already describe exactly the edge extent.
common["parameter_range"] = [float(spline.FirstParameter()), float(spline.LastParameter())]
data = {"kind": kind, **common, "degree": spline.Degree(),
"poles": [vector(spline.Pole(i)) for i in range(1, spline.NbPoles() + 1)],
"weights": [float(spline.Weight(i)) for i in range(1, spline.NbPoles() + 1)]}
if kind == "bspline":
data.update(knots=[float(spline.Knot(i)) for i in range(1, spline.NbKnots() + 1)],
multiplicities=[spline.Multiplicity(i) for i in range(1, spline.NbKnots() + 1)],
periodic=spline.IsPeriodic())
return data
# Conics are kept analytic as a full parameterized curve description.
if kind in {"parabola", "hyperbola"}:
conic = adaptor.Parabola() if kind == "parabola" else adaptor.Hyperbola()
data = {"kind": kind, **common, "center": vector(conic.Location()),
"x_dir": vector(conic.XAxis().Direction()), "normal": vector(conic.Axis().Direction())}
if kind == "parabola":
data["focal"] = float(conic.Focal())
else:
data.update(major_radius=float(conic.MajorRadius()), minor_radius=float(conic.MinorRadius()))
return data
raise ValueError(f"Unsupported profile curve: {value.geom_type.name}")
def wire(value: Any) -> dict[str, Any]:
from build123d import Edge
from OCP.BRepTools import BRepTools_WireExplorer
explorer = BRepTools_WireExplorer(value.wrapped)
edges = []
while explorer.More():
edges.append(edge(Edge(explorer.Current())))
explorer.Next()
return {"edges": edges, "closed": bool(value.is_closed)}
def profile(value: Any) -> dict[str, Any]:
from build123d import Face, Plane, Vertex, Wire
if isinstance(value, Vertex):
return {"kind": "vertex", "point": vector(value.center())}
if isinstance(value, Wire):
value = Face(value)
if not isinstance(value, Face):
raise ValueError(f"A planar profile was expected, got {type(value).__name__}")
frame = Plane(value)
return {"kind": "face", **plane(frame),
"wires": [wire(value.outer_wire())] + [wire(w) for w in value.inner_wires()]}
def path(value: Any) -> dict[str, Any]:
from build123d import Edge, Wire
if isinstance(value, Edge):
return {"edges": [edge(value)], "closed": bool(value.is_closed)}
if not isinstance(value, Wire):
value = Wire(value.edges())
result = wire(value)
try:
frame = value.find_plane()
if frame is not None:
result.update(planar=True, **plane(frame))
except Exception:
pass
return result
@@ -0,0 +1,207 @@
"""Exact profile reconstruction through native sketch/curve APIs.
Planar input curves are transcribed into a local sketch, including rational
B-splines and ellipses. Nonplanar sweep paths remain geometry-tier wires.
No tessellation or final-body boundary reconstruction is used.
"""
from __future__ import annotations
import math
from typing import Any, Mapping, Sequence
from .emit import fmt_literal, fmt_num, fmt_vec
def dot(a, b):
return sum(float(x) * float(y) for x, y in zip(a, b))
def cross(a, b):
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
def unit(a):
length = math.sqrt(dot(a, a))
if length < 1e-12:
raise ValueError('degenerate frame axis')
return tuple(float(x) / length for x in a)
def frame(profile):
normal = unit(profile.get('normal', (0, 0, 1)))
u = profile.get('u') or profile.get('x_dir')
if u is None:
seed = (0, 1, 0) if abs(normal[0]) > .8 else (1, 0, 0)
u = unit(cross(seed, normal))
else:
u = unit(u)
v = unit(profile.get('v') or profile.get('y_dir') or cross(normal, u))
return profile.get('origin', (0, 0, 0)), u, v, normal
def circumcenter(a, b, c):
determinant = 2 * (a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]))
if abs(determinant) < 1e-15:
raise ValueError('arc points are collinear')
squared = [dot(p, p) for p in (a, b, c)]
return ((squared[0] * (b[1] - c[1]) + squared[1] * (c[1] - a[1]) + squared[2] * (a[1] - b[1])) / determinant,
(squared[0] * (c[0] - b[0]) + squared[1] * (a[0] - c[0]) + squared[2] * (b[0] - a[0])) / determinant)
def oriented_spline(edge):
"""Align basis poles with traced edge traversal before binding endpoints.
OCCT adaptor poles retain increasing parameter order even when a wire
traverses the edge backwards. Swapping only its endpoint refs distorts
cubic and higher-order curves, so reverse the entire exact basis.
"""
poles = edge.get('poles') or edge.get('control_points')
start, end = edge.get('start'), edge.get('end')
if not poles or start is None or end is None or math.dist(start, end) < 1e-9:
return edge
if math.dist(start, poles[-1]) > 1e-7 or math.dist(end, poles[0]) > 1e-7:
return edge
changed = dict(edge, poles=list(reversed(poles)))
if edge.get('weights'):
changed['weights'] = list(reversed(edge['weights']))
if edge.get('knots'):
total = edge['knots'][0] + edge['knots'][-1]
changed['knots'] = [total - knot for knot in reversed(edge['knots'])]
if edge.get('multiplicities'):
changed['multiplicities'] = list(reversed(edge['multiplicities']))
return changed
class Sketch:
def __init__(self, name, profile):
self.name = name
self.origin, self.u, self.v, self.normal = frame(profile)
plane_expr = "{'origin': " + fmt_vec(self.origin) + ", 'x_axis': " + fmt_vec(self.u) + ", 'y_axis': " + fmt_vec(self.v) + "}"
self.lines = [f" {name} = scad.make_sketch_rsketch(name={name!r}, plane={plane_expr})"]
self.points = {}
self.counter = 0
self.entities = 0
self.snapshot_entities = []
def local(self, point):
delta = [float(x) - float(y) for x, y in zip(point, self.origin)]
if abs(dot(delta, self.normal)) > 1e-5:
raise ValueError('nonplanar curve cannot be represented by sketch')
return dot(delta, self.u), dot(delta, self.v)
def point(self, coordinates):
key = tuple(round(x, 9) for x in coordinates)
if key not in self.points:
self.counter += 1
point_id = f'p{self.counter}'
self.points[key] = point_id
self.lines.append(f' {self.name} = scad.add_point_rsketch(sketch={self.name}, point_id={point_id!r}, x={fmt_num(coordinates[0])}, y={fmt_num(coordinates[1])})')
self.snapshot_entities.append({'id': point_id, 'kind': 'point', 'xy': list(coordinates)})
return self.points[key]
def entity(self, edge):
self.entities += 1
name = f'e{self.entities}'
prefix = f' {self.name} = scad.'
base = f'sketch={self.name}, entity_id={name!r}'
kind = edge['kind'].lower()
if kind == 'line':
a, b = self.point(self.local(edge['start'])), self.point(self.local(edge['end']))
self.lines.append(prefix + f'add_line_rsketch({base}, start={a!r}, end={b!r})')
self.snapshot_entities.append({'id': name, 'kind': 'line', 'start': a, 'end': b})
elif kind in ('arc', 'arc3') or (kind == 'circle' and edge.get('mid') is not None):
a, b, c = [self.local(edge[x]) for x in ('start', 'mid', 'end')]
center = circumcenter(a, b, c)
angles = [math.atan2(p[1] - center[1], p[0] - center[0]) for p in (a, b, c)]
if (angles[1] - angles[0]) % (2 * math.pi) > (angles[2] - angles[0]) % (2 * math.pi):
a, c = c, a
start, end, center_ref = self.point(a), self.point(c), self.point(center)
self.lines.append(prefix + f'add_arc_rsketch({base}, start={start!r}, end={end!r}, center={center_ref!r})')
self.snapshot_entities.append({'id': name, 'kind': 'arc', 'start': start, 'end': end, 'center': center_ref})
elif kind == 'circle':
center = self.point(self.local(edge['center']))
self.lines.append(prefix + f'add_circle_rsketch({base}, center={center!r}, radius={fmt_num(edge["radius"])})')
self.snapshot_entities.append({'id': name, 'kind': 'circle', 'center': center, 'radius': edge['radius']})
elif kind == 'ellipse':
if edge.get('trimmed'):
raise ValueError('trimmed ellipse requires exact trimmed B-spline data')
center3 = edge['center']
x_dir = edge.get('x_dir') or self.u
y_dir = edge.get('y_dir') or cross(edge.get('normal', self.normal), x_dir)
major3 = [c + edge['major_radius'] * d for c, d in zip(center3, x_dir)]
minor3 = [c + edge['minor_radius'] * d for c, d in zip(center3, y_dir)]
center, major, minor = [self.point(self.local(p)) for p in (center3, major3, minor3)]
self.lines.append(prefix + f'add_ellipse_rsketch({base}, center={center!r}, major_point={major!r}, minor_point={minor!r})')
self.snapshot_entities.append({'id': name, 'kind': 'ellipse', 'center': center, 'major_point': major, 'minor_point': minor})
elif kind in ('bspline', 'bezier'):
edge = oriented_spline(edge)
poles = edge.get('poles') or edge.get('control_points')
if not poles:
raise ValueError('B-spline poles missing')
a = self.point(self.local(edge.get('start', poles[0])))
b = self.point(self.local(edge.get('end', poles[-1])))
degree = int(edge.get('degree', len(poles) - 1 if kind == 'bezier' else 3))
knots = edge.get('knots', [0, 1] if kind == 'bezier' else None)
mults = edge.get('multiplicities', [degree + 1, degree + 1] if kind == 'bezier' else None)
self.lines.append(prefix + f'add_bspline_rsketch({base}, start={a!r}, end={b!r}, control_points={fmt_literal([self.local(p) for p in poles])}, degree={degree}, knots={fmt_literal(knots)}, multiplicities={fmt_literal(mults)}, weights={fmt_literal(edge.get("weights"))}, periodic={bool(edge.get("periodic", False))!r})')
self.snapshot_entities.append({'id': name, 'kind': 'bspline', 'start': a, 'end': b,
'control_points': [self.local(p) for p in poles], 'degree': degree,
'knots': knots, 'multiplicities': mults, 'weights': edge.get('weights'), 'periodic': edge.get('periodic', False)})
else:
raise ValueError(f'unsupported exact curve kind: {kind}')
def emit_profile(profile: Mapping[str, Any], name: str, *, as_wire: bool = False, snapshots=None):
"""Return source lines + face/wire expression; outer-first wire ordering."""
wires = profile.get('wires') or [{'edges': profile.get('edges', [])}]
if not wires or not wires[0].get('edges'):
raise ValueError('empty profile')
if as_wire and len(wires) > 1:
raise ValueError('a wire section cannot represent multiple disconnected loops')
sketch = Sketch(name + '_sketch', profile)
profile_ids = []
for wire in wires:
if not wire.get('edges'):
raise ValueError('empty inner profile')
profile_ids.append(f'e{sketch.entities + 1}')
for edge in wire['edges']:
sketch.entity(edge)
if snapshots is not None:
snapshots.append({'name': sketch.name, 'entities': sketch.snapshot_entities,
'closed': wires[0].get('closed', not as_wire),
'plane': {'origin': list(sketch.origin), 'x_axis': list(sketch.u), 'y_axis': list(sketch.v)}})
output = name + ('_wire' if as_wire else '_face')
api = 'make_wire_from_sketch_rwire' if as_wire else 'make_face_from_sketch_rface'
outer = '0' if len(wires) == 1 else repr(profile_ids[0])
holes = '' if len(wires) == 1 else f', inner_profiles={profile_ids[1:]!r}'
sketch.lines.append(f' {output} = scad.{api}(sketch={sketch.name}, profile={outer}{holes})')
return sketch.lines, output
def emit_path(path: Mapping[str, Any], name: str, *, snapshots=None):
if path.get('normal') is not None and path.get('planar', True):
return emit_profile(path, name, as_wire=True, snapshots=snapshots)
lines, edges = [], []
path_edges = path.get('edges') or [edge for wire in path.get('wires', []) for edge in wire.get('edges', [])]
for index, edge in enumerate(path_edges):
ref = f'{name}_edge{index}'
kind = edge['kind']
if kind == 'line':
expression = f'scad.make_line_redge(start={fmt_vec(edge["start"])}, end={fmt_vec(edge["end"])})'
elif kind in ('arc', 'arc3'):
expression = f'scad.make_three_point_arc_redge(start={fmt_vec(edge["start"])}, middle={fmt_vec(edge["mid"])}, end={fmt_vec(edge["end"])})'
elif kind == 'circle':
expression = f'scad.make_circle_redge(center={fmt_vec(edge["center"])}, radius={fmt_num(edge["radius"])}, normal={fmt_vec(edge.get("normal", (0, 0, 1)))})'
elif kind in ('bspline', 'bezier'):
edge = oriented_spline(edge)
degree = int(edge.get('degree', len(edge['poles']) - 1 if kind == 'bezier' else 3))
expression = (f'scad.make_spline_redge(control_points={fmt_literal(edge["poles"])}, degree={degree}, '
f'knots={fmt_literal(edge.get("knots"))}, multiplicities={fmt_literal(edge.get("multiplicities"))}, '
f'weights={fmt_literal(edge.get("weights"))}, periodic={bool(edge.get("periodic", False))!r})')
else:
raise ValueError(f'unsupported nonplanar path curve: {kind}')
lines.append(f' {ref} = {expression}')
edges.append(ref)
if not edges:
raise ValueError('empty sweep path')
output = name + '_wire'
lines.append(f' {output} = scad.make_wire_from_edges_rwire(edges=[{", ".join(edges)}])')
return lines, output
+493
View File
@@ -0,0 +1,493 @@
"""Translate a portable build123d operation trace into explicit FTC dataflow.
Only recorded feature inputs are reconstructed. Unknown operations block their
own dependent chain instead of being replaced by final-result geometry.
"""
from __future__ import annotations
import math
import re
from typing import Any, Mapping
from .emit import SlugAllocator, block_header, emit_module, fingerprint_selector, fmt_literal, fmt_num, fmt_vec
from .profiles import cross, dot, emit_path, emit_profile, frame, unit
def _named(parameters, *names, default=None):
for name in names:
if name in parameters and parameters[name] is not None:
return parameters[name]
return default
def _variable(name):
return 'body_' + re.sub('[^a-zA-Z0-9_]', '_', str(name))
def _axis(parameters):
value = parameters.get('axis', (0, 0, 1))
if isinstance(value, dict):
return value.get('direction', (0, 0, 1)), value.get('origin', (0, 0, 0))
return value, parameters.get('origin', (0, 0, 0))
def _profiles(step):
profiles = step.get('profiles') or [step.get('profile')]
holes = step.get('inner_wires') or []
if holes and len(profiles) == 1 and profiles[0]:
profile = dict(profiles[0])
wires = list(profile.get('wires', []))
for hole in holes:
wires.extend(hole.get('wires', [hole]) if isinstance(hole, dict) else [])
profile['wires'] = wires
profiles = [profile]
return profiles
def _matrix_operations(matrix):
"""Decompose an affine matrix into local scale, rotation, translation."""
if isinstance(matrix, dict):
matrix = matrix.get('matrix')
if len(matrix) == 16 and not isinstance(matrix[0], (list, tuple)):
matrix = [matrix[i:i + 4] for i in range(0, 16, 4)]
columns = [tuple(float(matrix[i][j]) for i in range(3)) for j in range(3)]
scales = [math.sqrt(dot(c, c)) for c in columns]
if min(scales) < 1e-12:
raise ValueError('singular affine transform')
axes = [tuple(x / scale for x in column) for column, scale in zip(columns, scales)]
if any(abs(dot(axes[i], axes[j])) > 1e-8 for i in range(3) for j in range(i + 1, 3)):
raise ValueError('affine shear cannot be represented by native scale/rotation')
if dot(cross(axes[0], axes[1]), axes[2]) < 0:
scales[0] = -scales[0]
axes[0] = tuple(-x for x in axes[0])
r = [[axes[j][i] for j in range(3)] for i in range(3)]
cosine = max(-1., min(1., (r[0][0] + r[1][1] + r[2][2] - 1) / 2))
angle = math.acos(cosine)
if angle < 1e-9:
axis = (0, 0, 1)
elif abs(angle - math.pi) < 1e-7:
diagonal = [max(0., (r[i][i] + 1) / 2) for i in range(3)]
pivot = max(range(3), key=lambda i: diagonal[i])
axis_list = [0., 0., 0.]
axis_list[pivot] = math.sqrt(diagonal[pivot])
for j in range(3):
if j != pivot:
axis_list[j] = (r[pivot][j] + r[j][pivot]) / (4 * axis_list[pivot])
axis = unit(axis_list)
else:
axis = unit((r[2][1] - r[1][2], r[0][2] - r[2][0], r[1][0] - r[0][1]))
return scales, axis, math.degrees(angle), tuple(float(matrix[i][3]) for i in range(3))
class TraceReplayer:
def __init__(self, trace: Mapping[str, Any], stem: str, constraints_mode: bool = False):
self.trace = trace
self.stem = stem
self.lines = []
self.variables = {}
self.steps = {}
self.unsupported = list(trace.get('unsupported', []))
self.slugs = SlugAllocator()
self.feature_count = 0
self.uses_ql = False
self.snapshots = []
self.constraints_mode = constraints_mode
self.constraint_reports = []
def profile(self, profile, name, as_wire=False):
if profile.get('kind') == 'vertex':
if not as_wire:
raise ValueError('vertex cannot be a solid profile')
output = name + '_vertex'
self.lines.append(f' {output} = scad.make_point_rvertex({", ".join(f"{axis}={fmt_num(x)}" for axis, x in zip("xyz", profile["point"]))})')
return output
lines, expression = emit_profile(profile, name, as_wire=as_wire, snapshots=self.snapshots)
self.lines.extend(lines)
return expression
def source(self, step):
ids = step.get('inputs', [])
if isinstance(ids, str):
ids = [ids]
missing = [ref for ref in ids if ref not in self.variables]
if missing:
raise ValueError(f'input feature unavailable: {missing}')
return [self.variables[ref] for ref in ids]
def build_step(self, step):
op = step['op'].lower()
p = step.get('parameters') or step.get('params') or {}
ident = step.get('id', f's{self.feature_count + 1}')
var = _variable(ident)
inputs = self.source(step)
create = op in {'box', 'cylinder', 'cone', 'sphere', 'torus', 'extrude', 'revolve', 'loft', 'sweep', 'extrude_linear', 'extrude_linear_with_rotation', 'extrude_taper', 'extrude_twist', 'extrude_until', 'sweep_multi'}
role = 'build' if create else {'union': 'add', 'fuse': 'add', 'cut': 'subtract', 'intersect': 'intersect', 'compound': 'pattern'}.get(op, 'modify')
tiers = ['profile=geometry'] if op in {'extrude', 'revolve', 'loft', 'sweep', 'extrude_linear', 'extrude_linear_with_rotation', 'torus', 'extrude_taper', 'extrude_twist', 'extrude_until', 'sweep_multi'} else []
if op in {'sweep', 'sweep_multi'}:
tiers.append('path=geometry')
self.lines.append(block_header(self.slugs.allocate(op), role, tiers))
if op in {'box', 'cylinder', 'cone', 'sphere', 'torus'}:
self.primitive(op, p, var)
elif op in {'extrude', 'extrude_linear'}:
profiles = _profiles(step)
if not all(profiles):
raise ValueError('extrusion profile missing')
direction = _named(p, 'direction', 'vector', 'dir', default=(0, 0, 1))
distance = _named(p, 'distance', 'amount', 'height')
if distance is None:
distance = math.sqrt(dot(direction, direction))
if distance < 0:
direction = [-float(x) for x in direction]
distance = -distance
refs = [self.profile(profile, f'{var}_profile{i}') for i, profile in enumerate(profiles)]
self.lines.append(f' {var} = [scad.extrude_rsolid(profile=_profile, direction={fmt_vec(direction)}, distance={fmt_num(distance)}) for _profile in [{", ".join(refs)}]]')
elif op in {'extrude_taper', 'extrude_until', 'extrude_twist', 'extrude_linear_with_rotation'}:
refs = [self.profile(profile, f'{var}_profile{i}') for i, profile in enumerate(_profiles(step))]
if op == 'extrude_taper':
vector = _named(p, 'direction', 'vector', default=(0, 0, 1))
expression = f'scad.extrude_taper_rsolid(profile=_profile, vector={fmt_vec(vector)}, taper={fmt_num(p["taper"])}, flip_inner={bool(p.get("flip_inner", True))!r})'
elif op == 'extrude_until':
if not inputs:
raise ValueError('until extrusion target missing')
target = f'[_b for _group in [{", ".join(inputs)}] for _b in _group]'
expression = f'scad.extrude_until_rsolid(profile=_profile, target={target}, direction={fmt_vec(p.get("direction", (0, 0, 1)))}, until={str(p.get("until", "NEXT"))!r})'
else:
direction = _named(p, 'normal', 'direction', 'vector', default=(0, 0, 1))
distance = math.sqrt(dot(direction, direction))
expression = f'scad.twisted_sweep_rsolid(profile=_profile, distance={fmt_num(distance)}, twist_angle={fmt_num(_named(p, "angle", "twist_angle", default=0))}, axis={fmt_vec(direction)}, origin={fmt_vec(_named(p, "center", "origin", default=(0, 0, 0)))}, guide_radius=1)'
self.lines.append(f' {var} = [{expression} for _profile in [{", ".join(refs)}]]')
elif op == 'revolve':
profiles = _profiles(step)
refs = [self.profile(profile, f'{var}_profile{i}') for i, profile in enumerate(profiles)]
axis, origin = _axis(p)
angle = _named(p, 'angle', 'arc', 'revolution_arc', default=360)
if angle < 0:
angle, axis = -angle, [-float(x) for x in axis]
self.lines.append(f' {var} = [scad.revolve_rsolid(profile=_profile, axis={fmt_vec(axis)}, angle={fmt_num(angle)}, origin={fmt_vec(origin)}) for _profile in [{", ".join(refs)}]]')
elif op == 'loft':
profiles = step.get('profiles') or []
refs = [self.profile(profile, f'{var}_section{i}', as_wire=True) for i, profile in enumerate(profiles)]
if len(refs) < 2:
raise ValueError('loft needs at least two recorded sections')
self.lines.append(f' {var} = [scad.loft_rsolid(profiles=[{", ".join(refs)}], ruled={bool(p.get("ruled", False))!r})]')
elif op in {'sweep', 'sweep_multi'}:
profiles = _profiles(step)
path = step.get('path')
if not path:
raise ValueError('sweep path missing')
path_lines, path_expr = emit_path(path, var + '_path', snapshots=self.snapshots)
self.lines.extend(path_lines)
refs = [self.profile(profile, f'{var}_profile{i}') for i, profile in enumerate(profiles)]
frenet = bool(_named(p, 'is_frenet', 'frenet', default=False))
if op == 'sweep_multi':
binormal = p.get('binormal')
if isinstance(binormal, dict):
raise ValueError('multisection sweep binormal wire missing from portable trace')
self.lines.append(f' {var} = [scad.sweep_multisection_rsolid(profiles=[{", ".join(refs)}], path={path_expr}, is_frenet={frenet!r}, binormal={fmt_literal(binormal)})]')
else:
if p.get('mode') is not None or str(p.get('transition', 'TRANSFORMED')) != 'TRANSFORMED':
raise ValueError('sweep mode/transition needs a native advanced sweep operator')
self.lines.append(f' {var} = [scad.sweep_rsolid(profile=_profile, path={path_expr}, is_frenet={frenet!r}) for _profile in [{", ".join(refs)}]]')
elif op == 'component':
if len(inputs) != 1:
raise ValueError('component requires one parent feature')
self.lines.append(f' {var} = [{inputs[0]}[{int(p["index"])}]]')
elif op in {'compound', 'copy', 'clean'}:
self.lines.append(f' {var} = [ _b for _group in [{", ".join(inputs)}] for _b in _group ]')
elif op in {'union', 'fuse', 'cut', 'intersect'}:
if not inputs:
raise ValueError('boolean inputs missing')
if len(inputs) == 1:
self.lines.append(f' {var} = list({inputs[0]})')
elif op == 'cut':
tools = f'[_b for _group in [{", ".join(inputs[1:])}] for _b in _group]'
self.lines.append(f' {var} = [scad.cut_rsolid(_b, {tools}) for _b in {inputs[0]}]')
elif op == 'intersect':
self.lines.append(f' {var} = [scad.intersect_rsolid([{", ".join(inputs)}])]')
else:
groups = step.get('result_groups')
if groups:
values = []
for group in groups:
group_refs = [self.variables[x] for x in group]
values.append(f'scad.union_rsolid([{", ".join(group_refs)}])' if len(group_refs) > 1 else f'{group_refs[0]}[0]')
self.lines.append(f' {var} = [{", ".join(values)}]')
elif step.get('result', {}).get('solid_count', 1) > 1:
raise ValueError('disconnected union requires recorded connected operand groups')
else:
self.lines.append(f' {var} = [scad.union_rsolid([{", ".join(inputs)}])]')
elif op in {'fillet', 'chamfer'}:
selector = fingerprint_selector(step.get('selection', []), 'edge')
self.uses_ql = True
if len(inputs) != 1:
raise ValueError('blend requires one parent feature')
if op == 'fillet':
extras = f'radius={fmt_num(p["radius"])}'
else:
extras = f'distance={fmt_num(_named(p, "length", "distance", "length1"))}'
second = _named(p, 'length2', 'distance2')
if second is not None and abs(float(second) - float(_named(p, 'length', 'distance', 'length1'))) > 1e-9:
extras += ', angle=' + fmt_num(math.degrees(math.atan2(float(second), float(_named(p, 'length', 'distance', 'length1')))))
direction = p.get('reference_direction')
if direction is None:
if p.get('reference_directions'):
raise ValueError('per-edge chamfer reference normals vary; the native operator requires one reference direction')
raise ValueError('asymmetric chamfer requires reference-face normal')
extras += ', reference_direction=' + fmt_vec(direction)
self.lines.append(f' {var} = [scad.{op}_rsolid(solid=_b, edges={selector}, {extras}) for _b in {inputs[0]}]')
elif op == 'draft':
if len(inputs) != 1:
raise ValueError('draft requires one parent feature')
selector = fingerprint_selector(step.get('selection', []), 'face')
self.uses_ql = True
plane = p.get('neutral_plane') or p.get('plane') or {}
angle = _named(p, 'angle', 'draft_angle')
if angle is None or not isinstance(plane, dict):
raise ValueError('draft angle or neutral plane missing')
self.lines.append(f' {var} = [scad.draft_rsolid(solid=_b, faces_to_draft={selector}, angle={fmt_num(angle)}, plane_origin={fmt_vec(plane.get("origin", (0, 0, 0)))}, plane_normal={fmt_vec(plane.get("normal", (0, 0, 1)))}) for _b in {inputs[0]}]')
elif op in {'offset', 'shell'}:
if len(inputs) != 1:
raise ValueError('offset requires one parent feature')
selections = step.get('selection', [])
selector = fingerprint_selector(selections, 'face') if selections else '[]'
self.uses_ql |= bool(selections)
amount = _named(p, 'offset', 'amount', 'thickness', 'distance')
if amount is None:
raise ValueError('offset distance missing')
self.lines.append(f' {var} = [scad.offset_rsolid(solid=_b, amount={fmt_num(amount)}, openings={selector}, tolerance={fmt_num(p.get("tolerance", 1e-4))}, kind={str(p.get("kind", "ARC"))!r}) for _b in {inputs[0]}]')
elif op == 'split':
self.split(step, p, inputs, var)
elif op in {'transform', 'translate', 'rotate', 'mirror', 'scale', 'move', 'moved', 'located', 'locate', 'transform_shape', 'transform_geometry'}:
self.transform(op, p, inputs, var)
else:
raise ValueError(f'unsupported op: {op}')
self.lines.append('')
self.variables[ident] = var
self.steps[ident] = step
self.feature_count += 1
def primitive(self, op, p, var):
plane = p.get('plane') or {}
origin = _named(p, 'origin', 'center', default=plane.get('origin', (0, 0, 0)))
axis = _named(p, 'axis', default=plane.get('normal', (0, 0, 1)))
if isinstance(axis, dict):
origin, axis = axis.get('origin', origin), axis.get('direction', (0, 0, 1))
x_dir = plane.get('x_dir', (1, 0, 0))
if op == 'box':
length = _named(p, 'length', 'x', default=p.get('width'))
width = _named(p, 'width', 'y', default=p.get('height'))
height = _named(p, 'height', 'z', default=p.get('depth'))
u, v = unit(x_dir), unit(cross(unit(axis), unit(x_dir)))
bottom = [float(origin[i]) + float(length) * u[i] / 2 + float(width) * v[i] / 2 for i in range(3)]
self.lines.extend([f' with scad.SimpleWorkplane(origin=(0, 0, 0), normal={fmt_vec(axis)}, x_dir={fmt_vec(x_dir)}):',
f' {var} = [scad.make_box_rsolid(width={fmt_num(length)}, height={fmt_num(width)}, depth={fmt_num(height)}, bottom_face_center={fmt_vec([dot(bottom, u), dot(bottom, v), dot(bottom, unit(axis))])})]'])
elif op in {'cylinder', 'cone'}:
angle = _named(p, 'angle', 'arc_size', default=360)
if abs(float(angle) - 360) > 1e-9:
axis, x_dir = unit(axis), unit(x_dir)
y_dir = unit(cross(axis, x_dir))
def world(x, y, z):
return [origin[i] + x * x_dir[i] + y * y_dir[i] + z * axis[i] for i in range(3)]
if op == 'cylinder':
radius = float(p['radius'])
theta = math.radians(float(angle))
start, mid, end = world(radius, 0, 0), world(radius * math.cos(theta / 2), radius * math.sin(theta / 2), 0), world(radius * math.cos(theta), radius * math.sin(theta), 0)
edges = [{'kind': 'line', 'start': origin, 'end': start}, {'kind': 'arc', 'start': start, 'mid': mid, 'end': end}, {'kind': 'line', 'start': end, 'end': origin}]
profile = {'origin': origin, 'u': x_dir, 'v': y_dir, 'normal': axis, 'wires': [{'edges': edges}]}
face = self.profile(profile, var + '_sector')
self.lines.append(f' {var} = [scad.extrude_rsolid(profile={face}, direction={fmt_vec(axis)}, distance={fmt_num(p["height"])})]')
else:
bottom_radius, top_radius = float(_named(p, 'base_radius', 'radius1', 'bottom_radius')), float(_named(p, 'radius2', 'top_radius', default=0))
points = [world(0, 0, 0), world(bottom_radius, 0, 0), world(top_radius, 0, float(p['height'])), world(0, 0, float(p['height']))]
edges = [{'kind': 'line', 'start': a, 'end': b} for a, b in zip(points, points[1:] + points[:1]) if sum((x - y) ** 2 for x, y in zip(a, b)) > 1e-20]
profile = {'origin': origin, 'u': x_dir, 'v': axis, 'normal': cross(x_dir, axis), 'wires': [{'edges': edges}]}
face = self.profile(profile, var + '_meridian')
self.lines.append(f' {var} = [scad.revolve_rsolid(profile={face}, axis={fmt_vec(axis)}, angle={fmt_num(angle)}, origin={fmt_vec(origin)})]')
return
if op == 'cylinder':
args = f'radius={fmt_num(p["radius"])}'
else:
args = f'bottom_radius={fmt_num(_named(p, "radius1", "bottom_radius", "base_radius"))}, top_radius={fmt_num(_named(p, "radius2", "top_radius", default=0))}'
self.lines.append(f' {var} = [scad.make_{op}_rsolid({args}, height={fmt_num(p["height"])}, bottom_face_center={fmt_vec(origin)}, axis={fmt_vec(axis)})]')
elif op == 'sphere':
if any(abs(float(p.get(key, default)) - default) > 1e-9 for key, default in [('angle1', -90), ('angle2', 90), ('angle3', 360)]):
radius, axis, x_dir = float(p['radius']), unit(axis), unit(x_dir)
theta1, theta2 = math.radians(float(p.get('angle1', -90))), math.radians(float(p.get('angle2', 90)))
def meridian(theta):
return [origin[i] + radius * math.cos(theta) * x_dir[i] + radius * math.sin(theta) * axis[i] for i in range(3)]
start, mid, end = meridian(theta1), meridian((theta1 + theta2) / 2), meridian(theta2)
bottom_axis = [origin[i] + radius * math.sin(theta1) * axis[i] for i in range(3)]
top_axis = [origin[i] + radius * math.sin(theta2) * axis[i] for i in range(3)]
edges = [{'kind': 'arc', 'start': start, 'mid': mid, 'end': end}]
edges.extend({'kind': 'line', 'start': a, 'end': b} for a, b in [(end, top_axis), (top_axis, bottom_axis), (bottom_axis, start)] if sum((x - y) ** 2 for x, y in zip(a, b)) > 1e-20)
profile = {'origin': origin, 'u': x_dir, 'v': axis, 'normal': cross(x_dir, axis), 'wires': [{'edges': edges}]}
face = self.profile(profile, var + '_meridian')
self.lines.append(f' {var} = [scad.revolve_rsolid(profile={face}, axis={fmt_vec(axis)}, angle={fmt_num(p.get("angle3", 360))}, origin={fmt_vec(origin)})]')
return
self.lines.append(f' {var} = [scad.make_sphere_rsolid(radius={fmt_num(p["radius"])}, center={fmt_vec(origin)})]')
else:
if abs(float(p.get('angle1', 0))) > 1e-9 or abs(float(p.get('angle2', 360)) - 360) > 1e-9:
raise ValueError('partial torus tube needs a traced meridian closure profile')
major, minor = _named(p, 'major_radius', 'radius1'), _named(p, 'minor_radius', 'radius2')
axis = unit(axis)
x_dir = unit(x_dir)
profile_origin = [o + float(major) * x for o, x in zip(origin, x_dir)]
profile = {'origin': profile_origin, 'u': x_dir, 'v': axis, 'normal': cross(x_dir, axis),
'wires': [{'edges': [{'kind': 'circle', 'center': profile_origin, 'radius': minor}]}]}
face = self.profile(profile, var + '_meridian')
self.lines.append(f' {var} = [scad.revolve_rsolid(profile={face}, axis={fmt_vec(axis)}, angle={fmt_num(_named(p, "angle3", "angle", default=360))}, origin={fmt_vec(origin)})]')
def transform(self, op, p, inputs, var):
if len(inputs) != 1:
raise ValueError('transform requires one parent feature')
expression = '_b'
matrix = _named(p, 'matrix', 'matrix4x4', 't_matrix', 'location', 'loc')
if matrix is None and isinstance(p.get('transform'), (dict, list, tuple)):
matrix = p['transform']
if matrix is not None:
try:
scales, axis, angle, vector = _matrix_operations(matrix)
except ValueError as error:
if 'shear' not in str(error):
raise
raw_matrix = matrix.get('matrix') if isinstance(matrix, dict) else matrix
expression = f'scad.transform_rsolid(solid=_b, matrix={fmt_literal(raw_matrix)})'
self.lines.append(f' {var} = [{expression} for _b in {inputs[0]}]')
return
if any(abs(x - 1) > 1e-10 for x in scales):
expression = f'scad.scale_rsolid(solid={expression}, factors={fmt_vec(scales)}, center=(0, 0, 0))'
if abs(angle) > 1e-10:
expression = f'scad.rotate_shape(shape={expression}, angle={fmt_num(angle)}, axis={fmt_vec(axis)}, origin=(0, 0, 0))'
if any(abs(x) > 1e-10 for x in vector):
expression = f'scad.translate_shape(shape={expression}, vector={fmt_vec(vector)})'
elif op == 'mirror' or p.get('mirror_plane') is not None:
plane = p.get('mirror_plane') or p.get('plane') or {}
expression = f'scad.mirror_shape(shape=_b, plane_origin={fmt_vec(plane.get("origin", (0, 0, 0)))}, plane_normal={fmt_vec(plane.get("normal", (0, 0, 1)))})'
elif op == 'rotate' or p.get('angle') is not None:
axis, origin = _axis(p)
expression = f'scad.rotate_shape(shape=_b, angle={fmt_num(p["angle"])}, axis={fmt_vec(axis)}, origin={fmt_vec(origin)})'
elif op == 'scale' or p.get('method') == 'scale' or p.get('factor') is not None or p.get('factors') is not None:
factors = _named(p, 'factors', 'factor', 'scale', default=1)
if isinstance(factors, (int, float)):
factors = (factors,) * 3
expression = f'scad.scale_rsolid(solid=_b, factors={fmt_vec(factors)}, center={fmt_vec(_named(p, "center", "about", default=(0, 0, 0)))})'
else:
vector = _named(p, 'vector', 'translation', 'offset')
if vector is None:
raise ValueError('transform has no supported parameters')
expression = f'scad.translate_shape(shape=_b, vector={fmt_vec(vector)})'
self.lines.append(f' {var} = [{expression} for _b in {inputs[0]}]')
def split(self, step, p, inputs, var):
if len(inputs) != 1:
raise ValueError('split requires one parent feature')
plane = _named(p, 'plane', 'bisect_by', 'tool', default={})
if not isinstance(plane, dict) or 'normal' not in plane:
raise ValueError('only planar solid splits are supported')
origin, u, v, normal = frame(plane)
source_step = self.steps[step['inputs'][0]]
bbox = source_step.get('result', {}).get('bbox') or self.trace.get('b3d_bbox')
if not bbox or len(bbox) != 6:
raise ValueError('split needs the source feature bounding box')
corners = [(x, y, z) for x in (bbox[0], bbox[3]) for y in (bbox[1], bbox[4]) for z in (bbox[2], bbox[5])]
projected = [[dot([c[i] - origin[i] for i in range(3)], axis) for c in corners] for axis in (u, v, normal)]
margin = max(math.sqrt(sum((bbox[i + 3] - bbox[i]) ** 2 for i in range(3))), 1)
center2 = [(min(a) + max(a)) / 2 for a in projected[:2]]
width, height = [max(a) - min(a) + margin * 2 for a in projected[:2]]
depth = max(abs(x) for x in projected[2]) + margin
tool_origin = [origin[i] + center2[0] * u[i] + center2[1] * v[i] for i in range(3)]
keep = str(p.get('keep', 'BOTH')).upper().split('.')[-1]
refs = []
component_sides = step.get('result_component_sides')
ordered_sides = component_sides if keep == 'BOTH' and component_sides else ['TOP', 'BOTTOM']
for side in ordered_sides:
label = str(side).lower()
if label not in {'top', 'bottom'}:
raise ValueError(f'unknown split component side: {side}')
sign = 1 if label == 'top' else -1
if keep != 'BOTH' and keep != label.upper():
continue
tool = var + '_' + label
self.lines.extend([f' with scad.SimpleWorkplane(origin={fmt_vec(tool_origin)}, normal={fmt_vec([sign * x for x in normal])}, x_dir={fmt_vec(u)}):',
f' {tool} = scad.make_box_rsolid(width={fmt_num(width)}, height={fmt_num(height)}, depth={fmt_num(depth)}, bottom_face_center=(0, 0, 0))'])
refs.append(f'scad.intersect_rsolid(_b, [{tool}])')
if not refs:
raise ValueError(f'unknown split keep mode: {keep}')
self.lines.append(f' {var} = [_piece for _b in {inputs[0]} for _piece in [{", ".join(refs)}]]')
def replay(self):
for step in self.trace.get('steps', []):
before = len(self.lines)
before_ql = self.uses_ql
before_sketches = len(self.snapshots)
before_slugs = dict(self.slugs.counts)
try:
self.build_step(step)
for snapshot in self.snapshots[before_sketches:]:
snapshot.update({'feature_id': step.get('id'), 'op': step.get('op'), 'role': 'profile'})
except (ValueError, KeyError, TypeError, IndexError) as error:
del self.lines[before:]
del self.snapshots[before_sketches:]
self.uses_ql = before_ql
self.slugs.counts = before_slugs
self.unsupported.append(f'{step.get("id", "?")} {step.get("op", "?")}: {error}')
requested = self.trace.get('result_refs') if 'result_refs' in self.trace else self.trace.get('results')
if requested is None:
requested = [self.trace['steps'][-1]['id']] if self.trace.get('steps') else []
if isinstance(requested, str):
requested = [requested]
refs = [self.variables[x] for x in requested if isinstance(x, str) and x in self.variables]
missing = [x for x in requested if x not in self.variables]
if missing:
self.unsupported.append(f'final result features unavailable: {missing}')
if not refs:
self.unsupported.append('feature tree produced no solid')
if self.constraints_mode:
self.recover_constraints()
count = int(self.trace.get('solid_count') or sum(self.steps[x].get('result', {}).get('solid_count', 1) for x in requested if x in self.steps) or 1)
source = emit_module(self.stem, self.lines, refs, self.unsupported, self.uses_ql, count)
return source, {'status': 'partial' if self.unsupported else 'ok', 'feature_count': self.feature_count,
'unsupported': self.unsupported, 'result_refs': requested,
'notes': [], 'schema_version': '1.0', 'solid_count': count,
'artifact_type': 'assembly' if count > 1 else 'part',
'sketches': self.snapshots, 'sketch_count': len(self.snapshots),
'constraint_recovery': self.constraint_reports}
def recover_constraints(self):
"""Reuse the source-agnostic CQ inference engine without changing it.
It admits only geometry-entailed constraints whose production solver
preserves coordinates. Unsupported entity families retain geometry.
"""
import sys
from pathlib import Path
sibling = str(Path(__file__).resolve().parents[2] / 'cadqueryftc')
if sibling not in sys.path:
sys.path.insert(0, sibling)
from cqftc.constraints import emit_constraint_lines, recover_constraints_guarded
for snapshot in self.snapshots:
if any(entity['kind'] not in {'point', 'line', 'circle', 'arc'} for entity in snapshot['entities']):
self.constraint_reports.append({'name': snapshot['name'], 'status': 'unsupported',
'reason': 'constraint recovery does not handle ellipse/B-spline entities', 'constraints': []})
continue
try:
report = recover_constraints_guarded(snapshot, timeout=30)
except Exception as error:
report = {'status': 'error', 'reason': str(error), 'constraints': []}
report['name'] = snapshot['name']
self.constraint_reports.append(report)
if not report.get('coords_ok'):
continue
name = snapshot['name']
constraints = [line.replace(' s = ', f' {name} = ').replace('sketch=s,', f'sketch={name},')
for line in emit_constraint_lines(report)]
for index, line in enumerate(self.lines):
if f'sketch={name}, profile=' in line and ('make_wire_from_sketch_rwire' in line or 'make_face_from_sketch_rface' in line):
self.lines[index:index] = constraints
break
def replay_trace_to_ftc(trace: Any, *, stem: str = 'part', constraints_mode: bool = False):
if hasattr(trace, 'to_dict'):
trace = trace.to_dict()
if not isinstance(trace, Mapping):
raise TypeError('trace must be a portable JSON mapping')
return TraceReplayer(trace, stem, constraints_mode=constraints_mode).replay()
@@ -0,0 +1,8 @@
"""Versioned, portable feature trace contract."""
SCHEMA_VERSION = "1.0"
def empty_trace():
return {"schema_version": SCHEMA_VERSION, "steps": [], "result_refs": [],
"b3d_status": "ok", "b3d_volume": None, "b3d_bbox": None,
"solid_count": 0, "unsupported": [], "error": ""}
+407
View File
@@ -0,0 +1,407 @@
"""Execute build123d and capture the actual solid construction graph.
Instrumentation sits at the topology API: Builder, algebra and direct topology
calls consequently share one history. Sketches are transcribed as analytic/NURBS
profiles at feature boundaries. Tracing executes Python; only trusted models
should be supplied. Patches are scoped and restored even on execution failure.
"""
from __future__ import annotations
from contextlib import contextmanager
import functools
import hashlib
import inspect
from pathlib import Path
import sys
import threading
import traceback
from typing import Any
from . import geometry
from .schema import SCHEMA_VERSION, empty_trace
schema_version = SCHEMA_VERSION
_LOCK = threading.RLock()
class Recorder:
def __init__(self):
self.trace = empty_trace()
self.depth = 0
self.refs: dict[int, str] = {}
self.components: dict[int, tuple[str, int, Any]] = {}
self.ref_solids: dict[str, list[Any]] = {}
self.patches: list[tuple[Any, str, Any, bool]] = []
self.retained: list[Any] = []
self.serial = 0
@staticmethod
def key(shape):
return hash(shape.wrapped)
@staticmethod
def is_solid(shape):
return hasattr(shape, "solids") and bool(shape.solids())
def register(self, shape, ref):
if shape is None:
return
if isinstance(shape, (list, tuple)):
solids = [s for item in shape if item is not None for s in item.solids()]
if len(solids) == 1:
self.register(solids[0], ref)
else:
for index, solid in enumerate(solids):
self.components[self.key(solid)] = (ref, index, solid)
self.retained.append(solid.wrapped)
for item in shape:
if item is not None and len(item.solids()) == 1:
single = item.solids()[0]
if self.key(single) in self.components:
self.components[self.key(item)] = self.components[self.key(single)]
return
if not hasattr(shape, "wrapped") or shape.wrapped is None:
return
self.refs[self.key(shape)] = ref
self.retained.append(shape.wrapped)
solids = shape.solids()
if len(solids) == 1:
self.refs[self.key(solids[0])] = ref
self.retained.append(solids[0].wrapped)
elif len(solids) > 1:
for index, solid in enumerate(solids):
self.components[self.key(solid)] = (ref, index, solid)
self.retained.append(solid.wrapped)
def emit(self, op, inputs, parameters, result, source, **extra):
import build123d as b
from OCP.TopLoc import TopLoc_Location
results = result if isinstance(result, (list, tuple)) else [result]
solids = [s for obj in results if obj is not None for s in obj.solids()]
if len(solids) > 1:
extra["result_components"] = [geometry.metrics(s) for s in solids]
if op == "union" and len(solids) > 1:
groups = []
self.depth += 1
try:
for output in solids:
group = []
output_box = geometry.metrics(output)["bbox"]
for input_ref in inputs:
for operand in self.ref_solids.get(input_ref, []):
box = geometry.metrics(operand)["bbox"]
if any(box[i] < output_box[i] - 1e-5 or box[i+3] > output_box[i+3] + 1e-5 for i in range(3)):
continue
common = operand.intersect(output)
overlap = geometry.metrics(common)["volume"] if common is not None else 0.
operand_volume = geometry.metrics(operand)["volume"]
if abs(overlap - operand_volume) <= max(1e-6, abs(operand_volume) * 1e-7):
group.extend(self.reference(operand))
groups.append(list(dict.fromkeys(group)))
finally:
self.depth -= 1
extra["result_groups"] = groups
self.serial += 1
ref = f"s{self.serial}"
step = {"id": ref, "op": op, "inputs": list(dict.fromkeys(inputs)),
"parameters": parameters, "source": source,
"result": geometry.metrics(result), **extra}
self.trace["steps"].append(step)
self.register(result, ref)
self.ref_solids[ref] = [b.Solid(s.wrapped.Moved(TopLoc_Location())) for s in solids]
return ref
def unsupported(self, message, shape=None, source="unknown"):
entry = {"source": source, "reason": message}
if entry not in self.trace["unsupported"]:
self.trace["unsupported"].append(entry)
if shape is not None:
return self.emit("unsupported", [], {"reason": message}, shape, source)
return None
def reference(self, shape):
if shape is None:
return []
if isinstance(shape, (list, tuple)):
return [r for item in shape for r in self.reference(item)]
if hasattr(shape, "part") and not hasattr(shape, "wrapped"):
return self.reference(shape.part)
if not hasattr(shape, "wrapped") or shape.wrapped is None or not self.is_solid(shape):
return []
key = self.key(shape)
if key in self.refs:
return [self.refs[key]]
if key in self.components:
parent, index, solid = self.components[key]
return [self.emit("component", [parent], {"index": index, "fingerprint": geometry.metrics(solid)}, solid, "Shape.solids")]
solids = shape.solids()
known = [self.refs.get(self.key(s)) for s in solids]
if all(known):
if len(set(known)) == 1:
self.register(shape, known[0])
return [known[0]]
return [self.emit("compound", known, {}, shape, "Compound")]
if all(self.key(s) in self.refs or self.key(s) in self.components for s in solids):
children = [ref for solid in solids for ref in self.reference(solid)]
return [self.emit("compound", children, {}, shape, "Compound")]
ref = self.unsupported(f"Untraced solid construction: {type(shape).__name__}", shape)
return [ref]
def patch(self, owner, name, replacement):
own_attribute = name in owner.__dict__
original = inspect.getattr_static(owner, name)
self.patches.append((owner, name, original, own_attribute))
setattr(owner, name, replacement)
def bind(self, fn, args, kwargs):
bound = inspect.signature(fn).bind(*args, **kwargs)
bound.apply_defaults()
return dict(bound.arguments)
def wrap(self, owner, name, op, *, factory=False):
fn = getattr(owner, name)
descriptor = inspect.getattr_static(owner, name)
@functools.wraps(fn)
def wrapped(*args, **kwargs):
if self.depth:
return fn(*args, **kwargs)
receiver = None if factory else args[0]
if receiver is not None and not self.is_solid(receiver):
return fn(*args, **kwargs)
params = self.bind(fn, args, kwargs)
params.pop("self", None)
# Materialize iterables once: feature generators must still execute normally.
for field in ("objs", "profiles", "edge_list", "faces", "openings", "inner_wires"):
value = params.get(field)
if value is not None and not isinstance(value, (list, tuple)) and not hasattr(value, "wrapped"):
params[field] = list(value)
# Rebind the materialized values to preserve the original call contract.
bound = inspect.signature(fn).bind(*args, **kwargs)
for field, value in params.items():
if field in bound.arguments:
bound.arguments[field] = value
inputs = self.reference(receiver) if receiver is not None else []
extra = {}
encoded = {}
try:
for field, value in params.items():
if field in {"obj", "profile", "section", "surface"} and op in {"extrude", "extrude_taper", "extrude_until", "revolve", "sweep", "extrude_twist", "thicken"}:
extra["profile"] = geometry.profile(value)
elif field in {"objs", "profiles"} and op in {"loft", "sweep_multi"}:
extra["profiles"] = [geometry.profile(v) for v in value]
elif field == "path" and op in {"sweep", "sweep_multi"}:
extra["path"] = geometry.path(value)
elif field in {"edge_list", "faces", "openings"}:
extra["selection"] = [geometry.fingerprint(v, receiver) for v in value or []]
elif field in {"to_fuse", "to_cut", "to_intersect", "target"}:
inputs.extend(self.reference(value))
elif field == "inner_wires":
extra["inner_wires"] = [geometry.wire(v) for v in value or []]
else:
encoded[field] = geometry.serialize(value)
except Exception as exc:
extra["geometry_error"] = str(exc)
self.unsupported(f"Cannot transcribe {name} inputs: {exc}", source=f"{owner.__name__}.{name}")
if op == "chamfer" and params.get("length2") is not None and params["length2"] != params["length"]:
# The native kernel assigns distance1 relative to an adjacent
# face, even when no reference face is supplied by the caller.
import build123d as b
from build123d.topology.three_d import IndexedDataMap_TopoDS_Shape_List_TopoDS_Shape_TopTools_ShapeMapHasher
from OCP.TopExp import TopExp
from OCP.TopAbs import TopAbs_EDGE, TopAbs_FACE
adjacency = IndexedDataMap_TopoDS_Shape_List_TopoDS_Shape_TopTools_ShapeMapHasher()
TopExp.MapShapesAndAncestors_s(receiver.wrapped, TopAbs_EDGE, TopAbs_FACE, adjacency)
directions = []
for selected in params["edge_list"]:
explicit = params.get("face")
reference = explicit if explicit is not None else next(face for face in receiver.faces() if face.wrapped.IsSame(adjacency.FindFromKey(selected.wrapped).First()))
direction = geometry.vector(reference.normal_at(selected.position_at(.5)))
directions.append(direction)
encoded["reference_directions"] = directions
if directions and all(sum((a-b)**2 for a,b in zip(directions[0], item)) < 1e-12 for item in directions):
encoded["reference_direction"] = directions[0]
if op == "transform":
encoded["method"] = name
if name == "scale" and params.get("about") is None:
encoded["about"] = geometry.vector(receiver.location.position)
if name == "transformed":
from OCP.gp import gp_Trsf, gp_Ax1, gp_Pnt, gp_Dir, gp_Vec
import math
rotation = params["rotate"]
if hasattr(rotation, "X"):
rotation = geometry.vector(rotation)
rotations = []
for i, angle in enumerate(rotation):
trsf = gp_Trsf()
axis = [0., 0., 0.]
axis[i] = 1.
trsf.SetRotation(gp_Ax1(gp_Pnt(), gp_Dir(*axis)), math.radians(angle))
rotations.append(trsf)
translation = gp_Trsf()
offset = params["offset"]
translation.SetTranslation(gp_Vec(*(geometry.vector(offset) if hasattr(offset, "X") else offset)))
transformation = translation * rotations[0] * rotations[1] * rotations[2]
encoded["matrix"] = [[float(transformation.Value(i, j)) for j in range(1, 5)] for i in range(1, 4)] + [[0., 0., 0., 1.]]
if name in {"locate", "located"}:
# Absolute location requires replacing the current shape location.
import build123d as b
loc = params["loc"]
encoded["matrix"] = geometry.location_matrix(loc * receiver.location.inverse())
elif name in {"move", "moved"}:
loc = params["loc"]
encoded["matrix"] = geometry.location_matrix(getattr(loc, "location", loc))
self.depth += 1
try:
result = fn(*bound.args, **bound.kwargs)
finally:
self.depth -= 1
if result is not None and (self.is_solid(result) if not isinstance(result, (list, tuple)) else any(self.is_solid(v) for v in result if v is not None)):
if op == "split" and isinstance(result, tuple) and len(result) == 2:
for value, keep in zip(result, ["TOP", "BOTTOM"]):
if value is not None:
self.emit(op, inputs, {**encoded, "keep": keep}, value, f"{owner.__name__}.{name}", **extra)
else:
self.emit(op, inputs, encoded, result, f"{owner.__name__}.{name}", **extra)
return result
if isinstance(descriptor, classmethod):
# `fn` is already bound to the class; discard the newly supplied cls.
@functools.wraps(fn)
def class_wrapped(cls, *args, **kwargs):
return wrapped(*args, **kwargs)
self.patch(owner, name, classmethod(class_wrapped))
elif isinstance(descriptor, staticmethod):
self.patch(owner, name, staticmethod(wrapped))
else:
self.patch(owner, name, wrapped)
def install(self):
import build123d as b
factories = {"make_box": "box", "make_cylinder": "cylinder", "make_cone": "cone",
"make_sphere": "sphere", "make_torus": "torus", "make_wedge": "wedge",
"extrude": "extrude", "extrude_taper": "extrude_taper", "extrude_until": "extrude_until",
"extrude_linear_with_rotation": "extrude_twist", "revolve": "revolve",
"make_loft": "loft", "sweep": "sweep", "sweep_multi": "sweep_multi", "thicken": "thicken"}
for name, op in factories.items():
if hasattr(b.Solid, name):
self.wrap(b.Solid, name, op, factory=True)
for name, op in {"fuse": "union", "cut": "cut", "intersect": "intersect", "split": "split"}.items():
self.wrap(b.Shape, name, op)
for name, op in {"fillet": "fillet", "chamfer": "chamfer", "offset_3d": "offset", "hollow": "shell", "draft": "draft"}.items():
owner = next((c for c in b.Solid.__mro__ if name in c.__dict__), None)
if owner is not None:
self.wrap(owner, name, op)
for name in ("moved", "move", "located", "locate", "translate", "rotate", "mirror", "scale", "transformed", "transform_shape", "transform_geometry"):
self.wrap(b.Shape, name, "transform")
original_clean = b.Shape.clean
original_copy = b.Shape.__deepcopy__
@functools.wraps(original_copy)
def deepcopy(shape, memo):
refs = self.reference(shape) if not self.depth and self.is_solid(shape) else []
self.depth += 1
try:
result = original_copy(shape, memo)
finally:
self.depth -= 1
if refs:
self.register(result, refs[0])
return result
self.patch(b.Shape, "__deepcopy__", deepcopy)
original_location = inspect.getattr_static(b.Shape, "location")
def set_location(shape, loc):
if self.depth or not self.is_solid(shape):
original_location.fset(shape, loc)
return
inputs = self.reference(shape)
matrix = geometry.location_matrix(loc * shape.location.inverse())
self.depth += 1
try:
original_location.fset(shape, loc)
finally:
self.depth -= 1
self.emit("transform", inputs, {"method": "locate", "matrix": matrix}, shape, "Shape.location")
self.patch(b.Shape, "location", property(original_location.fget, set_location, original_location.fdel, original_location.__doc__))
@functools.wraps(original_clean)
def clean(shape):
refs = self.reference(shape) if not self.depth and self.is_solid(shape) else []
self.depth += 1
try:
result = original_clean(shape)
finally:
self.depth -= 1
if refs:
self.register(result, refs[0])
return result
self.patch(b.Shape, "clean", clean)
def restore(self):
for owner, name, original, own_attribute in reversed(self.patches):
if own_attribute:
setattr(owner, name, original)
else:
delattr(owner, name)
self.patches.clear()
def _find_result(namespace):
from build123d import BuildPart, Shape
for name in ("result", "part", "model", "solid", "body"):
value = namespace.get(name)
if isinstance(value, BuildPart):
return value.part
if isinstance(value, Shape) and value.solids():
return value
if isinstance(value, (list, tuple)) and any(isinstance(v, Shape) and v.solids() for v in value):
return value
for value in reversed(list(namespace.values())):
if isinstance(value, BuildPart) and value.part is not None:
return value.part
if isinstance(value, Shape) and value.solids():
return value
return None
def trace_source(source: str, filename: str = "<build123d-model>") -> dict[str, Any]:
"""Execute a trusted program and return a portable feature graph."""
with _LOCK:
recorder = Recorder()
namespace = {"__name__": "__build123d_trace__", "__file__": filename}
old_path = list(sys.path)
sys.path.insert(0, str(Path(filename).resolve().parent))
try:
recorder.install()
try:
exec(compile(source, filename, "exec"), namespace)
except Exception:
recorder.trace["b3d_status"] = "error"
recorder.trace["error"] = traceback.format_exc()
result = _find_result(namespace)
if result is None:
recorder.trace["b3d_status"] = "error"
recorder.trace["error"] += "\nNo solid result found in model namespace"
else:
recorder.trace["result_refs"] = recorder.reference(result)
summary = geometry.metrics(result)
recorder.trace.update(b3d_volume=summary["volume"], b3d_bbox=summary["bbox"], solid_count=summary["solid_count"])
recorder.trace["b3d_default_volume"] = summary.get("default_volume", summary["volume"])
recorder.trace["b3d_volume_gk"] = summary["volume"]
values = result if isinstance(result, (list, tuple)) else [result]
recorder.trace["b3d_valid"] = all(v.is_valid for v in values)
recorder.trace["b3d_area"] = summary["area"]
finally:
recorder.restore()
sys.path[:] = old_path
recorder.trace["source_file"] = filename
recorder.trace["source_sha256"] = hashlib.sha256(source.encode("utf-8")).hexdigest()
import build123d
recorder.trace["build123d_version"] = getattr(build123d, "__version__", "unknown")
return recorder.trace
def trace_file(path: str | Path) -> dict[str, Any]:
path = Path(path).resolve()
return trace_source(path.read_text(encoding="utf-8"), str(path))
@@ -0,0 +1,314 @@
"""Stage 3 acceptance, independent of the source CAD interpreter.
Each generated program runs in a separate process. Acceptance requires all
source metrics, complete translation, real nonempty valid solids, and matching
volume, absolute bounds and solid count. Optional STEP comparison checks both
directions of the geometric difference.
"""
from __future__ import annotations
import json
import math
import os
from pathlib import Path
import signal
import subprocess
import sys
import tempfile
import time
from typing import Any, Mapping
VOLUME_RTOL = 1e-3
VOLUME_ATOL = 1e-6
BBOX_RTOL = 1e-3
BBOX_ATOL = 1e-4
DIFFERENCE_RTOL = 1e-3
def _finite_number(value: Any) -> bool:
return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
def _bbox(value: Any) -> bool:
return (isinstance(value, (list, tuple)) and len(value) == 6
and all(_finite_number(v) for v in value)
and all(value[i] <= value[i + 3] for i in range(3)))
def _positive_count(value: Any) -> bool:
return isinstance(value, int) and not isinstance(value, bool) and value > 0
def _translation_notes(payload: Mapping[str, Any]) -> bool:
return any(bool(value) for name, value in payload.items()
if name in {"unsupported", "untranslated", "unhandled"} or name.startswith("unknown"))
def compare_metrics(trace: Mapping[str, Any], actual: Mapping[str, Any],
meta: Mapping[str, Any] | None, *,
volume_rtol: float = VOLUME_RTOL, volume_atol: float = VOLUME_ATOL,
bbox_rtol: float = BBOX_RTOL, bbox_atol: float = BBOX_ATOL,
difference_rtol: float = DIFFERENCE_RTOL,
require_reference: bool = False) -> dict[str, Any]:
"""Compare untrusted JSON evidence; missing metrics always reject."""
reasons: list[str] = []
if trace.get("b3d_status") != "ok":
reasons.append("source_failed")
expected_volume, expected_bbox = trace.get("b3d_volume"), trace.get("b3d_bbox")
expected_count = trace.get("solid_count")
valid_source = (_finite_number(expected_volume) and expected_volume > 0
and _bbox(expected_bbox) and _positive_count(expected_count)
and bool(trace.get("result_refs")))
if not valid_source:
reasons.append("missing_source_metrics")
if trace.get("b3d_valid") is False or trace.get("b3d_is_valid") is False:
reasons.append("invalid_source")
if _translation_notes(trace):
reasons.append("unsupported_source")
if not isinstance(meta, Mapping) or meta.get("status") != "ok":
reasons.append("incomplete_translation")
if isinstance(meta, Mapping) and _translation_notes(meta):
reasons.append("untranslated_operations")
if actual.get("status") != "ok":
reasons.append("build_failed")
if not _positive_count(actual.get("body_count")):
reasons.append("empty_bodies")
if actual.get("is_valid") is not True:
reasons.append("invalid_topology")
volume, bounds, count = actual.get("volume"), actual.get("bbox"), actual.get("solid_count")
valid_actual = (_finite_number(volume) and volume > 0 and _bbox(bounds)
and _positive_count(count))
if not valid_actual:
reasons.append("missing_actual_metrics")
volume_error = bbox_error = bbox_absolute_error = area_error = None
if valid_source and valid_actual:
volume_error = abs(volume - expected_volume) / abs(expected_volume)
if abs(volume - expected_volume) > volume_atol + volume_rtol * abs(expected_volume):
reasons.append("volume_mismatch")
# Six world coordinates, scaled by axis span (never by world position).
# A rigid translation therefore fails even when every extent matches.
spans = [max(expected_bbox[i + 3] - expected_bbox[i], 1.0) for i in range(3)]
deviations = [abs(a - b) for a, b in zip(bounds, expected_bbox)]
bbox_absolute_error = max(deviations)
bbox_error = max(delta / spans[i % 3] for i, delta in enumerate(deviations))
if any(delta > bbox_atol + bbox_rtol * spans[i % 3]
for i, delta in enumerate(deviations)):
reasons.append("bbox_mismatch")
if count != expected_count:
reasons.append("solid_count_mismatch")
expected_area, area = trace.get("b3d_area"), actual.get("area")
if expected_area is not None:
if not (_finite_number(expected_area) and expected_area > 0 and _finite_number(area) and area > 0):
reasons.append("missing_area_metrics")
else:
area_error = abs(area - expected_area) / expected_area
if abs(area - expected_area) > volume_atol + volume_rtol * abs(expected_area):
reasons.append("area_mismatch")
difference = actual.get("symmetric_difference_volume")
difference_error = None
if require_reference:
reference_volume = actual.get("reference_volume")
if (actual.get("reference_status") != "ok" or not _finite_number(difference)
or difference < 0 or not _finite_number(reference_volume) or reference_volume <= 0):
reasons.append("reference_error")
else:
difference_error = difference / reference_volume
if difference > volume_atol + difference_rtol * reference_volume:
reasons.append("symmetric_difference_mismatch")
if "roundtrip_actual_volume" in actual:
exported = {"status": "ok", "volume": actual.get("roundtrip_actual_volume"),
"bbox": actual.get("roundtrip_actual_bbox"),
"solid_count": actual.get("roundtrip_actual_solid_count"),
"body_count": actual.get("body_count"),
"is_valid": actual.get("roundtrip_actual_valid")}
original = {"b3d_status": "ok", "b3d_volume": volume, "b3d_bbox": bounds,
"solid_count": count, "result_refs": ["actual"]}
check = compare_metrics(original, exported, {"status": "ok"},
volume_rtol=volume_rtol, volume_atol=volume_atol,
bbox_rtol=bbox_rtol, bbox_atol=bbox_atol)
if check["quality"] != "accepted":
reasons.append("reference_roundtrip_changed_geometry")
return {
"quality": "rejected" if reasons else "accepted", "reasons": reasons,
"b3d_volume": expected_volume if _finite_number(expected_volume) else None,
"ftc_volume": volume if _finite_number(volume) else None,
"b3d_bbox": expected_bbox if _bbox(expected_bbox) else None,
"ftc_bbox": bounds if _bbox(bounds) else None,
"b3d_solid_count": expected_count, "ftc_solid_count": count,
"body_count": actual.get("body_count"), "is_valid": actual.get("is_valid"),
"volume_error": volume_error, "bbox_error": bbox_error,
"b3d_area": expected_area if _finite_number(expected_area) else None,
"ftc_area": area if _finite_number(area) else None,
"area_error": area_error,
"bbox_absolute_error": bbox_absolute_error,
"symmetric_difference_volume": difference if _finite_number(difference) else None,
"symmetric_difference_error": difference_error,
}
def _load_json(path: Path) -> dict[str, Any]:
payload = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
raise ValueError(f"JSON root must be an object: {path}")
return payload
def _interpreter(executable: str | None) -> str:
executable = executable or sys.executable
# Keep a venv symlink instead of resolving it to the base Python binary.
return os.path.abspath(executable) if os.sep in executable else executable
def _process(command: list[str], staging: Path, env: Mapping[str, str],
output: Path, timeout: float) -> dict[str, Any]:
if timeout <= 0:
return {"status": "timeout", "error": "case timeout exhausted before reference comparison"}
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, cwd=staging, env=env,
start_new_session=os.name == "posix")
try:
stdout, stderr = process.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
if os.name == "posix":
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
else:
process.kill()
stdout, stderr = process.communicate()
return {"status": "timeout", "error": f"build exceeded {timeout:g} seconds",
"stdout": stdout[-4000:], "stderr": stderr[-4000:]}
if output.exists():
try:
result = _load_json(output)
except (ValueError, OSError) as exc:
result = {"status": "worker_error", "error": str(exc)}
else:
result = {"status": "worker_error", "error": f"worker exited {process.returncode} without metrics"}
if process.returncode and result.get("status") == "ok":
result.update(status="worker_error", error=f"worker exited {process.returncode}")
if stdout.strip():
result["stdout"] = stdout[-4000:]
if stderr.strip():
result["stderr"] = stderr[-4000:]
return result
def _worker(ftc_path: Path, workdir: Path | None, timeout: float,
reference_step: Path | None, python_executable: str | None,
reference_python: str | None = None,
export_options: Mapping[str, Any] | None = None) -> dict[str, Any]:
if timeout <= 0 or not math.isfinite(timeout):
raise ValueError("timeout must be a positive finite number")
if workdir is not None:
workdir.mkdir(parents=True, exist_ok=True)
tool_dir = Path(__file__).resolve().parent.parent
repo_root = tool_dir.parents[2]
with tempfile.TemporaryDirectory(prefix="b3ftc-validate-", dir=workdir) as tmp:
staging = Path(tmp).resolve()
output = staging / "result.json"
command = [_interpreter(python_executable), str(tool_dir / "b3ftc/_validate_worker.py"),
"--ftc", str(ftc_path.resolve()), "--output", str(output),
"--staging-dir", str(staging)]
actual_step = staging / "actual.step"
if reference_step is not None and reference_python is not None:
command.extend(["--export-step", str(actual_step)])
if export_options:
command.extend(["--export-options", json.dumps(export_options)])
elif reference_step is not None:
command.extend(["--reference-step", str(reference_step.resolve())])
env = os.environ.copy()
env["PYTHONPATH"] = os.pathsep.join([str(repo_root / "src"), str(tool_dir),
env.get("PYTHONPATH", "")])
started = time.monotonic()
result = _process(command, staging, env, output, timeout)
if reference_python is not None and reference_step is not None and result.get("status") == "ok":
ref_output = staging / "reference.json"
command = [_interpreter(reference_python), str(tool_dir / "b3ftc/_reference_worker.py"),
"--actual-step", str(actual_step), "--reference-step", str(reference_step.resolve()),
"--output", str(ref_output)]
ref = _process(command, staging, env, ref_output, timeout - (time.monotonic() - started))
result.update({key: value for key, value in ref.items()
if key.startswith(("reference_", "roundtrip_actual_", "symmetric_difference_"))})
if ref.get("status") != "ok":
result.update(reference_status="error", reference_error=ref.get("reference_error", ref.get("error", "")))
return result
def validate_row(ftc_path: Path, trace_path: Path, workdir: Path | None = None, *,
timeout: float = 120, reference_step: Path | None = None,
python_executable: str | None = None,
reference_python: str | None = None) -> dict[str, Any]:
"""Validate one FTC. Errors are returned as rejected rows for batch use."""
ftc_path, trace_path = Path(ftc_path), Path(trace_path)
stem = ftc_path.name.removesuffix(".ftc.py")
row: dict[str, Any] = {"stem": stem, "quality": "rejected", "metrics_quality": "rejected", "metrics_reasons": ["not_evaluated"]}
try:
if not ftc_path.is_file():
return {**row, "build": "missing_ftc", "reasons": ["missing_ftc"]}
if not trace_path.is_file():
return {**row, "build": "missing_trace", "reasons": ["missing_trace"]}
trace = _load_json(trace_path)
meta_path = ftc_path.with_name(stem + ".meta.json")
meta = _load_json(meta_path) if meta_path.is_file() else None
# Reject absent/failed source or incomplete conversion without executing it.
preliminary = compare_metrics(trace, {}, meta)
source_reasons = [reason for reason in preliminary["reasons"] if reason in {
"source_failed", "missing_source_metrics", "invalid_source", "unsupported_source",
"incomplete_translation", "untranslated_operations"}]
if source_reasons:
return {**row, **preliminary, "build": "not_run", "reasons": source_reasons,
"error": trace.get("error", "")}
metadata = trace.get("source_metadata") or {}
export_options = metadata.get("export_options", trace.get("export_options"))
metrics = _worker(ftc_path, Path(workdir) if workdir is not None else None,
timeout, Path(reference_step) if reference_step is not None else None,
python_executable, reference_python, export_options)
result = compare_metrics(trace, metrics, meta, require_reference=reference_step is not None)
basic = compare_metrics(trace, metrics, meta, require_reference=False)
return {**row, **result, "build": metrics.get("status", "worker_error"),
"metrics_quality": basic["quality"], "metrics_reasons": basic["reasons"],
"error": metrics.get("error", ""),
"reference_status": metrics.get("reference_status"),
"reference_kernel": metrics.get("reference_kernel"),
"reference_export_options": metrics.get("reference_export_options"),
"reference_boolean_fuzzy_tolerance": metrics.get("reference_boolean_fuzzy_tolerance"),
"reference_python": reference_python,
"build_kernel": metrics.get("build_kernel"),
"volume_method": metrics.get("volume_method"),
"area_method": metrics.get("area_method"),
"reference_error": metrics.get("reference_error", ""),
"stdout": metrics.get("stdout", ""), "stderr": metrics.get("stderr", "")}
except Exception as exc:
return {**row, "build": "validator_error", "reasons": ["validator_error"],
"error": f"{type(exc).__name__}: {exc}"}
def validate_directory(ftc_dir: Path, traces_dir: Path, *, timeout: float = 120,
reference_step_dir: Path | None = None, limit: int | None = None,
python_executable: str | None = None,
reference_python: str | None = None) -> dict[str, Any]:
"""Check the union of FTC and trace stems, never omit a failed conversion."""
ftc_dir, traces_dir = Path(ftc_dir), Path(traces_dir)
stems = sorted({path.name.removesuffix(".ftc.py") for path in ftc_dir.glob("*.ftc.py")}
| {path.name.removesuffix(".trace.json") for path in traces_dir.glob("*.trace.json")})
if limit is not None:
if limit < 0:
raise ValueError("limit must be nonnegative")
stems = stems[:limit]
rows = [validate_row(ftc_dir / (stem + ".ftc.py"), traces_dir / (stem + ".trace.json"),
timeout=timeout, python_executable=python_executable,
reference_python=reference_python,
reference_step=(Path(reference_step_dir) / (stem + ".step"))
if reference_step_dir is not None else None) for stem in stems]
return {"schema_version": "1.0", "rows": rows,
"counts": {quality: sum(row["quality"] == quality for row in rows)
for quality in ("accepted", "partial", "rejected")},
"tolerances": {"volume_relative": VOLUME_RTOL, "volume_absolute": VOLUME_ATOL,
"bbox_relative_to_axis_span": BBOX_RTOL, "bbox_absolute": BBOX_ATOL,
"symmetric_difference_relative": DIFFERENCE_RTOL},
"volume_method": "Gauss-Kronrod, epsilon=1e-9, closed shells, BSpline spans",
"area_method": "Independent geometry copy, C1 continuity spans, adaptive epsilon=1e-10",
"reference_step_dir": str(reference_step_dir) if reference_step_dir else None,
"reference_python": reference_python}
@@ -0,0 +1,44 @@
"""Stage 4: count actual traced operations and report conversion gaps."""
import argparse
from collections import Counter
import json
from pathlib import Path
def profile_traces(paths):
operations, sources, unsupported = Counter(), Counter(), Counter()
rows = []
for path in paths:
trace = json.loads(Path(path).read_text(encoding="utf-8"))
for step in trace.get("steps", []):
operations[step["op"]] += 1
sources[step.get("source", step["op"])] += 1
for note in trace.get("unsupported", []):
unsupported[note.get("reason", str(note)) if isinstance(note, dict) else str(note)] += 1
rows.append({"stem": trace.get("stem", Path(path).name.removesuffix(".trace.json")),
"status": trace.get("b3d_status"), "steps": len(trace.get("steps", [])),
"unsupported": len(trace.get("unsupported", []))})
return {"model_count": len(rows), "operations": dict(operations.most_common()),
"source_methods": dict(sources.most_common()), "unsupported": dict(unsupported.most_common()), "rows": rows}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--traces-dir", required=True)
parser.add_argument("--report")
args = parser.parse_args(argv)
paths = sorted(Path(args.traces_dir).glob("*.trace.json"))
if not paths:
parser.error("no traces found")
report = profile_traces(paths)
text = json.dumps(report, ensure_ascii=False, indent=2) + "\n"
if args.report:
path = Path(args.report)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
print(text)
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,66 @@
"""Stage 2: translate portable build123d traces into native FTC Python."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent))
def safe_stem(stem):
if not isinstance(stem, str) or stem in ("", ".", "..") or any(c in stem for c in ("/", "\\", "\x00", "\n", "\r")):
raise ValueError("stem must be a single nonempty filename")
return stem
def translate_trace_file(trace_path: Path, out_dir: Path, *, constraints_mode=False):
from b3ftc.replay import replay_trace_to_ftc
from b3ftc.schema import SCHEMA_VERSION
payload = json.loads(trace_path.read_text(encoding="utf-8"))
stem = safe_stem(payload.get("stem", trace_path.name.removesuffix(".trace.json")))
if payload.get("schema_version") != SCHEMA_VERSION:
raise ValueError(f"unsupported trace schema: {payload.get('schema_version')!r}")
options = {"constraints_mode": True} if constraints_mode else {}
source, meta = replay_trace_to_ftc(payload, stem=stem, **options)
meta = {"stem": stem, "source_file": payload.get("source_file"), **meta}
snapshots = meta.pop("sketches", [])
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / f"{stem}.ftc.py").write_text(source, encoding="utf-8")
(out_dir / f"{stem}.meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8")
(out_dir / f"{stem}.sketches.json").write_text(json.dumps({"stem": stem, "constraints_mode": constraints_mode, "sketches": snapshots},
ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8")
return stem, source, meta
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
inputs = parser.add_mutually_exclusive_group(required=True)
inputs.add_argument("--trace")
inputs.add_argument("--traces-dir")
parser.add_argument("--out", default="tools/research/build123dftc/out/ftc")
parser.add_argument("--constraints", choices=("on", "off"), default="off", help="recover inferred constraints with the existing CQ engine")
args = parser.parse_args(argv)
paths = [Path(args.trace)] if args.trace else sorted(Path(args.traces_dir).glob("*.trace.json"))
if not paths:
parser.error("no traces found")
failed = 0
for path in paths:
try:
stem, source, meta = translate_trace_file(path, Path(args.out), constraints_mode=args.constraints == "on")
failed += meta["status"] != "ok"
print(f"{stem}: {meta['status']} ({meta.get('feature_count', 0)} features, {len(meta.get('unsupported', []))} unsupported)", flush=True)
except Exception as error:
failed += 1
stem = safe_stem(path.name.removesuffix(".trace.json"))
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
(out / f"{stem}.meta.json").write_text(json.dumps({"stem": stem, "status": "error", "unsupported": [f"{type(error).__name__}: {error}"]}, indent=2) + "\n")
print(f"{stem}: translation_error: {type(error).__name__}: {error}", flush=True)
print(f"translated {len(paths)} traces, {failed} incomplete -> {args.out}")
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,121 @@
"""Stage 1: execute trusted build123d models in isolated worker processes."""
from __future__ import annotations
import argparse
import json
import math
import os
from pathlib import Path
import signal
import subprocess
import sys
TOOLS = Path(__file__).resolve().parent
sys.path.insert(0, str(TOOLS))
from b3ftc.schema import empty_trace
def discover_inputs(*, input_file=None, inputs_dir=None, manifest=None):
if input_file:
paths = [Path(input_file).resolve()]
elif manifest:
path = Path(manifest).resolve()
payload = json.loads(path.read_text(encoding="utf-8"))
paths = [(path.parent / item["file"]).resolve() for item in payload["examples"]]
elif inputs_dir:
paths = sorted(Path(inputs_dir).resolve().glob("*.py"))
else:
raise ValueError("one input source is required")
if not paths:
raise ValueError("no Python models found")
if any(not p.is_file() for p in paths):
raise FileNotFoundError("some declared model files do not exist")
stems = [p.stem for p in paths]
if len(set(stems)) != len(stems):
raise ValueError("model stems must be unique within one batch")
return paths
def trace_model(path: Path, out_dir: Path, *, stem=None, timeout=120, python_executable=None, source_metadata=None):
from build123d_to_ftc import safe_stem
if not math.isfinite(timeout) or timeout <= 0:
raise ValueError("timeout must be finite and positive")
path = path.resolve()
stem = safe_stem(stem or path.stem)
out_dir.mkdir(parents=True, exist_ok=True)
output = out_dir / f"{stem}.trace.json"
temporary = out_dir / f"{stem}.trace.tmp.json"
log_path = out_dir / f"{stem}.trace.log"
temporary.unlink(missing_ok=True)
command = [python_executable or sys.executable, str(TOOLS / "b3ftc/_trace_worker.py"),
str(path), str(temporary.resolve())]
with log_path.open("w", encoding="utf-8") as log:
process = subprocess.Popen(command, stdout=log, stderr=log, cwd=path.parent,
start_new_session=True)
try:
code = process.wait(timeout=timeout)
failure = f"trace worker exited with code {code}" if code else ""
except subprocess.TimeoutExpired:
if os.name == "posix":
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
else:
process.kill()
process.wait()
failure = f"source execution timed out after {timeout}s"
if failure or not temporary.exists():
payload = empty_trace()
payload.update(b3d_status="error", source_file=str(path), error=failure or "worker produced no trace")
with log_path.open("rb") as log:
log.seek(max(0, log_path.stat().st_size - 4096))
payload["error"] += "\n" + log.read().decode("utf-8", errors="replace")
else:
payload = json.loads(temporary.read_text(encoding="utf-8"))
payload["stem"] = stem
if source_metadata:
payload["source_metadata"] = source_metadata
temporary.write_text(json.dumps(payload, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8")
temporary.replace(output)
return payload
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
inputs = parser.add_mutually_exclusive_group(required=True)
inputs.add_argument("--input", dest="input_file", help="one trusted Python source")
inputs.add_argument("--inputs-dir", "--dataset", dest="inputs_dir", help="directory of Python models")
inputs.add_argument("--manifest", help="JSON examples manifest, paths relative to manifest")
parser.add_argument("--out", default="tools/research/build123dftc/out/traces")
parser.add_argument("--stem", help="output stem for one source")
parser.add_argument("--timeout", type=float, default=120)
parser.add_argument("--limit", type=int)
parser.add_argument("--python", dest="python_executable", help="interpreter with build123d installed")
args = parser.parse_args(argv)
if not math.isfinite(args.timeout) or args.timeout <= 0 or (args.limit is not None and args.limit <= 0):
parser.error("timeout and limit must be positive")
if args.stem and not args.input_file:
parser.error("--stem requires --input")
paths = discover_inputs(input_file=args.input_file, inputs_dir=args.inputs_dir, manifest=args.manifest)
metadata = {}
if args.manifest:
manifest_path = Path(args.manifest).resolve()
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
metadata = {str((manifest_path.parent / row["file"]).resolve()):
{key: row[key] for key in ("source_url", "source_sha256", "export_options") if key in row}
for row in manifest["examples"]}
paths = paths[:args.limit] if args.limit else paths
failed = 0
for path in paths:
row = trace_model(path, Path(args.out), stem=args.stem, timeout=args.timeout,
python_executable=args.python_executable, source_metadata=metadata.get(str(path)))
failed += row["b3d_status"] != "ok"
print(f"{row['stem']}: {row['b3d_status']} ({len(row['steps'])} operations, "
f"{len(row['unsupported'])} unsupported)", flush=True)
print(f"captured {len(paths)} models, {failed} failed -> {args.out}")
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,45 @@
"""Stage 3 — validate generated FTC solids against source traces and optional STEP."""
from __future__ import annotations
import argparse
import json
import math
from pathlib import Path
from b3ftc.validation import validate_directory
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--ftc-dir", type=Path, required=True)
parser.add_argument("--traces-dir", type=Path, required=True)
parser.add_argument("--report", type=Path)
parser.add_argument("--timeout", type=float, default=120)
parser.add_argument("--reference-step-dir", type=Path)
parser.add_argument("--reference-python", help="Optional independent OCCT interpreter for STEP differences")
parser.add_argument("--limit", type=int)
parser.add_argument("--python", dest="python_executable", help="SimpleCADAPI worker interpreter")
args = parser.parse_args(argv)
if not args.ftc_dir.is_dir() or not args.traces_dir.is_dir():
parser.error("--ftc-dir and --traces-dir must be existing directories")
if not math.isfinite(args.timeout) or args.timeout <= 0:
parser.error("--timeout must be positive and finite")
if args.limit is not None and args.limit < 0:
parser.error("--limit must be nonnegative")
if args.reference_python and not args.reference_step_dir:
parser.error("--reference-python requires --reference-step-dir")
report = validate_directory(args.ftc_dir, args.traces_dir, timeout=args.timeout,
reference_step_dir=args.reference_step_dir, limit=args.limit,
python_executable=args.python_executable,
reference_python=args.reference_python)
for row in report["rows"]:
print(f"{row['stem']}: {row['quality']} (build={row['build']}, reasons={','.join(row['reasons']) or 'none'})")
print(json.dumps(report["counts"]))
if args.report is not None:
args.report.parent.mkdir(parents=True, exist_ok=True)
args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
return 0 if report["rows"] and not (report["counts"]["rejected"] or report["counts"]["partial"]) else 1
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,328 @@
"""Generate a version-specific public build123d API and corpus inventory.
This is research evidence, not a declaration that conversion is implemented.
Run with the same interpreter as the source model corpus.
"""
from __future__ import annotations
import argparse
import ast
from collections import Counter
from enum import Enum
import inspect
import hashlib
import json
from pathlib import Path
from typing import Any
DOCUMENTATION_SOURCES = [
"https://build123d.readthedocs.io/en/v0.13.0/objects.html",
"https://build123d.readthedocs.io/en/v0.13.0/operations.html",
"https://build123d.readthedocs.io/en/v0.13.0/key_concepts_builder.html",
"https://build123d.readthedocs.io/en/v0.13.0/key_concepts_algebra.html",
"https://build123d.readthedocs.io/en/v0.13.0/direct_api_reference.html",
]
OPERATORS = {
"__add__", "__radd__", "__sub__", "__and__", "__mul__", "__rmul__",
"__matmul__", "__xor__", "__mod__", "__neg__", "__invert__",
}
TRANSFORMS = {
"move", "moved", "locate", "located", "translate", "rotate", "scale",
"mirror", "transform_shape", "transform_geometry", "transformed",
}
FEATURES = {
"extrude", "extrude_taper", "extrude_until", "extrude_linear_with_rotation",
"revolve", "sweep", "sweep_multi", "loft", "fillet", "chamfer", "draft",
"hollow", "offset", "offset_2d", "offset_3d", "split", "split_by_perimeter",
"thicken", "dprism", "trim", "trim_infinite", "trim_to_length",
"trim_to_other", "make_holes", "without_holes", "close", "stitch", "combine",
"clean", "fix", "fix_degenerate_edges", "to_splines", "reversed", "wrap",
"wrap_faces", "cut", "fuse", "intersect", "fillet_2d", "chamfer_2d",
"project", "project_to_shape", "project_faces", "sew_faces",
}
def category(name: str, obj: Any) -> str:
module = getattr(obj, "__module__", "")
if inspect.isclass(obj) and issubclass(obj, Enum):
return "enum"
if module.startswith("build123d.operations_"):
return "operation"
if module.startswith("build123d.objects_"):
return "object_" + module.removeprefix("build123d.objects_")
if name.startswith("Build"):
return "builder"
if name.endswith("Locations") or name == "Locations":
return "locations"
if module.startswith("build123d.topology"):
return "direct_topology"
if module == "build123d.geometry":
return "geometry"
if "export" in module or name.startswith("Export"):
return "export"
if "import" in module or name.startswith("import_"):
return "import"
if module == "build123d.joints":
return "assembly_joint"
if module == "build123d.drafting":
return "drawing_object"
if not callable(obj):
return "constant_or_type_alias"
return "utility"
def source_info(obj: Any, package_dir: Path) -> dict[str, Any]:
result: dict[str, Any] = {}
try:
source = Path(inspect.getsourcefile(obj) or "")
result["source_file"] = str(source.relative_to(package_dir.parent))
result["source_line"] = inspect.getsourcelines(obj)[1]
except (TypeError, ValueError, OSError):
pass
try:
result["signature"] = str(inspect.signature(obj))
except (TypeError, ValueError):
pass
return result
def member_category(name: str, raw: Any, owner: type) -> str:
if isinstance(raw, property):
return "property"
if name in OPERATORS:
return "algebra_operator"
if name in TRANSFORMS:
return "transform"
if name.startswith("make_") or name == "from_bounding_box":
return "factory"
if name in FEATURES:
return "feature"
if name in {"__enter__", "__exit__"}:
return "context_lifecycle"
if issubclass(owner, Enum):
return "enum_member"
return "query_or_utility"
class ModelVisitor(ast.NodeVisitor):
"""Count modeling calls, excluding entrypoint and constant-false docs branches."""
def __init__(self, exports: set[str]):
self.exports = exports
self.constants: dict[str, Any] = {}
self.calls: Counter[str] = Counter()
self.methods: Counter[str] = Counter()
self.operators: Counter[str] = Counter()
self.builders = False
self.aliases = {"build123d"}
def visit_Import(self, node: ast.Import) -> None:
for alias in node.names:
if alias.name == "build123d":
self.aliases.add(alias.asname or alias.name)
def visit_Assign(self, node: ast.Assign) -> None:
if isinstance(node.value, ast.Constant):
for target in node.targets:
if isinstance(target, ast.Name):
self.constants[target.id] = node.value.value
self.generic_visit(node)
def visit_If(self, node: ast.If) -> None:
test = node.test
is_entrypoint = (
isinstance(test, ast.Compare)
and isinstance(test.left, ast.Name)
and test.left.id == "__name__"
)
if is_entrypoint:
return
if isinstance(test, ast.Name) and self.constants.get(test.id) is False:
for stmt in node.orelse:
self.visit(stmt)
return
self.generic_visit(node)
def visit_Call(self, node: ast.Call) -> None:
func = node.func
if isinstance(func, ast.Name) and func.id in self.exports:
self.calls[func.id] += 1
self.builders |= func.id in {"BuildLine", "BuildSketch", "BuildPart"}
elif isinstance(func, ast.Attribute):
if isinstance(func.value, ast.Name) and func.value.id in self.aliases:
self.calls[func.attr] += 1
self.builders |= func.attr in {"BuildLine", "BuildSketch", "BuildPart"}
else:
self.methods[func.attr] += 1
self.generic_visit(node)
def visit_BinOp(self, node: ast.BinOp) -> None:
self.operators[type(node.op).__name__] += 1
self.generic_visit(node)
def inventory(manifest_path: Path) -> dict[str, Any]:
import build123d as bd
from build123d.build_common import BaseObjectMeta, Builder
from build123d.topology.shape_core import Shape
from build123d.topology.one_d import Mixin1D
from build123d.topology.two_d import Mixin2D
from build123d.topology.three_d import Mixin3D
package_dir = Path(bd.__file__).parent
manifest = json.loads(manifest_path.read_text())
top_level: list[dict[str, Any]] = []
members: dict[str, dict[str, Any]] = {}
classes: dict[str, list[str]] = {}
extra_classes = [Shape, Mixin1D, Mixin2D, Mixin3D, Builder, BaseObjectMeta]
for name in bd.__all__:
obj = getattr(bd, name)
record = {
"name": name,
"kind": "class" if inspect.isclass(obj) else "function" if callable(obj) else "value",
"category": category(name, obj),
"module": getattr(obj, "__module__", type(obj).__module__),
"conversion_status": "unverified",
**source_info(obj, package_dir),
}
if inspect.isclass(obj) and issubclass(obj, Enum):
record["values"] = list(obj.__members__)
top_level.append(record)
if inspect.isclass(obj):
extra_classes.append(obj)
for cls in dict.fromkeys(extra_classes):
refs = []
for name in sorted(dir(cls)):
if name.startswith("_") and name not in OPERATORS | {"__enter__", "__exit__", "__call__"}:
continue
owner = next((parent for parent in cls.__mro__ if name in vars(parent)), None)
if owner is None or not owner.__module__.startswith("build123d"):
continue
raw = vars(owner)[name]
value = raw.fget if isinstance(raw, property) else raw.__func__ if isinstance(raw, (staticmethod, classmethod)) else raw
if not callable(value) and not isinstance(raw, property):
continue
key = owner.__module__ + "." + owner.__name__ + "." + name
refs.append(key)
if key not in members:
members[key] = {
"name": name,
"owner": owner.__module__ + "." + owner.__name__,
"category": member_category(name, raw, owner),
"descriptor": "property" if isinstance(raw, property) else "classmethod" if isinstance(raw, classmethod) else "staticmethod" if isinstance(raw, staticmethod) else "method",
"conversion_status": "unverified",
**source_info(value, package_dir),
}
classes[cls.__module__ + "." + cls.__name__] = refs
models = []
all_calls: Counter[str] = Counter()
all_methods: Counter[str] = Counter()
for item in manifest["examples"]:
model_path = manifest_path.parent / item["file"]
visitor = ModelVisitor(set(bd.__all__))
visitor.visit(ast.parse(model_path.read_text()))
all_calls.update(visitor.calls)
all_methods.update(visitor.methods)
models.append({
"id": item["id"], "name": item["name"], "file": item["file"],
"source_url": item["source_url"],
"builder_context_present": visitor.builders,
"top_level_call_sites": dict(visitor.calls.most_common()),
"method_call_sites": dict(visitor.methods.most_common()),
"operator_syntax_counts": dict(visitor.operators.most_common()),
})
return {
"schema_version": 1,
"purpose": "Version-specific API inventory and static source corpus evidence; unverified is not implemented support.",
"build123d_version": bd.__version__,
"corpus_tag": manifest["tag"],
"corpus_commit": manifest["commit"],
"sources": DOCUMENTATION_SOURCES,
"scope": "203 package __all__ exports plus public build123d-declared members reachable through these classes, Shape, topology mixins and Builder; Python/OCP internals are excluded.",
"counts": {
"top_level_exports": len(top_level), "unique_public_member_declarations": len(members),
"class_interfaces": len(classes), "corpus_models": len(models),
"corpus_distinct_top_level_calls": len(all_calls),
"corpus_top_level_call_sites": sum(all_calls.values()),
"top_level_by_category": dict(Counter(item["category"] for item in top_level)),
"members_by_category": dict(Counter(item["category"] for item in members.values())),
},
"top_level_api": top_level,
"members": members,
"class_members": classes,
"corpus": {
"counting_note": "AST call sites, not runtime execution counts. Constant-false GEN_DOCS branches and __main__ export blocks are omitted; loops/functions are counted syntactically. Operator counts include numeric arithmetic.",
"top_level_calls": dict(all_calls.most_common()),
"method_calls": dict(all_methods.most_common()),
"models": models,
},
}
def validation_evidence(data: dict[str, Any], report_path: Path, traces_dir: Path | None) -> None:
"""Link only verified samples, never promote an entire API parameter space."""
report = json.loads(report_path.read_text())
rows = {row["stem"]: row for row in report["rows"]}
accepted = {stem for stem, row in rows.items() if row.get("quality") == "accepted"}
usage: dict[str, set[str]] = {}
for model in data["corpus"]["models"]:
stem = Path(model["file"]).stem
for api in model["top_level_call_sites"]:
usage.setdefault(api, set()).add(stem)
observed_members: dict[str, set[str]] = {}
if traces_dir is not None:
for path in traces_dir.glob("*.trace.json"):
stem = path.name.removesuffix(".trace.json")
trace = json.loads(path.read_text())
for step in trace.get("steps", []):
source = step.get("source")
if source and step.get("op") != "unsupported":
observed_members.setdefault(source, set()).add(stem)
source_report = {"path": str(report_path),
"sha256": hashlib.sha256(report_path.read_bytes()).hexdigest()}
for record in data["top_level_api"]:
exercised = usage.get(record["name"], set())
verified = sorted(exercised & accepted)
if verified:
record["conversion_status"] = "verified_sampled_usage"
record["validation_evidence"] = {
"accepted_models": verified,
"rejected_or_unverified_models": sorted(exercised - accepted),
"scope": "Model-level evidence for the listed source calls only; other argument variants remain unverified.",
}
for record in data["members"].values():
source = record["owner"].rsplit(".", 1)[-1] + "." + record["name"]
exercised = observed_members.get(source, set())
verified = sorted(exercised & accepted)
if verified:
record["conversion_status"] = "verified_sampled_usage"
record["validation_evidence"] = {"accepted_models": verified,
"scope": "Captured member call in accepted models; other argument variants remain unverified."}
data["verification"] = {"source_report": source_report,
"accepted_models": sorted(accepted),
"rejected_or_unverified_models": sorted(set(rows) - accepted),
"scope": "Sample-level acceptance is not a claim of all-API or all-parameter coverage.",
"verified_top_level_entries": sum(r["conversion_status"] == "verified_sampled_usage" for r in data["top_level_api"]),
"verified_public_member_entries": sum(r["conversion_status"] == "verified_sampled_usage" for r in data["members"].values())}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--manifest", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--validation-report", type=Path, help="Optional strict stage-3 report for sample evidence")
parser.add_argument("--traces-dir", type=Path, help="Trace source member names supporting the validation report")
args = parser.parse_args()
data = inventory(args.manifest.resolve())
if args.validation_report is not None:
validation_evidence(data, args.validation_report, args.traces_dir)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
print(json.dumps(data["counts"], indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()