Merge pull request #41 from So3Lab/bugfix/connector-interface-hash
fix(placement): integer-tick canonical identity for all hashed frames
This commit is contained in:
@@ -26,7 +26,7 @@ from ..product.connector import (
|
||||
from ..product.constraint import Constraint, ScalarLimit
|
||||
from ..product.material import Material
|
||||
from ..product.part import Part
|
||||
from ..product.placement import Placement
|
||||
from ..product.placement import placement_from_canonical, placement_ticks
|
||||
from ..scene.archive import canonical_zip_bytes, preflight_zip_bytes
|
||||
from .assembly_definition import (
|
||||
AssemblyDefinition,
|
||||
@@ -599,7 +599,7 @@ def _runtime_connector(interface: ConnectorInterface) -> Connector:
|
||||
name=interface.name,
|
||||
anchor=ConnectorAnchor(
|
||||
"placement",
|
||||
placement=Placement(**dict(interface.local_frame)),
|
||||
placement=placement_from_canonical(interface.local_frame),
|
||||
),
|
||||
)
|
||||
raise ArtifactValidationError(
|
||||
@@ -695,11 +695,11 @@ def _apply_verified_snapshot(
|
||||
for component_id in authored.component_ids():
|
||||
candidate = candidate.with_component_placement(
|
||||
component_id,
|
||||
Placement(**dict(by_id[component_id])),
|
||||
placement_from_canonical(by_id[component_id]),
|
||||
)
|
||||
if any(
|
||||
candidate.get_component(component_id).placement.to_dict()
|
||||
!= dict(by_id[component_id])
|
||||
placement_ticks(candidate.get_component(component_id).placement)
|
||||
!= placement_ticks(by_id[component_id])
|
||||
for component_id in authored.component_ids()
|
||||
):
|
||||
return None
|
||||
@@ -765,7 +765,7 @@ def materialize_definition(
|
||||
Component(
|
||||
component_id=item.instance_id,
|
||||
item=direct[item.definition_id],
|
||||
placement=Placement(**dict(item.placement)),
|
||||
placement=placement_from_canonical(item.placement),
|
||||
name=item.name,
|
||||
)
|
||||
for item in node.instances
|
||||
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Mapping
|
||||
|
||||
from ..product.placement import Placement
|
||||
from ..product.placement import canonical_frame
|
||||
from .canonical import (
|
||||
ArtifactValidationError,
|
||||
content_hash,
|
||||
@@ -25,6 +25,12 @@ def _closed(data: Mapping[str, Any], required: set[str], path: str) -> None:
|
||||
unknown = sorted(actual - required)
|
||||
detail = f"missing={missing}, unknown={unknown}"
|
||||
raise ArtifactValidationError("fields_invalid", path, detail)
|
||||
def _canonical_local_frame(value: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"""Normalize connector frames into integer-tick identity form."""
|
||||
try:
|
||||
return canonical_frame(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ArtifactValidationError("frame_invalid", "/connector/local_frame", str(exc)) from exc
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -137,10 +143,7 @@ class ConnectorInterface:
|
||||
raise ArtifactValidationError("name_invalid", "/connector/name", "name must be null or non-empty")
|
||||
if self.anchor_kind not in {"geometry", "placement", "public"}:
|
||||
raise ArtifactValidationError("connector_invalid", "/connector/anchor_kind", "unsupported anchor kind")
|
||||
try:
|
||||
frame = Placement(**dict(self.local_frame)).to_dict()
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ArtifactValidationError("frame_invalid", "/connector/local_frame", str(exc)) from exc
|
||||
frame = _canonical_local_frame(self.local_frame)
|
||||
object.__setattr__(self, "local_frame", frame)
|
||||
if self.anchor_kind == "geometry" and self.binding is None:
|
||||
raise ArtifactValidationError("connector_invalid", "/connector/binding", "geometry connector requires binding")
|
||||
@@ -274,7 +277,7 @@ class PartInstance:
|
||||
if self.name is not None and (not isinstance(self.name, str) or not self.name.strip()):
|
||||
raise ArtifactValidationError("name_invalid", "/instance/name", "name must be null or non-empty")
|
||||
try:
|
||||
object.__setattr__(self, "placement", Placement(**dict(self.placement)).to_dict())
|
||||
object.__setattr__(self, "placement", canonical_frame(self.placement))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ArtifactValidationError("frame_invalid", "/instance/placement", str(exc)) from exc
|
||||
|
||||
|
||||
@@ -41,8 +41,8 @@ from ..recording.graph import GraphSession, get_active_session, record_operation
|
||||
from ..product.assembly import Assembly, _component_occurrence_placements
|
||||
from ..product.solver import inspect_assembly_constraints
|
||||
from ..product.connector import ConnectorRef, resolve_connector_ref_placement
|
||||
from ..product.placement import canonical_frame, placement_ticks
|
||||
from ..product.part import Part
|
||||
from ..product.placement import Placement
|
||||
from .assembly_state import (
|
||||
AssemblyInterfaceSnapshot,
|
||||
load_latest_assembly_state,
|
||||
@@ -167,7 +167,7 @@ def _solved_snapshot(assembly: Assembly) -> Mapping[str, Any]:
|
||||
"component_placements": [
|
||||
{
|
||||
"instance_id": component.component_id,
|
||||
"placement": component.placement.to_dict(),
|
||||
"placement": placement_ticks(component.placement),
|
||||
}
|
||||
for component in sorted(
|
||||
assembly.components,
|
||||
@@ -183,7 +183,7 @@ def _authored_component_placements(
|
||||
assembly: Assembly,
|
||||
) -> Mapping[str, Mapping[str, Any]]:
|
||||
current = {
|
||||
component.component_id: component.placement.to_dict()
|
||||
component.component_id: placement_ticks(component.placement)
|
||||
for component in assembly.components
|
||||
}
|
||||
authored = assembly._get_runtime(_AUTHORED_PLACEMENTS_RUNTIME_KEY)
|
||||
@@ -204,7 +204,7 @@ def _authored_component_placements(
|
||||
"authored component placement must be a frame object",
|
||||
)
|
||||
try:
|
||||
normalized[str(component_id)] = Placement(**dict(placement)).to_dict()
|
||||
normalized[str(component_id)] = canonical_frame(placement)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ArtifactValidationError(
|
||||
"assembly_provenance_invalid",
|
||||
|
||||
@@ -28,7 +28,7 @@ from ..product.solver import (
|
||||
solve_assembly_constraints,
|
||||
)
|
||||
from ..product.constraint import ConstraintReport
|
||||
from ..product.placement import Placement
|
||||
from ..product.placement import Placement, placement_from_canonical, placement_ticks
|
||||
from .assembly_state import AssemblyInterfaceSnapshot, effective_interface_hashes
|
||||
from .dependency_graph import (
|
||||
AssemblyDependencyGraph,
|
||||
@@ -172,7 +172,7 @@ def propagate_assembly_dirty_state(
|
||||
current_instances = {
|
||||
component.component_id: {
|
||||
"definition_id": definition_by_instance[component.component_id],
|
||||
"placement": component.placement.to_dict(),
|
||||
"placement": placement_ticks(component.placement),
|
||||
}
|
||||
for component in assembly.components
|
||||
}
|
||||
@@ -318,17 +318,20 @@ def _authored_assembly(
|
||||
"authored component placements do not match assembly instances",
|
||||
)
|
||||
authored = {
|
||||
str(component_id): Placement(**dict(placement)).to_dict()
|
||||
str(component_id): placement_from_canonical(placement)
|
||||
for component_id, placement in raw.items()
|
||||
}
|
||||
restored = assembly
|
||||
for component_id, placement in authored.items():
|
||||
restored = restored.with_component_placement(
|
||||
component_id,
|
||||
Placement(**placement),
|
||||
placement,
|
||||
)
|
||||
restored._set_runtime(_AUTHORED_PLACEMENTS_RUNTIME_KEY, authored)
|
||||
return restored, authored
|
||||
restored._set_runtime(
|
||||
_AUTHORED_PLACEMENTS_RUNTIME_KEY,
|
||||
{key: value.to_dict() for key, value in authored.items()},
|
||||
)
|
||||
return restored, {key: value.to_dict() for key, value in authored.items()}
|
||||
|
||||
|
||||
def assembly_component_solve_key(
|
||||
@@ -374,7 +377,7 @@ def assembly_component_solve_key(
|
||||
{
|
||||
"instance_id": instance_id,
|
||||
"definition_id": by_id[instance_id],
|
||||
"authored_placement": instance_by_id[instance_id].placement.to_dict(),
|
||||
"authored_placement": placement_ticks(instance_by_id[instance_id].placement),
|
||||
}
|
||||
for instance_id in component.instance_ids
|
||||
],
|
||||
@@ -405,7 +408,7 @@ def _encode_component_result(
|
||||
"placements": [
|
||||
{
|
||||
"instance_id": instance_id,
|
||||
"placement": solved.get_component(instance_id).placement.to_dict(),
|
||||
"placement": placement_ticks(solved.get_component(instance_id).placement),
|
||||
}
|
||||
for instance_id in component.instance_ids
|
||||
],
|
||||
@@ -518,11 +521,11 @@ def _apply_component_payload(
|
||||
for instance_id in component.instance_ids:
|
||||
candidate = candidate.with_component_placement(
|
||||
instance_id,
|
||||
Placement(**dict(by_id[instance_id])),
|
||||
placement_from_canonical(by_id[instance_id]),
|
||||
)
|
||||
if any(
|
||||
candidate.get_component(instance_id).placement.to_dict()
|
||||
!= dict(by_id[instance_id])
|
||||
placement_ticks(candidate.get_component(instance_id).placement)
|
||||
!= placement_ticks(by_id[instance_id])
|
||||
for instance_id in component.instance_ids
|
||||
):
|
||||
raise ValueError("top-level and occurrence placements differ")
|
||||
@@ -654,7 +657,7 @@ def solve_assembly_incrementally(
|
||||
result = _with_component_path_placement(
|
||||
result,
|
||||
tuple(record["component_path"]),
|
||||
Placement(**dict(record["placement"])),
|
||||
placement_from_canonical(record["placement"]),
|
||||
)
|
||||
component_results.append(
|
||||
ComponentSolveResult(
|
||||
|
||||
@@ -9,7 +9,7 @@ from .._internal.semantic import SemanticValueMixin, _validate_identifier
|
||||
from .connector import ConnectorRef, resolve_connector, resolve_item_connector
|
||||
from .constraint import Constraint, _validate_constraints
|
||||
from .part import Part
|
||||
from .placement import Placement
|
||||
from .placement import Placement, placement_from_canonical, placement_ticks
|
||||
|
||||
_AUTHORED_PLACEMENTS_RUNTIME_KEY = "assembly.authored_component_placements"
|
||||
|
||||
@@ -375,7 +375,7 @@ def _component_occurrence_placements(
|
||||
records.append(
|
||||
{
|
||||
"component_path": list(component_path),
|
||||
"placement": component.placement.to_dict(),
|
||||
"placement": placement_ticks(component.placement),
|
||||
}
|
||||
)
|
||||
if isinstance(component.item, Assembly):
|
||||
@@ -465,7 +465,7 @@ def _restore_component_occurrence_placements(
|
||||
memo: Dict[Tuple[int, Tuple[Any, ...]], Assembly] = {}
|
||||
|
||||
def placement_key(placement: Mapping[str, Any]) -> Tuple[Any, ...]:
|
||||
value = Placement(**dict(placement))
|
||||
value = placement_from_canonical(placement)
|
||||
return (
|
||||
value.origin,
|
||||
value.x_axis,
|
||||
@@ -497,7 +497,7 @@ def _restore_component_occurrence_placements(
|
||||
components = []
|
||||
for component in owner.components:
|
||||
component_path = (*prefix, component.component_id)
|
||||
placement = Placement(**dict(by_path[component_path]))
|
||||
placement = placement_from_canonical(by_path[component_path])
|
||||
item = (
|
||||
rebuild(component.item, component_path)
|
||||
if isinstance(component.item, Assembly)
|
||||
|
||||
@@ -9,7 +9,7 @@ from typing import Any, Mapping
|
||||
from ..artifacts.assembly_definition import AssemblyDefinition
|
||||
from ..artifacts.canonical import canonical_bytes, content_hash, parse_canonical_json
|
||||
from ..artifacts.part_definition import PartDefinition
|
||||
from .placement import identity_placement
|
||||
from .placement import identity_placement, placement_ticks
|
||||
|
||||
Definition = PartDefinition | AssemblyDefinition
|
||||
|
||||
@@ -167,7 +167,7 @@ def compile_product_occurrence_graph(root: Definition) -> ProductOccurrenceGraph
|
||||
root,
|
||||
(root.definition_id,),
|
||||
None,
|
||||
identity_placement().to_dict(),
|
||||
placement_ticks(identity_placement()),
|
||||
None,
|
||||
None,
|
||||
root.metadata.get("name"),
|
||||
|
||||
@@ -4,14 +4,13 @@ from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, Tuple
|
||||
from typing import Any, Dict, Mapping, Tuple
|
||||
|
||||
from .._internal.semantic import SemanticValueMixin, _finite_float
|
||||
|
||||
Vec3 = Tuple[float, float, float]
|
||||
_AXIS_TOLERANCE = 1e-9
|
||||
_ORTHOGONAL_TOLERANCE = 1e-7
|
||||
|
||||
def _vec3(value: Any, *, field_name: str) -> Vec3:
|
||||
if not isinstance(value, (list, tuple)) or len(value) != 3:
|
||||
raise ValueError(f"{field_name} must be a 3-element tuple or list")
|
||||
@@ -105,6 +104,46 @@ class Placement(SemanticValueMixin):
|
||||
+ local[2] * self.z_axis[2],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_exact_frame(
|
||||
cls,
|
||||
origin: Vec3,
|
||||
x_axis: Vec3,
|
||||
y_axis: Vec3,
|
||||
z_axis: Vec3,
|
||||
) -> "Placement":
|
||||
"""Build a Placement that keeps durable-boundary components verbatim.
|
||||
|
||||
Tick frames are validated in tick space and must survive a
|
||||
reconstruct -> re-tick cycle bit-exactly, so orthonormality is
|
||||
checked (never recomputed) here. Residual axis error stays below
|
||||
1e-9, far inside solver tolerances.
|
||||
"""
|
||||
origin_value = _vec3(origin, field_name="origin")
|
||||
x_value = _vec3(x_axis, field_name="x_axis")
|
||||
y_value = _vec3(y_axis, field_name="y_axis")
|
||||
z_value = _vec3(z_axis, field_name="z_axis")
|
||||
for name, axis in (("x_axis", x_value), ("y_axis", y_value), ("z_axis", z_value)):
|
||||
if abs(_norm(axis) - 1.0) > 2.0e-6:
|
||||
raise ValueError(f"{name} must be a unit vector")
|
||||
for name, dot in (
|
||||
("x_axis/y_axis", _dot(x_value, y_value)),
|
||||
("x_axis/z_axis", _dot(x_value, z_value)),
|
||||
("y_axis/z_axis", _dot(y_value, z_value)),
|
||||
):
|
||||
if abs(dot) > 2.0e-6:
|
||||
raise ValueError(f"{name} must be orthogonal")
|
||||
if _dot(_cross(x_value, y_value), z_value) <= 0.9:
|
||||
raise ValueError("axes must define a right-handed frame")
|
||||
instance = cls.__new__(cls)
|
||||
object.__setattr__(instance, "origin", origin_value)
|
||||
object.__setattr__(instance, "x_axis", x_value)
|
||||
object.__setattr__(instance, "y_axis", y_value)
|
||||
object.__setattr__(instance, "z_axis", z_value)
|
||||
object.__setattr__(instance, "_metadata", {})
|
||||
object.__setattr__(instance, "_runtime", {})
|
||||
return instance
|
||||
|
||||
def compose(self, child: "Placement") -> "Placement":
|
||||
if not isinstance(child, Placement):
|
||||
raise TypeError("child must be a Placement")
|
||||
@@ -123,8 +162,99 @@ class Placement(SemanticValueMixin):
|
||||
}
|
||||
|
||||
|
||||
def identity_placement() -> Placement:
|
||||
return Placement((0.0, 0.0, 0.0))
|
||||
_POSITION_CHUNK_MM = 1.0e-9
|
||||
_DIRECTION_CHUNK = 1.0e-9
|
||||
_FRAME_KEYS = ("origin", "x_axis", "y_axis", "z_axis")
|
||||
_TICK_UNIT_LENGTH = 1.0 / _DIRECTION_CHUNK
|
||||
|
||||
|
||||
def _quantize_tick(value: float, chunk: float) -> int:
|
||||
return round(float(value) / chunk)
|
||||
|
||||
def _is_tick_vector(values: Any) -> bool:
|
||||
return (
|
||||
isinstance(values, (list, tuple))
|
||||
and len(values) == 3
|
||||
and all(isinstance(item, int) and not isinstance(item, bool) for item in values)
|
||||
)
|
||||
def placement_ticks(value: Any) -> Dict[str, Any]:
|
||||
"""Return the integer-tick identity form of a placement frame.
|
||||
|
||||
Tick frames are the only representation that is hashed or persisted:
|
||||
they are exact integers, so canonical JSON bytes and content hashes are
|
||||
stable across save/load cycles regardless of floating-point noise. The
|
||||
stored ``z_axis`` is authoritative (derived once from ``x_axis ×
|
||||
y_axis`` by :class:`Placement` at write time) and is never recomputed.
|
||||
"""
|
||||
if isinstance(value, Mapping) and all(
|
||||
_is_tick_vector(value.get(key)) for key in _FRAME_KEYS
|
||||
):
|
||||
return validate_placement_ticks(value)
|
||||
placement = value if isinstance(value, Placement) else Placement(**dict(value))
|
||||
return {
|
||||
"origin": [_quantize_tick(item, _POSITION_CHUNK_MM) for item in placement.origin],
|
||||
"x_axis": [_quantize_tick(item, _DIRECTION_CHUNK) for item in placement.x_axis],
|
||||
"y_axis": [_quantize_tick(item, _DIRECTION_CHUNK) for item in placement.y_axis],
|
||||
"z_axis": [_quantize_tick(item, _DIRECTION_CHUNK) for item in placement.z_axis],
|
||||
}
|
||||
|
||||
|
||||
def placement_frame_mm(value: Mapping[str, Any]) -> Dict[str, Any]:
|
||||
"""Return a millimetre float frame from a tick (or legacy float) frame."""
|
||||
return placement_from_canonical(value).to_dict()
|
||||
|
||||
|
||||
def validate_placement_ticks(value: Mapping[str, Any]) -> Dict[str, Any]:
|
||||
"""Validate a persisted tick frame with exact integer arithmetic."""
|
||||
if not isinstance(value, Mapping) or set(value) != set(_FRAME_KEYS):
|
||||
raise ValueError("tick frame fields must be exactly origin/x_axis/y_axis/z_axis")
|
||||
for key in _FRAME_KEYS:
|
||||
if not _is_tick_vector(value[key]):
|
||||
raise ValueError(f"{key} must be three integer ticks")
|
||||
squared = {
|
||||
name: sum(item * item for item in value[name])
|
||||
for name in ("x_axis", "y_axis", "z_axis")
|
||||
}
|
||||
max_error = 2.0e-6 * _TICK_UNIT_LENGTH
|
||||
for name, total in squared.items():
|
||||
low = (_TICK_UNIT_LENGTH - max_error) ** 2
|
||||
high = (_TICK_UNIT_LENGTH + max_error) ** 2
|
||||
if not low <= total <= high:
|
||||
raise ValueError(f"{name} must be a unit direction in tick form")
|
||||
dot = sum(a * b for a, b in zip(value["x_axis"], value["y_axis"]))
|
||||
if abs(dot) > 2.0e-6 * _TICK_UNIT_LENGTH**2:
|
||||
raise ValueError("x_axis and y_axis must be orthogonal in tick form")
|
||||
x, y, z = value["x_axis"], value["y_axis"], value["z_axis"]
|
||||
handedness = (
|
||||
(x[1] * y[2] - x[2] * y[1]) * z[0]
|
||||
+ (x[2] * y[0] - x[0] * y[2]) * z[1]
|
||||
+ (x[0] * y[1] - x[1] * y[0]) * z[2]
|
||||
)
|
||||
if handedness <= int(0.9 * _TICK_UNIT_LENGTH**3):
|
||||
raise ValueError("x_axis and y_axis must define a right-handed frame")
|
||||
return {key: list(value[key]) for key in _FRAME_KEYS}
|
||||
|
||||
|
||||
def canonical_frame(value: Mapping[str, Any]) -> Dict[str, Any]:
|
||||
"""Tick form of a frame: persisted ticks validate in place, floats upgrade."""
|
||||
if isinstance(value, Mapping) and all(
|
||||
_is_tick_vector(value.get(key)) for key in _FRAME_KEYS
|
||||
):
|
||||
return validate_placement_ticks(value)
|
||||
return placement_ticks(value)
|
||||
|
||||
|
||||
def placement_from_canonical(value: Mapping[str, Any]) -> Placement:
|
||||
"""Rebuild a runtime Placement from a tick frame (or a legacy float frame)."""
|
||||
if all(_is_tick_vector(value.get(key)) for key in _FRAME_KEYS):
|
||||
return Placement.from_exact_frame(
|
||||
tuple(item * _POSITION_CHUNK_MM for item in value["origin"]),
|
||||
tuple(item * _DIRECTION_CHUNK for item in value["x_axis"]),
|
||||
tuple(item * _DIRECTION_CHUNK for item in value["y_axis"]),
|
||||
tuple(item * _DIRECTION_CHUNK for item in value["z_axis"]),
|
||||
)
|
||||
frame = {key: tuple(value[key]) for key in _FRAME_KEYS if key in value}
|
||||
return Placement(**frame)
|
||||
|
||||
|
||||
def compose_placements(parent: Placement, child: Placement) -> Placement:
|
||||
@@ -133,6 +263,11 @@ def compose_placements(parent: Placement, child: Placement) -> Placement:
|
||||
return parent.compose(child)
|
||||
|
||||
|
||||
def identity_placement() -> Placement:
|
||||
return Placement((0.0, 0.0, 0.0))
|
||||
|
||||
|
||||
|
||||
def inverse_placement(placement: Placement) -> Placement:
|
||||
if not isinstance(placement, Placement):
|
||||
raise TypeError("placement must be a Placement")
|
||||
@@ -146,7 +281,6 @@ def inverse_placement(placement: Placement) -> Placement:
|
||||
y_axis=(x_axis[1], y_axis[1], z_axis[1]),
|
||||
)
|
||||
|
||||
|
||||
def relative_placement(base: Placement, target: Placement) -> Placement:
|
||||
return inverse_placement(base).compose(target)
|
||||
|
||||
@@ -164,6 +298,10 @@ def translate_z_placement(distance: float) -> Placement:
|
||||
|
||||
__all__ = [
|
||||
"Placement",
|
||||
"placement_ticks",
|
||||
"validate_placement_ticks",
|
||||
"canonical_frame",
|
||||
"placement_from_canonical",
|
||||
"compose_placements",
|
||||
"identity_placement",
|
||||
"inverse_placement",
|
||||
|
||||
@@ -54,7 +54,7 @@ from ..product.connector import Connector, ConnectorRef, GeometryRef
|
||||
from ..product.constraint import ScalarLimit
|
||||
from ..product.material import Material
|
||||
from ..product.part import Part
|
||||
from ..product.placement import Placement
|
||||
from ..product.placement import Placement, placement_ticks
|
||||
from ..topology.model import (
|
||||
GRAPH_SCHEMA_VERSION,
|
||||
OperationGraph,
|
||||
@@ -2596,10 +2596,10 @@ def _execute_graph(
|
||||
occurrence_placements,
|
||||
)
|
||||
if any(
|
||||
result.get_component(
|
||||
component_id
|
||||
).placement.to_dict()
|
||||
!= dict(by_id[component_id])
|
||||
placement_ticks(
|
||||
result.get_component(component_id).placement
|
||||
)
|
||||
!= placement_ticks(by_id[component_id])
|
||||
for component_id in authored.component_ids()
|
||||
):
|
||||
ctx.fail(
|
||||
|
||||
@@ -28,7 +28,7 @@ from ..artifacts.feature_graph import (
|
||||
from ..artifacts.part_io import encode_part_definition, load_part_definition
|
||||
from ..core import Edge, Face, Solid, Vertex
|
||||
from ..kernel.ocp_properties import center_of_mass
|
||||
from ..product.placement import Placement, identity_placement
|
||||
from ..product.placement import Placement, identity_placement, placement_from_canonical
|
||||
from .archive import canonical_zip_bytes, preflight_zip_bytes
|
||||
from .canonical import (
|
||||
canonical_json_bytes,
|
||||
@@ -529,7 +529,7 @@ def _part_geometry(
|
||||
|
||||
|
||||
def _placement(value: Mapping[str, Any]) -> Placement:
|
||||
return Placement(**dict(value))
|
||||
return placement_from_canonical(value)
|
||||
|
||||
|
||||
def _node_id(path: tuple[str, ...]) -> str:
|
||||
|
||||
@@ -2,7 +2,32 @@ def _vec(v):
|
||||
return App.Vector(float(v[0]), float(v[1]), float(v[2]))
|
||||
|
||||
|
||||
_TICK_CHUNK = 1e-9
|
||||
|
||||
|
||||
def _is_tick_vector(values):
|
||||
return (
|
||||
isinstance(values, (list, tuple))
|
||||
and len(values) == 3
|
||||
and all(isinstance(item, int) and not isinstance(item, bool) for item in values)
|
||||
)
|
||||
|
||||
|
||||
def _frame_mm(payload):
|
||||
origin = payload.get("origin")
|
||||
if origin is not None and all(
|
||||
_is_tick_vector(payload.get(key))
|
||||
for key in ("origin", "x_axis", "y_axis", "z_axis")
|
||||
):
|
||||
return {
|
||||
key: [component * _TICK_CHUNK for component in payload[key]]
|
||||
for key in ("origin", "x_axis", "y_axis", "z_axis")
|
||||
}
|
||||
return payload
|
||||
|
||||
|
||||
def _placement_from_axes_payload(payload):
|
||||
payload = _frame_mm(dict(payload or {}))
|
||||
origin = payload.get("origin", (0.0, 0.0, 0.0))
|
||||
x_axis = payload.get("x_axis", (1.0, 0.0, 0.0))
|
||||
y_axis = payload.get("y_axis", (0.0, 1.0, 0.0))
|
||||
|
||||
@@ -16,6 +16,7 @@ import tempfile
|
||||
import zlib
|
||||
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
|
||||
|
||||
from ...product.placement import placement_frame_mm
|
||||
from ...recording.serializer import _execute_graph
|
||||
from ...topology import OperationGraph, OperationNode
|
||||
|
||||
@@ -2957,7 +2958,16 @@ class SimpleCADFusionRuntime:
|
||||
return self._set_output(node, assembly)
|
||||
if op == 'make_solve_assembly_constraints_rassembly':
|
||||
assembly = dict(self._first_output(inputs[0]))
|
||||
placements = dict(params.get('component_placements') or {})
|
||||
placements = {
|
||||
str(component_id): {
|
||||
'kind': 'placement',
|
||||
'params': placement_frame_mm(frame),
|
||||
}
|
||||
for component_id, frame in (
|
||||
(str(key), value)
|
||||
for key, value in dict(params.get('component_placements') or {}).items()
|
||||
)
|
||||
}
|
||||
components = []
|
||||
for component in assembly.get('components') or []:
|
||||
component = dict(component)
|
||||
@@ -2973,7 +2983,7 @@ class SimpleCADFusionRuntime:
|
||||
placements = {
|
||||
str(record.get('instance_id') or ''): {
|
||||
'kind': 'placement',
|
||||
'params': dict(record.get('placement') or {}),
|
||||
'params': placement_frame_mm(record.get('placement') or {}),
|
||||
}
|
||||
for record in (params.get('component_placements') or [])
|
||||
if isinstance(record, dict)
|
||||
|
||||
@@ -28,6 +28,7 @@ from OCP.TopAbs import TopAbs_SOLID
|
||||
from OCP.gp import gp_Ax2, gp_Dir, gp_Pnt
|
||||
|
||||
from ...operators import _make_geo_selector
|
||||
from ...product.placement import placement_frame_mm
|
||||
from ...recording.serializer import _execute_graph, _resolve_shape_from_geo_selector
|
||||
from ...topology import OperationGraph
|
||||
|
||||
@@ -5021,7 +5022,7 @@ class SimpleCADSolidWorksRuntime:
|
||||
if component_id in solved_placements:
|
||||
component['placement'] = {
|
||||
'kind': 'placement',
|
||||
'params': dict(solved_placements[component_id]),
|
||||
'params': placement_frame_mm(solved_placements[component_id]),
|
||||
}
|
||||
components.append(component)
|
||||
assembly['components'] = components
|
||||
@@ -5032,7 +5033,7 @@ class SimpleCADSolidWorksRuntime:
|
||||
placements = {
|
||||
str(record.get('instance_id') or ''): {
|
||||
'kind': 'placement',
|
||||
'params': dict(record.get('placement') or {}),
|
||||
'params': placement_frame_mm(record.get('placement') or {}),
|
||||
}
|
||||
for record in (params.get('component_placements') or [])
|
||||
if isinstance(record, dict)
|
||||
|
||||
@@ -138,6 +138,39 @@ def test_connector_interface_hash_includes_public_name() -> None:
|
||||
assert named.interface_hash != unnamed.interface_hash
|
||||
|
||||
|
||||
def test_connector_interface_hash_uses_normalized_frame() -> None:
|
||||
raw_frame = {
|
||||
"origin": [41.7193000900063, -14.849242404917511, 0.0],
|
||||
"x_axis": [0.7071067811865474, -0.7071067811865477, 0.0],
|
||||
"y_axis": [0.5000000000000001, 0.49999999999999983, -0.7071067811865475],
|
||||
"z_axis": [0.5000000000000002, 0.4999999999999999, 0.7071067811865476],
|
||||
}
|
||||
connector = ConnectorInterface(
|
||||
connector_id="roller_axis",
|
||||
name=None,
|
||||
anchor_kind="placement",
|
||||
local_frame=raw_frame,
|
||||
binding=None,
|
||||
)
|
||||
payload = canonical_bytes(connector.to_dict())
|
||||
for _ in range(10):
|
||||
connector = ConnectorInterface.from_dict(json.loads(payload))
|
||||
assert canonical_bytes(connector.to_dict()) == payload
|
||||
nearby = deepcopy(raw_frame)
|
||||
nearby["origin"][0] += 1e-10
|
||||
nearby["y_axis"][0] += 1e-15
|
||||
same_chunk = ConnectorInterface(
|
||||
connector_id="roller_axis", name=None, anchor_kind="placement",
|
||||
local_frame=nearby, binding=None,
|
||||
)
|
||||
assert same_chunk.interface_hash == connector.interface_hash
|
||||
changed = json.loads(payload)
|
||||
changed["local_frame"]["origin"][0] += 2_000_000 # 0.002 mm in 1e-9 mm ticks
|
||||
with pytest.raises(ArtifactValidationError) as caught:
|
||||
ConnectorInterface.from_dict(changed)
|
||||
assert caught.value.reason == "hash_invalid"
|
||||
|
||||
|
||||
def test_part_definition_canonical_roundtrip_and_blob_validation():
|
||||
definition = _part_definition()
|
||||
parsed = parse_artifact_json(definition.canonical_bytes, kind="part_definition")
|
||||
|
||||
@@ -5,6 +5,7 @@ from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from simplecadapi.product.placement import placement_ticks
|
||||
|
||||
import simplecadapi as scad
|
||||
from simplecadapi.artifacts.canonical import (
|
||||
@@ -212,11 +213,14 @@ def test_assemble_keeps_authored_placements_separate_from_solved_snapshot(
|
||||
for item in train.definition.solved_snapshot["component_placements"]
|
||||
}
|
||||
|
||||
identity = scad.identity_placement_rplacement().to_dict()
|
||||
identity = placement_ticks(scad.identity_placement_rplacement())
|
||||
assert authored["gear_a"] == identity
|
||||
assert authored["gear_b"] == identity
|
||||
assert solved["gear_a"]["origin"] == [5.0, 4.0, 2.0]
|
||||
assert solved["gear_b"]["origin"] == [25.0, 4.0, 2.0]
|
||||
assert solved["gear_a"]["origin"] == placement_ticks(
|
||||
scad.make_placement_rplacement(origin=(5.0, 4.0, 2.0))
|
||||
)["origin"]
|
||||
assert solved["gear_b"]["origin"] == placement_ticks(
|
||||
scad.make_placement_rplacement(origin=(25.0, 4.0, 2.0))
|
||||
)["origin"]
|
||||
assert train.definition.interface_hashes.geometry == content_hash(
|
||||
{
|
||||
"instances": [
|
||||
@@ -235,8 +239,8 @@ def test_assemble_keeps_authored_placements_separate_from_solved_snapshot(
|
||||
|
||||
rebuilt = scad.materialize_definition(train.definition)
|
||||
assert isinstance(rebuilt, scad.Assembly)
|
||||
assert rebuilt.get_component("gear_a").placement.to_dict() == solved["gear_a"]
|
||||
assert rebuilt.get_component("gear_b").placement.to_dict() == solved["gear_b"]
|
||||
assert placement_ticks(rebuilt.get_component("gear_a").placement) == solved["gear_a"]
|
||||
assert placement_ticks(rebuilt.get_component("gear_b").placement) == solved["gear_b"]
|
||||
|
||||
|
||||
def test_nested_occurrence_placements_survive_materialization_and_replay(
|
||||
@@ -381,9 +385,9 @@ def test_nested_occurrence_placements_survive_materialization_and_replay(
|
||||
for record in fixture.definition.solved_snapshot["occurrence_placements"]
|
||||
}
|
||||
|
||||
assert occurrence_placements[("bearing", "inner_ring")]["x_axis"] == pytest.approx(
|
||||
quarter_turn.x_axis
|
||||
)
|
||||
assert occurrence_placements[("bearing", "inner_ring")]["x_axis"] == [
|
||||
round(value * 1.0e9) for value in quarter_turn.x_axis
|
||||
]
|
||||
|
||||
for restored in (
|
||||
fixture.value,
|
||||
|
||||
@@ -7,6 +7,10 @@ import importlib
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from simplecadapi.product.placement import placement_frame_mm
|
||||
|
||||
from test_product_exporter import _build_nested_package
|
||||
|
||||
|
||||
@@ -76,11 +80,9 @@ def test_product_payload_resolves_references_and_keeps_solved_placements(
|
||||
for record in evaluations[0]["component_placements"]
|
||||
if record["instance_id"] == "inner_b"
|
||||
)
|
||||
assert inner_b["placement"]["origin"] == [
|
||||
0,
|
||||
-0.3882285676537811,
|
||||
0.051111260566397476,
|
||||
]
|
||||
assert placement_frame_mm(inner_b["placement"])["origin"] == pytest.approx(
|
||||
[0.0, -0.3882285676537811, 0.051111260566397476]
|
||||
)
|
||||
|
||||
|
||||
def test_runtime_uses_shared_nested_product_definitions(tmp_path: Path) -> None:
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
|
||||
from simplecadapi.artifacts.canonical import content_hash
|
||||
from simplecadapi.artifacts.references import ConnectorInterface, PartInstance
|
||||
from simplecadapi.product.placement import (
|
||||
canonical_frame,
|
||||
placement_from_canonical,
|
||||
placement_ticks,
|
||||
)
|
||||
|
||||
|
||||
def _euler_frame(a: float, b: float, c: float) -> dict[str, list[float]]:
|
||||
ca, sa = math.cos(a), math.sin(a)
|
||||
cb, sb = math.cos(b), math.sin(b)
|
||||
cc, sc = math.cos(c), math.sin(c)
|
||||
return {
|
||||
"origin": [41.7193000900063, -14.849242404917511, 0.0],
|
||||
"x_axis": [ca * cb, sa * cb, -sb],
|
||||
"y_axis": [ca * sb * sc - sa * cc, sa * sb * sc + ca * cc, cb * sc],
|
||||
}
|
||||
|
||||
|
||||
def test_tick_frames_survive_reconstruct_and_re_tick() -> None:
|
||||
randomizer = random.Random(20260906)
|
||||
|
||||
for _ in range(500):
|
||||
raw = _euler_frame(*(randomizer.uniform(-math.pi, math.pi) for _ in range(3)))
|
||||
ticks = placement_ticks(raw)
|
||||
rebuilt = placement_from_canonical(ticks)
|
||||
|
||||
assert placement_ticks(rebuilt) == ticks
|
||||
assert rebuilt.to_dict() == {
|
||||
key: [value * 1e-9 for value in ticks[key]] for key in ticks
|
||||
}
|
||||
|
||||
|
||||
def test_part_instance_round_trip_is_byte_stable() -> None:
|
||||
instance = PartInstance("wheel", "wheel-definition", None, _euler_frame(0.73, -1.21, 2.34))
|
||||
restored = PartInstance.from_dict(instance.to_dict())
|
||||
|
||||
assert restored.to_dict() == instance.to_dict()
|
||||
assert content_hash(restored.to_dict()) == content_hash(instance.to_dict())
|
||||
|
||||
|
||||
def test_connector_round_trip_is_byte_stable() -> None:
|
||||
frame = _euler_frame(-0.4, 0.9, 1.7)
|
||||
connector = ConnectorInterface("axis", None, "placement", frame, None)
|
||||
restored = ConnectorInterface.from_dict(connector.to_dict())
|
||||
|
||||
assert restored.to_dict() == connector.to_dict()
|
||||
assert content_hash(restored.to_dict()) == content_hash(connector.to_dict())
|
||||
|
||||
|
||||
def test_legacy_float_frames_upgrade_to_ticks() -> None:
|
||||
raw = _euler_frame(0.7, 1.1, -0.4)
|
||||
ticks = placement_ticks(raw)
|
||||
instance = PartInstance("wheel", "wheel-definition", None, raw)
|
||||
|
||||
assert instance.placement == ticks
|
||||
assert canonical_frame(instance.placement) == ticks
|
||||
Reference in New Issue
Block a user