Commit Graph

13 Commits

Author SHA1 Message Date
yuliuse 56bcc62e49 feat(whucad): WHUCAD vector → FTC translator toolset under tools/research
Decode the WHUCAD h5 vector sequences (256-level quantized CATIA/DeepCAD
command matrices) and translate them into SimpleCADAPI FTC sources,
mirroring the histjson tool suite:

- whucad_vec.py       self-contained decoder (numpy only; differential-
                      checked against the original cadlib, 1419/1419 exact)
- whucad_select.py    Topo/Select history references -> ql predicates
- whucad_to_ftc.py    translator (keyword-form call emission, histjson
                      convention; unsupported forms annotated, never
                      approximated)
- whucad_profile.py   feature/curve/select-form distribution + coverage
- whucad_validate.py  sampled build + BRep-truth volume reconciliation
                      (scale-corrected: vectors carry no absolute scale)
- whucad_batch.py     whole-dataset batch entry point
- check_port.py       differential check vs the original cadlib decode
- test_whucad_translation_output.py  output-contract tests (embedded
                      vectors; no dataset download needed)

Full-dataset run: 146,331 models -> 146,331 .py, 424,947 features decoded,
380,074 feature blocks emitted (89.4%). pyproject gains a 'whucad' extra
(h5py).
2026-09-10 22:07:28 +08:00
NiJingzhe aac0fbb29d feat(cache): script-anchored part cache, keyword-form corpus, 2.1.2
- @scad.part/@scad.assemble anchor defaults to the builder script's own
  directory: cache + interface state land beside the source, standalone
  scripts run anywhere, and the pyproject.toml walk-up requirement is
  gone (explicit project_root still relocates the anchor)
- file_input() paths resolve relative to the anchor; in-repo examples
  rewritten to script-relative declarations
- HistCAD translator emits keyword-form sketch-family calls (corpus
  self-documentation), pinned by tests; booleans stay positional by
  *solids signature
- both translators emit project_root=Path(__file__).parent explicitly;
  examples/histcad_demo regenerated (STEP volume reconciliation held)
- FTC convention documents @scad.part parameters and the cache contract
- version stamps 2.1.2 + bilingual update notes
2026-09-10 00:11:28 +08:00
NiJingzhe 90af1346e5 docs: usage-first README for the cadqueryftc toolset 2026-09-09 21:59:22 +08:00
NiJingzhe 022d14b733 feat: keyword-only call emission for training-corpus self-documentation
All sketch-family calls emitted by the translator now pass every argument
by keyword — add_point/add_line/add_circle/add_arc, constrain_* (via a
per-kind parameter-name table), and the face/wire promotions — so the
parameter meaning is legible from the corpus itself.  The only exception
is the boolean *solids varargs (union/cut/intersect), which have no
parameter names to take.

Also fixes an f-string trap the keyword pass exposed: a conversion
(`!r`) applies to the whole conditional expression, silently quoting the
numeric branch of value formatting (constrain_radius value='32.4' →
solver TypeError); formatting now goes through a helper.

New corpus pin: generated sources contain no positional sketch-family
calls.  Full regeneration reconciles at the same precision as before
(washer 1.6e-16, wheel 4.6e-16, rarray 0.0; pulley 5/5 sketches riveted).
2026-09-09 21:19:33 +08:00
NiJingzhe e56c17dec3 refactor: single-choke-point sketch capture in SketchScript.render
Capture previously lived per emission call site (plain profiles, sweep
paths) — the taper loft sections and countersink cones built their
SketchScripts directly and silently bypassed snapshots and constraint
recovery, which is why pulley's extrude-3 carried constraints while its
two taper blocks did not.

SketchScript.render is now the one capture point: it fires the replayer
sink (block-context stamping, snapshot collection, constraint recovery)
and appends the sink's constraint lines after the entities. Every
construction site — profiles, loft/taper sections, countersink cones,
sweep paths, and pattern seeds (whose loop-expression plane header is
supported via render(header=...)) — is captured by construction; no call
site remembers anything. emit_profile_sketch reverts to pure formatting
(sink forwarded, snapshot return removed).

Pulley now reports 5/5 sketches riveted (taper sections included) and
wheel 2 sketches (pattern seed captured; the 63-point outline still
degrades to timeout). New tests pin the invariant: the pulley taper
blocks carry section constraints, and a SketchScript sink fires exactly
once per render. Real pulley trace baked as a fixture.
2026-09-09 17:35:59 +08:00
NiJingzhe 1ca73e214a feat: snapshot constraint recovery for the CadQuery FTC translator
Adds the auto-constraint discovery and extraction layer discussed for the
CadQuery pipeline, as a source-agnostic capability:

- every translation now writes <stem>.sketches.json: per-block planar
  sketch snapshots (plane frame + typed entities in local coordinates +
  closedness) — the schema-facing interface any front-end can emit.
- cqftc/constraints.py implements the recovery axioms: candidates are only
  snapshot-entailed relations (P2); admission is the production SolveSpace
  solver's DOF drop with redundancy-introducing candidates rejected — the
  DOF counter alone is fooled by rank-deficient systems (P3); a riveted set
  must also pass the perturbation basin test, a jittered rebuild converging
  back onto the snapshot (P1); measured values emit verbatim (P4); ids
  carry the inf<N>_<Kind> provenance prefix (P5).
- candidates run in an intent-typicality ladder (anchor, H/V, parallel/
  perpendicular, tangency/equal/concentric, lengths/radii, orientation,
  adjacent angles, half-grid distances) under per-tier and global solve
  budgets; sketches above 24 entities recover in a subprocess worker with a
  wall-clock escape hatch because SolveSpace's redundancy analysis can
  explode combinatorially on large freeform outlines.
- cadquery_to_ftc.py --constraints on emits the recovered sets inline
  between sketch entities and promotion; results graded riveted/partial/
  timeout in the meta sidecar; --constraints off output is byte-identical
  to before.
- fixtures: hexagon/washer/revolve-ring/slot sketches rivet with canonical
  human-shaped sets (e.g. hexagon = fix + 2H + 2 parallel + 3 equal-length
  + length + signed dx + 60 deg) and constrained builds still reconcile at
  machine precision; the 63-point wheel outline honestly degrades to
  timeout. 22 tests, ty clean.

Sign-convention traps fixed along the way: distance_x value is signed
(b - a); emitting abs() pulled a rank-complete hexagon onto a mirrored
branch (caught by the coords-reconciliation gate).
2026-09-08 23:53:38 +08:00
NiJingzhe 216a7ed625 feat: CadQuery→FTC translator toolset under tools/research (cadqueryftc)
Port the runtime-tracer half of PR #30 (feat/cadquery_converter) and rewrite
its emission layer to the current Feature Tree Convention, following the
tools/research/histjson four-stage pattern (trace / translate / validate /
profile + responsibility wall: the translator only translates).

- tracer/ (instrument, fingerprint, cq_runner, worker) ported near-verbatim:
  runs under .venv-cq (Python 3.11 + cadquery 2.8); records resolved plane
  frames, serialized args, selector strings, and geometric fingerprints of
  actually-selected faces/edges plus ground-truth volume/bbox per program.
- emission rewritten for FTC: block headers with closed role vocabulary and
  no positional slugs; transcribed planar profiles authored through the
  sketch API (local coords, pooled points, three-point arcs via
  circumcenter) annotated profile=geometry; booleans in list form over a
  histjson-shaped bodies dataflow; fillet/chamfer/shell selections
  synthesized as QL predicate bands from trace fingerprints with
  take/exactly cardinality; through-cut depths derived from the trace
  bbox; zero in-source verification; literal numbers only.
- unknown ops become untranslated notes, never silent drops; static-AST
  path and exploratory scoring/edit-bench from the PR intentionally not
  ported.
- directory named cadqueryftc so it can never shadow `import cadquery`.
- fixtures are real traces captured with cadquery 2.8; 13 tests pin format
  contracts + volume reconciliation (all four reconcile at <=2.2e-12 rel
  err) with no cadquery required in CI; full test/ suite 1516 passed.
2026-09-08 15:53:51 +08:00
NiJingzhe 54017d0f3d docs(histcad): usage guide for the histjson tool suite
Covers the five user questions in reading order: how to translate (single
case / batch / demos), what the output is (annotated FTC anatomy, tier
annotation semantics, constraint_id channel), coverage (structure 100% ops,
geometry channel 85.0%/76.7% pass, constraint channel 90.3%/93.0% solvable
on the standard 100-case samples), why things fail (four-way taxonomy:
unmapped forms / dataset-side constraint errors / build-level union
contract / known dataset artifacts), and how to find the non-translatable
entries (conflicts analyzer cross-tables + dump-uid, validate reports,
in-source notes, profiler). Numbers reproduce with the pinned
count/stride commands at the end.
2026-09-04 16:40:37 +08:00
NiJingzhe cc2946dd2e refactor(histcad): translator only translates — no preflight, no tier decisions
Per user ruling: the translator unconditionally translates what the dataset
carries (constraints included, --constraints on|off, default on). The auto
mode, in-process preflight, drift gate and sidecar conflict report are gone
from the translator — auditing now lives entirely in histcad_conflicts.py,
which renders each feature's translated prefix with the same StepEmitter
and classifies the solve itself (solved / drifted >1e-3 / conflicting /
exec_error) on top of the residual + dof + halfSpace analysis.
histcad_validate.py is build + STEP volume reconciliation only.

Generated sources are unchanged in shape (single path, constraint_id tags,
pure FTC blocks); demos regenerated with full constraint sets and still
reconcile to STEP at machine precision. Purity tests updated to pin the
sharper contract: unconditional constraint translation, pooled-coincident
elision, and that the translator module never imports the SDK.
2026-09-04 15:15:24 +08:00
NiJingzhe 48c77c2055 feat(histcad): pure training-data translation, tools under research/histjson
Generated sources carry the model only: the dual-path constraint fallback,
SKETCH_CONFLICTS/SKETCH_TIER_FALLBACKS audit globals and strict=False
inspection are gone from translated code. Tier decisions and conflict
auditing moved to translation time: auto mode solves each feature's
constrained sketch prefix in-process (preflight), emits sketch tier when it
solves AND reproduces the transcribed coordinates (max point move <= 1e-3,
the drift gate), otherwise transcribed geometry; diagnostics go to the
sidecar report (<case>.ftc.py.report.json).

Root causes found by the new histcad_conflicts.py residual analyzer and
fixed in the translator:
- point-pair H/V distances are directed: sign now taken from coordinates
  (the stored length is a magnitude) — was the top Fusion conflict source
- Tangent on arcs needs an endpoint selector: picked as the nearest shared
  junction with the other curve
- MajorRadius/MinorRadius store full axis lengths: halved to semi-axes
  (solver was stretching ellipses 2x)
- Horizontal/Vertical flat line lists map each line individually
- variadic Equal chains get per-pair constraint ids (duplicate-id crash)
- Coincident entries whose refs pooled onto the same point are elided:
  degenerate point-coincident equations made the solver Jacobian singular
  and showed exact-geometry sketches as conflicting

SDK: constrain_concentric_rsketch now accepts ellipse targets (backend
resolves the ellipse center point).

Validation (100-case samples, constraints=auto): Fusion360 72 pass,
sketch-tier retention 77.5% (conflicts: 19 diverged + 1 conflicting);
DeepCAD 83 pass, retention 85.0% (9 diverged, 0 solver-conflicting).
Demos regenerated, volumes reconcile to STEP. Purity pinned by
test/test_histcad_translation_output.py (9 tests). Full suite 1489 passed.
2026-09-04 14:28:49 +08:00
NiJingzhe c092b3d49e feat(research): constraint translation channel with per-conflict dataset auditing
The translator now emits native sketch constraints (auto mode): every
HistCAD entry maps to a constrain_* call tagged with its source identity
(constraint_id='h7_Distance'), variadic chains decompose with suffixed
ids, and value_exprs evaluate through a unit-aware expression parser
(mm/in/cm/m/ft/yd plus arithmetic and mixed-unit sums like
'61.5 in + 8ft').

Stability comes from an honest dual path per feature: entities bind to
s_geo, constraints derive s, promotion tries the constrained sketch and
falls back to the geometry prefix when the solver reports conflict. The
except branch re-inspects with strict=False and records WHICH constraint
entries failed into SKETCH_CONFLICTS — the pipeline doubles as a dataset
constraint-quality auditor (rounded coordinates vs over-determined
systems are the observed conflict source).

Sampled auto-mode results (volume still machine-exact on passes):
- DeepCAD 100: 83 pass, sketch-tier retention 92.1% (conflicts:
  Length 7, Distance 6, Diameter 2, Equal 1)
- Fusion360 100: 67 pass, retention 66.2% (Distance dominates with 49 —
  its halfSpace signed-offset dialect needs side semantics work)
Demo regenerated with 28 constraint calls, volume unchanged at 349.4558.
2026-09-04 13:09:32 +08:00
NiJingzhe 962e78edac feat(research): histcad->FTC translator and STEP reconciliation harness
histcad_to_ftc.py: one FTC feature block per HistCAD step — plane mapping
from Euler+translation (convention Rx@Ry@Rz, calibrated exactly against
packaged STEP on mixed-angle samples), coordinate-pooled sketch entities
(arc endpoints ordered so the CCW promotion sweep passes through the
HistCAD middle point, nurbs knot compression, three-point ellipses),
containment-based outer/hole nesting with island support, per-mode
booleans, and an honest multi-body policy (disjoint NewBody/Join bodies
stay separate; BODIES exported for the harness).

histcad_validate.py: strided-sample executor comparing total solid
volume against the packaged STEP ground truth (1e-3 relative tolerance).
2026-09-04 05:53:54 +08:00
NiJingzhe 77584b1e20 feat(research): histcad dataset profiler tool
Streams HistCAD sequence tarballs and aggregates the feature/entity/
constraint vocabulary, sizing FTC translation coverage gaps with counts.
Scan outputs land in gitignored tools/research/out/.
2026-09-04 04:43:44 +08:00