cadrev 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cadrev/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """cadrev: verifiable CAD reconstruction from papers."""
2
+
3
+
4
+ class Fault(Exception):
5
+ """Why one entry of a project cannot be read or evaluated. Whatever reads the entry catches it
6
+ and files it as a finding under `rule`, or under its own rule where the fault names none. One
7
+ with no message repeats a finding already filed."""
8
+
9
+ def __init__(self, message: str = "", rule: str | None = None):
10
+ super().__init__(message)
11
+ self.message, self.rule = message, rule
cadrev/build.py ADDED
@@ -0,0 +1,664 @@
1
+ """Run model.py and hold what it returns to the model contract: parts, datums, the assembly, and
2
+ for a mechanism its joints, loops, couplings and cables."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import importlib.util
7
+ import math
8
+ import re
9
+ import sys
10
+ import traceback
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import NamedTuple
14
+
15
+ from . import Fault, ledger, released, schema, units
16
+ from .project import Project, expr_names
17
+
18
+
19
+ class _ParamError(AttributeError):
20
+ """A param model.py reads that has no value."""
21
+
22
+
23
+ class Params:
24
+ """Read-only parameter access that records which parameters the model used."""
25
+
26
+ def __init__(self, values: dict[str, float], declared):
27
+ self._values, self._declared, self.used = values, set(declared), set()
28
+
29
+ def __setattr__(self, name: str, value) -> None:
30
+ if not name.startswith("_") and name != "used":
31
+ raise AttributeError(f"param {name!r} is set in params.yaml, not in model.py")
32
+ super().__setattr__(name, value)
33
+
34
+ def __getattr__(self, name: str) -> float:
35
+ if name.startswith("_"):
36
+ raise AttributeError(name)
37
+ if name not in self._values:
38
+ why = "has no value" if name in self._declared else "is not in params.yaml"
39
+ raise _ParamError(f"param {name!r} {why}")
40
+ self.used.add(name)
41
+ return self._values[name]
42
+
43
+
44
+ class JointType(NamedTuple):
45
+ mjcf: str | None # its MJCF joint type; None for a fixed joint, one body with its parent
46
+ quantity: str | None # what its value, range and poses are in
47
+ moves: str # the verb a finding says it moves by
48
+ symbol: str = "" # printed after a compared value of it
49
+
50
+
51
+ JOINT_TYPES = {
52
+ "revolute": JointType("hinge", "angle", "turns", "°"),
53
+ "slide": JointType("slide", "length", "slides"),
54
+ "fixed": JointType(None, None, "stays"),
55
+ }
56
+ DRIVES = ("actuated", "passive")
57
+ # What a coupling is stated by: the quantity of its param, and whether it couples a revolute
58
+ # joint with a slide (a lead) or two joints of one type (a ratio).
59
+ COUPLING_BY = {"ratio": ("fraction", False), "lead": ("length", True)}
60
+ AS_BUILT = "as built" # names the end of a one-ended range that no param states: a move of 0
61
+ _MOTION = {"joint": schema.JOINT, "coupling": schema.COUPLING, "cable": schema.CABLE}
62
+ # What model.py's build may return.
63
+ _RETURNS = (
64
+ "parts",
65
+ "datums",
66
+ "assembly",
67
+ "sheets",
68
+ "threads",
69
+ "loops",
70
+ *(f"{kind}s" for kind in _MOTION),
71
+ )
72
+
73
+
74
+ @dataclass
75
+ class Mass:
76
+ """A part's mass, the param it is weighed by (`by` is mass or density), and its centre of mass
77
+ and inertia about it in the part's frame (ixx iyy izz ixy ixz iyz), as the MJCF prints them."""
78
+
79
+ mass: float
80
+ by: str
81
+ param: str
82
+ center: tuple[float, ...]
83
+ inertia: tuple[float, ...]
84
+
85
+
86
+ class Threaded(NamedTuple):
87
+ """A plain cylinder of a part made for a thread: the datum it is declared at, the thread
88
+ param, whether it carries the thread or clears its screw, whether it is a hole or a shank,
89
+ and the cylinder's diameter, a point on its axis and the axis's direction, in the part's
90
+ frame."""
91
+
92
+ at: str
93
+ part: str
94
+ param: str
95
+ fit: str # threaded or clearance
96
+ hole: bool # a hole, its wall facing its axis; else a shank
97
+ diameter: float
98
+ origin: tuple[float, float, float]
99
+ direction: tuple[float, float, float]
100
+
101
+
102
+ @dataclass
103
+ class Model:
104
+ parts: dict
105
+ datums: dict[str, tuple[float, float, float]]
106
+ assembly: dict # instance -> (part name, Location)
107
+ used: set[str] # the params model.py read
108
+ # Where each part cut from a region of a cut file lies on its sheet: <source>@<x>,<y> ->
109
+ # (part name, Location), carrying its outline (released.outline) onto the region.
110
+ sheets: dict = field(default_factory=dict)
111
+ joints: dict = field(default_factory=dict)
112
+ loops: dict = field(default_factory=dict)
113
+ couplings: dict = field(default_factory=dict)
114
+ cables: dict = field(default_factory=dict)
115
+ masses: dict[str, Mass] = field(default_factory=dict)
116
+ # Each hole or shank declared for a thread, once held to the thread's sizes.
117
+ threads: list[Threaded] = field(default_factory=list)
118
+ # True when a finding dropped the joints, loops, couplings and cables build() returned.
119
+ dropped: bool = False
120
+ # The joints the pose this assembly is placed at moves, itself or through a coupling or loop.
121
+ moved: frozenset[str] = frozenset()
122
+
123
+ @property
124
+ def moving(self) -> dict:
125
+ """The joints that move their child: all but the fixed ones."""
126
+ return {n: j for n, j in self.joints.items() if j["type"] != "fixed"}
127
+
128
+ def quantity(self, joint: str) -> str:
129
+ """What a moving joint's value is in: an angle or a length."""
130
+ return str(JOINT_TYPES[self.joints[joint]["type"]].quantity)
131
+
132
+ def instance_datum(self, name: str) -> tuple[str, tuple[float, float, float]]:
133
+ """The instance <instance>.<feature> names, and that datum's point in its part's frame."""
134
+ inst = prefix(name, self.assembly)
135
+ datum = f"{self.assembly[inst][0]}.{name[len(inst) + 1 :]}" if inst else None
136
+ if datum not in self.datums:
137
+ raise Fault(f"{name} names no <instance>.<feature> datum of the assembly")
138
+ return str(inst), self.datums[datum]
139
+
140
+ def placed(self, name: str):
141
+ """Where the assembly places the datum <instance>.<feature>, as a build123d Vector."""
142
+ from build123d import Location
143
+
144
+ inst, point = self.instance_datum(name)
145
+ return (self.assembly[inst][1] * Location(point)).position
146
+
147
+ def path_length(self, path: list[str]) -> float:
148
+ """The length of a cable's path through its datums, where the assembly places them."""
149
+ points = [self.placed(d) for d in path]
150
+ return sum((b - a).length for a, b in zip(points, points[1:]))
151
+
152
+
153
+ def unmoving(model: Model, joint: str) -> str:
154
+ """What a name is, where a joint that moves was expected."""
155
+ return "a fixed joint" if joint in model.joints else "not a joint"
156
+
157
+
158
+ def prefix(name: str, owners) -> str | None:
159
+ """The longest of owners that name starts with as <owner>.<feature>, or None."""
160
+ return max((o for o in owners if str(name).startswith(f"{o}.")), key=len, default=None)
161
+
162
+
163
+ def printed(*values: float) -> tuple[float, ...]:
164
+ """values rounded to the 12 digits the MJCF prints, so the export and report.json agree."""
165
+ return tuple(float(f"{v:.12g}") for v in values)
166
+
167
+
168
+ def range_ends(p: Project, joint: dict) -> list[tuple[str, float]]:
169
+ """A joint's range as its two ends, low first, each (the param it is from, its value): a range
170
+ of one param runs from the assembly as built to that param, either way."""
171
+ ends: list[tuple[str, float]] = [(str(name), p.values[name]) for name in joint["range"]]
172
+ return ends if len(ends) == 2 else sorted([(AS_BUILT, 0.0), *ends], key=lambda end: end[1])
173
+
174
+
175
+ def coupling_by(coupling: dict) -> tuple[str, str]:
176
+ """What a coupling is stated by: (ratio or lead, its param)."""
177
+ key = next(k for k in COUPLING_BY if k in coupling)
178
+ return key, coupling[key]
179
+
180
+
181
+ class InStep(NamedTuple):
182
+ """A coupling's two joints, moving in step: driven at ratio times driver, in the project's
183
+ units of each; law says how, as a finding words it."""
184
+
185
+ name: str
186
+ driver: str
187
+ driven: str
188
+ ratio: float
189
+ law: str
190
+
191
+
192
+ def in_step(p: Project, model: Model) -> list[InStep]:
193
+ """Each coupling's pair of joints moving in proportion, at its ratio or at its lead per full
194
+ turn of its revolute joint."""
195
+ found = []
196
+ for name, coupling in model.couplings.items():
197
+ key, param = coupling_by(coupling)
198
+ driver, driven, value = coupling["driver"], coupling["driven"], p.values[param]
199
+ if key == "ratio":
200
+ law = f"moves {driven} {value:g} times {driver}"
201
+ found.append(InStep(name, driver, driven, value, law))
202
+ continue
203
+ turn = 2 * math.pi / units.size("angle", p.units)
204
+ turns = model.quantity(driver) == "angle"
205
+ revolute, slide = (driver, driven) if turns else (driven, driver)
206
+ law = f"moves {slide} {value:g} per full turn of {revolute}"
207
+ ratio = value / turn if turns else turn / value
208
+ found.append(InStep(name, driver, driven, ratio, law))
209
+ return found
210
+
211
+
212
+ def _contract(result) -> None:
213
+ """A Fault saying why build()'s return breaks the model contract, if it does."""
214
+ from build123d import Location
215
+ from build123d.topology import Shape
216
+
217
+ if not isinstance(result, dict):
218
+ raise Fault(f"must return a mapping of parts, datums and assembly, not {_type(result)}")
219
+ if unknown := [key for key in result if key not in _RETURNS]:
220
+ raise Fault(
221
+ f"returns {', '.join(map(repr, unknown))}, where it may return {', '.join(_RETURNS)}"
222
+ )
223
+ for key in _RETURNS:
224
+ if not isinstance(result.get(key, {}), dict):
225
+ raise Fault(f"{key} must be a mapping of names, not {_type(result[key])}")
226
+ for name in result.get(key, {}):
227
+ if not isinstance(name, str):
228
+ raise Fault(f"{key}: the name {name!r} must be text")
229
+ for name, part in result.get("parts", {}).items():
230
+ if not isinstance(part, Shape):
231
+ raise Fault(f"part {name} must be a build123d shape, not {_type(part)}")
232
+ if not re.fullmatch(r"[\w.-]+", str(name)): # it names build/parts/<name>.step
233
+ raise Fault(f"part name {name!r} must be letters, digits, '_', '.' or '-'")
234
+ for name, point in result.get("datums", {}).items():
235
+ if not (_listed(point, 3) and all(isinstance(c, (int, float)) for c in point)):
236
+ raise Fault(f"datum {name} must be an (x, y, z) tuple of numbers, not {point!r}")
237
+ for name, param in result.get("threads", {}).items():
238
+ if not isinstance(param, str):
239
+ raise Fault(f"thread at {name} must name a thread param, not {param!r}")
240
+ for key, what in (("assembly", "assembly instance"), ("sheets", "sheets region")):
241
+ for name, entry in result.get(key, {}).items():
242
+ placed = _listed(entry, 2) and isinstance(entry[0], str)
243
+ if not (placed and isinstance(entry[1], Location)):
244
+ raise Fault(f"{what} {name} must be a (part name, Location) pair")
245
+ for name, pair in result.get("loops", {}).items():
246
+ if not (_listed(pair, 2) and all(isinstance(d, str) for d in pair)):
247
+ raise Fault(f"loop {name} must be two <instance>.<feature> datums, not {pair!r}")
248
+ for kind, spec in _MOTION.items():
249
+ entries = result.get(f"{kind}s", {})
250
+ for name, entry in entries.items():
251
+ problems: list[str] = []
252
+ # As the schema reads it: a key set to None counts as absent.
253
+ entries[name] = entry = schema.conform(entry, spec, f"{kind} {name}", problems)
254
+ if not problems and (problem := _unfit(kind, entry)):
255
+ problems.append(f"{kind} {name}: {problem}")
256
+ if problems:
257
+ raise Fault(problems[0].partition(";")[0])
258
+
259
+
260
+ def _type(value) -> str:
261
+ return type(value).__name__
262
+
263
+
264
+ def _listed(value, count: int) -> bool:
265
+ return isinstance(value, (list, tuple)) and len(value) == count
266
+
267
+
268
+ def _unfit(kind: str, entry: dict) -> str | None:
269
+ """Why a joint, coupling or cable of the right shape still states no motion."""
270
+ if kind == "joint":
271
+ if entry.get("type") not in JOINT_TYPES:
272
+ return f"type must be one of {', '.join(JOINT_TYPES)}, not {entry.get('type')!r}"
273
+ if "parent" not in entry or "child" not in entry:
274
+ return "parent and child each name an assembly instance"
275
+ if entry["type"] == "fixed":
276
+ return None # what else it takes is [model-joint]'s to say
277
+ if len(entry.get("axis", ())) != 2:
278
+ return f"axis must be two datums of its child, not {entry.get('axis')!r}"
279
+ if "range" in entry and len(entry["range"]) not in (1, 2):
280
+ return f"range must be one or two param names, not {entry['range']!r}"
281
+ if entry.get("drive") not in DRIVES:
282
+ return f"drive must be actuated or passive, not {entry.get('drive')!r}"
283
+ elif kind == "coupling":
284
+ if len(COUPLING_BY.keys() & entry.keys()) != 1 or not {"driver", "driven"} <= entry.keys():
285
+ return "names a driver, a driven and one of ratio or lead"
286
+ elif len(entry.get("path", ())) < 2:
287
+ return f"path must be two or more datums, not {entry.get('path')!r}"
288
+ return None
289
+
290
+
291
+ def _failure(exc: BaseException, model: Path) -> str:
292
+ """The exception, with the model.py line it was raised from unless it names a param."""
293
+ if isinstance(exc, _ParamError):
294
+ return f"AttributeError: {exc}"
295
+ message = f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__
296
+ frames = [f for f in traceback.extract_tb(exc.__traceback__) if Path(f.filename) == model]
297
+ return (
298
+ f"{message} (model.py line {frames[-1].lineno}: {frames[-1].line})" if frames else message
299
+ )
300
+
301
+
302
+ def build(p: Project) -> Model | None:
303
+ """The model model.py builds from the resolved params, held to the contract; None after a
304
+ [model-build] or [model-return] finding. A finding on its motion keeps the build and drops
305
+ the joints, loops, couplings and cables."""
306
+ path = p.root / "model.py"
307
+ spec = importlib.util.spec_from_file_location("cadrev_model", path)
308
+ assert spec is not None and spec.loader is not None # a .py path always gets a source loader
309
+ module = importlib.util.module_from_spec(spec)
310
+ params = Params(p.values, p.params)
311
+ writes_bytecode, sys.dont_write_bytecode = sys.dont_write_bytecode, True # no __pycache__/
312
+ try:
313
+ spec.loader.exec_module(module)
314
+ result = module.build(params)
315
+ except (Exception, SystemExit) as exc: # noqa: BLE001 - a broken model is a finding, not a crash
316
+ p.error("model-build", f"model.build failed: {_failure(exc, path)}")
317
+ return None
318
+ finally:
319
+ sys.dont_write_bytecode = writes_bytecode
320
+ try:
321
+ _contract(result)
322
+ except Fault as fault:
323
+ p.error("model-return", f"model.build {fault.message}")
324
+ return None
325
+ model = Model(
326
+ parts=result.get("parts", {}),
327
+ datums={
328
+ k: (float(x), float(y), float(z)) for k, (x, y, z) in result.get("datums", {}).items()
329
+ },
330
+ assembly=result.get("assembly", {}),
331
+ used=params.used,
332
+ sheets=result.get("sheets", {}),
333
+ **{
334
+ f"{kind}s": result.get(f"{kind}s", {})
335
+ for kind in ("joint", "loop", "coupling", "cable")
336
+ },
337
+ )
338
+ declared = result.get("threads", {})
339
+ _hold_units(p, model, set(declared.values()))
340
+ for name, part in model.parts.items():
341
+ solids = len(part.solids())
342
+ if not part.is_valid:
343
+ p.error("part-invalid", f"part {name}: solid is not valid")
344
+ elif solids == 1 and part.volume <= p.length_tol**3:
345
+ p.error("part-invalid", f"part {name}: has no volume; build it as a solid")
346
+ elif solids != 1:
347
+ p.error(
348
+ "part-invalid",
349
+ f"part {name}: is {solids} solids, not one; fuse its bodies, or make each its own "
350
+ "part placed in the assembly",
351
+ )
352
+ for name, point in model.datums.items():
353
+ part = prefix(name, model.parts)
354
+ if part is not None:
355
+ gap = released.off_solid(model.parts[part], point, p.length_tol)
356
+ if gap is not None:
357
+ p.error("datum-off-solid", f"datum {name} of part {part}: {released.off(gap)}")
358
+ faces: dict[tuple, str] = {} # each part's cylindrical face declared for a thread: its datum
359
+ for at, param in declared.items():
360
+ with p.filing("model-thread", f"thread at {at}: "):
361
+ model.threads.append(_threaded(p, model, at, param, faces))
362
+ for inst, (part, _) in list(model.assembly.items()):
363
+ if part not in model.parts:
364
+ p.error("assembly-part", f"assembly instance {inst}: unknown part {part!r}")
365
+ del model.assembly[inst]
366
+ if _motion_faults(p, model):
367
+ model.joints, model.loops, model.couplings, model.cables = {}, {}, {}, {}
368
+ model.dropped = True
369
+ model.masses = _mass_model(p, model)
370
+ return model
371
+
372
+
373
+ def _threaded(p: Project, model: Model, at: str, param: str, faces: dict[tuple, str]) -> Threaded:
374
+ """The cylinder a thread is declared on, held to the thread's sizes: it carries the thread
375
+ from its minor diameter to its major, or clears its screw from there to the loosest
376
+ clearance hole its table gives, as a released body's hole may be any of them. A hole or
377
+ shank is declared once, at one datum, so a count of them counts each once."""
378
+ part = prefix(at, model.parts)
379
+ if part is None or at not in model.datums:
380
+ raise Fault("is not a <part>.<feature> datum")
381
+ size = p.thread_params.get(param)
382
+ if size is None:
383
+ if param in p.values or param not in p.params:
384
+ raise Fault(f"{param} is not a thread param; give it thread: in params.yaml")
385
+ raise Fault() # the param's own finding says why it has no value
386
+ tol, thread = p.length_tol, size.thread
387
+ loosest = None if thread.loosest is None else thread.loosest * size.per_mm
388
+ widest = float(size) if loosest is None else loosest
389
+ # A datum on the axis of a hole in a boss lies on the boss's axis too: the hole is the one
390
+ # of them the thread fits.
391
+ diameter, origin, direction, face = released.cylinder_at(
392
+ model.parts[part],
393
+ model.datums[at],
394
+ tol,
395
+ at,
396
+ or_axis=True,
397
+ fits=lambda found: size.minor - tol <= found <= widest + tol,
398
+ )
399
+ # By part too: two parts may be built as one shape.
400
+ if faces.setdefault((part, id(face)), at) != at:
401
+ raise Fault(f"lies on the hole or shank {faces[part, id(face)]} already declares")
402
+ if size.minor - tol <= diameter <= size + tol:
403
+ fit = "threaded"
404
+ elif loosest is not None and size < diameter <= loosest + tol:
405
+ fit = "clearance"
406
+ else:
407
+ hole = "" if loosest is None else f" nor a clearance hole for it (up to Ø{loosest:.4g})"
408
+ raise Fault(
409
+ f"its cylinder is Ø{diameter:.4g}, {'neither' if hole else 'not'} {thread.name}'s "
410
+ f"thread (Ø{size.minor:.4g} to Ø{float(size):g}; its tap drill is Ø{size.tap:.4g})"
411
+ f"{hole}"
412
+ )
413
+ return Threaded(
414
+ at, part, param, fit, released.is_hole(face), printed(diameter)[0], origin, direction
415
+ )
416
+
417
+
418
+ def _hold_units(p: Project, model: Model, threaded: set[str]) -> None:
419
+ """Each param the model reads or exports is printed in a unit of the quantity it is used as,
420
+ and each param is read by something."""
421
+ for name in sorted(model.used):
422
+ p.hold_param(name, ("length", "angle", "count"), "in model.py")
423
+ ranges = {n for joint in model.joints.values() for n in joint.get("range", [])}
424
+ for name, joint in model.moving.items():
425
+ for param in joint.get("range", []):
426
+ p.hold_param(param, (model.quantity(name),), f"in a {joint['type']} joint's range")
427
+ coupled = set()
428
+ for name, coupling in model.couplings.items():
429
+ key, param = coupling_by(coupling)
430
+ coupled.add(param)
431
+ p.hold_param(param, (COUPLING_BY[key][0],), f"as coupling {name}'s {key}")
432
+ for count in _worked_from(p, param) if key == "ratio" else []:
433
+ # A ratio is worked out from counts, from lengths as a belt's pulley diameters are, or
434
+ # from angles as a cord's closed value over the travel of the joint that winds it.
435
+ unit, ref = p.printed_as(count)
436
+ if not (ref and p.prints_length(ref)):
437
+ counted = unit is None or units.quantity(unit) == "count"
438
+ expected = ("count",) if counted else ("count", "length", "angle")
439
+ p.hold_param(count, expected, f"in coupling {name}'s ratio")
440
+ named = {n for c in p.checks for n in ledger.named_by_checks(p, c)}
441
+ fit = {p.meta.get("clearance")} - {None} # the loosest fit
442
+ # A screw's length is what is bought, whether or not the model reads it.
443
+ exported = ranges | coupled | set(ledger.mass_params(p)) | threaded
444
+ exported |= set(p.screws.values()) | fit
445
+ derived = {n for spec in p.params.values() for n in expr_names(str(spec.get("expr") or ""))}
446
+ p.resolution = ledger.resolution(p) - model.used - derived - exported
447
+ for name in sorted(p.values.keys() - model.used - derived - named - exported):
448
+ p.warn("param-unused", f"param {name} is defined but the model never reads it")
449
+
450
+
451
+ def _worked_from(p: Project, name: str, through: tuple[str, ...] = ()) -> list[str]:
452
+ """The params a derived param's value is worked out from, through every derived param its
453
+ expr reads: those with a basis of their own."""
454
+ spec = p.params.get(name) or {}
455
+ if spec.get("basis") != "derived" or name in through:
456
+ return []
457
+ out = []
458
+ for n in sorted(expr_names(str(spec.get("expr", ""))) & p.params.keys()):
459
+ derived = (p.params[n] or {}).get("basis") == "derived"
460
+ out += _worked_from(p, n, (*through, name)) if derived else [n]
461
+ return list(dict.fromkeys(out))
462
+
463
+
464
+ def _motion_faults(p: Project, model: Model) -> bool:
465
+ """File [model-joint], [model-loop], [model-coupling] and [model-cable] for each joint, loop,
466
+ coupling and cable the assembly cannot hold; whether there is any."""
467
+ before = len(p.findings)
468
+ moved_by: dict[str, str] = {} # child instance -> the joint moving it
469
+ for name, joint in model.joints.items():
470
+ with p.filing("model-joint", f"joint {name}: "):
471
+ _joint_fault(p, model, joint, moved_by)
472
+ if (
473
+ joint["child"] not in moved_by
474
+ and {joint["parent"], joint["child"]} <= model.assembly.keys()
475
+ ):
476
+ moved_by[joint["child"]] = name
477
+ ringed: set[str] = set()
478
+ for start in moved_by:
479
+ ring, inst = [moved_by[start]], model.joints[moved_by[start]]["parent"]
480
+ while inst in moved_by and inst != start and len(ring) <= len(moved_by):
481
+ ring.append(moved_by[inst])
482
+ inst = model.joints[moved_by[inst]]["parent"]
483
+ if inst == start and not ringed & set(ring):
484
+ ringed |= set(ring)
485
+ p.error(
486
+ "model-joint",
487
+ f"joint {ring[0]}: {start} moves itself through {', '.join(ring)}; close a ring of "
488
+ "joints with a loop instead",
489
+ )
490
+ for name, pair in model.loops.items():
491
+ with p.filing("model-loop", f"loop {name}: "):
492
+ for datum in pair:
493
+ model.instance_datum(datum)
494
+ for name, coupling in model.couplings.items():
495
+ with p.filing("model-coupling", f"coupling {name}: "):
496
+ _coupling_fault(p, model, coupling)
497
+ for name, cable in model.cables.items():
498
+ with p.filing("model-cable", f"cable {name}: "):
499
+ for datum in cable["path"]:
500
+ model.instance_datum(datum)
501
+ return len(p.findings) > before
502
+
503
+
504
+ def _joint_fault(p: Project, model: Model, joint: dict, moved_by: dict) -> None:
505
+ for key in ("parent", "child"):
506
+ if joint[key] not in model.assembly:
507
+ raise Fault(f"{key} {joint[key]} is not an instance of the assembly")
508
+ if joint["child"] in moved_by:
509
+ raise Fault(f"{joint['child']} is already the child of joint {moved_by[joint['child']]}")
510
+ if joint["type"] == "fixed":
511
+ if extra := [key for key in joint if key not in ("type", "parent", "child")]:
512
+ raise Fault(
513
+ f"a fixed joint moves {joint['child']} with {joint['parent']}, so it takes no "
514
+ f"{', '.join(extra)}; make it revolute or slide if it moves"
515
+ )
516
+ return
517
+ points = []
518
+ for datum in joint["axis"]:
519
+ if prefix(datum, model.assembly) != joint["child"]:
520
+ raise Fault(f"axis {datum} is not a datum of its child {joint['child']}")
521
+ points.append(model.instance_datum(datum)[1])
522
+ if math.dist(*points) <= p.length_tol:
523
+ raise Fault(f"axis {' and '.join(joint['axis'])} coincide, so they give no direction")
524
+ for param in joint.get("range", []):
525
+ if param not in p.values:
526
+ raise Fault(f"range names {param}, which params.yaml does not define")
527
+ if "range" in joint:
528
+ (low, lo), (high, hi) = range_ends(p, joint)
529
+ if lo > hi:
530
+ raise Fault(f"range {low} {lo:g} exceeds {high} {hi:g}")
531
+
532
+
533
+ def _coupling_fault(p: Project, model: Model, coupling: dict) -> None:
534
+ driver, driven = coupling["driver"], coupling["driven"]
535
+ for key, joint in (("driver", driver), ("driven", driven)):
536
+ if joint not in model.moving:
537
+ raise Fault(f"{key} {joint} is {unmoving(model, joint)}")
538
+ if driver == driven:
539
+ raise Fault(f"driver and driven are both {driver}; a coupling ties two joints")
540
+ key, param = coupling_by(coupling)
541
+ if (model.quantity(driver) != model.quantity(driven)) != COUPLING_BY[key][1]:
542
+ raise Fault(
543
+ f"a {key} does not couple these joints: a ratio couples two joints of one type, a "
544
+ "lead a revolute joint and a slide"
545
+ )
546
+ if param not in p.values:
547
+ raise Fault(f"{key} names {param}, which params.yaml does not define")
548
+ if p.values[param] == 0:
549
+ moved = "the slide" if key == "lead" else driven
550
+ raise Fault(f"{key} {param} is 0, so {moved} never moves")
551
+
552
+
553
+ def _mass_model(p: Project, model: Model) -> dict[str, Mass]:
554
+ """Each part's Mass from params.yaml's parts: its datasheet mass, or its volume times its
555
+ density, with the solid's inertia scaled to that mass. In a model with joints every part an
556
+ instance places needs an entry."""
557
+ from build123d import CenterOf
558
+
559
+ for name in p.parts.keys() - model.parts.keys():
560
+ p.error("part-mass", f"params.yaml parts {name}: model.build returns no part {name}")
561
+ placed = {part for part, _ in model.assembly.values()}
562
+ masses = {}
563
+ for name, part in model.parts.items():
564
+ entry = p.parts.get(name) or {}
565
+ by = next(iter(entry), None)
566
+ if by is None:
567
+ if model.joints and name in placed:
568
+ p.error(
569
+ "part-mass",
570
+ f"part {name}: params.yaml parts gives it no mass or density, so the MJCF "
571
+ "export cannot weigh it",
572
+ )
573
+ elif entry[by] not in p.params:
574
+ p.error(
575
+ "part-mass",
576
+ f"part {name}: params.yaml parts names {by} {entry[by]}, which params.yaml does "
577
+ "not define",
578
+ )
579
+ elif entry[by] in p.values and part.volume > 0: # one with none is [part-invalid]
580
+ volume, value = part.volume, p.values[entry[by]]
581
+ mass = value if by == "mass" else volume * value
582
+ inertia = part.matrix_of_inertia
583
+ pairs = ((0, 0), (1, 1), (2, 2), (0, 1), (0, 2), (1, 2))
584
+ masses[name] = Mass(
585
+ mass=printed(mass)[0],
586
+ by=by,
587
+ param=entry[by],
588
+ center=printed(*part.center(CenterOf.MASS)),
589
+ inertia=printed(*(mass / volume * inertia[i][j] for i, j in pairs)),
590
+ )
591
+ return masses
592
+
593
+
594
+ # The project length units build123d's STEP export names; a part in any other is scaled to mm.
595
+ _STEP_UNITS = {"mm": "MM", "cm": "CM", "m": "M", "µm": "MC", "in": "IN", "ft": "FT"}
596
+
597
+
598
+ def export(p: Project, model: Model) -> list[Path]:
599
+ """Write build/parts/<part>.step and build/assembly.step, each at its true size whatever the
600
+ project's length unit: a CAD program opens a 2 in part as 50.8 mm, not as 2 mm."""
601
+ from build123d import Unit, export_step
602
+
603
+ out = p.root / "build"
604
+ (out / "parts").mkdir(parents=True, exist_ok=True)
605
+ unit = p.units["length"]
606
+ written = []
607
+ for name, part in model.parts.items():
608
+ written.append(out / "parts" / f"{name}.step")
609
+ if unit in _STEP_UNITS:
610
+ part.label = name
611
+ export_step(part, str(written[-1]), unit=Unit[_STEP_UNITS[unit]])
612
+ else:
613
+ scaled = part.scale(units.convert(1.0, unit, {"length": "mm"}))
614
+ scaled.label = name
615
+ export_step(scaled, str(written[-1]))
616
+ if model.assembly:
617
+ written.append(out / "assembly.step")
618
+ _export_assembly(p.meta.get("name", "assembly"), model, units.UNITS[unit].si, written[-1])
619
+ return written
620
+
621
+
622
+ def _export_assembly(name: str, model: Model, unit: float, path: Path) -> None:
623
+ """Write the assembly as a CAD program's tree shows it: each part once, under its own name,
624
+ and each instance an occurrence of its part, under the instance's name. build123d's
625
+ export_step names a part after the last of its instances. unit is the project's length unit
626
+ in metres."""
627
+ # OCP's modules re-export a compiled module whose names pyright cannot see, so they are
628
+ # looked up by name.
629
+ ocp = {
630
+ module: importlib.import_module(f"OCP.{module}")
631
+ for module in (
632
+ "IFSelect", "Message", "STEPCAFControl", "STEPControl", "TCollection", "TDataStd",
633
+ "TDocStd", "TopLoc", "XCAFApp", "XCAFDoc",
634
+ )
635
+ } # fmt: skip
636
+ text = ocp["TCollection"].TCollection_ExtendedString
637
+ named = ocp["TDataStd"].TDataStd_Name.Set_s
638
+ tool = ocp["XCAFDoc"].XCAFDoc_DocumentTool
639
+
640
+ doc = ocp["TDocStd"].TDocStd_Document(text("XmlOcaf"))
641
+ ocp["XCAFApp"].XCAFApp_Application.GetApplication_s().NewDocument(text("MDTV-XCAF"), doc)
642
+ tool.SetLengthUnit_s(doc, unit) # as export_step is told a part's
643
+ shapes = tool.ShapeTool_s(doc.Main())
644
+ top = shapes.NewShape()
645
+ named(top, text(name))
646
+ origin = ocp["TopLoc"].TopLoc_Location()
647
+ parts = {}
648
+ for inst, (part, location) in model.assembly.items():
649
+ shape = model.parts[part].wrapped
650
+ if part not in parts:
651
+ # A part built at a location of its own is added without it, and each instance
652
+ # carries it: a located shape would be written as an unnamed part.
653
+ parts[part] = shapes.AddShape(shape.Located(origin), False)
654
+ named(parts[part], text(part))
655
+ placed = location.wrapped.Multiplied(shape.Location())
656
+ named(shapes.AddComponent(top, parts[part], placed), text(inst))
657
+ shapes.UpdateAssemblies()
658
+ quiet = ocp["Message"].Message_Gravity.Message_Fail # OCCT's transfer log, off the console
659
+ for printer in ocp["Message"].Message.DefaultMessenger_s().Printers():
660
+ printer.SetTraceLevel(quiet)
661
+ writer = ocp["STEPCAFControl"].STEPCAFControl_Writer()
662
+ writer.Transfer(doc, ocp["STEPControl"].STEPControl_StepModelType.STEPControl_AsIs)
663
+ if writer.Write(str(path)) != ocp["IFSelect"].IFSelect_ReturnStatus.IFSelect_RetDone:
664
+ raise RuntimeError(f"could not write {path}")