robot-models-lib 0.2.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.
Files changed (96) hide show
  1. robot_models/__init__.py +18 -0
  2. robot_models/actuators/__init__.py +1 -0
  3. robot_models/actuators/rungs/README.md +24 -0
  4. robot_models/actuators/rungs/coulomb_viscous/README.md +61 -0
  5. robot_models/actuators/rungs/coulomb_viscous/model.js +14 -0
  6. robot_models/actuators/rungs/coulomb_viscous/model.json +102 -0
  7. robot_models/actuators/rungs/coulomb_viscous/model.py +24 -0
  8. robot_models/actuators/rungs/datasheet/README.md +65 -0
  9. robot_models/actuators/rungs/datasheet/model.js +14 -0
  10. robot_models/actuators/rungs/datasheet/model.json +138 -0
  11. robot_models/actuators/rungs/datasheet/model.py +24 -0
  12. robot_models/actuators/rungs/dcmotor/README.md +63 -0
  13. robot_models/actuators/rungs/dcmotor/model.json +163 -0
  14. robot_models/actuators/rungs/ideal/README.md +60 -0
  15. robot_models/actuators/rungs/ideal/model.js +6 -0
  16. robot_models/actuators/rungs/ideal/model.json +90 -0
  17. robot_models/actuators/rungs/ideal/model.py +13 -0
  18. robot_models/actuators/rungs/load/README.md +65 -0
  19. robot_models/actuators/rungs/load/model.js +15 -0
  20. robot_models/actuators/rungs/load/model.json +117 -0
  21. robot_models/actuators/rungs/load/model.py +25 -0
  22. robot_models/actuators/rungs/lugre/README.md +72 -0
  23. robot_models/actuators/rungs/lugre/model.js +24 -0
  24. robot_models/actuators/rungs/lugre/model.json +164 -0
  25. robot_models/actuators/rungs/lugre/model.py +30 -0
  26. robot_models/actuators/rungs/ripple/README.md +64 -0
  27. robot_models/actuators/rungs/ripple/model.js +17 -0
  28. robot_models/actuators/rungs/ripple/model.json +119 -0
  29. robot_models/actuators/rungs/ripple/model.py +27 -0
  30. robot_models/actuators/rungs/stribeck/README.md +65 -0
  31. robot_models/actuators/rungs/stribeck/model.js +17 -0
  32. robot_models/actuators/rungs/stribeck/model.json +126 -0
  33. robot_models/actuators/rungs/stribeck/model.py +28 -0
  34. robot_models/actuators/servo/README.md +278 -0
  35. robot_models/actuators/servo/__init__.py +7 -0
  36. robot_models/actuators/servo/bldc/README.md +186 -0
  37. robot_models/actuators/servo/bldc/__init__.py +5 -0
  38. robot_models/actuators/servo/bldc/bldc_motor.py +93 -0
  39. robot_models/actuators/servo/bldc/ladder.py +268 -0
  40. robot_models/actuators/servo/foc_controller/README.md +127 -0
  41. robot_models/actuators/servo/foc_controller/__init__.py +3 -0
  42. robot_models/actuators/servo/foc_controller/ladder.py +207 -0
  43. robot_models/actuators/servo/gearbox/README.md +148 -0
  44. robot_models/actuators/servo/gearbox/__init__.py +5 -0
  45. robot_models/actuators/servo/gearbox/gearbox.py +36 -0
  46. robot_models/actuators/servo/gearbox/ladder.py +214 -0
  47. robot_models/actuators/servo/integrated_servo.py +33 -0
  48. robot_models/actuators/servo/ladder.py +593 -0
  49. robot_models/arms/__init__.py +1 -0
  50. robot_models/arms/rigid_body_chain/README.md +151 -0
  51. robot_models/arms/rigid_body_chain/__init__.py +3 -0
  52. robot_models/arms/rigid_body_chain/ladder.py +228 -0
  53. robot_models/conveyors/__init__.py +1 -0
  54. robot_models/conveyors/conveyor/README.md +140 -0
  55. robot_models/conveyors/conveyor/__init__.py +1 -0
  56. robot_models/conveyors/conveyor/ladder.py +203 -0
  57. robot_models/datasheet/__init__.py +56 -0
  58. robot_models/datasheet/datasheet.py +355 -0
  59. robot_models/datasheet/literal.py +144 -0
  60. robot_models/datasheet/source.py +328 -0
  61. robot_models/datasheet/stated.py +135 -0
  62. robot_models/datasheet/units.py +57 -0
  63. robot_models/end_effectors/__init__.py +1 -0
  64. robot_models/end_effectors/gripper/README.md +112 -0
  65. robot_models/end_effectors/gripper/__init__.py +3 -0
  66. robot_models/end_effectors/gripper/ladder.py +150 -0
  67. robot_models/homing/__init__.py +38 -0
  68. robot_models/homing/cad_bundle.py +206 -0
  69. robot_models/homing/contact.py +201 -0
  70. robot_models/homing/fit.py +126 -0
  71. robot_models/homing/metrics.py +237 -0
  72. robot_models/homing/protocols.py +72 -0
  73. robot_models/homing/types.py +256 -0
  74. robot_models/ladder.py +645 -0
  75. robot_models/markers/__init__.py +1 -0
  76. robot_models/markers/aruco_marker/README.md +92 -0
  77. robot_models/markers/aruco_marker/__init__.py +2 -0
  78. robot_models/markers/aruco_marker/ladder.py +142 -0
  79. robot_models/references.py +429 -0
  80. robot_models/sensors/__init__.py +1 -0
  81. robot_models/sensors/camera/README.md +118 -0
  82. robot_models/sensors/camera/__init__.py +3 -0
  83. robot_models/sensors/camera/ladder.py +108 -0
  84. robot_models/sensors/encoder/README.md +103 -0
  85. robot_models/sensors/encoder/__init__.py +5 -0
  86. robot_models/sensors/encoder/ladder.py +133 -0
  87. robot_models/sensors/hyperspectral_camera/README.md +107 -0
  88. robot_models/sensors/hyperspectral_camera/__init__.py +1 -0
  89. robot_models/sensors/hyperspectral_camera/ladder.py +151 -0
  90. robot_models/sensors/rgbd/README.md +113 -0
  91. robot_models/sensors/rgbd/__init__.py +5 -0
  92. robot_models/sensors/rgbd/ladder.py +113 -0
  93. robot_models_lib-0.2.0.dist-info/METADATA +143 -0
  94. robot_models_lib-0.2.0.dist-info/RECORD +96 -0
  95. robot_models_lib-0.2.0.dist-info/WHEEL +4 -0
  96. robot_models_lib-0.2.0.dist-info/licenses/LICENSE +21 -0
robot_models/ladder.py ADDED
@@ -0,0 +1,645 @@
1
+ """A part type's ladder of models (PEP 0004): which parameters each rung needs, and which rung it falls back on.
2
+
3
+ from robot_models.ladder import ladders
4
+ servo = ladders()["integrated_servo"]
5
+ servo.parameters("M3.stribeck") # what the rung needs, inherited ones included (its required names)
6
+ servo.holds("M3.stribeck") # ... plus what it reads when stated (its optional names)
7
+ servo.fallback("M3.lugre") # ("M3.lugre", "M3.stribeck", "M2.coulomb_viscous", "M1.datasheet", "M0.ideal")
8
+ servo.canonical("frictionloss_nm") # "coulomb_friction": another name for a quantity resolves to the type's own
9
+ servo.unpack("thermal_r_c") # ("thermal_resistance", "thermal_time_constant"): a packed array's quantities
10
+
11
+ - **One vocabulary per type.** A type lists its parameters once (`vocabulary`); a rung names the ones it adds. Any other
12
+ name for the same quantity is an `Alias`, with a note whenever it is not the same quantity one for one; a name that
13
+ packs several quantities into one array is a `Packed`, never an alias of one of them.
14
+ - **A ladder is a tree of bases.** Each rung extends one base and needs everything its base needs; the base chain is its
15
+ fallback. Rung keys are composed from explicit fields (`M{level}.{name}`) and never parsed.
16
+ - **Required or optional.** `adds` are what the rung's model cannot run without; `optional` are what it reads when a
17
+ source states them (a default or another route covers them otherwise). A name optional below may become required
18
+ above (M1 states coulomb_friction, M2 needs it); nothing is added twice down one chain.
19
+ - **Each rung shows its equation and its references.** `equation` and `references` on every rung.
20
+ - **Type data only.** Parameter names, units, definitions and equations: never a value measured on one unit, never a
21
+ maker. What a deployment sets (gains, caps, the station's gravity) is listed as `DeploymentOnly`, not put on a rung.
22
+
23
+ Each type folder holds one `ladder.py` with `LADDER = Ladder(...)`; `ladders()` finds them by walking the package, so no
24
+ hand-kept registry exists for concurrent edits to collide on. Stdlib only, like robot_models.datasheet.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import difflib
30
+ import importlib
31
+ import re
32
+ from collections.abc import Mapping
33
+ from dataclasses import dataclass
34
+ from pathlib import Path
35
+
36
+ KINDS = ("physics", "residual", "learned")
37
+ # WHY fixed levels for the two learned kinds (sim2real decision-rung-keys-2026-11-05, kept by PEP 0004): M6 is always
38
+ # the grey-box residual and M7 always the black-box net, on every type, so "M6" means the same thing everywhere.
39
+ RESIDUAL_LEVEL = 6
40
+ LEARNED_LEVEL = 7
41
+ TOP_PHYSICS_LEVEL = 5
42
+
43
+ WEAR_LAWS = {
44
+ "linear": "p(u) = p0 + k·u",
45
+ "sqrt": "p(u) = p0 + k·√u",
46
+ "archard": "p(u) = p0 + k·Σ(load·distance): wear grows with the load carried times the distance slid",
47
+ }
48
+
49
+ DEPLOYMENT_ROLES = {
50
+ "config": "a setting a deployment writes (a gain, a cap, a rate): read from its config, never fitted to the type",
51
+ "assembly": "a property of where the part is mounted (the station's gravity, a base frame): the description's",
52
+ }
53
+
54
+ # WHY refuse these endings (robotparts SCHEMA2: "Names carry no units"; PEP 0004 decision 1): the unit lives on the
55
+ # Parameter, so one quantity cannot get a second name per unit (frictionloss_nm, armature_kg_m2). Direction words that
56
+ # look like units (fov_h, resolution_v) are deliberately not in the list.
57
+ UNIT_SUFFIXES = (
58
+ "_nm", "_nm_a", "_nm_rad", "_nm_s_rad", "_n_m", "_n_s_m", "_kg_m2", "_kg", "_rad_s", "_rad", "_deg", "_rpm",
59
+ "_mm", "_ms", "_hz", "_ohm", "_px", "_pct", "_per_h", "_per_sqrt_h", "_per_km", "_per_cycle", "_per_nm_rev",
60
+ "_s", "_m", "_n",
61
+ )
62
+
63
+ # WHY a table for kv alone: robotparts' registry spells kv only in rpm/V; its SI unit is rad/(s·V) (registry si_unit).
64
+ SI_SPELLING = {"rpm/V": "rad/(s·V)"}
65
+
66
+ _WORD = re.compile(r"^[a-z][a-z0-9_]*$")
67
+
68
+
69
+ def _word(what: str, text: object) -> None:
70
+ if not isinstance(text, str) or not _WORD.match(text):
71
+ raise ValueError(f"{what} {text!r} must be a snake_case word: lower-case letters, digits and _")
72
+
73
+
74
+ def _hint(name: str, known) -> str:
75
+ near = difflib.get_close_matches(name, list(known), n=1)
76
+ return f" (did you mean {near[0]!r}?)" if near else ""
77
+
78
+
79
+ def _ordered(names) -> tuple[str, ...]:
80
+ """Names in first-seen order, each once."""
81
+ return tuple(dict.fromkeys(names))
82
+
83
+
84
+ # --- the records -----------------------------------------------------------------------------------------------------
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class Reference:
89
+ """Where to learn a model: a real, citable work (sim2real's cards check DOIs and URLs; this keeps their shape)."""
90
+
91
+ title: str # authors (year). Title. Venue volume(issue):pages
92
+ url: str = "" # "" when the work has no stable URL
93
+ kind: str = "paper" # paper | book | chapter | standard | doc | code | preprint
94
+ doi: str = ""
95
+ note: str = "" # what in it the rung uses
96
+
97
+ def __post_init__(self) -> None:
98
+ if not self.title.strip():
99
+ raise ValueError("a reference needs its title: authors (year). Title. Venue")
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class Parameter:
104
+ """One quantity in a type's vocabulary: its canonical name, its SI unit and what it means."""
105
+
106
+ name: str # canonical: a registry key, a typed field, a rung term, else sim2real's name less its unit
107
+ unit: str # SI ("" for a ratio or a count); a wear rate is per its usage unit (N·m/h, N/km)
108
+ definition: str # one line
109
+ shape: str = "scalar" # scalar | integer | text | pair | list | map | pose | per joint | per link
110
+ note: str = ""
111
+
112
+ def __post_init__(self) -> None:
113
+ _word("parameter", self.name)
114
+ for suffix in UNIT_SUFFIXES:
115
+ if self.name.endswith(suffix):
116
+ raise ValueError(f"parameter {self.name!r} carries a unit in its name ({suffix!r}): names carry no "
117
+ f"units; name it {self.name[: -len(suffix)]!r} with unit=... and list "
118
+ f"{self.name!r} as an Alias")
119
+ if not isinstance(self.unit, str):
120
+ raise TypeError(f"parameter {self.name}: unit must be a str ('' when dimensionless), not {self.unit!r}")
121
+ if not self.definition.strip():
122
+ raise ValueError(f"parameter {self.name}: a one-line definition is required")
123
+ if not self.shape.strip():
124
+ raise ValueError(f"parameter {self.name}: shape is 'scalar' unless it says otherwise")
125
+
126
+
127
+ @dataclass(frozen=True)
128
+ class Wear:
129
+ """A wear rung's statement that `parameter` grows with use: p(u) = law(p0, rate, u). The rung adds `rate`."""
130
+
131
+ parameter: str # the parameter that wears (the rung holds it)
132
+ usage: str # deployment hours | vibration hours | belt distance | torque-weighted revolutions ...
133
+ usage_unit: str # h | km | N·m·rev | cycle
134
+ law: str # a WEAR_LAWS key
135
+ rate: str # the rate parameter, one the rung adds
136
+
137
+ def __post_init__(self) -> None:
138
+ _word("wear parameter", self.parameter)
139
+ _word("wear rate", self.rate)
140
+ if self.law not in WEAR_LAWS:
141
+ raise ValueError(f"wear of {self.parameter}: law {self.law!r} is not one of {', '.join(WEAR_LAWS)}")
142
+ if not self.usage.strip() or not self.usage_unit.strip():
143
+ raise ValueError(f"wear of {self.parameter}: say what it wears with (usage) and in what unit (usage_unit)")
144
+
145
+
146
+ @dataclass(frozen=True)
147
+ class Alias:
148
+ """Another name for ONE canonical parameter: an old key, a sim2real twin name, an atlas or exporter column."""
149
+
150
+ name: str
151
+ canonical: str
152
+ note: str = "" # required in spirit whenever the alias is not the same quantity one for one (side, phase
153
+ # vs line to line, a level vs a difference, as mounted vs the part alone)
154
+ # WHY a unit on the alias (PEP 0004, the physics review): od_mm, camera_latency_ms or an unsuffixed old key can
155
+ # otherwise be converted only by parsing the name. "" means the canonical parameter's own SI unit.
156
+ unit: str = ""
157
+
158
+ def __post_init__(self) -> None:
159
+ if not isinstance(self.name, str) or not self.name.strip() or self.name != self.name.strip():
160
+ raise ValueError(f"alias {self.name!r}: a non-empty name with no surrounding spaces")
161
+ _word(f"alias {self.name}'s canonical", self.canonical)
162
+ if not isinstance(self.unit, str):
163
+ raise TypeError(f"alias {self.name}: unit is a str ('' for the canonical SI unit), not {self.unit!r}")
164
+
165
+
166
+ @dataclass(frozen=True)
167
+ class Packed:
168
+ """A name for an array that packs several canonical quantities: MuJoCo's `thermal`, the rack twin's `thermal_r_c`.
169
+
170
+ WHY not an Alias of its first entry (PEP 0004, the fidelity review): `thermal_r_c -> thermal_resistance` would sort
171
+ a (K/W, s) pair into a scalar's row of a parameter × source table. `canonical()` refuses a packed name; `unpack()`
172
+ names what it carries.
173
+ """
174
+
175
+ name: str
176
+ holds: tuple[str, ...] # the canonical quantities it carries
177
+ note: str = "" # what else it carries, its unit, where its layout is defined
178
+ ordered: bool = False # True when `holds` is its full entry order; False when it carries at least these
179
+
180
+ def __post_init__(self) -> None:
181
+ object.__setattr__(self, "holds", tuple(self.holds))
182
+ if not isinstance(self.name, str) or not self.name.strip() or self.name != self.name.strip():
183
+ raise ValueError(f"packed {self.name!r}: a non-empty name with no surrounding spaces")
184
+ if not self.holds:
185
+ raise ValueError(f"packed {self.name}: name the canonical quantities it carries in holds=(...)")
186
+ for name in self.holds:
187
+ _word(f"packed {self.name} holds", name)
188
+ if len(set(self.holds)) != len(self.holds):
189
+ raise ValueError(f"packed {self.name} names a quantity twice: {self.holds}")
190
+
191
+
192
+ @dataclass(frozen=True)
193
+ class DeploymentOnly:
194
+ """A name some model uses that is not the type's: a deployment sets it (config) or the mount gives it (assembly)."""
195
+
196
+ name: str
197
+ role: str # a DEPLOYMENT_ROLES key
198
+ why: str # where it belongs instead
199
+
200
+ def __post_init__(self) -> None:
201
+ if self.role not in DEPLOYMENT_ROLES:
202
+ raise ValueError(f"deployment-only {self.name}: role {self.role!r} is not one of "
203
+ f"{', '.join(DEPLOYMENT_ROLES)} (a driver's parameter belongs to the foc_controller type)")
204
+ if not self.why.strip():
205
+ raise ValueError(f"deployment-only {self.name}: say where it belongs instead")
206
+
207
+
208
+ @dataclass(frozen=True)
209
+ class Rung:
210
+ """One model on a type's ladder. It needs everything its base needs plus `adds`; its fallback is its base."""
211
+
212
+ level: int # robotparts' layer: 0 ideal, 1 datasheet, 2 Coulomb + viscous, 3 state-dependent friction,
213
+ # 4 drivetrain, 5 electrics and heat; 6 the residual, 7 the learned net
214
+ name: str # a word unique among the rungs of its level: "stribeck", "wear"
215
+ title: str # one line
216
+ base: str | None # the key of the rung it extends; None for the root (M0) and for a learned net
217
+ adds: tuple[str, ...] = () # required: new over its base, or optional below and required from here
218
+ kind: str = "physics"
219
+ # WHY optional (PEP 0004; robotparts' model.json marks each term required or not): the coverage consumer counts
220
+ # what a rung needs. M1.datasheet states every typed field but needs none of them beyond M0, as robotparts' own
221
+ # M1 marks all its terms required: false; stribeck_exponent is 2 when absent.
222
+ optional: tuple[str, ...] = ()
223
+ code: str = "" # a folder under robot_models with the runnable equation, e.g. "actuators/rungs/stribeck"
224
+ wears: tuple[Wear, ...] = ()
225
+ # WHY pairs and not copies (PEP 0004 decision 4): a rung that needs another type's parameters (an integrated servo
226
+ # needs its driver's delay) names that type's rung; the parameters stay in the other type's vocabulary.
227
+ composes: tuple[tuple[str, str], ...] = ()
228
+ equation: str = "" # the model, in the parameters' canonical names (or the source's own, said so)
229
+ references: tuple[Reference, ...] = ()
230
+ note: str = ""
231
+
232
+ @property
233
+ def key(self) -> str:
234
+ # WHY composed, never parsed (sim2real CONTRACT "never parse a rung key"): level and name are the fields.
235
+ return f"M{self.level}.{self.name}"
236
+
237
+ def __post_init__(self) -> None:
238
+ for name in ("adds", "optional", "wears", "composes", "references"):
239
+ object.__setattr__(self, name, tuple(getattr(self, name)))
240
+ object.__setattr__(self, "composes", tuple(tuple(pair) for pair in self.composes))
241
+ if isinstance(self.level, bool) or not isinstance(self.level, int) or not 0 <= self.level <= LEARNED_LEVEL:
242
+ raise ValueError(f"rung {self.name!r}: level {self.level!r} must be an int from 0 to {LEARNED_LEVEL}")
243
+ _word("rung name", self.name)
244
+ key = self.key
245
+ if not self.title.strip():
246
+ raise ValueError(f"{key}: a one-line title is required")
247
+ if self.kind not in KINDS:
248
+ raise ValueError(f"{key}: kind {self.kind!r} is not one of {', '.join(KINDS)}")
249
+ expected = {"residual": RESIDUAL_LEVEL, "learned": LEARNED_LEVEL}.get(self.kind)
250
+ if expected is not None and self.level != expected:
251
+ raise ValueError(f"{key}: a {self.kind} rung is M{expected} on every type; set level={expected}")
252
+ if self.kind == "physics" and self.level > TOP_PHYSICS_LEVEL:
253
+ raise ValueError(f"{key}: physics rungs stop at M{TOP_PHYSICS_LEVEL}; M6 is the residual, M7 the net")
254
+ if self.base is None and self.kind == "physics" and self.level != 0:
255
+ raise ValueError(f"{key}: only the root M0 has no base; name the rung it extends, e.g. base='M0.ideal'")
256
+ if self.base is not None and self.kind == "learned":
257
+ raise ValueError(f"{key}: a learned net extends no model and needs none of its parameters: base=None")
258
+ if self.base is None and self.kind == "residual":
259
+ raise ValueError(f"{key}: a residual corrects a physics rung: name it as base")
260
+ if self.base is not None and not isinstance(self.base, str):
261
+ raise TypeError(f"{key}: base is a rung key (a str) or None, not {self.base!r}")
262
+ if self.kind != "physics" and (self.adds or self.optional):
263
+ raise ValueError(f"{key}: a {self.kind} rung's weights are not named parameters: adds=(), optional=()")
264
+ if self.kind != "physics" and self.wears:
265
+ raise ValueError(f"{key}: only a physics rung wears")
266
+ for name in (*self.adds, *self.optional):
267
+ _word(f"{key} adds", name)
268
+ if len(set(self.adds)) != len(self.adds) or len(set(self.optional)) != len(self.optional):
269
+ raise ValueError(f"{key} names a parameter twice: adds {self.adds}, optional {self.optional}")
270
+ both = sorted(set(self.adds) & set(self.optional))
271
+ if both:
272
+ raise ValueError(f"{key}: {', '.join(both)} is both required (adds) and optional; pick one")
273
+ if self.code and (self.code.startswith("/") or "\\" in self.code or ".." in self.code.split("/")):
274
+ raise ValueError(f"{key}: code {self.code!r} is a folder relative to robot_models, e.g. "
275
+ f"'actuators/rungs/stribeck'")
276
+ for pair in self.composes:
277
+ if len(pair) != 2:
278
+ raise ValueError(f"{key}: composes holds (type, rung key) pairs, not {pair!r}")
279
+ _word(f"{key} composes type", pair[0])
280
+ for reference in self.references:
281
+ if not isinstance(reference, Reference):
282
+ raise TypeError(f"{key}: references holds Reference(...)s (robot_models.references), not "
283
+ f"{reference!r}")
284
+
285
+
286
+ # --- the ladder ------------------------------------------------------------------------------------------------------
287
+
288
+
289
+ @dataclass(frozen=True)
290
+ class Ladder:
291
+ """A type's vocabulary and its rungs. Built once per type folder, in that folder's `ladder.py` as `LADDER`."""
292
+
293
+ type: str # the type id: "integrated_servo", "depth_camera"
294
+ title: str # one line: what the type is, with no maker in it
295
+ vocabulary: tuple[Parameter, ...]
296
+ rungs: tuple[Rung, ...]
297
+ aliases: tuple[Alias, ...] = ()
298
+ packed: tuple[Packed, ...] = ()
299
+ deployment: tuple[DeploymentOnly, ...] = ()
300
+ # WHY (PEP 0003 §6, PEP 0004 decision 3): where a type has a Datasheet class, its typed fields ARE rung M1.datasheet
301
+ datasheet: type | None = None
302
+ note: str = ""
303
+
304
+ def __post_init__(self) -> None:
305
+ _word("type", self.type)
306
+ if not self.title.strip():
307
+ raise ValueError(f"{self.type}: a one-line title is required")
308
+ for name in ("vocabulary", "rungs", "aliases", "packed", "deployment"):
309
+ object.__setattr__(self, name, tuple(getattr(self, name)))
310
+ self._check_vocabulary()
311
+ self._check_rungs()
312
+ self._check_names()
313
+ if self.datasheet is not None:
314
+ self._check_datasheet()
315
+
316
+ # --- reading it ------------------------------------------------------------------------------------------------
317
+
318
+ @property
319
+ def keys(self) -> tuple[str, ...]:
320
+ return tuple(rung.key for rung in self.rungs)
321
+
322
+ @property
323
+ def names(self) -> tuple[str, ...]:
324
+ """The canonical parameter names, in vocabulary order."""
325
+ return tuple(parameter.name for parameter in self.vocabulary)
326
+
327
+ def rung(self, key: str) -> Rung:
328
+ for rung in self.rungs:
329
+ if rung.key == key:
330
+ return rung
331
+ raise KeyError(f"{self.type} has no rung {key!r}{_hint(key, self.keys)}; its rungs: {', '.join(self.keys)}")
332
+
333
+ def fallback(self, key: str) -> tuple[str, ...]:
334
+ """The rung and every rung below it through its bases, down to the root: what it falls back on, in order."""
335
+ chain = [key]
336
+ rung = self.rung(key)
337
+ while rung.base is not None:
338
+ chain.append(rung.base)
339
+ rung = self.rung(rung.base)
340
+ return tuple(chain)
341
+
342
+ def parameters(self, key: str) -> tuple[str, ...]:
343
+ """Every parameter the rung NEEDS, inherited ones included: the root's first, the rung's own last.
344
+
345
+ WHY required only (PEP 0004 decision 8, robotparts' coverage KPI): "the specific terms we are looking for", so a
346
+ part that states no flange size still reaches M2.coulomb_viscous.
347
+ """
348
+ return _ordered(name for step in reversed(self.fallback(key)) for name in self.rung(step).adds)
349
+
350
+ def optional(self, key: str) -> tuple[str, ...]:
351
+ """What the rung reads when a source states it, through its bases, less what it needs."""
352
+ needed = set(self.parameters(key))
353
+ return _ordered(name for step in reversed(self.fallback(key)) for name in self.rung(step).optional
354
+ if name not in needed)
355
+
356
+ def holds(self, key: str) -> tuple[str, ...]:
357
+ """Everything the rung reads: what it needs, then what it reads when stated."""
358
+ return (*self.parameters(key), *self.optional(key))
359
+
360
+ def composed(self, key: str) -> dict[str, str]:
361
+ """{type: rung key} of the other types this rung needs, through its bases; the nearest rung's choice wins."""
362
+ found: dict[str, str] = {}
363
+ for step in self.fallback(key):
364
+ for other, rung_key in self.rung(step).composes:
365
+ found.setdefault(other, rung_key)
366
+ return found
367
+
368
+ def canonical(self, name: str) -> str:
369
+ """The type's own name for `name`: itself when canonical, the alias's target otherwise."""
370
+ if name in self.names:
371
+ return name
372
+ for alias in self.aliases:
373
+ if alias.name == name:
374
+ return alias.canonical
375
+ packed = self.packing(name)
376
+ if packed is not None:
377
+ raise KeyError(f"{name!r} packs {', '.join(packed.holds)} into one array, so it is no single parameter of "
378
+ f"{self.type}: unpack it with ladder.unpack({name!r})")
379
+ known = [*self.names, *(alias.name for alias in self.aliases)]
380
+ raise KeyError(f"{name!r} is neither a parameter nor an alias of {self.type}{_hint(name, known)}")
381
+
382
+ def unpack(self, name: str) -> tuple[str, ...]:
383
+ """The canonical quantities a packed name carries."""
384
+ packed = self.packing(name)
385
+ if packed is None:
386
+ raise KeyError(f"{name!r} is not a packed name of {self.type}{_hint(name, [p.name for p in self.packed])}")
387
+ return packed.holds
388
+
389
+ def resolve(self, name: str) -> tuple[str, ...]:
390
+ """The canonical names behind any name the type knows: (canonical,) for a parameter or an alias, the
391
+ quantities a packed name carries. A deployment-only name or an unknown one raises KeyError."""
392
+ return self.unpack(name) if self.packing(name) is not None else (self.canonical(name),)
393
+
394
+ def parameter(self, name: str) -> Parameter:
395
+ canonical = self.canonical(name)
396
+ return next(parameter for parameter in self.vocabulary if parameter.name == canonical)
397
+
398
+ def alias(self, name: str) -> Alias | None:
399
+ return next((alias for alias in self.aliases if alias.name == name), None)
400
+
401
+ def packing(self, name: str) -> Packed | None:
402
+ return next((packed for packed in self.packed if packed.name == name), None)
403
+
404
+ # --- checking it -----------------------------------------------------------------------------------------------
405
+
406
+ def _check_vocabulary(self) -> None:
407
+ seen: set[str] = set()
408
+ for parameter in self.vocabulary:
409
+ if not isinstance(parameter, Parameter):
410
+ raise TypeError(f"{self.type}: the vocabulary holds Parameter(...)s, not {parameter!r}")
411
+ if parameter.name in seen:
412
+ raise ValueError(f"{self.type}: {parameter.name} is in the vocabulary twice; one quantity, one entry")
413
+ seen.add(parameter.name)
414
+
415
+ def _check_rungs(self) -> None:
416
+ by_key: dict[str, Rung] = {}
417
+ for rung in self.rungs:
418
+ if not isinstance(rung, Rung):
419
+ raise TypeError(f"{self.type}: rungs holds Rung(...)s, not {rung!r}")
420
+ if rung.key in by_key:
421
+ raise ValueError(f"{self.type}: two rungs are {rung.key}; a level's rungs need different names")
422
+ by_key[rung.key] = rung
423
+ for rung in self.rungs:
424
+ if rung.base is None:
425
+ continue
426
+ if rung.base not in by_key:
427
+ raise KeyError(f"{self.type} {rung.key}: base {rung.base!r} is no rung of this ladder"
428
+ f"{_hint(rung.base, by_key)}; base is the key of the rung it extends")
429
+ if by_key[rung.base].level > rung.level:
430
+ raise ValueError(f"{self.type} {rung.key}: its base {rung.base} is a higher layer; a rung falls back "
431
+ f"down the ladder, never up")
432
+ roots = [rung.key for rung in self.rungs if rung.base is None and rung.kind == "physics"]
433
+ if len(roots) != 1:
434
+ raise ValueError(f"{self.type}: a ladder has one root, M0 with base=None; found {roots or 'none'}")
435
+ for rung in self.rungs: # WHY before anything walks the bases: a loop would never end
436
+ path, step = [rung.key], rung
437
+ while step.base is not None:
438
+ if step.base in path:
439
+ loop = " -> ".join([*path[path.index(step.base):], step.base])
440
+ raise ValueError(f"{self.type}: the bases loop ({loop}); every chain of bases ends at the root "
441
+ f"{roots[0]}")
442
+ path.append(step.base)
443
+ step = by_key[step.base]
444
+ vocabulary = set(self.names)
445
+ for rung in self.rungs:
446
+ for name in (*rung.adds, *rung.optional):
447
+ if name not in vocabulary:
448
+ raise KeyError(f"{self.type} {rung.key} adds {name!r}, which is not in the {self.type} "
449
+ f"vocabulary{_hint(name, vocabulary)}; add a Parameter for it, or, if it is "
450
+ f"another name for one, add the canonical name and list {name!r} as an Alias")
451
+ needed = set(self.parameters(rung.base)) if rung.base else set()
452
+ stated = set(self.optional(rung.base)) if rung.base else set()
453
+ for name in rung.adds:
454
+ if name in needed:
455
+ raise ValueError(f"{self.type} {rung.key} adds {name}, which {self._owner(rung.base, name)} "
456
+ f"below it already adds: a rung adds only what is new over its base; drop it")
457
+ for name in rung.optional:
458
+ if name in needed or name in stated:
459
+ raise ValueError(f"{self.type} {rung.key} lists {name} as optional, which "
460
+ f"{self._owner(rung.base, name)} below it already holds; drop it")
461
+ holds = needed | stated | set(rung.adds) | set(rung.optional)
462
+ for wear in rung.wears:
463
+ if wear.rate not in rung.adds:
464
+ raise ValueError(f"{self.type} {rung.key}: wear rate {wear.rate} must be a parameter this rung "
465
+ f"adds")
466
+ if wear.parameter not in holds or wear.parameter == wear.rate:
467
+ raise ValueError(f"{self.type} {rung.key}: {wear.parameter} wears, but the rung does not hold it "
468
+ f"(its parameters: {', '.join(sorted(holds))})")
469
+ on_a_rung = {name for rung in self.rungs for name in (*rung.adds, *rung.optional)}
470
+ orphans = [name for name in self.names if name not in on_a_rung]
471
+ if orphans:
472
+ raise ValueError(f"{self.type}: {', '.join(orphans)} no rung adds; the vocabulary is what the ladder "
473
+ f"holds, so put each on the rung that first reads it (optional when it only states it) "
474
+ f"or drop it")
475
+
476
+ def _owner(self, base: str, name: str) -> str:
477
+ return next(step for step in self.fallback(base)
478
+ if name in self.rung(step).adds or name in self.rung(step).optional)
479
+
480
+ def _check_names(self) -> None:
481
+ vocabulary = set(self.names)
482
+ seen: set[str] = set()
483
+ for alias in self.aliases:
484
+ if not isinstance(alias, Alias):
485
+ raise TypeError(f"{self.type}: aliases holds Alias(...)es, not {alias!r}")
486
+ if alias.name in vocabulary:
487
+ raise ValueError(f"{self.type}: {alias.name} is canonical, so it cannot also be an alias")
488
+ if alias.canonical not in vocabulary:
489
+ raise KeyError(f"{self.type}: alias {alias.name} points at {alias.canonical!r}, which is not in the "
490
+ f"vocabulary{_hint(alias.canonical, vocabulary)}")
491
+ if alias.name in seen:
492
+ raise ValueError(f"{self.type}: alias {alias.name} is listed twice")
493
+ seen.add(alias.name)
494
+ for packed in self.packed:
495
+ if not isinstance(packed, Packed):
496
+ raise TypeError(f"{self.type}: packed holds Packed(...)s, not {packed!r}")
497
+ if packed.name in vocabulary or packed.name in seen:
498
+ raise ValueError(f"{self.type}: {packed.name} is a parameter or an alias of the type, so it cannot "
499
+ f"also be a packed name")
500
+ for name in packed.holds:
501
+ if name not in vocabulary:
502
+ raise KeyError(f"{self.type}: packed {packed.name} holds {name!r}, which is not in the "
503
+ f"vocabulary{_hint(name, vocabulary)}")
504
+ seen.add(packed.name)
505
+ for other in self.deployment:
506
+ if not isinstance(other, DeploymentOnly):
507
+ raise TypeError(f"{self.type}: deployment holds DeploymentOnly(...)s, not {other!r}")
508
+ if other.name in vocabulary or other.name in seen:
509
+ raise ValueError(f"{self.type}: {other.name} is a parameter, an alias or a packed name of the type, "
510
+ f"so it is not deployment-only")
511
+ seen.add(other.name)
512
+ for rung in self.rungs:
513
+ for other, _ in rung.composes:
514
+ if other == self.type:
515
+ raise ValueError(f"{self.type} {rung.key} composes its own type; a rung's base says that")
516
+
517
+ def _check_datasheet(self) -> None:
518
+ fields = self.datasheet.typed_fields()
519
+ for name, spec in fields.items():
520
+ if name not in self.names:
521
+ raise KeyError(f"{self.type}: the {self.datasheet.__name__} field {name} is not in the vocabulary; "
522
+ f"start it from datasheet_vocabulary({self.datasheet.__name__})")
523
+ unit, expected = self.parameter(name).unit, si_unit(spec.units)
524
+ if unit != expected:
525
+ raise ValueError(f"{self.type}: {name} has unit {unit!r}, but {self.datasheet.__name__}.{name} is "
526
+ f"{expected!r} in SI")
527
+ if "M1.datasheet" not in self.keys:
528
+ raise KeyError(f"{self.type}: a type with a Datasheet class has rung M1.datasheet, its typed fields")
529
+ held = set(self.holds("M1.datasheet"))
530
+ if held != set(fields):
531
+ missing, extra = sorted(set(fields) - held), sorted(held - set(fields))
532
+ raise ValueError(f"{self.type}: M1.datasheet holds exactly the {self.datasheet.__name__} fields, needed "
533
+ f"or optional (missing {missing or 'none'}; not fields: {extra or 'none'})")
534
+
535
+
536
+ # --- the datasheet as vocabulary -------------------------------------------------------------------------------------
537
+
538
+
539
+ def si_unit(units: Mapping[str, float]) -> str:
540
+ """The SI spelling of a datasheet field's unit family: "" when dimensionless, else the spelling with factor 1."""
541
+ if units.get("") == 1.0:
542
+ return ""
543
+ for unit, factor in units.items():
544
+ if factor == 1.0:
545
+ return unit
546
+ for unit in units:
547
+ if unit in SI_SPELLING:
548
+ return SI_SPELLING[unit]
549
+ raise ValueError(f"no SI spelling among {list(units)}: add one to SI_SPELLING")
550
+
551
+
552
+ def datasheet_vocabulary(datasheet: type) -> tuple[Parameter, ...]:
553
+ """A Datasheet class's typed fields as Parameters, in declaration order: rung M1's names, units and definitions
554
+ taken from the class, so the datasheet and the ladder can never hold two spellings of one field."""
555
+ shapes = {"number": "scalar", "integer": "integer", "text": "text"}
556
+ return tuple(Parameter(name, si_unit(spec.units), spec.definition, shapes[spec.kind])
557
+ for name, spec in datasheet.typed_fields().items())
558
+
559
+
560
+ # --- finding every type's ladder -------------------------------------------------------------------------------------
561
+
562
+
563
+ @dataclass(frozen=True)
564
+ class Found:
565
+ ladder: Ladder
566
+ module: str # "robot_models.actuators.servo.ladder"
567
+ folder: str # the type folder, relative to the package: "actuators/servo" (a consumer's join key)
568
+
569
+
570
+ def discover(root: Path | None = None, package: str = "robot_models") -> dict[str, Found]:
571
+ """Every type's ladder, found by walking the package for `ladder.py` files, {type: Found}.
572
+
573
+ WHY a walk and not a registry (PEP 0004): each new type adds one folder and touches no shared file. The checks
574
+ that span ladders run here: one ladder per type, and every composed (type, rung) exists.
575
+ """
576
+ root = Path(__file__).resolve().parent if root is None else Path(root)
577
+ # WHY: the import system caches each folder's listing; a type folder made since (a lane's, a test's) would be
578
+ # missed when its parent's mtime has not moved past the cache, which made discovery flaky within one second.
579
+ importlib.invalidate_caches()
580
+ found: dict[str, Found] = {}
581
+ for path in sorted(root.rglob("ladder.py")):
582
+ folder = path.parent.relative_to(root)
583
+ if not folder.parts: # WHY: this module is the package's own ladder.py, the core, not a type's
584
+ continue
585
+ if any(part.startswith((".", "__")) for part in folder.parts):
586
+ continue
587
+ module_name = ".".join((package, *folder.parts, "ladder"))
588
+ module = importlib.import_module(module_name)
589
+ ladder = getattr(module, "LADDER", None)
590
+ if not isinstance(ladder, Ladder):
591
+ raise TypeError(f"{module_name} defines no LADDER = Ladder(...); each type folder's ladder.py holds one")
592
+ if ladder.type in found:
593
+ raise ValueError(f"two ladders are type {ladder.type!r}: {found[ladder.type].module} and {module_name}")
594
+ found[ladder.type] = Found(ladder, module_name, folder.as_posix())
595
+ for item in found.values():
596
+ for rung in item.ladder.rungs:
597
+ for other, rung_key in rung.composes:
598
+ if other not in found:
599
+ raise KeyError(f"{item.ladder.type} {rung.key} composes type {other!r}, which no ladder "
600
+ f"is{_hint(other, found)}")
601
+ found[other].ladder.rung(rung_key)
602
+ return found
603
+
604
+
605
+ def ladders(root: Path | None = None, package: str = "robot_models") -> dict[str, Ladder]:
606
+ """{type: Ladder} for every type folder."""
607
+ return {name: item.ladder for name, item in discover(root, package).items()}
608
+
609
+
610
+ def needs(found: Mapping[str, Ladder], type_name: str, key: str) -> dict[str, tuple[str, ...]]:
611
+ """{type: parameters} a rung needs, its own type first, then each type it composes (at the composed rung).
612
+
613
+ WHY a function over the ladders (the breakage review): `parameters()` is one type's; a servo's driver delay sits
614
+ in foc_controller's vocabulary, and the coverage consumer must not walk `composed()` by hand.
615
+ """
616
+ ladder = found[type_name]
617
+ result = {type_name: ladder.parameters(key)}
618
+ for other, rung_key in ladder.composed(key).items():
619
+ result[other] = found[other].parameters(rung_key)
620
+ return result
621
+
622
+
623
+ __all__ = [
624
+ "DEPLOYMENT_ROLES",
625
+ "KINDS",
626
+ "LEARNED_LEVEL",
627
+ "RESIDUAL_LEVEL",
628
+ "TOP_PHYSICS_LEVEL",
629
+ "UNIT_SUFFIXES",
630
+ "WEAR_LAWS",
631
+ "Alias",
632
+ "DeploymentOnly",
633
+ "Found",
634
+ "Ladder",
635
+ "Packed",
636
+ "Parameter",
637
+ "Reference",
638
+ "Rung",
639
+ "Wear",
640
+ "datasheet_vocabulary",
641
+ "discover",
642
+ "ladders",
643
+ "needs",
644
+ "si_unit",
645
+ ]
@@ -0,0 +1 @@
1
+ """Marker types by type folder (PEP 0004): aruco_marker/."""