Skip to content

Official Codebase of 3DCodeVerse

Python

conventions: one instance-suffix rule (split_instance) for the measure table, the contract match and refine grouping

gaoypeng521b36b787da
diff --git a/harness/codeverse3d/conventions.py b/harness/codeverse3d/conventions.py
index 75d0e353..937d48c7 100644
--- a/harness/codeverse3d/conventions.py
+++ b/harness/codeverse3d/conventions.py
@@ -191,6 +191,19 @@ def to_snake(name: str) -> str:
PASCAL_RE = re.compile(r"^[A-Z][A-Za-z0-9]*(?:_\d+)?$")
+#: how an instance name maps to its part: ``Leg_2`` (the contract's ``Name_N``), Blender's
+#: auto-suffix ``Leg.001`` and ``Leg-2`` all read as part ``Leg``; up to three digits, so a
+#: scene asset's hex id that happens to be all digits (``DonkeyCart_800006``) is no index.
+_INSTANCE_RE = re.compile(r"^(?P<base>.+?)[_.-](?P<idx>\d{1,3})$")
+
+
+def split_instance(name: str) -> tuple[str, str]:
+ """``Leg_2`` → (``Leg``, ``"2"``); a name with no instance suffix → (name, ``""``). THE
+ instance rule: the measure table, the contract match and refine grouping all read it."""
+ m = _INSTANCE_RE.match(name)
+ return (m.group("base"), m.group("idx")) if m else (name, "")
+
+
def to_pascal(name: str) -> str:
"""``seat_cushion`` / ``seat cushion`` → ``SeatCushion``; a name that is already
PascalCase (no underscore) comes back unchanged, so ``TVStand`` stays ``TVStand``.
diff --git a/harness/codeverse3d/languages/urdf/__init__.py b/harness/codeverse3d/languages/urdf/__init__.py
index e33ef306..179ee318 100644
--- a/harness/codeverse3d/languages/urdf/__init__.py
+++ b/harness/codeverse3d/languages/urdf/__init__.py
@@ -566,7 +566,6 @@ def compute_urdf_frames(plan: ArticulatedPlan) -> UrdfFrames:
"""Pure function: plan → link frames + joint rows in the enforced convention."""
parts = _expand_parts(plan)
base_names = {to_snake(p.name) for p in plan.parts}
- instance_links = {n for n, p, _ in parts if p.instances > 1}
root = to_snake(plan.root_link)
links: dict[str, LinkFrame] = {}
pivot_of: dict[str, tuple[float, float, float]] = {}
@@ -594,7 +593,8 @@ def compute_urdf_frames(plan: ArticulatedPlan) -> UrdfFrames:
parent, child = to_snake(j.parent), to_snake(j.child)
if parent in base_names and parent not in {n for n, _, _ in parts}:
parent = f"{parent}_1" # joint to an instanced parent → first instance
- children = [n for n, p, _ in parts if n == child or (n in instance_links and n.rsplit("_", 1)[0] == child)]
+ # one instance link by its own name, else the part and every instance link it expanded to
+ children = [n for n, p, _ in parts if n == child or to_snake(p.name) == child]
for k, c in enumerate(children):
add_joint(j, c, parent, "" if len(children) == 1 else f"_{k + 1}")
diff --git a/harness/codeverse3d/orchestrator.py b/harness/codeverse3d/orchestrator.py
index 67685e0e..46cea34e 100644
--- a/harness/codeverse3d/orchestrator.py
+++ b/harness/codeverse3d/orchestrator.py
@@ -26,7 +26,7 @@ from codeverse3d.contracts.artifacts import GateReport, Judgment
from codeverse3d.contracts.common import Budget
from codeverse3d.contracts.plan import AcceptanceItem, Plan
from codeverse3d.contracts.run import RoundRecord, RunStatus, StepTime
-from codeverse3d.conventions import to_snake
+from codeverse3d.conventions import split_instance, to_snake
from codeverse3d.cost.tally import timed
from codeverse3d.proc import EventLog
from codeverse3d.workspace import Workspace
@@ -387,12 +387,8 @@ def compact_instructions(tasks: Sequence[RefineTask], max_lines: int = 6) -> lis
# ----------------------------------------------------------------------------- helpers
def _split_instance(target: str) -> tuple[str, str]:
- """``BackLeg_1`` → (``BackLeg``, ``1``) per the ``Name_0..N-1`` instance naming
- convention; anything else → (target, "")."""
- base, sep, suffix = (target or "").rpartition("_")
- if sep and base and suffix.isdigit():
- return base, suffix
- return target or "overall", ""
+ """``conventions.split_instance``; an empty target is ``overall``."""
+ return split_instance(target) if target else ("overall", "")
def _instance_base(target: str) -> str:
diff --git a/harness/codeverse3d/spatial/contract.py b/harness/codeverse3d/spatial/contract.py
index f34e0a45..8032cc5a 100644
--- a/harness/codeverse3d/spatial/contract.py
+++ b/harness/codeverse3d/spatial/contract.py
@@ -23,7 +23,6 @@ Severity policy (``tol = max(tol_m, REL_TOL × plan extent)`` per axis):
from __future__ import annotations
-import re
import time
from dataclasses import dataclass
@@ -42,6 +41,7 @@ from codeverse3d.conventions import (
CONTACT_GAP_M,
FRAME_AXES,
Frame,
+ split_instance,
to_authoring_frame,
to_snake,
)
@@ -106,20 +106,16 @@ def glb_vec_to_plan(v, language: str, *, extents: bool = False) -> np.ndarray:
# --------------------------------------------------------------------------- matching
-def _instance_re(snake: str) -> re.Pattern[str]:
- return re.compile(rf"^{re.escape(snake)}(?:[_.-]?\d{{1,3}})?$")
-
-
def match_parts(plan_parts: list[PartPlan], measured: list[PartMeasure]) -> tuple[dict[str, list[PartMeasure]], list[PartMeasure]]:
"""Map each plan part → measured rows (``Name``, ``Name_0``… accepted); plus unmatched rows.
- Exact names are claimed FIRST, and the ``Name_0..Name_N`` instance pass never takes
- a node that another plan part names exactly. ``_instance_re("shelf")`` matches
- ``shelf2``, so a plan of ``Shelf`` + ``Shelf2`` used to have ``Shelf`` swallow the
- ``Shelf2`` node before ``Shelf2`` was considered — a false "missing from the GLB"
- ERROR and a real 0.75 judge cap on geometry that matched the plan exactly.
- ``Shelf``/``Shelf2``, ``Slat``/``Slat1``, ``Tier``/``Tier2`` are ordinary planner
- output for PascalCase part names.
+ Exact names are claimed FIRST, and the ``Name_0..Name_N`` instance pass
+ (``conventions.split_instance``) never takes a node that another plan part names
+ exactly. The instance pattern once took ``shelf2`` for ``Shelf``, so a plan of
+ ``Shelf`` + ``Shelf2`` had ``Shelf`` swallow the ``Shelf2`` node before ``Shelf2`` was
+ considered — a false "missing from the GLB" ERROR and a real 0.75 judge cap on geometry
+ that matched the plan exactly. ``Shelf``/``Shelf2``, ``Slat``/``Slat1``, ``Tier``/``Tier2``
+ are ordinary planner output for PascalCase part names.
"""
remaining = {m.name: m for m in measured}
matched: dict[str, list[PartMeasure]] = {pp.name: [] for pp in plan_parts}
@@ -131,9 +127,9 @@ def match_parts(plan_parts: list[PartPlan], measured: list[PartMeasure]) -> tupl
remaining.pop(m.name, None)
matched[pp.name].extend(hits)
for pp in plan_parts: # pass 2: its Name_0..Name_N instances
- pat = _instance_re(to_snake(pp.name))
+ snake = to_snake(pp.name)
hits = [m for n, m in list(remaining.items())
- if to_snake(n) not in reserved and pat.match(to_snake(n))]
+ if to_snake(n) not in reserved and split_instance(to_snake(n))[0] == snake]
for m in hits:
remaining.pop(m.name, None)
matched[pp.name].extend(hits)
diff --git a/harness/codeverse3d/spatial/measure.py b/harness/codeverse3d/spatial/measure.py
index e721fd53..be62c869 100644
--- a/harness/codeverse3d/spatial/measure.py
+++ b/harness/codeverse3d/spatial/measure.py
@@ -21,7 +21,6 @@ from __future__ import annotations
import contextlib
import json
-import re
import struct
import threading
from collections import Counter, OrderedDict
@@ -33,6 +32,7 @@ import numpy as np
import trimesh
from codeverse3d.contracts.artifacts import Measurement, PartMeasure
+from codeverse3d.conventions import split_instance
__all__ = [
"load_scene",
@@ -47,9 +47,6 @@ __all__ = [
"merged_mesh",
]
-_INSTANCE_RE = re.compile(r"^(?P<base>.+?)[_.-](?P<idx>\d{1,3})$")
-
-
class GlbLoadError(RuntimeError):
"""The GLB could not be loaded or contains no mesh geometry."""
@@ -429,16 +426,14 @@ def instance_groups(names: list[str]) -> OrderedDict[str, list[str]]:
"""Group ``Leg_0, Leg_1, Leg_2`` → ``{"Leg": [...]}``; singletons keep their name."""
groups: OrderedDict[str, list[str]] = OrderedDict()
for n in names:
- m = _INSTANCE_RE.match(n)
- key = m.group("base") if m else n
- groups.setdefault(key, []).append(n)
+ groups.setdefault(split_instance(n)[0], []).append(n)
# a "group" with a single member is just the part itself
out: OrderedDict[str, list[str]] = OrderedDict()
for key, members in groups.items():
if len(members) > 1:
- # a bare base name ("lens" beside "lens_1") lands in the group without
- # matching the regex — sort it first instead of crashing on the None match
- members = sorted(members, key=lambda n: int(m.group("idx")) if (m := _INSTANCE_RE.match(n)) else -1)
+ # a bare base name ("lens" beside "lens_1") lands in the group with no
+ # index — sort it first
+ members = sorted(members, key=lambda n: int(split_instance(n)[1] or -1))
out[key if len(members) > 1 else members[0]] = members
return out
@@ -479,7 +474,7 @@ def measure_summary_table(m: Measurement, max_rows: int = 30) -> str:
if len(ps) == 1:
label, size_txt = key, fmt_extent_cm(ext)
else:
- label = f"{key} ×{len(ps)} ({members[0]}..{members[-1].rsplit('_', 1)[-1]})"
+ label = f"{key} ×{len(ps)} ({members[0]}..{split_instance(members[-1])[1]})"
each = np.max([np.subtract(p.bbox_max, p.bbox_min) for p in ps], axis=0)
size_txt = f"{fmt_extent_cm(each)} each, span {fmt_extent_cm(ext)}"
tris = sum(p.tri_count for p in ps)
diff --git a/harness/tests/core/test_names.py b/harness/tests/core/test_names.py
index 3e693caa..cc9db3ef 100644
--- a/harness/tests/core/test_names.py
+++ b/harness/tests/core/test_names.py
@@ -10,7 +10,7 @@ from pathlib import Path
from codeverse3d.contracts.common import Track
from codeverse3d.contracts.plan import StaticPlan
-from codeverse3d.conventions import PASCAL_RE, to_pascal, to_snake
+from codeverse3d.conventions import PASCAL_RE, split_instance, to_pascal, to_snake
from codeverse3d.languages.blender import lint_blender_source
from codeverse3d.languages.cadquery import lint_cadquery_source
from codeverse3d.languages.urdf import _IDENT as URDF_LINK_RE
@@ -91,3 +91,20 @@ def test_the_part_name_lints_accept_acronyms():
def test_material_words_split_acronyms():
hit = family_for("PVCPipe")
assert hit is not None and hit == family_for("pvc pipe")
+
+
+def test_one_instance_rule_for_every_reader():
+ """``conventions.split_instance`` is the rule the measure table, the contract match and
+ refine grouping read (four hand-written copies until 2026-09-23 — the refine grouping
+ read ``DonkeyCart_800006``, a scene asset's all-digit hex id, as instance 800006)."""
+ from codeverse3d.orchestrator import _canon_target, _instance_base
+ from codeverse3d.spatial.measure import instance_groups
+
+ rows = {"Leg_2": ("Leg", "2"), "Leg.001": ("Leg", "001"), "leg-3": ("leg", "3"), "Leg_1_2": ("Leg_1", "2"),
+ "Leg": ("Leg", ""), "Shelf2": ("Shelf2", ""), "HDMIPort1": ("HDMIPort1", ""),
+ "DonkeyCart_800006": ("DonkeyCart_800006", ""), "Leg_": ("Leg_", "")}
+ assert {n: split_instance(n) for n in rows} == rows
+ assert list(instance_groups(["Leg_1", "Leg.002", "Shelf", "Shelf2", "Cart_800006", "Cart_801"])) == \
+ ["Leg", "Shelf", "Shelf2", "Cart_800006", "Cart_801"]
+ assert _instance_base("DonkeyCart_800006") == "DonkeyCart_800006" and _instance_base("") == "overall"
+ assert _canon_target("leg_1", {"leg": "Leg"}) == "Leg_1"