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
@@ -0,0 +1,203 @@
1
+ """A belt driven through a drum: the conveyor that carries parcels past an arm, as a ladder of models (PEP 0004).
2
+
3
+ The ladder climbs from an ideal belt (the drum's turns become belt travel, a rigid mass moves under a force) through
4
+ friction on the belt, the belt's stretch between drum and load (where the moving mass splits into the drive side's and
5
+ the load side's), and friction that grows with the belt's distance, to a grey-box residual and a black-box network. Its
6
+ rungs are numbered by the actuator's layers (sim2real's decision, the same M2 and M3 friction rungs, here as forces on
7
+ the belt); there is no M1 because the type has no Datasheet class yet.
8
+
9
+ Spec: PEP 0004 §5.12 and §6.11.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from robot_models import references
15
+ from robot_models.ladder import Alias, DeploymentOnly, Ladder, Parameter, Rung, Wear
16
+
17
+ # --- vocabulary, grouped by the rung that first reads it -------------------------------------------------------------
18
+
19
+ VOCABULARY = (
20
+ # M0.ideal: the drum turns the motor's rotation into belt travel; one rigid mass moves
21
+ Parameter(
22
+ name="drum_radius", unit="m",
23
+ definition="Radius of the drive drum the belt wraps.",
24
+ ),
25
+ Parameter(
26
+ name="gear_ratio", unit="",
27
+ definition="Motor turns per drum turn.",
28
+ ),
29
+ Parameter(
30
+ name="moving_mass", unit="kg",
31
+ definition="The moving mass referred to the belt: belt, drum and reflected rotor.",
32
+ ),
33
+ # M2.coulomb_viscous
34
+ Parameter(
35
+ name="coulomb_friction", unit="N",
36
+ definition="Coulomb friction force on the belt: the constant force that opposes its motion.",
37
+ ),
38
+ Parameter(
39
+ name="viscous_friction", unit="N·s/m",
40
+ definition="Viscous friction coefficient on the belt.",
41
+ ),
42
+ # M3.stribeck
43
+ Parameter(
44
+ name="breakaway_force", unit="N",
45
+ definition="Static friction on the belt: the force that starts it moving from rest.",
46
+ ),
47
+ Parameter(
48
+ name="stribeck_velocity", unit="m/s",
49
+ definition="Belt speed over which friction falls from breakaway_force to coulomb_friction.",
50
+ ),
51
+ # M4.stretch
52
+ Parameter(
53
+ name="stretch_stiffness", unit="N/m",
54
+ definition="The belt's stiffness along its length, between drum and load.",
55
+ ),
56
+ Parameter(
57
+ name="stretch_damping", unit="N·s/m",
58
+ definition="Damping of the belt's stretch between drum and load.",
59
+ ),
60
+ Parameter(
61
+ name="drum_mass", unit="kg",
62
+ definition=("The drive side's mass referred to the belt, read from M4: the drum and the reflected rotor; "
63
+ "moving_mass less drum_mass moves with the load."),
64
+ ),
65
+ # M4.wear
66
+ Parameter(
67
+ name="friction_growth", unit="N/km",
68
+ definition=("How fast the friction level grows per kilometre of belt travel (idlers and slider bed wearing); "
69
+ "breakaway_force and coulomb_friction grow together."),
70
+ ),
71
+ )
72
+
73
+ # --- the rungs, M0 upward --------------------------------------------------------------------------------------------
74
+
75
+ # WHY belt distance: idlers and the slider bed wear with the belt's travel, not its hours (M4.wear).
76
+ BELT_DISTANCE = "belt distance"
77
+ KILOMETRES = "km"
78
+
79
+ RUNGS = (
80
+ Rung(
81
+ level=0,
82
+ name="ideal",
83
+ title="An ideal belt: kinematics and a rigid mass",
84
+ base=None,
85
+ adds=("drum_radius", "gear_ratio", "moving_mass"),
86
+ equation="x = θ_motor·drum_radius/gear_ratio; (moving_mass + load)·ẍ = F",
87
+ references=(references.ZHANG_XIA_2011,),
88
+ # WHY no M1 (PEP 0004 §5.12): rungs are numbered by the actuator's layers, and a datasheet rung needs a
89
+ # Datasheet class, which the conveyor does not have yet.
90
+ note="numbered by the actuator's layers (sim2real's decision); no M1: no Datasheet class yet.",
91
+ ),
92
+ Rung(
93
+ level=2,
94
+ name="coulomb_viscous",
95
+ title="Coulomb and viscous friction on the belt",
96
+ base="M0.ideal",
97
+ adds=("coulomb_friction", "viscous_friction"),
98
+ equation="F_f = coulomb_friction·sign(ẋ) + viscous_friction·ẋ",
99
+ references=(references.ARMSTRONG_1994, references.ZHANG_XIA_2011),
100
+ ),
101
+ Rung(
102
+ level=3,
103
+ name="stribeck",
104
+ title="Static friction (Stribeck)",
105
+ base="M2.coulomb_viscous",
106
+ adds=("breakaway_force", "stribeck_velocity"),
107
+ # WHY the equation squares the Stribeck velocity ratio and has no exponent parameter (PEP 0004 §5.12): no
108
+ # conveyor source (sim2real's conveyor card, robotparts' stribeck rung it points at) states an exponent, so it
109
+ # is held at the actuator's default of 2 instead of being an optional parameter as in the actuator's
110
+ # M3.stribeck.
111
+ equation=("F_f = (coulomb_friction + (breakaway_force − coulomb_friction)·exp(−(|ẋ|/stribeck_velocity)²))"
112
+ "·sign(ẋ) + viscous_friction·ẋ"),
113
+ references=(references.ARMSTRONG_1994,),
114
+ note="the actuator's M3.stribeck as forces on the belt.",
115
+ ),
116
+ Rung(
117
+ level=4,
118
+ name="stretch",
119
+ title="Belt stretch: drum and load as two masses",
120
+ base="M3.stribeck",
121
+ adds=("stretch_stiffness", "stretch_damping", "drum_mass"),
122
+ # WHY drum_mass splits moving_mass rather than adding to it: M0's moving_mass already counts the drum and the
123
+ # reflected rotor, so a drum mass on top of it would count the drum twice.
124
+ equation=("drum: drum_mass·ẍ_d = gear_ratio·τ/drum_radius − stretch_stiffness·(x_d − x_l) "
125
+ "− stretch_damping·(ẋ_d − ẋ_l); load: (moving_mass − drum_mass + load)·ẍ_l = the same "
126
+ "stretch force − F_f"),
127
+ references=(references.SPONG_1987, references.HE_2017),
128
+ note="M4 splits moving_mass: drum_mass on the drive side of the stretch, the rest moves with the load.",
129
+ ),
130
+ Rung(
131
+ level=4,
132
+ name="wear",
133
+ title="Friction that grows with belt distance",
134
+ base="M4.stretch",
135
+ adds=("friction_growth",),
136
+ # WHY both levels at one rate: growing coulomb_friction alone would pass breakaway_force and turn M3's Stribeck
137
+ # term negative (friction rising with speed, no static peak); the drop between them stays as fitted.
138
+ wears=(
139
+ Wear(parameter="breakaway_force", usage=BELT_DISTANCE, usage_unit=KILOMETRES, law="linear",
140
+ rate="friction_growth"),
141
+ Wear(parameter="coulomb_friction", usage=BELT_DISTANCE, usage_unit=KILOMETRES, law="linear",
142
+ rate="friction_growth"),
143
+ ),
144
+ equation=("breakaway_force and coulomb_friction both grow by friction_growth·s "
145
+ "(the Stribeck drop stays)"),
146
+ references=(references.LU_MEEKER_1993, references.ZHANG_XIA_2011),
147
+ ),
148
+ Rung(
149
+ level=6,
150
+ name="residual",
151
+ title="Grey-box residual on M4.wear",
152
+ base="M4.wear",
153
+ kind="residual",
154
+ equation=("M4.wear + an MLP residual drive force from 3 samples of belt speed error, belt speed and "
155
+ "motor current"),
156
+ references=(references.NGUYEN_TUONG_2010, references.ZENG_2020),
157
+ ),
158
+ Rung(
159
+ level=7,
160
+ name="learned",
161
+ title="Black-box network",
162
+ base=None,
163
+ kind="learned",
164
+ equation="an MLP over 3 samples of position error and belt speed → drive force",
165
+ references=(references.HWANGBO_2019, references.HWANGBO_2019_ARXIV),
166
+ ),
167
+ )
168
+
169
+ # --- other names for the same quantities ------------------------------------------------------------------------------
170
+
171
+ ALIASES = (
172
+ Alias(name="drum_radius_m", canonical="drum_radius"),
173
+ Alias(name="drum_radius_mm", canonical="drum_radius", unit="mm"),
174
+ Alias(name="moving_mass_kg", canonical="moving_mass"),
175
+ Alias(name="coulomb_n", canonical="coulomb_friction"),
176
+ Alias(name="viscous_n_s_m", canonical="viscous_friction"),
177
+ Alias(name="static_n", canonical="breakaway_force"),
178
+ Alias(name="stretch_stiffness_n_m", canonical="stretch_stiffness"),
179
+ Alias(name="stretch_damping_n_s_m", canonical="stretch_damping"),
180
+ Alias(name="coulomb_growth_n_per_km", canonical="friction_growth"),
181
+ )
182
+
183
+ # --- what a deployment sets, not the type ----------------------------------------------------------------------------
184
+
185
+ DEPLOYMENT = (
186
+ DeploymentOnly(
187
+ name="load_mass_kg", role="assembly",
188
+ why="The parcels on the belt: the deployment's.",
189
+ ),
190
+ DeploymentOnly(
191
+ name="encoder_counts_per_m", role="config",
192
+ why="Derived from the encoder, the ratio and the drum radius.",
193
+ ),
194
+ )
195
+
196
+ LADDER = Ladder(
197
+ type="conveyor",
198
+ title="A belt driven through a drum.",
199
+ vocabulary=VOCABULARY,
200
+ rungs=RUNGS,
201
+ aliases=ALIASES,
202
+ deployment=DEPLOYMENT,
203
+ )
@@ -0,0 +1,56 @@
1
+ """robot_models.datasheet: typed part fields, and a part's values resolved from its raw sources (PEP 0003).
2
+
3
+ from robot_models.datasheet import Source, Stated # what a sources/<name>.py writes, with its type:
4
+ values = IntegratedServo(peak_torque=Stated(3.47, "N·m", "堵转扭矩(Stall Torque)"), ...)
5
+ from robot_models.datasheet import Sources # what a part file loads
6
+ from robot_models.actuators.servo import IntegratedServo # a type: its typed fields
7
+
8
+ Stdlib only, like the rest of robot_models' core.
9
+ """
10
+
11
+ from . import literal, units
12
+ from .datasheet import (
13
+ ELECTRICAL,
14
+ EXTRA,
15
+ GROUPS,
16
+ INTERFACES,
17
+ KEY_SPECS,
18
+ MECHANICAL,
19
+ PERFORMANCE,
20
+ Datasheet,
21
+ Disagreement,
22
+ Field,
23
+ FieldSpec,
24
+ check_source,
25
+ check_value,
26
+ reflected,
27
+ )
28
+ from .source import KINDS, ROLES, ColumnError, Role, Source, Sources, load_source
29
+ from .stated import Stated
30
+
31
+ __all__ = [
32
+ "ELECTRICAL",
33
+ "EXTRA",
34
+ "GROUPS",
35
+ "INTERFACES",
36
+ "KEY_SPECS",
37
+ "KINDS",
38
+ "ROLES",
39
+ "MECHANICAL",
40
+ "PERFORMANCE",
41
+ "ColumnError",
42
+ "Datasheet",
43
+ "Disagreement",
44
+ "Field",
45
+ "Role",
46
+ "FieldSpec",
47
+ "Source",
48
+ "Sources",
49
+ "Stated",
50
+ "check_source",
51
+ "check_value",
52
+ "literal",
53
+ "load_source",
54
+ "reflected",
55
+ "units",
56
+ ]
@@ -0,0 +1,355 @@
1
+ """`Datasheet`: a part type's typed fields, and a part's values resolved from its sources.
2
+
3
+ A type is a frozen dataclass of typed fields, one per parameter, each declared with `Field(units, definition)`:
4
+
5
+ @dataclass(frozen=True)
6
+ class IntegratedServo(BldcMotor):
7
+ gear_ratio: Stated | None = Field(RATIO, "Rotor turns per output turn ...", group=PERFORMANCE)
8
+
9
+ A part's datasheet is an instance, resolved from its sources by an explicit rule:
10
+
11
+ datasheet = IntegratedServo.from_sources(sources, prefer=[steadywin["GDZ34"], sources.estimates],
12
+ pick={"kt": steadywin["GDS34"]})
13
+
14
+ - **prefer**: the first source in the list that states a field gives it.
15
+ - **pick**: one line per field taken from elsewhere (the part file says why, beside it).
16
+ - **never silently**: every other statement stays readable (`statements`), and `disagreements()` lists each field whose
17
+ sources differ from the chosen value, which the table marks.
18
+
19
+ WHY typed fields named as robotparts' registry keys (PEP 0003): one vocabulary. A name the registry lacks is the name
20
+ the catalogue already uses for it (`rated_phase_current`, `max_axial_load`); robotparts' user tests hold both rules.
21
+ WHY unknown names refuse: a typo (`nominal_votlage`) must not land quietly among the custom values; a custom value is
22
+ written in the source's `extra = {...}`.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import dataclasses
28
+ import difflib
29
+ import math
30
+ from collections.abc import Iterable, Mapping
31
+ from dataclasses import dataclass, field, replace
32
+ from typing import Any, ClassVar
33
+
34
+ from .source import ColumnError, Source, Sources
35
+ from .stated import Stated
36
+
37
+ KEY_SPECS = "Key specs"
38
+ PERFORMANCE = "Performance"
39
+ ELECTRICAL = "Electrical"
40
+ MECHANICAL = "Mechanical"
41
+ INTERFACES = "Interfaces"
42
+ EXTRA = "As the source names them"
43
+ # robotparts.dev's datasheet sections, in its order (build/site_pages.py SPEC_GROUPS)
44
+ GROUPS = (KEY_SPECS, PERFORMANCE, ELECTRICAL, MECHANICAL, INTERFACES, EXTRA)
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class FieldSpec:
49
+ """What a typed field accepts. `units` maps each accepted spelling to its SI factor; the first is the display
50
+ unit. `side` and `reflect` are for a quantity defined on the rotor that a geared part's source may state at the
51
+ output: value_at_rotor = value_at_output × gear_ratio ** reflect (Kv +1, Kt −1, inertia −2)."""
52
+
53
+ units: Mapping[str, float]
54
+ definition: str
55
+ group: str
56
+ kind: str = "number" # number | integer | text
57
+ positive: bool = False
58
+ side: str | None = None
59
+ reflect: int = 0
60
+
61
+ @property
62
+ def unit(self) -> str:
63
+ return next(iter(self.units), "")
64
+
65
+
66
+ def Field(units: Mapping[str, float], definition: str, *, group: str, kind: str = "number", positive: bool = False,
67
+ side: str | None = None, reflect: int = 0) -> Any:
68
+ """Declare a typed field of a part type. WHY a capitalised function returning a dataclass field: the pydantic /
69
+ SQLModel spelling (`x: T = Field(...)`), read as a declaration."""
70
+ if group not in GROUPS or group in (KEY_SPECS, EXTRA):
71
+ raise ValueError(f"group {group!r}: one of {', '.join(GROUPS[1:-1])} (key specs are the type's KEY_SPECS)")
72
+ spec = FieldSpec(dict(units), definition, group, kind, positive, side, reflect)
73
+ # WHY kw_only: a source file names every value (`peak_torque=Stated(...)`), so the editor's signature and
74
+ # completion list the fields by name, and a bare positional Stated can never land in the wrong field
75
+ return field(default=None, kw_only=True, metadata={"datasheet": spec})
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class Disagreement:
80
+ """A field whose sources differ from the value chosen for it."""
81
+
82
+ name: str
83
+ chosen: Stated
84
+ others: tuple[Stated, ...]
85
+
86
+ def text(self) -> str:
87
+ others = ", ".join(f"{stated.source.label} {stated.text()}" for stated in self.others)
88
+ return f"{self.name}: chose {self.chosen.text()} ({self.chosen.source.label}); differs: {others}"
89
+
90
+
91
+ @dataclass(frozen=True)
92
+ class Datasheet:
93
+ """The base of every part type: its typed fields (declared by the subclass), the custom values (`extra`), and,
94
+ when resolved from sources, the sources and the rule that chose each value."""
95
+
96
+ KEY_SPECS: ClassVar[tuple[str, ...]] = ()
97
+
98
+ extra: Mapping[str, Stated] = field(default_factory=dict, kw_only=True)
99
+ # WHY init=False: set only by from_sources, never written in a source file, so they stay out of the signature the
100
+ # editor shows while he types a source's values
101
+ sources: tuple[Source, ...] = field(default=(), init=False, compare=False, repr=False)
102
+ prefer: tuple[Source, ...] = field(default=(), init=False, compare=False, repr=False)
103
+ picks: Mapping[str, Source] = field(default_factory=dict, init=False, compare=False, repr=False)
104
+
105
+ # --- the type ---------------------------------------------------------------------------------------------
106
+
107
+ @classmethod
108
+ def typed_fields(cls) -> dict[str, FieldSpec]:
109
+ """Every typed field of this type, {name: FieldSpec}, in declaration order."""
110
+ return {f.name: f.metadata["datasheet"] for f in dataclasses.fields(cls) if "datasheet" in f.metadata}
111
+
112
+ @classmethod
113
+ def group_of(cls, name: str) -> str:
114
+ if name in cls.KEY_SPECS:
115
+ return KEY_SPECS
116
+ spec = cls.typed_fields().get(name)
117
+ return spec.group if spec else EXTRA
118
+
119
+ @classmethod
120
+ def rows(cls) -> list[tuple[str, list[str]]]:
121
+ """The typed field names grouped as robotparts.dev groups them: Key specs first, in KEY_SPECS order."""
122
+ fields = cls.typed_fields()
123
+ grouped: dict[str, list[str]] = {group: [] for group in GROUPS}
124
+ grouped[KEY_SPECS] = [name for name in cls.KEY_SPECS if name in fields]
125
+ for name, spec in fields.items():
126
+ if name not in cls.KEY_SPECS:
127
+ grouped[spec.group].append(name)
128
+ return [(group, names) for group, names in grouped.items() if names]
129
+
130
+ # --- checking a value -------------------------------------------------------------------------------------
131
+
132
+ def __post_init__(self) -> None:
133
+ fields = self.typed_fields()
134
+ for name, spec in fields.items():
135
+ stated = getattr(self, name)
136
+ if stated is not None:
137
+ check_value(type(self).__name__, name, spec, stated)
138
+ for name, stated in self.extra.items():
139
+ if name in fields:
140
+ raise ValueError(f"{type(self).__name__}: extra {name!r} is a typed field; set it as one")
141
+ if not isinstance(stated, Stated):
142
+ raise TypeError(f"{type(self).__name__}: extra {name!r} must be a Stated, not {stated!r}")
143
+
144
+ # --- resolving it from sources ----------------------------------------------------------------------------
145
+
146
+ @classmethod
147
+ def from_sources(cls, sources: Sources | Iterable[Source], *, prefer: Iterable[Source],
148
+ pick: Mapping[str, Source] | None = None) -> Datasheet:
149
+ """Each typed field from the first source in `prefer` that states it, unless `pick` names its source.
150
+
151
+ Every source is checked against the type first: a name that is not a typed field refuses (with the nearest
152
+ field name), so a custom value must be in the source's `extra`. A source written for another model
153
+ (`applies_to`) is never preferred, only picked.
154
+ """
155
+ everything = tuple(sources)
156
+ prefer = tuple(prefer)
157
+ pick = dict(pick or {})
158
+ fields = cls.typed_fields()
159
+ for source in everything:
160
+ check_source(cls, source)
161
+ for source in prefer:
162
+ if source.is_related:
163
+ raise ValueError(f"{source.label} is for {source.applies_to}, not this part: pick a field from it "
164
+ f"explicitly instead of preferring it")
165
+ for name, source in pick.items():
166
+ if name not in fields and not any(name in s.extra for s in everything):
167
+ raise KeyError(f"pick names {name!r}, which is no field of {cls.__name__} and no source's extra")
168
+ if source.states(name) is None:
169
+ raise KeyError(f"pick takes {name} from {source.label}, which states no {name}")
170
+
171
+ def chosen(name: str) -> Stated | None:
172
+ if name in pick:
173
+ return pick[name].states(name)
174
+ for source in prefer:
175
+ stated = source.states(name)
176
+ if stated is not None:
177
+ return stated
178
+ return None
179
+
180
+ values = {name: chosen(name) for name in fields}
181
+ extra_names = [name for source in everything for name in source.extra]
182
+ extra = {name: chosen(name) for name in dict.fromkeys(extra_names)}
183
+ extra = {name: stated for name, stated in extra.items() if stated is not None}
184
+ gear_ratio = values.get("gear_ratio")
185
+ for name, spec in fields.items():
186
+ stated = values[name]
187
+ if stated is not None and stated.at is not None and spec.side is not None and stated.at != spec.side:
188
+ values[name] = reflected(name, spec, stated, gear_ratio)
189
+ sheet = cls(**values, extra=extra)
190
+ for name, value in (("sources", everything), ("prefer", prefer), ("picks", pick)):
191
+ object.__setattr__(sheet, name, value) # the frozen instance's bookkeeping, filled once, right here
192
+ return sheet
193
+
194
+ # --- reading every statement ------------------------------------------------------------------------------
195
+
196
+ def chosen(self, name: str) -> Stated | None:
197
+ """The value chosen for a typed field or an extra name."""
198
+ if name in self.typed_fields():
199
+ return getattr(self, name)
200
+ return self.extra.get(name)
201
+
202
+ def statements(self, name: str) -> list[Stated]:
203
+ """Every source's (and column's) statement of `name`, in table order: preferred sources first."""
204
+ found = []
205
+ for source in self.columns():
206
+ stated = source.states(name)
207
+ if stated is not None:
208
+ found.append(stated)
209
+ return found
210
+
211
+ def stating(self) -> list[Source]:
212
+ """The sources that state at least one value: a header with no values (a photo, a CAD file, a manual not read
213
+ yet) catalogues a raw file and is not a column."""
214
+ return [source for source in self.sources if source.states_anything]
215
+
216
+ def columns(self) -> list[Source]:
217
+ """One entry per source and column, in table order: the preferred sources in their order, then the rest by
218
+ name; a source's columns in the source's own order. Only sources that state something."""
219
+ by_name = {source.name: source for source in self.stating()}
220
+ names = dict.fromkeys([source.name for source in self.prefer] + sorted(by_name))
221
+ return [view for name in names if name in by_name for view in by_name[name].statements()]
222
+
223
+ def gaps(self) -> list[str]:
224
+ """The typed fields no source states."""
225
+ return [name for name in self.typed_fields() if getattr(self, name) is None]
226
+
227
+ def disagreements(self) -> list[Disagreement]:
228
+ """Each field whose sources state something other than the chosen value (compared in SI, on the field's
229
+ side of the reducer), with every differing statement. A source for another model (`applies_to`) is shown
230
+ beside the values but never counted: a sibling's winding is expected to differ."""
231
+ found = []
232
+ fields = self.typed_fields()
233
+ for name in [*fields, *self.extra]:
234
+ chosen = self.chosen(name)
235
+ if chosen is None:
236
+ continue
237
+ spec = fields.get(name)
238
+ others = tuple(stated for stated in self.statements(name) if not stated.source.is_related
239
+ and not same(self._comparable(spec, stated), self._comparable(spec, chosen)))
240
+ if others:
241
+ found.append(Disagreement(name, chosen, others))
242
+ return found
243
+
244
+ def agrees(self, name: str, stated: Stated) -> bool:
245
+ chosen = self.chosen(name)
246
+ if chosen is None:
247
+ return False
248
+ spec = self.typed_fields().get(name)
249
+ return same(self._comparable(spec, stated), self._comparable(spec, chosen))
250
+
251
+ def _comparable(self, spec: FieldSpec | None, stated: Stated) -> Any:
252
+ """A statement as a comparable value: SI, carried to the field's side of the reducer (a derived value is
253
+ already there); a text as itself; a number in a unit nobody can convert as (value, unit)."""
254
+ if not stated.is_number:
255
+ return stated.value
256
+ try:
257
+ value = stated.si
258
+ except ValueError:
259
+ return (stated.value, stated.unit)
260
+ if spec is not None and spec.side is not None and stated.at not in (None, spec.side):
261
+ ratio = getattr(self, "gear_ratio", None)
262
+ if ratio is None:
263
+ return (stated.value, stated.unit, stated.at)
264
+ value *= ratio.si ** spec.reflect
265
+ return value
266
+
267
+
268
+ def same(a: Any, b: Any) -> bool:
269
+ if isinstance(a, float) and isinstance(b, float):
270
+ return math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-15)
271
+ return a == b
272
+
273
+
274
+ def reflected(name: str, spec: FieldSpec, stated: Stated, gear_ratio: Stated | None) -> Stated:
275
+ """A rotor-side field a source states at the output, carried to the rotor through the gear ratio, marked as
276
+ derived from the statement (which the table still shows as written)."""
277
+ if gear_ratio is None:
278
+ raise ValueError(f"{name} is stated at the {stated.at} ({stated.text()}) but no source gives gear_ratio")
279
+ ratio = gear_ratio.si
280
+ factor = ratio ** spec.reflect if stated.at == "output" else ratio ** -spec.reflect
281
+ value = float(f"{stated.value * factor:.12g}")
282
+ basis = (f"{stated.text()} at the {stated.at} ({stated.source.label if stated.source else 'source'}) "
283
+ f"× gear_ratio {ratio:g}{'' if spec.reflect == 1 else f'^{spec.reflect}'}")
284
+ return replace(stated, value=value, at=None, basis=basis, derived_from=stated)
285
+
286
+
287
+ def check_value(type_name: str, name: str, spec: FieldSpec, stated: Any) -> None:
288
+ """One typed field's value: a single Stated, in one of the field's units, of its kind; else a loud refusal."""
289
+ where = f"{type_name}.{name}"
290
+ if not isinstance(stated, Stated):
291
+ raise TypeError(f"{where} must be a Stated(...), not {stated!r}")
292
+ if stated.by_column:
293
+ # a source's statement may give one value per column (a driver board, a winding): each is checked alone. A
294
+ # resolved datasheet never holds one: from_sources reads each source through one column.
295
+ for column in stated.value:
296
+ check_value(type_name, name, spec, stated.for_column(column))
297
+ return
298
+ unit = stated.unit or ""
299
+ if unit not in spec.units:
300
+ accepted = ", ".join(repr(u) for u in spec.units) or "none"
301
+ raise ValueError(f"{where}: unit {unit!r} is not one this field takes ({accepted}); {spec.definition}")
302
+ if spec.kind in ("number", "integer"):
303
+ if not stated.is_number:
304
+ raise TypeError(f"{where} is {stated.value!r}: a number is needed")
305
+ if spec.kind == "integer" and not float(stated.value).is_integer():
306
+ raise ValueError(f"{where} is {stated.value!r}: a whole number is needed")
307
+ if spec.positive and stated.value <= 0:
308
+ raise ValueError(f"{where} is {stated.value!r}: it must be > 0")
309
+ elif spec.kind == "text" and not isinstance(stated.value, str):
310
+ raise TypeError(f"{where} is {stated.value!r}: a text is needed")
311
+
312
+
313
+ def check_source(cls: type[Datasheet], source: Source) -> None:
314
+ """Every value a source states is a typed field of `cls` in an accepted unit; every extra key is not. A source
315
+ written as another type must be one `cls` extends (a BldcMotor statement can feed an IntegratedServo)."""
316
+ fields = cls.typed_fields()
317
+ if source.type is not None and not issubclass(cls, source.type):
318
+ raise TypeError(f"sources/{source.name}.py is written as {source.type.__name__}(...), but this part is "
319
+ f"{cls.__name__}, which does not extend it")
320
+ for name, stated in source.values.items():
321
+ if name not in fields:
322
+ near = difflib.get_close_matches(name, list(fields), n=1)
323
+ hint = f" (did you mean {near[0]}?)" if near else ""
324
+ raise KeyError(f"sources/{source.name}.py: {name} is not a field of {cls.__name__}{hint}; "
325
+ f"a value the type has no field for goes in extra = {{...}}")
326
+ spec = fields[name]
327
+ for column in source.columns or (None,):
328
+ value = stated.for_column(column) if column and stated.by_column else stated
329
+ check_value(f"sources/{source.name}.py", name, spec, value)
330
+ if stated.at is not None and spec.side is None:
331
+ raise ValueError(f"sources/{source.name}.py: {name} says at={stated.at!r}, but {cls.__name__}.{name} "
332
+ f"is defined on one side only ({spec.definition})")
333
+ for name in source.extra:
334
+ if name in fields:
335
+ raise KeyError(f"sources/{source.name}.py: extra {name!r} is a typed field of {cls.__name__}; "
336
+ f"write it as `{name} = Stated(...)`")
337
+
338
+
339
+ __all__ = [
340
+ "ELECTRICAL",
341
+ "EXTRA",
342
+ "GROUPS",
343
+ "INTERFACES",
344
+ "KEY_SPECS",
345
+ "MECHANICAL",
346
+ "PERFORMANCE",
347
+ "ColumnError",
348
+ "Datasheet",
349
+ "Disagreement",
350
+ "Field",
351
+ "FieldSpec",
352
+ "check_source",
353
+ "check_value",
354
+ "reflected",
355
+ ]