feat: add py-slvs sketch solver backend

This commit is contained in:
NiJingzhe
2026-07-30 00:58:31 +08:00
parent 31e26a71b6
commit 9e8450f192
32 changed files with 1674 additions and 427 deletions
+1 -1
View File
@@ -37,7 +37,7 @@ in a compact public API for creating solids, applying features, tagging semantic
intent, querying topology, exporting manufacturing files, and translating recorded
models into FreeCAD workflows.
Current release: `simplecadapi==2.0.2`.
Current release: `simplecadapi==2.0.3`.
## What It Provides
+1 -1
View File
@@ -30,7 +30,7 @@ SimpleCADAPI 2.0.2 新增跨 CAD 转换、浏览器三维场景查看、可回
SimpleCADAPI 是一个基于 OCP 的 Python CAD SDK,提供清晰的函数式建模操作和可重放的模型图。它在 OpenCascade 几何内核之上提供精简的公共 API,可用于创建实体、应用特征、添加语义标签、查询拓扑、导出制造文件,以及将记录的模型转换为 FreeCAD 工作流。
当前正式版本:`simplecadapi==2.0.2`。
当前正式版本:`simplecadapi==2.0.3`。
## 核心能力
+2 -2
View File
@@ -3,7 +3,7 @@
## Class Definition
```python
class SketchSolveResult(sketch_id: str, status: str, dof: int, residual_norm: float, iterations: int, solved_points: Dict[str, Tuple[float, float]], solved_scalars: Dict[str, float], diagnostics: Tuple[SketchConstraintDiagnostic, ...] = ())
class SketchSolveResult(sketch_id: str, status: str, dof: int, residual_norm: float, iterations: int, solved_points: Dict[str, Tuple[float, float]], solved_scalars: Dict[str, float], diagnostics: Tuple[SketchConstraintDiagnostic, ...] = (), backend: str = "unknown", backend_version: str = "unknown", backend_status_code: Optional[int] = None)
```
*Source: sketch.py*
@@ -14,4 +14,4 @@ class SketchSolveResult(sketch_id: str, status: str, dof: int, residual_norm: fl
## Description
Result of solving a declarative sketch.
Backend-neutral result of solving a declarative sketch. `backend`, `backend_version`, and `backend_status_code` identify the solver implementation that produced the result.
+1 -1
View File
@@ -14,4 +14,4 @@ def constrain_diameter_rsketch(sketch: Sketch, circle: Union[SketchRef, str], va
## Description
Add a driving circle diameter constraint.
Add a driving or reference diameter constraint to a sketch circle or circular arc.
+1 -1
View File
@@ -14,4 +14,4 @@ def constrain_equal_radius_rsketch(sketch: Sketch, a: Union[SketchRef, str], b:
## Description
Constrain two sketch circles to have equal radius.
Constrain any pair of sketch circles or circular arcs to have equal radius.
+1 -1
View File
@@ -14,4 +14,4 @@ def constrain_length_rsketch(sketch: Sketch, line: Union[SketchRef, str], value:
## Description
Add a driving line length constraint.
Add a driving or reference length constraint to a line, circular arc, or B-spline. B-spline reference length is measured by deterministic numerical evaluation; py-slvs driving length is currently supported for line endpoints only.
+1 -1
View File
@@ -14,4 +14,4 @@ def constrain_point_on_rsketch(sketch: Sketch, point: Union[SketchRef, str], ent
## Description
Constrain a sketch point to lie on a line or circle.
Constrain a sketch point to lie on a line, circle, or circular arc. For arcs, the solver enforces the supporting-circle radius; endpoint/sweep membership remains part of the sketch profile validation.
+1 -1
View File
@@ -14,4 +14,4 @@ def constrain_radius_rsketch(sketch: Sketch, circle: Union[SketchRef, str], valu
## Description
Add a driving circle radius constraint.
Add a driving or reference radius constraint to a sketch circle or circular arc.
+2 -2
View File
@@ -3,7 +3,7 @@
## API Definition
```python
def constrain_tangent_rsketch(sketch: Sketch, a: Union[SketchRef, str], b: Union[SketchRef, str], *, constraint_id: Optional[str] = None) -> Sketch
def constrain_tangent_rsketch(sketch: Sketch, a: Union[SketchRef, str], b: Union[SketchRef, str], *, at_a: Optional[str] = None, at_b: Optional[str] = None, mode: str = "external", constraint_id: Optional[str] = None) -> Sketch
```
*Source: operations.py*
@@ -14,4 +14,4 @@ def constrain_tangent_rsketch(sketch: Sketch, a: Union[SketchRef, str], b: Union
## Description
Constrain supported sketch curves to be tangent.
Constrain lines, circles, circular arcs, and cubic B-spline endpoints to be tangent. Arc/B-spline endpoint tangency requires `at_a` or `at_b` set to `"start"` or `"end"`. Circle-circle tangency supports `mode="external"` and `mode="internal"`.
+14
View File
@@ -26,6 +26,20 @@ sketch = constrain_distance_rsketch(sketch, "p0", "p1", 72.0)
`solve` is not a first-class modeling graph leaf. `make_wire_from_sketch_rwire(...)` and `make_face_from_sketch_rface(...)` run the sketch solver internally during `Sketch -> Wire/Face` promotion. Promotion graph nodes record `solve_snapshot` and `promotion_map` evidence, and promoted geometry receives `source_sketch`, `sketch_solve`, and sketch entity metadata/tags. `inspect_sketch_rsketchresult(...)` is diagnostic-only and does not record graph nodes.
The default sketch solver backend is `py-slvs` (`py-slvs==1.0.6`). The public sketch document and solve result do not expose native solver handles. Alternative backends implement `SketchSolverBackend.solve(sketch, *, options)`, register with `register_sketch_solver_backend(...)`, and can be selected by name with `Sketch.solve(backend="name")` or process-wide with `set_default_sketch_solver_backend(...)`. `SketchSolveResult` snapshots record `backend`, `backend_version`, and `backend_status_code` so replay evidence identifies the solver that produced it.
```python
class MyBackend:
name = "my-solver"
version = "1"
def solve(self, sketch, *, options):
return SketchSolveResult(...)
register_sketch_solver_backend(MyBackend())
set_default_sketch_solver_backend("my-solver")
```
In `.FCStd` translation, sketch promotion is represented by a visible `Sketcher::SketchObject`. `make_face_from_sketch_rface(...)` does not create a separate face bridge object in the graph path; downstream FreeCAD operations such as `Part::Extrusion` use the promoted Sketcher object as their base. FreeCAD Sketcher constraints are validated as they are added: constraints that are unsupported, crash-risky, or rejected as redundant by FreeCAD are recorded in `SimpleCADSketchConstraints.skipped` instead of being emitted in a way that would make the sketch unsolvable or force a synthetic base object.
# Assembly Constraint Status
+1 -1
View File
@@ -117,7 +117,7 @@ source API 名字不等于 canonical graph op 名字。Composite source API 可
```json
{
"schema_version": "2.0",
"producer_version": "2.0.2",
"producer_version": "2.0.3",
"capabilities": {
"selection_ref_strategies": true,
"geo_select_nodes": true,
+2 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "simplecadapi"
version = "2.0.2"
version = "2.0.3"
description = "A simplified OCP-native CAD modeling Python API"
readme = "README.md"
license = { file = "LICENSE" }
@@ -29,6 +29,7 @@ dependencies = [
"jsonschema>=4.25.1,<5.0.0",
"rfc8785>=0.1.4,<0.2.0",
"typing-extensions>=4.12,<5",
"py-slvs==1.0.6",
]
[project.optional-dependencies]
+2 -2
View File
@@ -5,9 +5,9 @@ license: AGPL-3.0
compatibility: Documentation/reference bundle for current SimpleCADAPI surfaces.
metadata:
project: simplecadapi
version: 2.0.2
version: 2.0.3
package-name: simplecadapi
package-version: 2.0.2
package-version: 2.0.3
---
# SimpleCAD SDK Skill
@@ -1,8 +1,8 @@
# SDK Overview
- Project: `simplecadapi`
- Version: `2.0.2`
- Package distribution: `simplecadapi==2.0.2`
- Version: `2.0.3`
- Package distribution: `simplecadapi==2.0.3`
## What this skill bundles
@@ -1,7 +1,7 @@
# SDK Package Summary
- Project: `simplecadapi`
- Version: `2.0.2`
- Version: `2.0.3`
- Summary: A simplified OCP-native CAD modeling Python API
## Scope
@@ -3,7 +3,7 @@
## Class Definition
```python
class SketchSolveResult(sketch_id: str, status: str, dof: int, residual_norm: float, iterations: int, solved_points: Dict[str, Tuple[float, float]], solved_scalars: Dict[str, float], diagnostics: Tuple[SketchConstraintDiagnostic, ...] = ())
class SketchSolveResult(sketch_id: str, status: str, dof: int, residual_norm: float, iterations: int, solved_points: Dict[str, Tuple[float, float]], solved_scalars: Dict[str, float], diagnostics: Tuple[SketchConstraintDiagnostic, ...] = (), backend: str = "unknown", backend_version: str = "unknown", backend_status_code: Optional[int] = None)
```
*Source: sketch.py*
@@ -14,4 +14,4 @@ class SketchSolveResult(sketch_id: str, status: str, dof: int, residual_norm: fl
## Description
Result of solving a declarative sketch.
Backend-neutral result of solving a declarative sketch. `backend`, `backend_version`, and `backend_status_code` identify the solver implementation that produced the result.
@@ -14,4 +14,4 @@ def constrain_diameter_rsketch(sketch: Sketch, circle: Union[SketchRef, str], va
## Description
Add a driving circle diameter constraint.
Add a driving or reference diameter constraint to a sketch circle or circular arc.
@@ -14,4 +14,4 @@ def constrain_equal_radius_rsketch(sketch: Sketch, a: Union[SketchRef, str], b:
## Description
Constrain two sketch circles to have equal radius.
Constrain any pair of sketch circles or circular arcs to have equal radius.
@@ -14,4 +14,4 @@ def constrain_length_rsketch(sketch: Sketch, line: Union[SketchRef, str], value:
## Description
Add a driving line length constraint.
Add a driving or reference length constraint to a line, circular arc, or B-spline. B-spline reference length is measured by deterministic numerical evaluation; py-slvs driving length is currently supported for line endpoints only.
@@ -14,4 +14,4 @@ def constrain_point_on_rsketch(sketch: Sketch, point: Union[SketchRef, str], ent
## Description
Constrain a sketch point to lie on a line or circle.
Constrain a sketch point to lie on a line, circle, or circular arc. For arcs, the solver enforces the supporting-circle radius; endpoint/sweep membership remains part of the sketch profile validation.
@@ -14,4 +14,4 @@ def constrain_radius_rsketch(sketch: Sketch, circle: Union[SketchRef, str], valu
## Description
Add a driving circle radius constraint.
Add a driving or reference radius constraint to a sketch circle or circular arc.
@@ -3,7 +3,7 @@
## API Definition
```python
def constrain_tangent_rsketch(sketch: Sketch, a: Union[SketchRef, str], b: Union[SketchRef, str], *, constraint_id: Optional[str] = None) -> Sketch
def constrain_tangent_rsketch(sketch: Sketch, a: Union[SketchRef, str], b: Union[SketchRef, str], *, at_a: Optional[str] = None, at_b: Optional[str] = None, mode: str = "external", constraint_id: Optional[str] = None) -> Sketch
```
*Source: operations.py*
@@ -14,4 +14,4 @@ def constrain_tangent_rsketch(sketch: Sketch, a: Union[SketchRef, str], b: Union
## Description
Constrain supported sketch curves to be tangent.
Constrain lines, circles, circular arcs, and cubic B-spline endpoints to be tangent. Arc/B-spline endpoint tangency requires `at_a` or `at_b` set to `"start"` or `"end"`. Circle-circle tangency supports `mode="external"` and `mode="internal"`.
@@ -26,6 +26,20 @@ sketch = constrain_distance_rsketch(sketch, "p0", "p1", 72.0)
`solve` is not a first-class modeling graph leaf. `make_wire_from_sketch_rwire(...)` and `make_face_from_sketch_rface(...)` run the sketch solver internally during `Sketch -> Wire/Face` promotion. Promotion graph nodes record `solve_snapshot` and `promotion_map` evidence, and promoted geometry receives `source_sketch`, `sketch_solve`, and sketch entity metadata/tags. `inspect_sketch_rsketchresult(...)` is diagnostic-only and does not record graph nodes.
The default sketch solver backend is `py-slvs` (`py-slvs==1.0.6`). The public sketch document and solve result do not expose native solver handles. Alternative backends implement `SketchSolverBackend.solve(sketch, *, options)`, register with `register_sketch_solver_backend(...)`, and can be selected by name with `Sketch.solve(backend="name")` or process-wide with `set_default_sketch_solver_backend(...)`. `SketchSolveResult` snapshots record `backend`, `backend_version`, and `backend_status_code` so replay evidence identifies the solver that produced it.
```python
class MyBackend:
name = "my-solver"
version = "1"
def solve(self, sketch, *, options):
return SketchSolveResult(...)
register_sketch_solver_backend(MyBackend())
set_default_sketch_solver_backend("my-solver")
```
In `.FCStd` translation, sketch promotion is represented by a visible `Sketcher::SketchObject`. `make_face_from_sketch_rface(...)` does not create a separate face bridge object in the graph path; downstream FreeCAD operations such as `Part::Extrusion` use the promoted Sketcher object as their base. FreeCAD Sketcher constraints are validated as they are added: constraints that are unsupported, crash-risky, or rejected as redundant by FreeCAD are recorded in `SimpleCADSketchConstraints.skipped` instead of being emitted in a way that would make the sketch unsolvable or force a synthetic base object.
# Assembly Constraint Status
@@ -117,7 +117,7 @@ source API 名字不等于 canonical graph op 名字。Composite source API 可
```json
{
"schema_version": "2.0",
"producer_version": "2.0.2",
"producer_version": "2.0.3",
"capabilities": {
"selection_ref_strategies": true,
"geo_select_nodes": true,
+16
View File
@@ -246,6 +246,15 @@ from .product import (
ScalarLimit,
)
from .sketch import Sketch, SketchConstraint, SketchConstraintDiagnostic, SketchRef, SketchSolveResult
from .sketch_solver import (
SketchSolverBackend,
SketchSolverOptions,
get_default_sketch_solver_backend,
get_sketch_solver_backend,
register_sketch_solver_backend,
set_default_sketch_solver_backend,
sketch_solver_backend,
)
from .tagging import (
LineageDerivation,
LineagePolicy,
@@ -580,6 +589,13 @@ __all__ = [
"SketchConstraintDiagnostic",
"SketchRef",
"SketchSolveResult",
"SketchSolverBackend",
"SketchSolverOptions",
"get_default_sketch_solver_backend",
"get_sketch_solver_backend",
"register_sketch_solver_backend",
"set_default_sketch_solver_backend",
"sketch_solver_backend",
"LineageDerivation",
"LineagePolicy",
"TagAttachment",
+92 -12
View File
@@ -2386,13 +2386,13 @@ def constrain_point_on_rsketch(
*,
constraint_id: Optional[str] = None,
) -> Sketch:
"""Constrain a sketch point to lie on a line or circle."""
"""Constrain a sketch point to lie on a line, circle, or circular arc."""
return _constrain_rsketch(
sketch,
"point_on",
[point, entity],
constraint_id=constraint_id,
expected=["point", ("line", "circle")],
expected=["point", ("line", "circle", "arc")],
)
@@ -2470,15 +2470,28 @@ def constrain_tangent_rsketch(
a: Union[SketchRef, str],
b: Union[SketchRef, str],
*,
at_a: Optional[str] = None,
at_b: Optional[str] = None,
mode: str = "external",
constraint_id: Optional[str] = None,
) -> Sketch:
"""Constrain supported sketch curves to be tangent."""
"""Constrain supported curves to be tangent on an explicit branch.
``at_a``/``at_b`` select ``"start"`` or ``"end"`` for arc and
B-spline endpoint tangency. Circle-circle tangency accepts
``mode="external"`` or ``mode="internal"``.
"""
if at_a not in {None, "start", "end"} or at_b not in {None, "start", "end"}:
raise ValueError("Tangent endpoint selectors must be 'start' or 'end'")
if mode not in {"external", "internal"}:
raise ValueError("Tangent mode must be 'external' or 'internal'")
return _constrain_rsketch(
sketch,
"tangent",
[a, b],
constraint_id=constraint_id,
expected=[("line", "circle"), ("line", "circle")],
metadata={"at_a": at_a, "at_b": at_b, "mode": mode},
expected=[("line", "circle", "arc", "bspline"), ("line", "circle", "arc", "bspline")],
)
@@ -2558,13 +2571,13 @@ def constrain_equal_radius_rsketch(
*,
constraint_id: Optional[str] = None,
) -> Sketch:
"""Constrain two sketch circles to have equal radius."""
"""Constrain two circles/arcs to have equal radius."""
return _constrain_rsketch(
sketch,
"equal_radius",
[a, b],
constraint_id=constraint_id,
expected=["circle", "circle"],
expected=[("circle", "arc"), ("circle", "arc")],
)
@@ -2639,7 +2652,7 @@ def constrain_length_rsketch(
constraint_id: Optional[str] = None,
driving: bool = True,
) -> Sketch:
"""Add a driving line length constraint."""
"""Add a driving length constraint to a line, arc, or B-spline."""
return _constrain_rsketch(
sketch,
"length",
@@ -2647,7 +2660,7 @@ def constrain_length_rsketch(
value=value,
constraint_id=constraint_id,
driving=driving,
expected=["line"],
expected=[("line", "arc", "bspline")],
)
@@ -2680,7 +2693,7 @@ def constrain_radius_rsketch(
constraint_id: Optional[str] = None,
driving: bool = True,
) -> Sketch:
"""Add a driving circle radius constraint."""
"""Add a driving circle or arc radius constraint."""
return _constrain_rsketch(
sketch,
"radius",
@@ -2688,7 +2701,7 @@ def constrain_radius_rsketch(
value=value,
constraint_id=constraint_id,
driving=driving,
expected=["circle"],
expected=[("circle", "arc")],
)
@@ -2700,7 +2713,7 @@ def constrain_diameter_rsketch(
constraint_id: Optional[str] = None,
driving: bool = True,
) -> Sketch:
"""Add a driving circle diameter constraint."""
"""Add a driving circle or arc diameter constraint."""
return _constrain_rsketch(
sketch,
"diameter",
@@ -2708,7 +2721,7 @@ def constrain_diameter_rsketch(
value=value,
constraint_id=constraint_id,
driving=driving,
expected=["circle"],
expected=[("circle", "arc")],
)
@@ -3121,6 +3134,73 @@ def _assert_sketch_solve_snapshot_dict_matches(
f"Sketch solve scalar '{scalar_id}' changed beyond recorded tolerance"
)
actual_entities = cast(Dict[str, Any], actual.get("solved_entities", {}))
expected_entities = cast(Dict[str, Any], snapshot.get("solved_entities", {}))
_assert_sketch_solved_entities_match(
actual_entities,
expected_entities,
tolerance=tolerance,
)
def _assert_sketch_solved_entities_match(
actual: Dict[str, Any],
expected: Dict[str, Any],
*,
tolerance: float,
) -> None:
if set(actual) != set(expected):
raise ValueError("Sketch solve entity set changed")
for entity_id, entity in actual.items():
_assert_sketch_solved_value_matches(
entity,
expected[entity_id],
tolerance=tolerance,
path=f"Sketch solve entity '{entity_id}'",
)
def _assert_sketch_solved_value_matches(
actual: Any,
expected: Any,
*,
tolerance: float,
path: str,
) -> None:
if isinstance(actual, Mapping) and isinstance(expected, Mapping):
if set(actual) != set(expected):
raise ValueError(f"{path} field set changed")
for key, value in actual.items():
_assert_sketch_solved_value_matches(
value,
expected[key],
tolerance=tolerance,
path=f"{path}.{key}",
)
return
if isinstance(actual, (list, tuple)) and isinstance(expected, (list, tuple)):
if len(actual) != len(expected):
raise ValueError(f"{path} sequence length changed")
for index, value in enumerate(actual):
_assert_sketch_solved_value_matches(
value,
expected[index],
tolerance=tolerance,
path=f"{path}[{index}]",
)
return
if (
isinstance(actual, (int, float))
and not isinstance(actual, bool)
and isinstance(expected, (int, float))
and not isinstance(expected, bool)
):
if abs(float(actual) - float(expected)) > tolerance:
raise ValueError(f"{path} changed beyond recorded tolerance")
return
if actual != expected:
raise ValueError(f"{path} changed")
def make_line_redge(
start: Tuple[ScalarLike, ScalarLike, ScalarLike],
+87 -386
View File
@@ -9,7 +9,7 @@ from __future__ import annotations
import math
import uuid
from dataclasses import dataclass, field
from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union
from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union, cast
import numpy as np
@@ -140,7 +140,7 @@ class SketchRef(TaggedMixin):
@dataclass
class SketchSolveResult(TaggedMixin):
"""Result of solving a declarative sketch."""
"""Backend-neutral result of solving a declarative sketch."""
sketch_id: str
status: str
@@ -149,7 +149,11 @@ class SketchSolveResult(TaggedMixin):
iterations: int
solved_points: Dict[str, Tuple[float, float]]
solved_scalars: Dict[str, float]
solved_entities: Dict[str, Dict[str, Any]] = field(default_factory=dict)
diagnostics: Tuple[SketchConstraintDiagnostic, ...] = ()
backend: str = "unknown"
backend_version: str = "unknown"
backend_status_code: Optional[int] = None
def __post_init__(self) -> None:
TaggedMixin.__init__(self)
@@ -166,8 +170,23 @@ class SketchSolveResult(TaggedMixin):
for key, value in self.solved_points.items()
},
"solved_scalars": dict(self.solved_scalars),
"solved_entities": self._serialize_solved_entities(),
"diagnostics": [diag.__dict__.copy() for diag in self.diagnostics],
"backend": self.backend,
"backend_version": self.backend_version,
"backend_status_code": self.backend_status_code,
}
def _serialize_solved_entities(self) -> Dict[str, Any]:
def serialize(value: Any) -> Any:
if isinstance(value, Mapping):
return {str(key): serialize(item) for key, item in value.items()}
if isinstance(value, (tuple, list)):
return [serialize(item) for item in value]
if isinstance(value, float):
return float(value)
return value
return cast(Dict[str, Any], serialize(self.solved_entities))
class Sketch(TaggedMixin, TopoMixein):
@@ -432,19 +451,38 @@ class Sketch(TaggedMixin, TopoMixein):
*,
construction: bool = False,
) -> "Sketch":
"""Add a B-spline curve edge defined by control points.
"""Add a B-spline whose poles participate in sketch solving."""
from .operations import (
_normalize_bspline_knots,
_normalize_bspline_weights,
)
The start/end point refs link the B-spline into the profile loop.
Control points are stored as literal 2-D coordinates (not point
entity ids) so the solver does not modify them.
"""
start_id = self.resolve_point_id(start)
end_id = self.resolve_point_id(end)
if start_id == end_id:
raise ValueError("A sketch bspline requires two distinct endpoint refs")
if len(control_points) < degree + 1:
raise ValueError(f"bspline requires at least degree+1 control points, got {len(control_points)}")
if isinstance(degree, bool) or int(degree) != degree:
raise ValueError("degree must be an integer")
degree_value = int(degree)
if degree_value < 1 or degree_value > 25:
raise ValueError("degree must be between 1 and 25")
if len(control_points) < degree_value + 1:
raise ValueError(
f"bspline requires at least degree+1 control points, got {len(control_points)}"
)
literal_cps = [[float(p[0]), float(p[1])] for p in control_points]
resolved_knots, resolved_multiplicities = _normalize_bspline_knots(
control_count=len(literal_cps),
degree=degree_value,
periodic=bool(periodic),
knots=knots,
multiplicities=multiplicities,
)
resolved_weights = _normalize_bspline_weights(weights, len(literal_cps))
start_entity = self.entities[start_id]
end_entity = self.entities[end_id]
literal_cps[0] = [_as_float(start_entity.data["x"]), _as_float(start_entity.data["y"])]
literal_cps[-1] = [_as_float(end_entity.data["x"]), _as_float(end_entity.data["y"])]
self._add_entity(
SketchEntity(
entity_id,
@@ -453,10 +491,10 @@ class Sketch(TaggedMixin, TopoMixein):
"start": start_id,
"end": end_id,
"control_points": literal_cps,
"degree": int(degree),
"knots": list(knots) if knots is not None else None,
"multiplicities": list(multiplicities) if multiplicities is not None else None,
"weights": list(weights) if weights is not None else None,
"degree": degree_value,
"knots": list(resolved_knots),
"multiplicities": list(resolved_multiplicities),
"weights": list(resolved_weights) if resolved_weights is not None else None,
"periodic": bool(periodic),
},
construction=construction,
@@ -499,12 +537,32 @@ class Sketch(TaggedMixin, TopoMixein):
strict: bool = True,
tolerance: float = 1e-7,
max_iterations: int = 80,
backend: Any = None,
) -> SketchSolveResult:
result = _SketchSolver(self, tolerance=tolerance, max_iterations=max_iterations).solve()
from .sketch_solver import (
SketchSolverOptions,
get_default_sketch_solver_backend,
get_sketch_solver_backend,
)
selected_backend = (
get_default_sketch_solver_backend()
if backend is None
else get_sketch_solver_backend(backend)
if isinstance(backend, str)
else backend
)
result = selected_backend.solve(
self,
options=SketchSolverOptions(
tolerance=float(tolerance),
max_iterations=int(max_iterations),
),
)
self._last_solve_result = result
if strict and result.status in {"conflicting", "failed"}:
raise ValueError(
f"Sketch solve failed with status={result.status}, residual={result.residual_norm:.6g}"
f"Sketch solve failed with status={result.status}, backend={result.backend}"
)
if require_fully_constrained and result.dof > 0:
raise ValueError(f"Sketch is underconstrained with {result.dof} remaining DOF")
@@ -580,27 +638,27 @@ class Sketch(TaggedMixin, TopoMixein):
end_angle += 2.0 * _math.pi
edges.append(
make_angle_arc_redge(
center=cp, radius=radius,
start_angle=start_angle, end_angle=end_angle,
center=cp,
radius=radius,
start_angle=start_angle,
end_angle=end_angle,
normal=(0.0, 0.0, 1.0),
)
)
elif entity.kind == "bspline":
cps_2d = entity.data["control_points"]
degree = int(entity.data.get("degree", 3))
knots = entity.data.get("knots")
multiplicities = entity.data.get("multiplicities")
weights = entity.data.get("weights")
periodic = bool(entity.data.get("periodic", False))
cps_3d = [(p[0], p[1], 0.0) for p in cps_2d]
solved_poles = [
tuple(point)
for point in result.solved_entities[eid]["control_points"]
]
cps_3d = [self._point3(point) for point in solved_poles]
edges.append(
make_spline_redge(
control_points=cps_3d,
degree=degree,
knots=knots,
multiplicities=multiplicities,
weights=weights,
periodic=periodic,
degree=int(entity.data["degree"]),
knots=entity.data["knots"],
multiplicities=entity.data["multiplicities"],
weights=entity.data.get("weights"),
periodic=bool(entity.data.get("periodic", False)),
)
)
else:
@@ -840,363 +898,6 @@ class Sketch(TaggedMixin, TopoMixein):
return ordered_points, ordered_edge_ids
class _SketchSolver:
def __init__(self, sketch: Sketch, *, tolerance: float, max_iterations: int) -> None:
self.sketch = sketch
self.tolerance = float(tolerance)
self.max_iterations = int(max_iterations)
self.point_ids = [
entity_id
for entity_id in sketch.entity_order
if sketch.entities[entity_id].kind == "point"
]
self.scalar_ids = [
f"circle:{entity_id}:radius"
for entity_id in sketch.entity_order
if sketch.entities[entity_id].kind == "circle"
]
self.var_names = [f"point:{pid}:x" for pid in self.point_ids]
self.var_names.extend(f"point:{pid}:y" for pid in self.point_ids)
self.var_names.extend(self.scalar_ids)
def solve(self) -> SketchSolveResult:
if not self.var_names:
return SketchSolveResult(
sketch_id=self.sketch.sketch_id,
status="solved",
dof=0,
residual_norm=0.0,
iterations=0,
solved_points={},
solved_scalars={},
)
x = self._initial_vector()
diagnostics: List[SketchConstraintDiagnostic] = []
iterations = 0
residual = self._residual_vector(x)
best_norm = float(np.linalg.norm(residual))
damping = 1e-6
for iterations in range(self.max_iterations):
if best_norm <= self.tolerance:
break
jacobian = self._finite_difference_jacobian(x, residual)
lhs = jacobian.T @ jacobian + damping * np.eye(len(x))
rhs = -(jacobian.T @ residual)
try:
step = np.linalg.solve(lhs, rhs)
except np.linalg.LinAlgError:
step = np.linalg.lstsq(lhs, rhs, rcond=None)[0]
if not np.all(np.isfinite(step)):
diagnostics.append(
SketchConstraintDiagnostic(None, "error", "nonfinite_step", "Sketch solver produced a non-finite step.")
)
break
accepted = False
scale = 1.0
while scale >= 1e-4:
candidate = x + scale * step
candidate_residual = self._residual_vector(candidate)
candidate_norm = float(np.linalg.norm(candidate_residual))
if candidate_norm <= best_norm:
x = candidate
residual = candidate_residual
best_norm = candidate_norm
accepted = True
damping = max(damping * 0.5, 1e-12)
break
scale *= 0.5
if not accepted:
damping = min(damping * 10.0, 1e6)
final_jacobian = self._finite_difference_jacobian(x, residual)
rank = int(np.linalg.matrix_rank(final_jacobian, tol=1e-7)) if final_jacobian.size else 0
dof = max(0, len(x) - rank)
if len(residual) > rank and best_norm <= self.tolerance:
diagnostics.append(
SketchConstraintDiagnostic(None, "warning", "redundant_constraints", "Sketch has redundant but consistent constraints.")
)
if best_norm > self.tolerance:
status = "conflicting"
diagnostics.append(
SketchConstraintDiagnostic(None, "error", "residual_too_large", "Sketch constraints could not be satisfied.", best_norm)
)
elif dof > 0:
status = "underconstrained"
diagnostics.append(
SketchConstraintDiagnostic(None, "warning", "underconstrained", f"Sketch has {dof} remaining DOF.")
)
else:
status = "solved"
points, scalars = self._state_from_vector(x)
return SketchSolveResult(
sketch_id=self.sketch.sketch_id,
status=status,
dof=dof,
residual_norm=best_norm,
iterations=iterations,
solved_points=points,
solved_scalars=scalars,
diagnostics=tuple(diagnostics),
)
def _initial_vector(self) -> np.ndarray:
values: List[float] = []
for point_id in self.point_ids:
entity = self.sketch.entities[point_id]
values.append(_as_float(entity.data["x"]))
for point_id in self.point_ids:
entity = self.sketch.entities[point_id]
values.append(_as_float(entity.data["y"]))
for scalar_id in self.scalar_ids:
_prefix, entity_id, _name = scalar_id.split(":", 2)
entity = self.sketch.entities[entity_id]
values.append(_as_float(entity.data["radius"]))
return np.array(values, dtype=float)
def _state_from_vector(self, x: np.ndarray) -> Tuple[Dict[str, Tuple[float, float]], Dict[str, float]]:
points: Dict[str, Tuple[float, float]] = {}
offset_y = len(self.point_ids)
for idx, point_id in enumerate(self.point_ids):
points[point_id] = (float(x[idx]), float(x[offset_y + idx]))
scalars: Dict[str, float] = {}
scalar_offset = 2 * len(self.point_ids)
for idx, scalar_id in enumerate(self.scalar_ids):
scalars[scalar_id] = float(x[scalar_offset + idx])
return points, scalars
def _finite_difference_jacobian(self, x: np.ndarray, residual: np.ndarray) -> np.ndarray:
if len(residual) == 0:
return np.zeros((0, len(x)))
jacobian = np.zeros((len(residual), len(x)), dtype=float)
for idx in range(len(x)):
step = 1e-6 * max(1.0, abs(float(x[idx])))
shifted = x.copy()
shifted[idx] += step
jacobian[:, idx] = (self._residual_vector(shifted) - residual) / step
return jacobian
def _residual_vector(self, x: np.ndarray) -> np.ndarray:
points, scalars = self._state_from_vector(x)
residuals: List[float] = []
for constraint in self.sketch.constraints:
residuals.extend(self._constraint_residuals(constraint, points, scalars))
return np.array(residuals, dtype=float)
def _constraint_residuals(
self,
constraint: SketchConstraint,
points: Mapping[str, Tuple[float, float]],
scalars: Mapping[str, float],
) -> List[float]:
refs = self.sketch._constraint_refs(constraint)
kind = constraint.kind
if kind == "fix":
return self._fix_residuals(refs[0], points, scalars)
if kind == "coincident":
a = self._point(refs[0], points)
b = self._point(refs[1], points)
return [a[0] - b[0], a[1] - b[1]]
if kind == "horizontal":
a, b = self._line_points(refs[0], points)
return [b[1] - a[1]]
if kind == "vertical":
a, b = self._line_points(refs[0], points)
return [b[0] - a[0]]
if kind == "parallel":
return [self._cross_normalized(refs[0], refs[1], points)]
if kind == "perpendicular":
return [self._dot_normalized(refs[0], refs[1], points)]
if kind == "collinear":
a, _b = self._line_points(refs[0], points)
return [self._cross_normalized(refs[0], refs[1], points), self._point_line_distance(a, refs[1], points)]
if kind == "equal_length":
return [self._line_length(refs[0], points) - self._line_length(refs[1], points)]
if kind == "equal_radius":
return [self._circle_radius(refs[0], scalars) - self._circle_radius(refs[1], scalars)]
if kind == "distance":
return [self._point_distance(refs[0], refs[1], points) - _as_float(constraint.value)]
if kind == "distance_x":
a = self._point(refs[0], points)
b = self._point(refs[1], points)
return [(b[0] - a[0]) - _as_float(constraint.value)]
if kind == "distance_y":
a = self._point(refs[0], points)
b = self._point(refs[1], points)
return [(b[1] - a[1]) - _as_float(constraint.value)]
if kind == "length":
return [self._line_length(refs[0], points) - _as_float(constraint.value)]
if kind == "angle":
return [self._line_angle_delta(refs[0], refs[1], points, _as_float(constraint.value))]
if kind == "radius":
return [self._circle_radius(refs[0], scalars) - _as_float(constraint.value)]
if kind == "diameter":
return [2.0 * self._circle_radius(refs[0], scalars) - _as_float(constraint.value)]
if kind == "point_on":
return self._point_on_residuals(refs[0], refs[1], points, scalars)
if kind == "concentric":
a = self._circle_center(refs[0], points)
b = self._circle_center(refs[1], points)
return [a[0] - b[0], a[1] - b[1]]
if kind == "midpoint":
point = self._point(refs[0], points)
a, b = self._line_points(refs[1], points)
return [point[0] - 0.5 * (a[0] + b[0]), point[1] - 0.5 * (a[1] + b[1])]
if kind == "tangent":
return [self._tangent_residual(refs[0], refs[1], points, scalars)]
if kind == "symmetric":
a = self._point(refs[0], points)
b = self._point(refs[1], points)
axis_a, axis_b = self._line_points(refs[2], points)
axis = self._sub(axis_b, axis_a)
mid = ((a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5)
return [self._point_line_distance(mid, refs[2], points), self._dot(self._sub(a, b), axis) / max(self._norm(axis), _POINT_EPS)]
raise ValueError(f"Unsupported sketch constraint kind '{kind}'")
def _fix_residuals(
self,
ref: SketchRef,
points: Mapping[str, Tuple[float, float]],
scalars: Mapping[str, float],
) -> List[float]:
entity = self.sketch.entities[ref.entity_id]
if ref.kind == "point" or entity.kind == "point":
pid = self.sketch.resolve_point_id(ref)
target = self.sketch.entities[pid]
point = points[pid]
return [point[0] - _as_float(target.data["x"]), point[1] - _as_float(target.data["y"])]
if entity.kind == "line":
start = self._fix_residuals(self.sketch.point_ref(f"{ref.entity_id}.start"), points, scalars)
end = self._fix_residuals(self.sketch.point_ref(f"{ref.entity_id}.end"), points, scalars)
return start + end
if entity.kind == "circle":
center = self._fix_residuals(self.sketch.point_ref(f"{ref.entity_id}.center"), points, scalars)
radius_key = f"circle:{ref.entity_id}:radius"
return center + [scalars[radius_key] - _as_float(entity.data["radius"])]
raise ValueError(f"Cannot fix sketch entity kind '{entity.kind}'")
def _point(self, ref: SketchRef, points: Mapping[str, Tuple[float, float]]) -> Tuple[float, float]:
return points[self.sketch.resolve_point_id(ref)]
def _line_points(
self, ref: SketchRef, points: Mapping[str, Tuple[float, float]]
) -> Tuple[Tuple[float, float], Tuple[float, float]]:
entity = self.sketch.entities[ref.entity_id]
if entity.kind != "line":
raise ValueError(f"Expected line ref, got '{entity.kind}'")
return points[str(entity.data["start"])], points[str(entity.data["end"])]
def _circle_center(self, ref: SketchRef, points: Mapping[str, Tuple[float, float]]) -> Tuple[float, float]:
entity = self.sketch.entities[ref.entity_id]
if entity.kind != "circle":
raise ValueError(f"Expected circle ref, got '{entity.kind}'")
return points[str(entity.data["center"])]
def _circle_radius(self, ref: SketchRef, scalars: Mapping[str, float]) -> float:
entity = self.sketch.entities[ref.entity_id]
if entity.kind != "circle":
raise ValueError(f"Expected circle ref, got '{entity.kind}'")
return scalars[f"circle:{ref.entity_id}:radius"]
def _point_distance(
self, a: SketchRef, b: SketchRef, points: Mapping[str, Tuple[float, float]]
) -> float:
return self._norm(self._sub(self._point(b, points), self._point(a, points)))
def _line_length(self, ref: SketchRef, points: Mapping[str, Tuple[float, float]]) -> float:
a, b = self._line_points(ref, points)
return self._norm(self._sub(b, a))
def _cross_normalized(self, a_ref: SketchRef, b_ref: SketchRef, points: Mapping[str, Tuple[float, float]]) -> float:
a0, a1 = self._line_points(a_ref, points)
b0, b1 = self._line_points(b_ref, points)
a = self._sub(a1, a0)
b = self._sub(b1, b0)
return self._cross(a, b) / max(self._norm(a) * self._norm(b), _POINT_EPS)
def _dot_normalized(self, a_ref: SketchRef, b_ref: SketchRef, points: Mapping[str, Tuple[float, float]]) -> float:
a0, a1 = self._line_points(a_ref, points)
b0, b1 = self._line_points(b_ref, points)
a = self._sub(a1, a0)
b = self._sub(b1, b0)
return self._dot(a, b) / max(self._norm(a) * self._norm(b), _POINT_EPS)
def _line_angle_delta(
self,
a_ref: SketchRef,
b_ref: SketchRef,
points: Mapping[str, Tuple[float, float]],
target: float,
) -> float:
a0, a1 = self._line_points(a_ref, points)
b0, b1 = self._line_points(b_ref, points)
a = self._sub(a1, a0)
b = self._sub(b1, b0)
angle = math.atan2(self._cross(a, b), self._dot(a, b))
return _angle_delta(angle - target)
def _point_on_residuals(
self,
point_ref: SketchRef,
entity_ref: SketchRef,
points: Mapping[str, Tuple[float, float]],
scalars: Mapping[str, float],
) -> List[float]:
point = self._point(point_ref, points)
entity = self.sketch.entities[entity_ref.entity_id]
if entity.kind == "line":
return [self._point_line_distance(point, entity_ref, points)]
if entity.kind == "circle":
center = self._circle_center(entity_ref, points)
radius = self._circle_radius(entity_ref, scalars)
return [self._norm(self._sub(point, center)) - radius]
raise ValueError(f"Unsupported point_on target kind '{entity.kind}'")
def _point_line_distance(
self,
point: Tuple[float, float],
line_ref: SketchRef,
points: Mapping[str, Tuple[float, float]],
) -> float:
a, b = self._line_points(line_ref, points)
ab = self._sub(b, a)
return self._cross(self._sub(point, a), ab) / max(self._norm(ab), _POINT_EPS)
def _tangent_residual(
self,
a_ref: SketchRef,
b_ref: SketchRef,
points: Mapping[str, Tuple[float, float]],
scalars: Mapping[str, float],
) -> float:
a_kind = self.sketch.entities[a_ref.entity_id].kind
b_kind = self.sketch.entities[b_ref.entity_id].kind
if {a_kind, b_kind} == {"line", "circle"}:
line_ref = a_ref if a_kind == "line" else b_ref
circle_ref = b_ref if a_kind == "line" else a_ref
center = self._circle_center(circle_ref, points)
return abs(self._point_line_distance(center, line_ref, points)) - self._circle_radius(circle_ref, scalars)
if a_kind == "circle" and b_kind == "circle":
a_center = self._circle_center(a_ref, points)
b_center = self._circle_center(b_ref, points)
return self._norm(self._sub(a_center, b_center)) - (
self._circle_radius(a_ref, scalars) + self._circle_radius(b_ref, scalars)
)
raise ValueError(f"Unsupported tangent target kinds '{a_kind}' and '{b_kind}'")
@staticmethod
def _sub(a: Tuple[float, float], b: Tuple[float, float]) -> Tuple[float, float]:
return (float(a[0] - b[0]), float(a[1] - b[1]))
@staticmethod
def _dot(a: Tuple[float, float], b: Tuple[float, float]) -> float:
return float(a[0] * b[0] + a[1] * b[1])
@staticmethod
def _cross(a: Tuple[float, float], b: Tuple[float, float]) -> float:
return float(a[0] * b[1] - a[1] * b[0])
@staticmethod
def _norm(a: Tuple[float, float]) -> float:
return float(math.hypot(a[0], a[1]))
__all__ = [
@@ -0,0 +1,26 @@
"""Pluggable sketch constraint solver backends.
Backends consume SimpleCAD's backend-neutral ``Sketch`` document and return
``SketchSolveResult``. Import backend implementations directly when selecting
one explicitly; the package-level registry only owns selection policy.
"""
from .backend import (
SketchSolverBackend,
SketchSolverOptions,
get_default_sketch_solver_backend,
get_sketch_solver_backend,
register_sketch_solver_backend,
set_default_sketch_solver_backend,
sketch_solver_backend,
)
__all__ = [
"SketchSolverBackend",
"SketchSolverOptions",
"get_default_sketch_solver_backend",
"get_sketch_solver_backend",
"register_sketch_solver_backend",
"set_default_sketch_solver_backend",
"sketch_solver_backend",
]
+129
View File
@@ -0,0 +1,129 @@
"""Backend protocol and process-local sketch solver selection."""
from __future__ import annotations
from contextlib import contextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, Iterator, Protocol, runtime_checkable
if TYPE_CHECKING:
from ..sketch import Sketch, SketchSolveResult
@dataclass(frozen=True)
class SketchSolverOptions:
"""Backend-neutral options for one solve request.
A backend may not support every numerical hint. It must still preserve
the result/status contract and must not silently invoke another backend.
"""
tolerance: float = 1e-7
max_iterations: int = 80
@runtime_checkable
class SketchSolverBackend(Protocol):
"""Boundary implemented by a sketch constraint solver backend."""
@property
def name(self) -> str:
"""Stable backend identifier persisted in solve evidence."""
...
@property
def version(self) -> str:
"""Backend implementation/package version."""
...
def solve(
self,
sketch: "Sketch",
*,
options: SketchSolverOptions,
) -> "SketchSolveResult":
"""Solve a backend-neutral sketch document without mutating it."""
...
_BACKENDS: Dict[str, SketchSolverBackend] = {}
_DEFAULT_BACKEND_NAME = "py-slvs"
def register_sketch_solver_backend(
backend: SketchSolverBackend,
*,
replace: bool = False,
) -> None:
"""Register a backend instance under its stable ``name``."""
name = str(backend.name).strip()
if not name:
raise ValueError("A sketch solver backend requires a non-empty name")
if name in _BACKENDS and not replace:
raise ValueError(f"Sketch solver backend '{name}' is already registered")
_BACKENDS[name] = backend
def _ensure_builtin_backend(name: str) -> None:
if name == "py-slvs" and name not in _BACKENDS:
from .py_slvs_backend import PySlvsSketchSolverBackend
register_sketch_solver_backend(PySlvsSketchSolverBackend())
def get_sketch_solver_backend(name: str | None = None) -> SketchSolverBackend:
"""Resolve a registered backend; omitted ``name`` selects the default."""
selected = str(name or _DEFAULT_BACKEND_NAME)
_ensure_builtin_backend(selected)
try:
return _BACKENDS[selected]
except KeyError as exc:
available = ", ".join(sorted(_BACKENDS)) or "none"
raise ValueError(
f"Unknown sketch solver backend '{selected}'; registered backends: {available}"
) from exc
def get_default_sketch_solver_backend() -> SketchSolverBackend:
"""Return the process-wide default sketch solver backend."""
return get_sketch_solver_backend(_DEFAULT_BACKEND_NAME)
def set_default_sketch_solver_backend(backend: str | SketchSolverBackend) -> None:
"""Set the process-wide default by registered name or backend instance."""
global _DEFAULT_BACKEND_NAME
if isinstance(backend, str):
selected = get_sketch_solver_backend(backend)
else:
register_sketch_solver_backend(backend, replace=True)
selected = backend
_DEFAULT_BACKEND_NAME = selected.name
@contextmanager
def sketch_solver_backend(
backend: str | SketchSolverBackend,
) -> Iterator[SketchSolverBackend]:
"""Temporarily select a default backend and restore it afterwards."""
previous = _DEFAULT_BACKEND_NAME
set_default_sketch_solver_backend(backend)
try:
yield get_default_sketch_solver_backend()
finally:
set_default_sketch_solver_backend(previous)
__all__ = [
"SketchSolverBackend",
"SketchSolverOptions",
"get_default_sketch_solver_backend",
"get_sketch_solver_backend",
"register_sketch_solver_backend",
"set_default_sketch_solver_backend",
"sketch_solver_backend",
]
@@ -0,0 +1,986 @@
"""SolveSpace ``py-slvs`` adapter for SimpleCAD sketch documents."""
from __future__ import annotations
import importlib.metadata
import math
from typing import TYPE_CHECKING, Dict, List, Mapping, Optional, Sequence, Tuple
from OCP.Geom import Geom_BSplineCurve
from OCP.GeomConvert import GeomConvert_BSplineCurveToBezierCurve
from OCP.TColgp import TColgp_Array1OfPnt
from OCP.TColStd import TColStd_Array1OfInteger, TColStd_Array1OfReal
from OCP.gp import gp_Pnt
from .backend import SketchSolverOptions
if TYPE_CHECKING:
from ..sketch import (
Sketch,
SketchConstraint,
SketchConstraintDiagnostic,
SketchRef,
SketchSolveResult,
)
_RESULT_OKAY = 0
_RESULT_INCONSISTENT = 1
_RESULT_DIDNT_CONVERGE = 2
_RESULT_TOO_MANY_UNKNOWNS = 3
_RESULT_INIT_ERROR = 4
_RESULT_REDUNDANT_OK = 5
class PySlvsSketchSolverBackend:
"""Sketch solver backend backed by the existing ``py-slvs`` package."""
name = "py-slvs"
@property
def version(self) -> str:
try:
return importlib.metadata.version("py-slvs")
except importlib.metadata.PackageNotFoundError:
return "unknown"
def solve(
self,
sketch: "Sketch",
*,
options: SketchSolverOptions,
) -> "SketchSolveResult":
del options # The libslvs C API does not expose these numerical knobs.
adapter = _PySlvsSystem(sketch)
return adapter.solve()
class _PySlvsSystem:
_FIXED_GROUP = 1
_SOLVE_GROUP = 2
def __init__(self, sketch: "Sketch") -> None:
try:
from py_slvs import slvs
except ImportError as exc:
raise RuntimeError(
"The default sketch solver backend requires 'py-slvs'. "
"Install SimpleCADAPI with its declared runtime dependencies."
) from exc
self.slvs = slvs
self.sketch = sketch
self.system = slvs.System()
self.workplane = self.system.addWorkplane(
self.system.addPoint3dV(0.0, 0.0, 0.0, group=self._FIXED_GROUP),
self.system.addNormal3dV(1.0, 0.0, 0.0, 0.0, group=self._FIXED_GROUP),
group=self._FIXED_GROUP,
)
self.point_handles: Dict[str, int] = {}
self.entity_handles: Dict[str, int] = {}
self.radius_entities: Dict[str, int] = {}
self.bspline_pole_handles: Dict[str, List[int]] = {}
self.bspline_segment_handles: Dict[str, List[int]] = {}
self.bspline_solver_modes: Dict[str, str] = {}
self.constraint_ids: Dict[int, str] = {}
self._measurement_constraints: List["SketchConstraint"] = []
def solve(self) -> "SketchSolveResult":
from ..sketch import SketchConstraintDiagnostic, SketchSolveResult
self._add_points()
self._add_entities()
self._add_constraints()
result_code = int(
self.system.solve(
self._SOLVE_GROUP,
reportFailed=True,
findFreeParams=True,
)
)
points = self._solved_points()
scalars = self._solved_scalars(points)
entities = self._solved_entities(points, scalars)
failed_ids = self._failed_constraint_ids()
diagnostics: List[SketchConstraintDiagnostic] = []
if result_code in {_RESULT_OKAY, _RESULT_REDUNDANT_OK}:
dof = max(0, int(self.system.Dof))
status = "underconstrained" if dof > 0 else "solved"
if result_code == _RESULT_REDUNDANT_OK:
diagnostics.append(
SketchConstraintDiagnostic(
None,
"warning",
"redundant_constraints",
"Sketch has redundant but consistent constraints.",
)
)
if dof > 0:
diagnostics.append(
SketchConstraintDiagnostic(
None,
"warning",
"underconstrained",
f"Sketch has {dof} remaining DOF.",
)
)
else:
dof = max(0, int(self.system.Dof))
status = "conflicting" if result_code == _RESULT_INCONSISTENT else "failed"
code, message = self._failure_description(result_code)
legacy_code = "residual_too_large" if result_code == _RESULT_INCONSISTENT else code
if failed_ids:
diagnostics.extend(
SketchConstraintDiagnostic(
constraint_id,
"error",
legacy_code,
message,
)
for constraint_id in failed_ids
)
else:
diagnostics.append(
SketchConstraintDiagnostic(None, "error", legacy_code, message)
)
self._add_measurements(points, scalars)
return SketchSolveResult(
sketch_id=self.sketch.sketch_id,
status=status,
dof=dof,
residual_norm=0.0 if result_code in {_RESULT_OKAY, _RESULT_REDUNDANT_OK} else math.inf,
iterations=0,
solved_points=points,
solved_scalars=scalars,
solved_entities=entities,
diagnostics=tuple(diagnostics),
backend=PySlvsSketchSolverBackend.name,
backend_version=PySlvsSketchSolverBackend().version,
backend_status_code=result_code,
)
def _add_points(self) -> None:
from ..sketch import _as_float
for entity_id in self.sketch.entity_order:
entity = self.sketch.entities[entity_id]
if entity.kind != "point":
continue
self.point_handles[entity_id] = self.system.addPoint2dV(
self.workplane,
_as_float(entity.data["x"]),
_as_float(entity.data["y"]),
group=self._SOLVE_GROUP,
)
def _add_entities(self) -> None:
from ..sketch import _as_float
for entity_id in self.sketch.entity_order:
entity = self.sketch.entities[entity_id]
if entity.kind == "point":
self.entity_handles[entity_id] = self.point_handles[entity_id]
elif entity.kind == "line":
self.entity_handles[entity_id] = self.system.addLineSegment(
self.point_handles[str(entity.data["start"])],
self.point_handles[str(entity.data["end"])],
group=self._SOLVE_GROUP,
)
elif entity.kind == "circle":
distance = self.system.addDistanceV(
_as_float(entity.data["radius"]),
group=self._SOLVE_GROUP,
)
self.radius_entities[entity_id] = distance
self.entity_handles[entity_id] = self.system.addCircle(
self.point_handles[str(entity.data["center"])],
self.system.getEntity(self.workplane).normal,
distance,
group=self._SOLVE_GROUP,
)
elif entity.kind == "arc":
self.entity_handles[entity_id] = self.system.addArcOfCircle(
self.workplane,
self.point_handles[str(entity.data["center"])],
self.point_handles[str(entity.data["start"])],
self.point_handles[str(entity.data["end"])],
group=self._SOLVE_GROUP,
)
elif entity.kind == "bspline":
self._add_bspline_entity(entity_id, entity.data)
else:
raise ValueError(f"Unsupported sketch entity kind '{entity.kind}'")
def _add_bspline_entity(
self,
entity_id: str,
data: Mapping[str, object],
) -> None:
raw_points = data["control_points"]
segments = self._bezier_segments_from_bspline(data)
solver_mode = "cubic_bezier" if segments is not None else "fixed_shape"
poles: List[int] = []
for index, point in enumerate(raw_points):
endpoint_id = (
str(data["start"])
if index == 0
else str(data["end"])
if index == len(raw_points) - 1
else None
)
if endpoint_id is not None:
endpoint = self.point_handles[endpoint_id]
poles.append(
self.system.addPoint2d(
self.workplane,
self.system.getEntityParam(endpoint, 0),
self.system.getEntityParam(endpoint, 1),
group=self._SOLVE_GROUP,
)
)
else:
poles.append(
self.system.addPoint2dV(
self.workplane,
float(point[0]),
float(point[1]),
group=self._SOLVE_GROUP if segments is not None else self._FIXED_GROUP,
)
)
self.bspline_pole_handles[entity_id] = poles
self.bspline_solver_modes[entity_id] = solver_mode
segment_handles: List[int] = []
for indices in segments or ():
handles = [poles[index] for index in indices]
segment_handles.append(
self.system.addCubic(
self.workplane,
handles[0],
handles[1],
handles[2],
handles[3],
group=self._SOLVE_GROUP,
)
)
self.bspline_segment_handles[entity_id] = segment_handles
if len(segment_handles) == 1:
self.entity_handles[entity_id] = segment_handles[0]
def _bezier_segments_from_bspline(
self,
data: Mapping[str, object],
) -> Optional[List[Tuple[int, int, int, int]]]:
control_points = data["control_points"]
weights = data.get("weights")
degree = int(data["degree"])
if bool(data.get("periodic", False)):
return None
if weights is not None and any(abs(float(weight) - 1.0) > 1e-12 for weight in weights):
return None
poles = TColgp_Array1OfPnt(1, len(control_points))
for index, point in enumerate(control_points, start=1):
poles.SetValue(index, gp_Pnt(float(point[0]), float(point[1]), 0.0))
knots = data["knots"]
knot_array = TColStd_Array1OfReal(1, len(knots))
for index, knot in enumerate(knots, start=1):
knot_array.SetValue(index, float(knot))
multiplicities = data["multiplicities"]
mult_array = TColStd_Array1OfInteger(1, len(multiplicities))
for index, multiplicity in enumerate(multiplicities, start=1):
mult_array.SetValue(index, int(multiplicity))
curve = Geom_BSplineCurve(
poles,
knot_array,
mult_array,
degree,
False,
)
converter = GeomConvert_BSplineCurveToBezierCurve(curve)
bezier_poles: List[Tuple[float, float]] = []
for segment_index in range(1, converter.NbArcs() + 1):
bezier = converter.Arc(segment_index)
if bezier.Degree() < 3:
bezier.Increase(3)
if bezier.Degree() != 3:
return None
segment = [
(float(bezier.Pole(index).X()), float(bezier.Pole(index).Y()))
for index in range(1, 5)
]
if segment_index == 1:
bezier_poles.extend(segment)
else:
bezier_poles.extend(segment[1:])
original = [tuple(map(float, point)) for point in control_points]
if len(bezier_poles) != len(original) or any(
math.dist(actual, expected) > 1e-9
for actual, expected in zip(bezier_poles, original)
):
return None
return [
(index, index + 1, index + 2, index + 3)
for index in range(0, len(original) - 1, 3)
]
def _add_constraints(self) -> None:
for constraint in self.sketch.constraints:
if not constraint.driving:
self._measurement_constraints.append(constraint)
continue
handles = self._lower_constraint(constraint)
for handle in handles:
self.constraint_ids[int(handle)] = constraint.constraint_id
def _lower_constraint(self, constraint: "SketchConstraint") -> Sequence[int]:
from ..sketch import _as_float
refs = self.sketch._constraint_refs(constraint)
kind = constraint.kind
if kind == "fix":
return self._fix(refs[0])
if kind == "coincident":
return [self.system.addPointsCoincident(self._point(refs[0]), self._point(refs[1]), self.workplane, group=self._SOLVE_GROUP)]
if kind == "horizontal":
return [self.system.addLineHorizontal(self._entity(refs[0]), self.workplane, group=self._SOLVE_GROUP)]
if kind == "vertical":
return [self.system.addLineVertical(self._entity(refs[0]), self.workplane, group=self._SOLVE_GROUP)]
if kind == "parallel":
return [self.system.addParallel(self._entity(refs[0]), self._entity(refs[1]), self.workplane, group=self._SOLVE_GROUP)]
if kind == "perpendicular":
return [self.system.addPerpendicular(self._entity(refs[0]), self._entity(refs[1]), self.workplane, group=self._SOLVE_GROUP)]
if kind == "collinear":
a = self._entity(refs[0])
b = self._entity(refs[1])
return [
self.system.addParallel(a, b, self.workplane, group=self._SOLVE_GROUP),
self.system.addPointOnLine(self._line_endpoint(refs[0], "start"), b, self.workplane, group=self._SOLVE_GROUP),
]
if kind == "equal_length":
return [self.system.addEqualLength(self._entity(refs[0]), self._entity(refs[1]), self.workplane, group=self._SOLVE_GROUP)]
if kind == "equal_radius":
return [self.system.addEqualRadius(self._entity(refs[0]), self._entity(refs[1]), group=self._SOLVE_GROUP)]
if kind == "distance":
return [self.system.addPointsDistance(_as_float(constraint.value), self._point(refs[0]), self._point(refs[1]), self.workplane, group=self._SOLVE_GROUP)]
if kind in {"distance_x", "distance_y"}:
return [self._add_axis_distance(constraint, refs, kind)]
if kind == "length":
entity = self.sketch.entities[refs[0].entity_id]
if entity.kind != "line":
raise ValueError(
"Driving length constraints are supported only for lines; "
f"use driving=False to measure {entity.kind} length"
)
return [self.system.addPointsDistance(
_as_float(constraint.value),
self.point_handles[str(entity.data["start"])],
self.point_handles[str(entity.data["end"])],
self.workplane,
group=self._SOLVE_GROUP,
)]
if kind in {"radius", "diameter"}:
diameter = _as_float(constraint.value) * (2.0 if kind == "radius" else 1.0)
target = self.sketch.entities[refs[0].entity_id]
if target.kind == "arc":
return [self.system.addDiameter(diameter, self._entity(refs[0]), group=self._SOLVE_GROUP)]
return [self.system.addDiameter(diameter, self._entity(refs[0]), group=self._SOLVE_GROUP)]
if kind == "point_on":
target = self.sketch.entities[refs[1].entity_id]
if target.kind == "line":
return [self.system.addPointOnLine(self._point(refs[0]), self._entity(refs[1]), self.workplane, group=self._SOLVE_GROUP)]
if target.kind in {"circle", "arc"}:
return [self.system.addPointOnCircle(self._point(refs[0]), self._entity(refs[1]), group=self._SOLVE_GROUP)]
raise ValueError(f"Unsupported point_on target kind '{target.kind}'")
if kind == "concentric":
return [self.system.addPointsCoincident(self._circle_center(refs[0]), self._circle_center(refs[1]), self.workplane, group=self._SOLVE_GROUP)]
if kind == "midpoint":
return [self.system.addMidPoint(self._point(refs[0]), self._entity(refs[1]), self.workplane, group=self._SOLVE_GROUP)]
if kind == "symmetric":
return [self.system.addSymmetricLine(self._point(refs[0]), self._point(refs[1]), self._entity(refs[2]), self.workplane, group=self._SOLVE_GROUP)]
if kind == "tangent":
return self._tangent(constraint, refs)
raise ValueError(f"Unsupported sketch constraint kind '{kind}'")
def _fix(self, ref: "SketchRef") -> Sequence[int]:
entity = self.sketch.entities[ref.entity_id]
if ref.kind == "point" or entity.kind == "point":
self._move_point_to_fixed_group(self._point(ref))
return []
if entity.kind in {"line", "arc"}:
point_ids = [str(entity.data["start"]), str(entity.data["end"])]
if entity.kind == "arc":
point_ids.append(str(entity.data["center"]))
for point_id in point_ids:
self._move_point_to_fixed_group(self.point_handles[point_id])
return []
if entity.kind == "bspline":
for handle in self.bspline_pole_handles[ref.entity_id]:
self._move_point_to_fixed_group(handle)
return []
if entity.kind == "circle":
self._move_point_to_fixed_group(self.point_handles[str(entity.data["center"])])
self._move_entity_to_fixed_group(self.radius_entities[ref.entity_id])
return []
raise ValueError(f"Cannot fix sketch entity kind '{entity.kind}'")
def _move_point_to_fixed_group(self, handle: int) -> None:
point = self.system.getEntity(handle)
point.group = self._FIXED_GROUP
self.system.addEntity(point, overwrite=True)
for index in (0, 1):
parameter = self.system.getParam(self.system.getEntityParam(handle, index))
parameter.group = self._FIXED_GROUP
self.system.addParam(parameter, overwrite=True)
def _move_entity_to_fixed_group(self, handle: int) -> None:
entity = self.system.getEntity(handle)
entity.group = self._FIXED_GROUP
self.system.addEntity(entity, overwrite=True)
parameter = self.system.getParam(self.system.getEntityParam(handle, 0))
parameter.group = self._FIXED_GROUP
self.system.addParam(parameter, overwrite=True)
def _add_axis_distance(
self,
constraint: "SketchConstraint",
refs: Sequence["SketchRef"],
kind: str,
) -> int:
from ..sketch import _as_float
origin = self.system.addPoint2dV(self.workplane, 0.0, 0.0, group=self._FIXED_GROUP)
direction = self.system.addPoint2dV(
self.workplane,
1.0 if kind == "distance_x" else 0.0,
0.0 if kind == "distance_x" else 1.0,
group=self._FIXED_GROUP,
)
axis = self.system.addLineSegment(origin, direction, group=self._FIXED_GROUP)
# SolveSpace's projected-distance sign is opposite to SimpleCAD's
# target convention (target = point_b - point_a).
return self.system.addPointsProjectDistance(
-_as_float(constraint.value),
self._point(refs[0]),
self._point(refs[1]),
axis,
group=self._SOLVE_GROUP,
)
def _tangent(
self,
constraint: "SketchConstraint",
refs: Sequence["SketchRef"],
) -> Sequence[int]:
entities = [self.sketch.entities[ref.entity_id] for ref in refs]
kinds = [entity.kind for entity in entities]
metadata = constraint.metadata
selectors = [metadata.get("at_a"), metadata.get("at_b")]
mode = str(metadata.get("mode", "external"))
if set(kinds) == {"line", "circle"}:
line_index = kinds.index("line")
circle_index = kinds.index("circle")
return self._line_circle_tangent(refs[line_index], refs[circle_index])
if kinds == ["circle", "circle"]:
return self._circle_circle_tangent(refs[0], refs[1], mode=mode)
curve_indices = [index for index, kind in enumerate(kinds) if kind in {"arc", "bspline"}]
if not curve_indices:
raise ValueError(f"Unsupported tangent target kinds '{kinds[0]}' and '{kinds[1]}'")
for index in curve_indices:
if selectors[index] not in {"start", "end"}:
raise ValueError(
f"Tangent constraint '{constraint.constraint_id}' requires "
f"at_{'a' if index == 0 else 'b'}='start' or 'end'"
)
if set(kinds) == {"line", "arc"}:
arc_index = kinds.index("arc")
line_index = kinds.index("line")
return [self.system.addArcLineTangent(
selectors[arc_index] == "end",
self._entity(refs[arc_index]),
self._entity(refs[line_index]),
group=self._SOLVE_GROUP,
)]
if set(kinds) == {"line", "bspline"}:
spline_index = kinds.index("bspline")
line_index = kinds.index("line")
return [self.system.addCubicLineTangent(
selectors[spline_index] == "end",
self._bspline_endpoint_segment(refs[spline_index], str(selectors[spline_index])),
self._entity(refs[line_index]),
self.workplane,
group=self._SOLVE_GROUP,
)]
if all(kind in {"arc", "bspline"} for kind in kinds):
handles = [
self._entity(ref) if kind == "arc" else self._bspline_endpoint_segment(ref, str(selector))
for ref, kind, selector in zip(refs, kinds, selectors)
]
return [self.system.addCurvesTangent(
selectors[0] == "end",
selectors[1] == "end",
handles[0],
handles[1],
self.workplane,
group=self._SOLVE_GROUP,
)]
raise ValueError(f"Unsupported tangent target kinds '{kinds[0]}' and '{kinds[1]}'")
def _line_circle_tangent(
self,
line_ref: "SketchRef",
circle_ref: "SketchRef",
) -> Sequence[int]:
center = self._circle_center(circle_ref)
circle = self._entity(circle_ref)
line = self._entity(line_ref)
tangent_point = self.system.addPoint2dV(
self.workplane,
*self._initial_tangent_point(circle_ref, line_ref),
group=self._SOLVE_GROUP,
)
radius_line = self.system.addLineSegment(center, tangent_point, group=self._SOLVE_GROUP)
return [
self.system.addPointOnCircle(tangent_point, circle, group=self._SOLVE_GROUP),
self.system.addPointOnLine(tangent_point, line, self.workplane, group=self._SOLVE_GROUP),
self.system.addPerpendicular(radius_line, line, self.workplane, group=self._SOLVE_GROUP),
]
def _circle_circle_tangent(
self,
a_ref: "SketchRef",
b_ref: "SketchRef",
*,
mode: str,
) -> Sequence[int]:
center_a = self._circle_center(a_ref)
center_b = self._circle_center(b_ref)
tangent_point = self.system.addPoint2dV(
self.workplane,
*self._initial_circle_tangent_point(a_ref, b_ref, mode=mode),
group=self._SOLVE_GROUP,
)
radius_a = self.system.addLineSegment(center_a, tangent_point, group=self._SOLVE_GROUP)
radius_b = self.system.addLineSegment(center_b, tangent_point, group=self._SOLVE_GROUP)
return [
self.system.addPointOnCircle(tangent_point, self._entity(a_ref), group=self._SOLVE_GROUP),
self.system.addPointOnCircle(tangent_point, self._entity(b_ref), group=self._SOLVE_GROUP),
self.system.addParallel(radius_a, radius_b, self.workplane, group=self._SOLVE_GROUP),
]
def _bspline_endpoint_segment(self, ref: "SketchRef", selector: str) -> int:
segments = self.bspline_segment_handles.get(ref.entity_id, [])
if not segments:
raise ValueError(
f"B-spline '{ref.entity_id}' is not representable by py-slvs cubic entities"
)
return segments[0] if selector == "start" else segments[-1]
def _initial_tangent_point(
self,
circle_ref: "SketchRef",
line_ref: "SketchRef",
) -> Tuple[float, float]:
from ..sketch import _as_float
circle = self.sketch.entities[circle_ref.entity_id]
center_entity = self.sketch.entities[str(circle.data["center"])]
center = (
_as_float(center_entity.data["x"]),
_as_float(center_entity.data["y"]),
)
line = self.sketch.entities[line_ref.entity_id]
start_entity = self.sketch.entities[str(line.data["start"])]
end_entity = self.sketch.entities[str(line.data["end"])]
start = (_as_float(start_entity.data["x"]), _as_float(start_entity.data["y"]))
end = (_as_float(end_entity.data["x"]), _as_float(end_entity.data["y"]))
direction = (end[0] - start[0], end[1] - start[1])
denominator = direction[0] * direction[0] + direction[1] * direction[1]
if denominator <= 1e-18:
raise ValueError("A tangent constraint requires a non-degenerate line")
parameter = (
(center[0] - start[0]) * direction[0]
+ (center[1] - start[1]) * direction[1]
) / denominator
return (
start[0] + parameter * direction[0],
start[1] + parameter * direction[1],
)
def _initial_circle_tangent_point(
self,
a_ref: "SketchRef",
b_ref: "SketchRef",
*,
mode: str,
) -> Tuple[float, float]:
from ..sketch import _as_float
centers: List[Tuple[float, float]] = []
for ref in (a_ref, b_ref):
circle = self.sketch.entities[ref.entity_id]
center = self.sketch.entities[str(circle.data["center"])]
centers.append((_as_float(center.data["x"]), _as_float(center.data["y"])))
direction = (centers[1][0] - centers[0][0], centers[1][1] - centers[0][1])
magnitude = math.hypot(*direction)
if magnitude <= 1e-18:
direction = (1.0, 0.0)
magnitude = 1.0
radius = self._initial_radius(a_ref)
if mode == "external":
direction_sign = 1.0
else:
direction_sign = (
1.0 if radius >= self._initial_radius(b_ref) else -1.0
)
return (
centers[0][0] + direction_sign * radius * direction[0] / magnitude,
centers[0][1] + direction_sign * radius * direction[1] / magnitude,
)
def _point(self, ref: "SketchRef") -> int:
return self.point_handles[self.sketch.resolve_point_id(ref)]
def _entity(self, ref: "SketchRef") -> int:
try:
return self.entity_handles[ref.entity_id]
except KeyError as exc:
raise ValueError(
f"Sketch entity '{ref.entity_id}' is not supported by py-slvs constraints"
) from exc
def _line_endpoint(self, ref: "SketchRef", endpoint: str) -> int:
entity = self.sketch.entities[ref.entity_id]
return self.point_handles[str(entity.data[endpoint])]
def _circle_center(self, ref: "SketchRef") -> int:
entity = self.sketch.entities[ref.entity_id]
if entity.kind not in {"circle", "arc"}:
raise ValueError(f"Entity '{ref.entity_id}' has no circular center")
return self.point_handles[str(entity.data["center"])]
def _initial_radius(self, ref: "SketchRef") -> float:
from ..sketch import _as_float
entity = self.sketch.entities[ref.entity_id]
if entity.kind == "circle":
return _as_float(entity.data["radius"])
center = self.sketch.entities[str(entity.data["center"])]
start = self.sketch.entities[str(entity.data["start"])]
return math.dist(
(_as_float(center.data["x"]), _as_float(center.data["y"])),
(_as_float(start.data["x"]), _as_float(start.data["y"])),
)
def _solved_points(self) -> Dict[str, Tuple[float, float]]:
points = {
point_id: self._point_coordinates(handle)
for point_id, handle in self.point_handles.items()
}
for entity_id, handles in self.bspline_pole_handles.items():
for index, handle in enumerate(handles):
points[f"bspline:{entity_id}:pole:{index}"] = self._point_coordinates(handle)
return points
def _point_coordinates(self, handle: int) -> Tuple[float, float]:
return (
float(self.system.getParam(self.system.getEntityParam(handle, 0)).val),
float(self.system.getParam(self.system.getEntityParam(handle, 1)).val),
)
def _solved_scalars(
self,
points: Mapping[str, Tuple[float, float]],
) -> Dict[str, float]:
scalars: Dict[str, float] = {}
for entity_id, distance_handle in self.radius_entities.items():
scalars[f"circle:{entity_id}:radius"] = float(
self.system.getParam(
self.system.getEntityParam(distance_handle, 0)
).val
)
for entity_id in self.sketch.entity_order:
entity = self.sketch.entities[entity_id]
if entity.kind == "arc":
center = points[str(entity.data["center"])]
start = points[str(entity.data["start"])]
radius = math.dist(center, start)
scalars[f"arc:{entity_id}:radius"] = radius
scalars[f"arc:{entity_id}:diameter"] = 2.0 * radius
return scalars
def _solved_entities(
self,
points: Mapping[str, Tuple[float, float]],
scalars: Mapping[str, float],
) -> Dict[str, Dict[str, object]]:
entities: Dict[str, Dict[str, object]] = {}
for entity_id in self.sketch.entity_order:
entity = self.sketch.entities[entity_id]
if entity.kind == "point":
entities[entity_id] = {
"kind": "point",
"point": points[entity_id],
}
elif entity.kind == "line":
start = points[str(entity.data["start"])]
end = points[str(entity.data["end"])]
entities[entity_id] = {
"kind": "line",
"start": start,
"end": end,
"length": math.dist(start, end),
}
elif entity.kind == "circle":
radius = scalars[f"circle:{entity_id}:radius"]
entities[entity_id] = {
"kind": "circle",
"center": points[str(entity.data["center"])],
"radius": radius,
"diameter": 2.0 * radius,
}
elif entity.kind == "arc":
center = points[str(entity.data["center"])]
start = points[str(entity.data["start"])]
end = points[str(entity.data["end"])]
start_angle = math.atan2(start[1] - center[1], start[0] - center[0])
end_angle = math.atan2(end[1] - center[1], end[0] - center[0])
radius = scalars.get(f"arc:{entity_id}:radius", math.dist(center, start))
sweep = (end_angle - start_angle) % (2.0 * math.pi)
entities[entity_id] = {
"kind": "arc",
"center": center,
"start": start,
"end": end,
"radius": radius,
"sweep": sweep,
"length": radius * sweep,
}
elif entity.kind == "bspline":
poles = [
points[f"bspline:{entity_id}:pole:{index}"]
for index in range(len(entity.data["control_points"]))
]
entities[entity_id] = {
"kind": "bspline",
"degree": int(entity.data["degree"]),
"control_points": poles,
"knots": list(entity.data["knots"]),
"multiplicities": list(entity.data["multiplicities"]),
"weights": entity.data.get("weights"),
"periodic": bool(entity.data.get("periodic", False)),
"segment_count": len(self.bspline_segment_handles[entity_id]),
}
entities[entity_id]["solver_representation"] = self.bspline_solver_modes[entity_id]
return entities
def _failed_constraint_ids(self) -> List[str]:
return list(
dict.fromkeys(
self.constraint_ids[handle]
for handle in map(int, self.system.Failed)
if handle in self.constraint_ids
)
)
def _add_measurements(
self,
points: Mapping[str, Tuple[float, float]],
scalars: Dict[str, float],
) -> None:
for constraint in self._measurement_constraints:
refs = self.sketch._constraint_refs(constraint)
key = f"constraint:{constraint.constraint_id}:value"
if constraint.kind == "distance":
scalars[key] = math.dist(
self._point_value(refs[0], points),
self._point_value(refs[1], points),
)
elif constraint.kind == "distance_x":
a = self._point_value(refs[0], points)
b = self._point_value(refs[1], points)
scalars[key] = b[0] - a[0]
elif constraint.kind == "distance_y":
a = self._point_value(refs[0], points)
b = self._point_value(refs[1], points)
scalars[key] = b[1] - a[1]
elif constraint.kind == "length":
entity = self.sketch.entities[refs[0].entity_id]
if entity.kind == "bspline":
scalars[key] = self._measure_bspline_length(refs[0], points)
elif entity.kind == "arc":
radius = math.dist(
points[str(entity.data["center"])],
points[str(entity.data["start"])],
)
scalars[key] = radius * self._arc_sweep(entity, points)
else:
scalars[key] = math.dist(
points[str(entity.data["start"])],
points[str(entity.data["end"])],
)
elif constraint.kind in {"radius", "diameter"}:
target = self.sketch.entities[refs[0].entity_id]
radius_key = (
f"circle:{refs[0].entity_id}:radius"
if target.kind == "circle"
else f"arc:{refs[0].entity_id}:radius"
)
radius = self._solved_scalars(points).get(radius_key)
if radius is None:
raise ValueError(f"No solved radius for '{refs[0].entity_id}'")
scalars[key] = radius * (2.0 if constraint.kind == "diameter" else 1.0)
elif constraint.kind == "angle":
scalars[key] = self._measured_angle_degrees(refs, points)
else:
raise ValueError(
f"Constraint kind '{constraint.kind}' cannot be used as a reference measurement"
)
@staticmethod
def _arc_sweep(
entity: object,
points: Mapping[str, Tuple[float, float]],
) -> float:
center = points[str(entity.data["center"])]
start = points[str(entity.data["start"])]
end = points[str(entity.data["end"])]
start_angle = math.atan2(start[1] - center[1], start[0] - center[0])
end_angle = math.atan2(end[1] - center[1], end[0] - center[0])
return (end_angle - start_angle) % (2.0 * math.pi)
def _measure_bspline_length(
self,
ref: "SketchRef",
points: Mapping[str, Tuple[float, float]],
) -> float:
entity = self.sketch.entities[ref.entity_id]
poles = [
points[f"bspline:{ref.entity_id}:pole:{index}"]
for index in range(len(entity.data["control_points"]))
]
weights = entity.data.get("weights")
samples = 64
length = 0.0
previous = poles[0]
for step in range(1, samples + 1):
current = self._evaluate_bspline(
poles,
int(entity.data["degree"]),
entity.data["knots"],
entity.data["multiplicities"],
step / samples,
weights=weights,
)
length += math.dist(previous, current)
previous = current
return length
@staticmethod
def _evaluate_bspline(
poles: Sequence[Tuple[float, float]],
degree: int,
unique_knots: Sequence[float],
multiplicities: Sequence[int],
parameter: float,
*,
weights: Optional[Sequence[float]] = None,
) -> Tuple[float, float]:
knots = [
value
for value, count in zip(unique_knots, multiplicities)
for _ in range(int(count))
]
u = min(max(float(parameter), knots[degree]), knots[-degree - 1])
if u >= knots[-degree - 1]:
return poles[-1]
basis = [
1.0 if knots[index] <= u < knots[index + 1] else 0.0
for index in range(len(knots) - 1)
]
for current_degree in range(1, degree + 1):
next_basis = []
for index in range(len(basis) - 1):
left_den = knots[index + current_degree] - knots[index]
right_den = knots[index + current_degree + 1] - knots[index + 1]
left = (
(u - knots[index]) / left_den * basis[index]
if left_den
else 0.0
)
right = (
(knots[index + current_degree + 1] - u) / right_den * basis[index + 1]
if right_den
else 0.0
)
next_basis.append(left + right)
basis = next_basis
resolved_weights = (
[1.0] * len(poles)
if weights is None
else [float(weight) for weight in weights]
)
weighted_basis = [
basis[index] * resolved_weights[index]
for index in range(len(poles))
]
denominator = sum(weighted_basis)
if abs(denominator) <= 1e-18:
raise ValueError("B-spline evaluation produced a zero rational denominator")
return tuple(
sum(weighted_basis[index] * poles[index][axis] for index in range(len(poles)))
/ denominator
for axis in (0, 1)
)
def _point_value(
self,
ref: "SketchRef",
points: Mapping[str, Tuple[float, float]],
) -> Tuple[float, float]:
return points[self.sketch.resolve_point_id(ref)]
def _measured_angle_degrees(
self,
refs: Sequence["SketchRef"],
points: Mapping[str, Tuple[float, float]],
) -> float:
directions = []
for ref in refs:
entity = self.sketch.entities[ref.entity_id]
start = points[str(entity.data["start"])]
end = points[str(entity.data["end"])]
directions.append((end[0] - start[0], end[1] - start[1]))
cross = directions[0][0] * directions[1][1] - directions[0][1] * directions[1][0]
dot = directions[0][0] * directions[1][0] + directions[0][1] * directions[1][1]
return math.degrees(math.atan2(cross, dot))
@staticmethod
def _failure_description(result_code: int) -> Tuple[str, str]:
return {
_RESULT_INCONSISTENT: (
"inconsistent_constraint",
"Sketch constraints are inconsistent.",
),
_RESULT_DIDNT_CONVERGE: (
"did_not_converge",
"Sketch solver did not converge.",
),
_RESULT_TOO_MANY_UNKNOWNS: (
"too_many_unknowns",
"Sketch exceeds the backend's unknown-parameter limit.",
),
_RESULT_INIT_ERROR: (
"backend_init_error",
"Sketch solver could not initialize the constraint system.",
),
}.get(
result_code,
("backend_failure", f"Sketch solver failed with result code {result_code}."),
)
__all__ = ["PySlvsSketchSolverBackend"]
+220
View File
@@ -306,6 +306,226 @@ class TestSketchApi(unittest.TestCase):
self.assertEqual(len(replayed), 1)
self.assertIsInstance(replayed[0], scad.Face)
def test_strict_snapshot_comparison_rejects_changed_solved_entity(self):
from simplecadapi.operations import _assert_sketch_solve_snapshot_dict_matches
recorded = {
"status": "solved",
"dof": 0,
"residual_norm": 0.0,
"solved_points": {},
"solved_scalars": {},
"solved_entities": {
"circle": {"kind": "circle", "center": [0.0, 0.0], "radius": 1.0}
},
}
changed = json.loads(json.dumps(recorded))
changed["solved_entities"]["circle"]["radius"] = 1.5
with self.assertRaisesRegex(ValueError, "circle.*radius"):
_assert_sketch_solve_snapshot_dict_matches(changed, recorded)
def test_default_solver_backend_is_py_slvs_and_persisted_in_snapshot(self):
result = scad.inspect_sketch_rsketchresult(
self._make_constrained_rectangle(),
require_fully_constrained=True,
)
self.assertEqual(scad.get_default_sketch_solver_backend().name, "py-slvs")
self.assertEqual(result.backend, "py-slvs")
self.assertEqual(result.backend_version, "1.0.6")
self.assertEqual(result.backend_status_code, 5)
self.assertEqual(result.to_dict()["backend"], "py-slvs")
def test_custom_solver_backend_can_be_selected_without_changing_sketch(self):
class OffsetBackend:
name = "test-offset"
version = "1"
def solve(self, sketch, *, options):
self.options = options
return scad.SketchSolveResult(
sketch_id=sketch.sketch_id,
status="underconstrained",
dof=2,
residual_norm=0.0,
iterations=0,
solved_points={"p": (3.0, 4.0)},
solved_scalars={},
backend=self.name,
backend_version=self.version,
)
sketch = scad.make_sketch_rsketch("custom")
sketch = scad.add_point_rsketch(sketch, "p", 0.0, 0.0)
backend = OffsetBackend()
scad.register_sketch_solver_backend(backend)
result = sketch.solve(backend="test-offset", strict=False)
self.assertEqual(result.solved_points["p"], (3.0, 4.0))
self.assertEqual(result.backend, "test-offset")
self.assertEqual(backend.options.tolerance, 1e-7)
self.assertEqual(sketch.entities["p"].data, {"x": 0.0, "y": 0.0})
def test_reference_dimension_is_measured_without_driving_geometry(self):
sketch = scad.make_sketch_rsketch("reference")
sketch = scad.add_point_rsketch(sketch, "a", 0.0, 0.0)
sketch = scad.add_point_rsketch(sketch, "b", 3.0, 4.0)
sketch = scad.constrain_fix_rsketch(sketch, "a")
sketch = scad.constrain_fix_rsketch(sketch, "b")
sketch = scad.constrain_distance_rsketch(
sketch,
"a",
"b",
99.0,
constraint_id="measured",
driving=False,
)
result = scad.inspect_sketch_rsketchresult(
sketch,
require_fully_constrained=True,
)
self.assertEqual(result.status, "solved")
self.assertEqual(result.solved_scalars["constraint:measured:value"], 5.0)
def test_arc_and_bspline_solve_results_cover_non_point_entities(self):
sketch = scad.make_sketch_rsketch("curves")
for point_id, point in {
"center": (0.0, 0.0),
"arc_start": (1.0, 0.0),
"arc_end": (0.0, 1.0),
"spline_start": (1.0, 0.0),
"spline_end": (3.0, 0.0),
}.items():
sketch = scad.add_point_rsketch(sketch, point_id, *point)
sketch = scad.add_arc_rsketch(sketch, "arc", "arc_start", "arc_end", "center")
sketch = scad.add_bspline_rsketch(
sketch,
"spline",
"spline_start",
"spline_end",
[(1.0, 0.0), (1.5, 1.0), (2.5, 1.0), (3.0, 0.0)],
knots=[0.0, 1.0],
multiplicities=[4, 4],
)
result = scad.inspect_sketch_rsketchresult(sketch, strict=False)
self.assertEqual(result.solved_entities["arc"]["kind"], "arc")
self.assertAlmostEqual(result.solved_entities["arc"]["radius"], 1.0)
self.assertEqual(result.solved_entities["spline"]["kind"], "bspline")
self.assertEqual(result.solved_entities["spline"]["solver_representation"], "cubic_bezier")
self.assertEqual(len(result.solved_entities["spline"]["control_points"]), 4)
def test_tangent_modes_and_curve_endpoint_selectors_are_serializable(self):
sketch = scad.make_sketch_rsketch("tangent_modes")
sketch = scad.add_point_rsketch(sketch, "a", 0.0, 0.0)
sketch = scad.add_point_rsketch(sketch, "b", 5.0, 0.0)
sketch = scad.add_circle_rsketch(sketch, "left", "a", 2.0)
sketch = scad.add_circle_rsketch(sketch, "right", "b", 1.0)
sketch = scad.constrain_tangent_rsketch(
sketch, "left", "right", mode="internal", constraint_id="internal"
)
tangent = sketch.constraints[-1]
self.assertEqual(tangent.metadata["mode"], "internal")
payload = sketch.to_dict()
self.assertEqual(payload["constraints"][-1]["metadata"]["mode"], "internal")
for mode, distance in (("external", 3.0), ("internal", 1.0)):
solved = scad.make_sketch_rsketch(f"{mode}_tangent")
solved = scad.add_point_rsketch(solved, "a", 0.0, 0.0)
solved = scad.add_point_rsketch(solved, "b", distance, 0.0)
solved = scad.add_circle_rsketch(solved, "left", "a", 2.0)
solved = scad.add_circle_rsketch(solved, "right", "b", 1.0)
solved = scad.constrain_fix_rsketch(solved, "left")
solved = scad.constrain_fix_rsketch(solved, "right")
solved = scad.constrain_tangent_rsketch(
solved, "left", "right", mode=mode, constraint_id="tangent"
)
result = scad.inspect_sketch_rsketchresult(
solved, require_fully_constrained=True
)
self.assertEqual(result.status, "solved")
def test_reference_length_measurement_supports_bspline(self):
sketch = scad.make_sketch_rsketch("spline_measure")
sketch = scad.add_point_rsketch(sketch, "a", 0.0, 0.0)
sketch = scad.add_point_rsketch(sketch, "b", 3.0, 0.0)
sketch = scad.add_bspline_rsketch(
sketch,
"curve",
"a",
"b",
[(0.0, 0.0), (1.0, 1.0), (2.0, 1.0), (3.0, 0.0)],
knots=[0.0, 1.0],
multiplicities=[4, 4],
)
sketch = scad.constrain_fix_rsketch(sketch, "curve")
sketch = scad.constrain_length_rsketch(
sketch, "curve", 0.0, driving=False, constraint_id="curve_length"
)
result = scad.inspect_sketch_rsketchresult(sketch, require_fully_constrained=True)
self.assertGreater(result.solved_scalars["constraint:curve_length:value"], 3.0)
def test_reference_arc_length_uses_radius_and_sweep(self):
sketch = scad.make_sketch_rsketch("arc_measure")
sketch = scad.add_point_rsketch(sketch, "center", 0.0, 0.0)
sketch = scad.add_point_rsketch(sketch, "start", 1.0, 0.0)
sketch = scad.add_point_rsketch(sketch, "end", 0.0, 1.0)
sketch = scad.add_arc_rsketch(sketch, "arc", "start", "end", "center")
sketch = scad.constrain_fix_rsketch(sketch, "arc")
sketch = scad.constrain_length_rsketch(
sketch, "arc", 0.0, driving=False, constraint_id="arc_length"
)
result = scad.inspect_sketch_rsketchresult(sketch, require_fully_constrained=True)
self.assertAlmostEqual(
result.solved_scalars["constraint:arc_length:value"],
result.solved_entities["arc"]["length"],
)
def test_driving_curve_length_is_rejected_instead_of_using_chord_length(self):
sketch = scad.make_sketch_rsketch("arc_driving_length")
sketch = scad.add_point_rsketch(sketch, "center", 0.0, 0.0)
sketch = scad.add_point_rsketch(sketch, "start", 1.0, 0.0)
sketch = scad.add_point_rsketch(sketch, "end", 0.0, 1.0)
sketch = scad.add_arc_rsketch(sketch, "arc", "start", "end", "center")
sketch = scad.constrain_length_rsketch(sketch, "arc", 2.0)
with self.assertRaisesRegex(ValueError, "Driving length constraints.*only for lines"):
scad.inspect_sketch_rsketchresult(sketch)
def test_reference_rational_bspline_length_uses_weights(self):
sketch = scad.make_sketch_rsketch("rational_spline_measure")
sketch = scad.add_point_rsketch(sketch, "a", 1.0, 0.0)
sketch = scad.add_point_rsketch(sketch, "b", 0.0, 1.0)
sketch = scad.add_bspline_rsketch(
sketch,
"curve",
"a",
"b",
[(1.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
degree=2,
knots=[0.0, 1.0],
multiplicities=[3, 3],
weights=[1.0, 2.0**-0.5, 1.0],
)
sketch = scad.constrain_fix_rsketch(sketch, "curve")
sketch = scad.constrain_length_rsketch(
sketch, "curve", 0.0, driving=False, constraint_id="curve_length"
)
result = scad.inspect_sketch_rsketchresult(sketch, require_fully_constrained=True)
self.assertAlmostEqual(
result.solved_scalars["constraint:curve_length:value"],
0.5 * 3.141592653589793,
places=3,
)
if __name__ == "__main__":
unittest.main()
Generated
+61 -1
View File
@@ -2077,6 +2077,64 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/8e/37/efad0257dc6e593a18957422533ff0f87ede7c9c6ea010a2177d738fb82f/pure_eval-0.2.3-py3-none-any.whl", hash = "sha256:1db8e35b67b3d218d818ae653e27f06c3aa420901fa7b081ca98cbedc874e0d0", size = 11842, upload-time = "2024-07-21T12:58:20.04Z" },
]
[[package]]
name = "py-slvs"
version = "1.0.6"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/da/c5/ac1a0f5f6872706eb6205ecd4774322892893943f8ac3537079701c183a3/py_slvs-1.0.6.tar.gz", hash = "sha256:53a4ff697cb42530b5a6d2f9a0199c874cad48f98891103c5ce8b7d4da40ae72", size = 2433600, upload-time = "2023-03-17T02:18:24.074Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/db/3c/3991191ada13a7e3b9aad000dc3f7448cb80c2a6f1aea51d4bb01f436895/py_slvs-1.0.6-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:bb270c54d0f81824a61b12609ea863ce2234df5045d772b7f3e9ffc9bd7dd107", size = 387588, upload-time = "2023-03-17T02:15:45.85Z" },
{ url = "https://files.pythonhosted.org/packages/0d/09/104f387e4a89ed47bf9332165105e02efa74dac17a089da738175d8f6bbb/py_slvs-1.0.6-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:973370964a5d8c8f944ed3e8ff699f28e35fc8f275257f816cc056223dc1a33a", size = 204746, upload-time = "2023-03-17T02:15:48.105Z" },
{ url = "https://files.pythonhosted.org/packages/0e/27/4a2df0aeca383940fd0a15c270e6f3071ca1d582fca5a2a49815aa3eea8f/py_slvs-1.0.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:01c6e9978fbe97a6fac85c468788e95e203680a591c8dc0cbea21882c969bc64", size = 187602, upload-time = "2023-03-17T02:15:51.15Z" },
{ url = "https://files.pythonhosted.org/packages/8c/6b/4bf3e59e4f84dea6958ee7bd8e9a406c812e6cb5f31ff60e5f753d2fe700/py_slvs-1.0.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:440ea402adbb2538637082ea050bea531cee8cbf2b82f798efe0b1c9bbf9024e", size = 283268, upload-time = "2023-03-17T02:15:53.506Z" },
{ url = "https://files.pythonhosted.org/packages/e9/1f/78f201a194353e88ea888eebcc906ac8d061a13c0920e58fef4ca3986e09/py_slvs-1.0.6-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4f4e6a0725619c3f9f4e89558aada78f67c34cd420e519e34de6af7c013b7f29", size = 290558, upload-time = "2023-03-17T02:15:55.835Z" },
{ url = "https://files.pythonhosted.org/packages/95/2c/fc8335af4f3d263209734806c3476857768f6e3031c0648c9bf78efa8cbe/py_slvs-1.0.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:764de612d21c082ddefd933e490c9e51454bc71a076aa4044b53358c63d10872", size = 316315, upload-time = "2023-03-17T02:15:59.491Z" },
{ url = "https://files.pythonhosted.org/packages/6a/f2/704936bb34c0f7147bc4de576b196510249706e4fa9aff8fa30e5ca0f6d9/py_slvs-1.0.6-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:9c943ada8b0845e59595c562849042ac0b51f81c621034b4ed0969822ecea4b1", size = 785473, upload-time = "2023-03-17T02:16:01.976Z" },
{ url = "https://files.pythonhosted.org/packages/92/be/e6c38df8af98f9a3ff59309cc724f8b658b5eb162059aa757991aa6f470d/py_slvs-1.0.6-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:f71f748773ba2d395fb8a02b6b2755376f6a8eee91f4cef64392e3cdc80b842a", size = 868856, upload-time = "2023-03-17T02:16:04.882Z" },
{ url = "https://files.pythonhosted.org/packages/ff/b4/783ff67ab8c3c01f38521d7e1460fc30d05758681def5b0d9b3c85d3b49b/py_slvs-1.0.6-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:aeb73e3337ffdb896375e79c5268a660880a91b9cea16d62b96afc399792c35e", size = 831391, upload-time = "2023-03-17T02:16:08.877Z" },
{ url = "https://files.pythonhosted.org/packages/f2/7f/a6046ae461e3043138d2deab8dcd7566be19ee8f2cfd188726e8e8b8f8a2/py_slvs-1.0.6-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:3c2c4f1aa70d1d625e39242addd4d1781b0fc9842bb36f174a16526517cc12ba", size = 1252242, upload-time = "2025-03-07T13:46:02.932Z" },
{ url = "https://files.pythonhosted.org/packages/a8/7a/fa83ed95fbc552ea431efe41ac7d794e327e9774f09cc967e5deedac3aea/py_slvs-1.0.6-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:4590ded8bf7d171c58b382a8518b7088aa27a40e323053d695c97e1c80827e5b", size = 1424167, upload-time = "2025-03-07T13:46:06.388Z" },
{ url = "https://files.pythonhosted.org/packages/52/db/cc88278945151a136af116dc6b6e5c658aefdad6a20e2c0f411ba8a3a275/py_slvs-1.0.6-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:605667778c9ef706482d10735bbae2a0078ffc7ff98a591397aa8e8347b4f1e3", size = 1328218, upload-time = "2025-03-07T13:46:09.604Z" },
{ url = "https://files.pythonhosted.org/packages/ee/9d/f4d607ec03c55b75b3cc660eaa115ef2b1c383e23f545639ff20e720f75d/py_slvs-1.0.6-cp310-cp310-win32.whl", hash = "sha256:3bef3a67ef077d6073c4a0a5d0067c6dc595cdaa681f64f3a62f9a21dd5a9a6b", size = 225239, upload-time = "2023-03-17T02:16:11.858Z" },
{ url = "https://files.pythonhosted.org/packages/69/b6/bb198f32304831acf6311a7cc89b7d907ed46e4166b838e91a267c960b43/py_slvs-1.0.6-cp310-cp310-win_amd64.whl", hash = "sha256:b338fd141c1c25e2ac7c92a07d1a2194f1707848e56e96bf45e4a70f93cb9c07", size = 269444, upload-time = "2023-03-17T02:16:14.924Z" },
{ url = "https://files.pythonhosted.org/packages/76/60/8c013b610ffb2fc77ab63ce652bcded4aab4c7033e9e5e70b5615b24580a/py_slvs-1.0.6-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:fe1610f0e10ce817f9c00761ad7228de82f8f80092ad37026b14b6fc0db45682", size = 387041, upload-time = "2023-03-17T02:16:17.189Z" },
{ url = "https://files.pythonhosted.org/packages/15/c7/6d5b8342498dac39172f1d033ef829df4984d39c53bc6117e94e13bc8b25/py_slvs-1.0.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a64b34dc0b59bc1a8c28488c6ef88170fca641e482d0a93f8cf3844e5d40f0a4", size = 204456, upload-time = "2023-03-17T02:16:19.115Z" },
{ url = "https://files.pythonhosted.org/packages/c3/85/23bade7e8764744c129bfb36d26ebf0b3fab6799265de38785f322d72b9e/py_slvs-1.0.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a045e6c02b47a6c9b56a3de293883e30efc48509d1b2f5c21fa7bd201c54f49a", size = 187348, upload-time = "2023-03-17T02:16:21.171Z" },
{ url = "https://files.pythonhosted.org/packages/d8/2a/8e1e904a8347dc74924b7fafe6a92c18811064a6f89d8437522afc34f9e7/py_slvs-1.0.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a1597063344c746ee392422a723c30086fda4690a9b88a8507a4452bb122e85e", size = 283212, upload-time = "2023-03-17T02:16:23.38Z" },
{ url = "https://files.pythonhosted.org/packages/fc/02/4990c7b9e7934a90165507ac17e2a86da3d5d58a6dd1808ab932fc5e4c97/py_slvs-1.0.6-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:00b7a719e3210be00a82057e814f9d2dcb8060c349b153a0d9777becb05d6c95", size = 290508, upload-time = "2023-03-17T02:16:26.532Z" },
{ url = "https://files.pythonhosted.org/packages/c1/6f/4fc004094a930ea7fad7699dd2c21193bf66322dc42093d7f8997e96f398/py_slvs-1.0.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2e61cc5e61b18083805d17f8b603e5f59c87415773e2b9e8afe78668dbc6043d", size = 316279, upload-time = "2023-03-17T02:16:28.9Z" },
{ url = "https://files.pythonhosted.org/packages/11/50/c8d1486b7847b4a93feae81788bd7a9a6164e654cc0fee6491dec30b14e8/py_slvs-1.0.6-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:6e634faaac139ab101dad556da3c88c01d21c45e5051d75101c31fcc00ad1a39", size = 785539, upload-time = "2023-03-17T02:16:31.426Z" },
{ url = "https://files.pythonhosted.org/packages/66/04/7bdca450d5727ab2cd98652dc98b671e115be0432d4bde359472073c0eb9/py_slvs-1.0.6-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:c90ded01851a00aad76a2ef14c70a5b526b0b6070d0196849f37c7c9a5922049", size = 868750, upload-time = "2023-03-17T02:16:34.523Z" },
{ url = "https://files.pythonhosted.org/packages/19/df/dff00745c3e1ef4cf6981c01bcbbcf39ef598b37fd25e6185bbb0782db05/py_slvs-1.0.6-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:9257446016001f2a3e6c81432e6fc3864e9e3536adf9ae63a9ce789a3d69aee0", size = 831731, upload-time = "2023-03-17T02:16:36.813Z" },
{ url = "https://files.pythonhosted.org/packages/e5/7f/43c054b75898fde5b9661e8bb03b0f1debbe39227a3cfe9b302a5b70f084/py_slvs-1.0.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:9a91a23bb5d0d4fec0e2466796ecbbd6a334ad1b8776ce96534effd9ac6beb21", size = 1252217, upload-time = "2025-03-07T13:46:12.169Z" },
{ url = "https://files.pythonhosted.org/packages/3f/a2/5aad318c2824c77b3d0be5aa57cf7990b535c082f37320e08ece6e69f29a/py_slvs-1.0.6-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5bab860b36b5ae45f334c2272901e4508c3f2079fefc773f06c5b52ba0c379dc", size = 1424179, upload-time = "2025-03-07T13:46:15.844Z" },
{ url = "https://files.pythonhosted.org/packages/2a/e2/e89584ef8af8cff1aa42a30a5c899e8783dad1e9c1a1030dbc467ac1a309/py_slvs-1.0.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:767ec7c7060314d8978ea602080e59409a4ed14caa26f965b6c4f7dec2964ac2", size = 1328211, upload-time = "2025-03-07T13:46:18.675Z" },
{ url = "https://files.pythonhosted.org/packages/a6/1c/304ece8c3705c3c2a8059cc32a9e8602fcf7938cc1fdacb8339b5185ed21/py_slvs-1.0.6-cp311-cp311-win32.whl", hash = "sha256:4cefe7bd9901d68a55d3c28a47da433911de7a754dfd534cc1be0af9983da681", size = 225266, upload-time = "2023-03-17T02:16:39.42Z" },
{ url = "https://files.pythonhosted.org/packages/4c/e2/6f048b99f4b85c3b15268de2ff834af365c625cdd85f3d27667a63cfeb49/py_slvs-1.0.6-cp311-cp311-win_amd64.whl", hash = "sha256:8ce4499ee1d9f17a4189d33b7f8afc61666c7661f76c3ffabf7ff019c7b79e11", size = 269668, upload-time = "2023-03-17T02:16:41.593Z" },
{ url = "https://files.pythonhosted.org/packages/db/65/98809f40aac36374312ba19d9b270d4042bcee917817e80e9fcafa66d67d/py_slvs-1.0.6-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:9c9ffdcd56ef2bc9b54a38cab0d3c60914cf96ea7e8e54fb812f125ab8135470", size = 425334, upload-time = "2025-03-07T13:46:20.796Z" },
{ url = "https://files.pythonhosted.org/packages/38/89/edd72f86faac3c8948398cbcf909ebe3e45bbb1d1f857cc9854a627e3c48/py_slvs-1.0.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:94a6eef93bf51507eaca443a6ec152a0170dbc296717c913c6daf9877fbd2751", size = 237742, upload-time = "2025-03-07T13:46:23.081Z" },
{ url = "https://files.pythonhosted.org/packages/66/46/748381fa23c5fc4020f4bc582e20f2483fae32b05e3b39544495129c943e/py_slvs-1.0.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2eb1a5652eb3c8371119b06cd357d599614778172fb271dbc23995ae4179006d", size = 205648, upload-time = "2025-03-07T13:46:25.476Z" },
{ url = "https://files.pythonhosted.org/packages/b2/b0/ebe2728ee889707be4fb4c7220b4441df3a15a16f000a44006a0f2ee2890/py_slvs-1.0.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f45c467a4526a09d2b9d32c1e48ef394bdea8110d4f4c3228c9a1fa22bfaa055", size = 295273, upload-time = "2025-03-07T13:46:27.135Z" },
{ url = "https://files.pythonhosted.org/packages/ab/c2/79b8b78939cb4509e3bd2be21ed3ef9bc9e2521fe2d7bc886a930a02ec7d/py_slvs-1.0.6-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c7ccf43a801eedf7eeb9b490773b95bab9468d54c82eaff714b6adcbd79cace2", size = 302728, upload-time = "2025-03-07T13:46:28.919Z" },
{ url = "https://files.pythonhosted.org/packages/02/6f/b7025abfa2d22d65a4b5fa5f12fdeeda10e5dd96d42ddccaa546c1c5a35b/py_slvs-1.0.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0a16cf9dcc453dcf9a920e61f03dba8ac426d03f397414d91243afce7f031c9b", size = 326778, upload-time = "2025-03-07T13:46:30.576Z" },
{ url = "https://files.pythonhosted.org/packages/05/79/3aff8efba831cc9ab140c1f5067ec18bf5064b63251108acdbe00a60e23f/py_slvs-1.0.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ca504ce4ad83adb2d849823d22e3e3857cb15f4e8a2f7d3cbc3f9a6f6116f2f5", size = 1252624, upload-time = "2025-03-07T13:46:33.11Z" },
{ url = "https://files.pythonhosted.org/packages/38/46/27ff4dac7cd9e618b529c292810675c1915c57ccd22125d1de64fa55c244/py_slvs-1.0.6-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:96e4826924026cd014f1e74d1fa7babdc48837516a129d1dfc10c6ac7d59b8d5", size = 1424528, upload-time = "2025-03-07T13:46:35.099Z" },
{ url = "https://files.pythonhosted.org/packages/8f/e2/12aad0e73980bfbcca032c01fc66bafd86742b20e6f6de29b92250b1bb99/py_slvs-1.0.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:334f470fe1b300d464cd749cded128a560c2f6414cca7629f80bfb1e03f556a8", size = 1328962, upload-time = "2025-03-07T13:46:36.864Z" },
{ url = "https://files.pythonhosted.org/packages/7b/51/e612525d90e1019046ca93a55ee77658b1ab4c67b944c3c97496bafcaf08/py_slvs-1.0.6-cp312-cp312-win32.whl", hash = "sha256:96f44ae602346eb517f8e1372470c9d9c10d57a17fb79d6964e53efa1882ecd1", size = 243521, upload-time = "2025-03-07T13:46:38.723Z" },
{ url = "https://files.pythonhosted.org/packages/5f/85/afc20196fea3b0264c6cf61ffcc69386cca26643efb115dcbb45d402a0fd/py_slvs-1.0.6-cp312-cp312-win_amd64.whl", hash = "sha256:97996401b6ff69c639e89399b5004a1d30e11cf0b26a32abd70cac3ad4667a13", size = 288235, upload-time = "2025-03-07T13:46:40.799Z" },
{ url = "https://files.pythonhosted.org/packages/11/53/8e39a7e62caa8a4d24e034c051a6cadb2bd572d3a665e8464298c77acb84/py_slvs-1.0.6-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:44bcc4d92b71b435b89642a803bda6f2f5dacbedb919dc7e4e1deeafd4de3e96", size = 425341, upload-time = "2025-03-07T13:46:42.458Z" },
{ url = "https://files.pythonhosted.org/packages/78/d1/1279480e9b9f92eab265bc2108d26050462672b455f5c4b3ae41c5d63be0/py_slvs-1.0.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:a7b0f2d7b4f2e72da8f674e6cf7cbee75a803c9c22976e94bf702ef280f3c99c", size = 237743, upload-time = "2025-03-07T13:46:44.57Z" },
{ url = "https://files.pythonhosted.org/packages/5b/70/12a8b4bdc72dc1a93acb2bf05a2f73ff302dfada5e94cd5e5a5189910a78/py_slvs-1.0.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:62087de72814e69561a9973a07bc007a57c75804d15d32026c96f999056bb2a6", size = 205652, upload-time = "2025-03-07T13:46:46.559Z" },
{ url = "https://files.pythonhosted.org/packages/c5/ba/b3d88729c6d2c3d6d901f50f8e976747638f345c62a6978a59d663efbd12/py_slvs-1.0.6-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7d81124379f6313e5a35f37a573bfaa97907cffe6bb66d9032a70d72b7e5360c", size = 295276, upload-time = "2025-03-07T13:46:48.209Z" },
{ url = "https://files.pythonhosted.org/packages/3d/5b/9f99bd3f52af2b499074dabbd187e72cb71734413cf49d3a142f11cca2de/py_slvs-1.0.6-cp313-cp313-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4fccd090766c233fa63eaf5b2a375a5bd657c1f213305f07f319c574c81e9ab0", size = 302731, upload-time = "2025-03-07T13:46:50.303Z" },
{ url = "https://files.pythonhosted.org/packages/ed/de/700895d6b5b6851920b537337b32040a3db65de85dd4105008f39cbfac6b/py_slvs-1.0.6-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ea0a9eb754d3efded198298381af8cff2a720e740fe534a2fe3e82bf531db453", size = 326780, upload-time = "2025-03-07T13:46:51.991Z" },
{ url = "https://files.pythonhosted.org/packages/90/1c/f5fb68bd70952c893f11f96970898652f8fd1b89284f54aa3a266f6eef26/py_slvs-1.0.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:9f8c607cd64c3820ce6302fbe0a82beaa443f688addee7888bdd4f8565dc8358", size = 1252628, upload-time = "2025-03-07T13:46:54.044Z" },
{ url = "https://files.pythonhosted.org/packages/c9/78/8318fbc6ad6945e5a25c65670218aca24a11469e61d4de62b11162d953b3/py_slvs-1.0.6-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:048e7aab79c2b593b54b2243fb3573ccf8acfa82decc85075c2d18a5e4ab5ab9", size = 1424532, upload-time = "2025-03-07T13:46:56.241Z" },
{ url = "https://files.pythonhosted.org/packages/e1/30/b1748e914c37aa6e4beb464f6c3bb89c414aa7e1b1e23bb5f49751dff9f9/py_slvs-1.0.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:5ee01f9c50d1d61ec89557875704c51f68168c7851b1c1c0bab17583ebe0a48e", size = 1328967, upload-time = "2025-03-07T13:46:58.702Z" },
{ url = "https://files.pythonhosted.org/packages/ac/02/356712a1b4b24ea321c69b1a033c8a7d5af07bc4debe9d517114dad1a0a3/py_slvs-1.0.6-cp313-cp313-win32.whl", hash = "sha256:816284a07c336b978a19483be135e7b84a78dc77b123ee50812f95f4bb0abbf2", size = 243196, upload-time = "2025-03-07T13:47:00.016Z" },
{ url = "https://files.pythonhosted.org/packages/f3/18/f4a67514dc7605600215178835c77a3dba898b0b314f391f760810550c22/py_slvs-1.0.6-cp313-cp313-win_amd64.whl", hash = "sha256:d67a0fffa272405d483395062dd84baee063a9c010f374901ffcf32f0d77c5c8", size = 287877, upload-time = "2025-03-07T13:47:01.518Z" },
]
[[package]]
name = "pycparser"
version = "2.22"
@@ -2704,13 +2762,14 @@ wheels = [
[[package]]
name = "simplecadapi"
version = "2.0.2"
version = "2.0.3"
source = { editable = "." }
dependencies = [
{ name = "cadquery-ocp" },
{ name = "jsonschema" },
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
{ name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
{ name = "py-slvs" },
{ name = "rfc8785" },
{ name = "rich" },
{ name = "typing-extensions" },
@@ -2752,6 +2811,7 @@ requires-dist = [
{ name = "matplotlib", marker = "extra == 'inverse-engineer'", specifier = ">=3.7.0" },
{ name = "mypy", marker = "extra == 'dev'", specifier = ">=1.0" },
{ name = "numpy", specifier = ">=1.21.0" },
{ name = "py-slvs", specifier = "==1.0.6" },
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=7.0" },
{ name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.0" },
{ name = "python-fcl", marker = "extra == 'collision'", specifier = ">=0.7.0.11" },