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,144 @@
1
+ """Is a `sources/<name>.py` literal-only, so a reader can parse it without running it? And `read`, that reader.
2
+
3
+ WHY (PEP 0003 §6): robotparts' catalogue build reads `part.py` files with an AST walk and never runs them (they arrive
4
+ in pull requests). A source file kept to literals can be read the same way, and stays a transcription: a conversion
5
+ or a sum is a derivation, and belongs in the part file or the type, never in what a source states.
6
+
7
+ Allowed at the top level: a docstring; `from robot_models... import ...` (and `from __future__`); `source = Source(...)`;
8
+ and `values = <Type>(field=Stated(...), ..., extra={"key": Stated(...), ...})`, whose arguments are literals (numbers,
9
+ text, True/False/None, tuples, lists and dicts of literals, a leading minus). The type's name is read as a name: the
10
+ static reader does not need to import it to know which field each keyword fills.
11
+
12
+ read("sources/steadywin_page.py")["values"]["peak_torque"]["value"] # {"GDZ34": 3.82, "GDS34": 3.47}, never run
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import ast
18
+ import pathlib
19
+ from typing import Any
20
+
21
+ STATED = "Stated"
22
+ SOURCE = "Source"
23
+ # The positional order of Stated(value, unit, as_written) and Source(title)
24
+ STATED_POSITIONAL = ("value", "unit", "as_written")
25
+ SOURCE_POSITIONAL = ("title",)
26
+
27
+
28
+ def problems(path: str | pathlib.Path) -> list[str]:
29
+ """What keeps the file from being read without running it; empty when it is literal-only."""
30
+ path = pathlib.Path(path)
31
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
32
+ found: list[str] = []
33
+ # the names imported from robot_models: a type called for `values` must be one of them, so a reader knows it is
34
+ # a type's constructor and not some function that computes the values
35
+ imported = {alias.asname or alias.name for node in tree.body if isinstance(node, ast.ImportFrom)
36
+ and node.module and node.module.split(".")[0] == "robot_models" for alias in node.names}
37
+ for index, node in enumerate(tree.body):
38
+ if index == 0 and isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):
39
+ continue
40
+ if isinstance(node, ast.ImportFrom) and node.level == 0 and node.module and (
41
+ node.module == "__future__" or node.module.split(".")[0] == "robot_models"):
42
+ continue
43
+ if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
44
+ target = node.targets[0].id
45
+ if target == "source":
46
+ found.extend(_call(node.value, (SOURCE,)))
47
+ continue
48
+ if target == "values":
49
+ found.extend(_typed_call(node.value, imported - {SOURCE, STATED}))
50
+ continue
51
+ found.append(f"line {node.lineno}: only `source = Source(...)` and `values = <Type>(...)` belong here, "
52
+ f"not `{target} = ...`")
53
+ continue
54
+ found.append(f"line {node.lineno}: only a docstring, the imports, `source = Source(...)` and "
55
+ f"`values = <Type>(...)` belong here ({type(node).__name__})")
56
+ return found
57
+
58
+
59
+ def _typed_call(node: ast.AST, types: set[str]) -> list[str]:
60
+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in types):
61
+ return [f"line {node.lineno}: values is a part type imported from robot_models, called with its fields "
62
+ f"(`IntegratedServo(...)`), not {ast.unparse(node)[:60]}"]
63
+ out = []
64
+ if node.args:
65
+ out.append(f"line {node.lineno}: every value is a keyword, `peak_torque=Stated(...)`")
66
+ for keyword in node.keywords:
67
+ if keyword.arg is None:
68
+ out.append(f"line {node.lineno}: no ** in a source file")
69
+ elif keyword.arg == "extra":
70
+ if not isinstance(keyword.value, ast.Dict):
71
+ out.append(f"line {keyword.value.lineno}: extra is a {{\"name\": Stated(...)}} dict")
72
+ continue
73
+ for key, value in zip(keyword.value.keys, keyword.value.values):
74
+ if not (isinstance(key, ast.Constant) and isinstance(key.value, str)):
75
+ out.append(f"line {keyword.value.lineno}: extra's keys are plain names in quotes")
76
+ out.extend(_call(value, (STATED,)))
77
+ else:
78
+ out.extend(_call(keyword.value, (STATED,)))
79
+ return out
80
+
81
+
82
+ def _call(node: ast.AST, constructors: tuple[str, ...]) -> list[str]:
83
+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in constructors):
84
+ return [f"line {node.lineno}: a value is {' or '.join(c + '(...)' for c in constructors)}, not "
85
+ f"{ast.unparse(node)[:60]}"]
86
+ out = []
87
+ for argument in [*node.args, *(keyword.value for keyword in node.keywords)]:
88
+ if not _literal(argument):
89
+ out.append(f"line {argument.lineno}: {ast.unparse(argument)[:60]} is not a literal (no arithmetic, "
90
+ f"names or calls in a source file)")
91
+ if any(keyword.arg is None for keyword in node.keywords) or any(isinstance(a, ast.Starred) for a in node.args):
92
+ out.append(f"line {node.lineno}: no * or ** in a source file")
93
+ return out
94
+
95
+
96
+ def _literal(node: ast.AST) -> bool:
97
+ if isinstance(node, ast.Constant):
98
+ return True
99
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub) and isinstance(node.operand, ast.Constant):
100
+ return isinstance(node.operand.value, (int, float)) and not isinstance(node.operand.value, bool)
101
+ if isinstance(node, (ast.Tuple, ast.List)):
102
+ return all(_literal(element) for element in node.elts)
103
+ if isinstance(node, ast.Dict):
104
+ return all(key is not None and _literal(key) for key in node.keys) and all(_literal(v) for v in node.values)
105
+ return False
106
+
107
+
108
+ # --- the static reader -------------------------------------------------------------------------------------------
109
+
110
+ def read(path: str | pathlib.Path) -> dict[str, Any]:
111
+ """A source file read without running it: {"source": {title, kind, role, file, ...}, "type": "IntegratedServo"
112
+ or None, "values": {field: {value, unit, as_written, ...}}, "extra": {name: {...}}}.
113
+
114
+ Refuses a file that is not literal-only (`problems`). Units, kinds and field names are NOT checked here: that is
115
+ the loader's job, with the type in hand. This is what a reader that must never run a file (a catalogue build, a
116
+ status table over `git archive`) uses.
117
+ """
118
+ path = pathlib.Path(path)
119
+ found = problems(path)
120
+ if found:
121
+ raise ValueError(f"{path.name} is not literal-only: " + "; ".join(found))
122
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
123
+ out: dict[str, Any] = {"source": None, "type": None, "values": {}, "extra": {}}
124
+ for node in tree.body:
125
+ if not (isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name)):
126
+ continue
127
+ target = node.targets[0].id
128
+ if target == "source":
129
+ out["source"] = _arguments(node.value, SOURCE_POSITIONAL)
130
+ elif target == "values":
131
+ out["type"] = node.value.func.id
132
+ for keyword in node.value.keywords:
133
+ if keyword.arg == "extra":
134
+ out["extra"] = {key.value: _arguments(value, STATED_POSITIONAL)
135
+ for key, value in zip(keyword.value.keys, keyword.value.values)}
136
+ else:
137
+ out["values"][keyword.arg] = _arguments(keyword.value, STATED_POSITIONAL)
138
+ return out
139
+
140
+
141
+ def _arguments(call: ast.Call, positional: tuple[str, ...]) -> dict[str, Any]:
142
+ arguments = {name: ast.literal_eval(argument) for name, argument in zip(positional, call.args)}
143
+ arguments.update({keyword.arg: ast.literal_eval(keyword.value) for keyword in call.keywords})
144
+ return arguments
@@ -0,0 +1,328 @@
1
+ """`Source`, one raw source's header, and `Sources`, the loader of a part's `sources/*.py`.
2
+
3
+ A part folder holds one `sources/<name>.py` per raw source (a saved page, a PDF, a seller's list, our own estimates),
4
+ beside the raw file it was read from, which carries the same name (`sources/steadywin_page.html` +
5
+ `sources/steadywin_page.py`). Each reads like a transcription: the header once, then the part type called with one
6
+ keyword per value, in the source's own order:
7
+
8
+ source = Source("SteadyWin product page", kind="manufacturer", role="product_page", url="https://...",
9
+ file="steadywin_page.html", sha256="...", read_on="2026-11-16", columns=("GDZ34", "GDS34"))
10
+
11
+ values = IntegratedServo(
12
+ nominal_voltage=Stated(24, "V", "额定电压(Nominal Voltage)"),
13
+ rated_torque=Stated({"GDZ34": 1.05, "GDS34": 1}, "N·m", "额定扭矩(Nominal Torque)"),
14
+ extra={"noise": Stated(60, "dB", "噪音(Noise)", bound="max")}, # what the type has no field for
15
+ )
16
+
17
+ WHY the type is called with keywords (Zach, 2026-11-16: "To get type completion you should be filling in these values
18
+ from the models"; proposal 1 of five, robotparts reports/source-file-proposals-2026-11-16.html): the editor completes
19
+ each field name from the type's own signature and marks an unknown one, and the type stays a frozen dataclass.
20
+
21
+ A header with no `values` is a raw file catalogued but not transcribed yet (a photo, a CAD file, a manual nobody has
22
+ read for values): it still says what the file is (`role`), where it came from and which bytes it is.
23
+
24
+ Loaded, `source.nominal_voltage` is the `Stated` (with `.as_written` and `.source`), `source["GDS34"]` is the
25
+ GDS34 column, and `source.rated_torque` on a two-column source refuses until a column is named.
26
+
27
+ WHY the .py IS the cache (Zach, 2026-11-16: "I want to cache the result ... I like python as ground truth"): the raw
28
+ file is parsed once, by a person or an extractor, into this file; nothing re-parses it at run time. WHY `sha256`:
29
+ a cache needs a key, or a re-captured raw file silently disagrees with its parse; the user tests compare it.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import hashlib
35
+ import importlib.util
36
+ import pathlib
37
+ import re
38
+ import types
39
+ from collections.abc import Iterator, Mapping
40
+ from dataclasses import KW_ONLY, dataclass, field, replace
41
+ from typing import Any, Literal, get_args
42
+
43
+ from .stated import Stated
44
+
45
+ # robotparts registry `source_kinds`, less "private" (a publishing flag, not a kind of evidence)
46
+ KINDS = ("manufacturer", "distributor", "retailer", "inspected", "derived", "estimated")
47
+
48
+ # What a raw file IS, robotparts user/README.md's file-name vocabulary. WHY a header field and no longer the file name
49
+ # (Zach, 2026-11-16: "the file names should be the exact same for the sources ... so they show up next to each other
50
+ # in the file viewer"): the name now pairs the raw file with its .py, so what the file is moves into the header.
51
+ Role = Literal["datasheet", "2d_drawing", "cad", "product_page", "manual", "seller_chat", "photo"]
52
+ ROLES: tuple[str, ...] = get_args(Role)
53
+
54
+
55
+ class ColumnError(AttributeError):
56
+ """A value read from a source with one column per variant, without naming the column, where the columns differ."""
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class Source:
61
+ """The header of one raw source: what it is, where its bytes are, and how it is laid out.
62
+
63
+ - `kind`: robotparts' source kinds (manufacturer, distributor, retailer, inspected, derived, estimated): who says.
64
+ - `role`: what the raw document is (`ROLES`: datasheet, 2d_drawing, cad, product_page, manual, seller_chat, photo),
65
+ one or several (a spec sheet that is also the drawing). None for a source that is no document (our estimates).
66
+ - `file`: the raw file(s), relative to the part's sources/ folder and named like the .py (`steadywin_page.html`,
67
+ `steadywin_page(spec_table).html`); the first is the one `sha256` pins.
68
+ - `columns`: the source's variant columns (driver boards, windings, units on a rack), when it has several.
69
+ - `applies_to`: the model the document is for, when not this part (a sibling's drawing). Such a source is shown,
70
+ never preferred: a value is taken from it only by an explicit pick.
71
+ - `private`: a document only Zach holds (a seller's chat). Its sha256 stays out of the .py, pinned instead in a
72
+ git-ignored `<raw file>.sha256` sidecar (`pinned_sha256`), so no tracked file identifies it.
73
+
74
+ `name` (the file's stem), `column`, `folder`, `values`, `extra` and `type` are set by the loader.
75
+ """
76
+
77
+ title: str
78
+ _: KW_ONLY
79
+ kind: str
80
+ role: Role | tuple[Role, ...] | None = None
81
+ url: str | None = None
82
+ file: str | tuple[str, ...] | None = None
83
+ sha256: str | None = None
84
+ read_on: str | None = None
85
+ columns: tuple[str, ...] = ()
86
+ applies_to: str | None = None
87
+ where: str | None = None
88
+ note: str | None = None
89
+ private: bool = False
90
+ name: str | None = None
91
+ column: str | None = None
92
+ folder: pathlib.Path | None = field(default=None, compare=False, repr=False)
93
+ values: Mapping[str, Stated] = field(default_factory=dict, compare=False, repr=False)
94
+ extra: Mapping[str, Stated] = field(default_factory=dict, compare=False, repr=False)
95
+ type: Any = field(default=None, compare=False, repr=False)
96
+
97
+ def __post_init__(self) -> None:
98
+ if self.kind not in KINDS:
99
+ raise ValueError(f"Source({self.title!r}): kind {self.kind!r} is not one of {', '.join(KINDS)}")
100
+ for role in self.roles:
101
+ if role not in ROLES:
102
+ raise ValueError(f"Source({self.title!r}): role {role!r} is not one of {', '.join(ROLES)}")
103
+ if self.private and self.sha256:
104
+ # WHY (2026-11-16, robotparts PEP 0005): a private document's hash identifies it, so it never enters a
105
+ # tracked file; it is pinned in a git-ignored sidecar beside the raw file instead (pinned_sha256)
106
+ raise ValueError(f"Source({self.title!r}) is private: keep its sha256 out of the .py, in "
107
+ f"sources/<file>.sha256 beside the raw file")
108
+ if self.column is not None and self.column not in self.columns:
109
+ raise KeyError(f"{self.title}: no column {self.column!r}; it has {', '.join(self.columns) or 'none'}")
110
+
111
+ def __hash__(self) -> int:
112
+ return hash((self.name, self.title, self.column))
113
+
114
+ # --- the files -------------------------------------------------------------------------------------------
115
+
116
+ @property
117
+ def files(self) -> tuple[str, ...]:
118
+ if self.file is None:
119
+ return ()
120
+ return (self.file,) if isinstance(self.file, str) else tuple(self.file)
121
+
122
+ @property
123
+ def roles(self) -> tuple[str, ...]:
124
+ if self.role is None:
125
+ return ()
126
+ return (self.role,) if isinstance(self.role, str) else tuple(self.role)
127
+
128
+ @property
129
+ def path(self) -> pathlib.Path | None:
130
+ """The first raw file on disk (it may be absent: raw files are git-ignored)."""
131
+ return self.folder / "sources" / self.files[0] if self.folder is not None and self.files else None
132
+
133
+ @property
134
+ def states_anything(self) -> bool:
135
+ """False for a header with no values yet: a raw file catalogued, not transcribed."""
136
+ return bool(self.values or self.extra)
137
+
138
+ @property
139
+ def sidecar(self) -> pathlib.Path | None:
140
+ """Where a private source pins its hash: `<raw file>.sha256` beside the raw file (git-ignored with it)."""
141
+ path = self.path
142
+ return path.with_name(path.name + ".sha256") if path is not None else None
143
+
144
+ @property
145
+ def pinned_sha256(self) -> str | None:
146
+ """The hash this source was parsed from: in the .py, or for a private source in its sidecar file."""
147
+ if not self.private:
148
+ return self.sha256
149
+ sidecar = self.sidecar
150
+ return sidecar.read_text().split()[0] if sidecar is not None and sidecar.is_file() else None
151
+
152
+ def file_sha256(self) -> str | None:
153
+ """The sha256 of the first raw file as it is on disk now, or None when it is not here."""
154
+ path = self.path
155
+ if path is None or not path.is_file():
156
+ return None
157
+ return hashlib.sha256(path.read_bytes()).hexdigest()
158
+
159
+ # --- reading it ------------------------------------------------------------------------------------------
160
+
161
+ @property
162
+ def label(self) -> str:
163
+ """`steadywin_page·GDS34`: the name a table column and a pick use."""
164
+ return f"{self.name}·{self.column}" if self.column else str(self.name)
165
+
166
+ @property
167
+ def is_related(self) -> bool:
168
+ return self.applies_to is not None
169
+
170
+ def __getitem__(self, column: str) -> Source:
171
+ """This source's `column` only: every value as that column states it."""
172
+ if column not in self.columns:
173
+ raise KeyError(f"{self.label} has no column {column!r}; it has {', '.join(self.columns) or 'none'}")
174
+ view = replace(self, column=column)
175
+ _fill(view, {name: stated.for_column(column) for name, stated in self.values.items()},
176
+ {name: stated.for_column(column) for name, stated in self.extra.items()})
177
+ return view
178
+
179
+ def states(self, name: str) -> Stated | None:
180
+ """What this source states for `name` (a typed field or an extra name), or None. On a source with columns,
181
+ read without one, a value that differs by column refuses: name the column."""
182
+ stated = self.values.get(name) or self.extra.get(name)
183
+ if stated is None:
184
+ return None
185
+ if stated.by_column and self.column is None:
186
+ raise ColumnError(f"{self.label} states {name} per column ({stated.text()}): name one, "
187
+ f"{self.name}[{next(iter(stated.value))!r}].{name}")
188
+ return stated
189
+
190
+ def __getattr__(self, name: str) -> Stated:
191
+ # only reached when normal lookup fails, so a field of Source itself always wins
192
+ if name.startswith("_"):
193
+ raise AttributeError(name)
194
+ values = self.__dict__.get("values", {})
195
+ extra = self.__dict__.get("extra", {})
196
+ if name not in values and name not in extra:
197
+ raise AttributeError(f"{self.label} states no {name!r}")
198
+ return self.states(name)
199
+
200
+ def statements(self) -> Iterator[Source]:
201
+ """Itself once per column (or once, when it has none): every view a table shows."""
202
+ if not self.columns or self.column is not None:
203
+ yield self
204
+ else:
205
+ for column in self.columns:
206
+ yield self[column]
207
+
208
+
209
+ def _fill(source: Source, values: dict[str, Stated], extra: dict[str, Stated]) -> None:
210
+ """Bind the values to their source. WHY object.__setattr__: a Stated points at its Source and the Source holds
211
+ its Stateds, so one of the two is filled after it is built; nothing else ever mutates them."""
212
+ bound = {name: replace(stated, name=name, source=source) for name, stated in values.items()}
213
+ bound_extra = {name: replace(stated, name=name, source=source) for name, stated in extra.items()}
214
+ object.__setattr__(source, "values", types.MappingProxyType(bound))
215
+ object.__setattr__(source, "extra", types.MappingProxyType(bound_extra))
216
+
217
+
218
+ def load_source(path: pathlib.Path, part_folder: pathlib.Path | None = None) -> Source:
219
+ """One `sources/<name>.py`, run and checked: it has a `source = Source(...)`, at most one `values = <Type>(...)`
220
+ whose keywords are that type's fields (the type checks each unit and kind as it is built), and a per-column value
221
+ names exactly the header's columns."""
222
+ from .datasheet import Datasheet # WHY here: datasheet.py imports this module
223
+
224
+ path = pathlib.Path(path)
225
+ module_name = f"robot_models_source_{abs(hash(str(path.resolve())))}_{path.stem}"
226
+ spec = importlib.util.spec_from_file_location(module_name, path)
227
+ module = importlib.util.module_from_spec(spec)
228
+ try:
229
+ spec.loader.exec_module(module)
230
+ except TypeError as error:
231
+ raise TypeError(f"sources/{path.name}: {_with_hint(error)}") from error
232
+ except ValueError as error:
233
+ raise ValueError(f"sources/{path.name}: {error}") from error
234
+ header = getattr(module, "source", None)
235
+ if not isinstance(header, Source):
236
+ raise ValueError(f"{path}: needs `source = Source(...)` (its header)")
237
+ for name, value in vars(module).items():
238
+ if name.startswith("_") or name in ("source", "values") or isinstance(value, (types.ModuleType, type)):
239
+ continue
240
+ if callable(value):
241
+ continue
242
+ if isinstance(value, Stated):
243
+ raise ValueError(f"sources/{path.name}: {name} = Stated(...) at the top level; write it as a keyword of "
244
+ f"the type, `values = <Type>({name}=Stated(...), ...)` (PEP 0003 amendment 1)")
245
+ raise ValueError(f"sources/{path.name}: {name} = {value!r}; a source file holds `source = Source(...)` and "
246
+ f"`values = <Type>(...)` only")
247
+ sheet = getattr(module, "values", None)
248
+ if sheet is not None and not isinstance(sheet, Datasheet):
249
+ raise ValueError(f"sources/{path.name}: values must be a part type called with its fields, "
250
+ f"`values = IntegratedServo(peak_torque=Stated(...), ...)`, not {type(sheet).__name__}")
251
+ values: dict[str, Stated] = {}
252
+ extra: dict[str, Stated] = {}
253
+ if sheet is not None:
254
+ values = {name: getattr(sheet, name) for name in sheet.typed_fields() if getattr(sheet, name) is not None}
255
+ extra = dict(sheet.extra)
256
+ for name, stated in {**values, **extra}.items():
257
+ if stated.by_column and set(stated.value) != set(header.columns):
258
+ raise ValueError(f"{path.name}: {name} gives columns {', '.join(stated.value)} but the header has "
259
+ f"{', '.join(header.columns) or 'none'}")
260
+ source = replace(header, name=path.stem, folder=pathlib.Path(part_folder) if part_folder else path.parent.parent,
261
+ type=type(sheet) if sheet is not None else None)
262
+ _fill(source, values, extra)
263
+ return source
264
+
265
+
266
+ def _with_hint(error: TypeError) -> str:
267
+ """`IntegratedServo.__init__() got an unexpected keyword argument 'nominal_votlage'`, plus the nearest field and
268
+ where a custom value goes: the editor marks the same typo before it ever runs."""
269
+ import difflib
270
+
271
+ text = str(error)
272
+ found = re.search(r"(\w+)\.__init__\(\) got an unexpected keyword argument '(\w+)'", text)
273
+ if not found:
274
+ return text
275
+ from .datasheet import Datasheet
276
+
277
+ owner = next((cls for cls in _subclasses(Datasheet) if cls.__name__ == found[1]), None)
278
+ fields = list(owner.typed_fields()) if owner else []
279
+ near = difflib.get_close_matches(found[2], fields, n=1)
280
+ hint = f" (did you mean {near[0]}?)" if near else ""
281
+ return (f"{found[2]} is not a field of {found[1]}{hint}; a value the type has no field for goes in "
282
+ f"extra={{...}}")
283
+
284
+
285
+ def _subclasses(cls: type) -> list[type]:
286
+ out = []
287
+ for sub in cls.__subclasses__():
288
+ out += [sub, *_subclasses(sub)]
289
+ return out
290
+
291
+
292
+ class Sources:
293
+ """Every `sources/*.py` beside a part file, by name: `sources = Sources(__file__)`, then `sources.steadywin_page`.
294
+
295
+ Iterating gives them in name order. A part folder with no `sources/` has none.
296
+ """
297
+
298
+ def __init__(self, part_file: str | pathlib.Path):
299
+ part_file = pathlib.Path(part_file).resolve()
300
+ self.folder = part_file.parent
301
+ directory = self.folder / "sources"
302
+ paths = sorted(directory.glob("*.py")) if directory.is_dir() else []
303
+ self._by_name: dict[str, Source] = {path.stem: load_source(path, self.folder) for path in paths
304
+ if not path.name.startswith("_")}
305
+
306
+ def __iter__(self) -> Iterator[Source]:
307
+ return iter(self._by_name.values())
308
+
309
+ def __len__(self) -> int:
310
+ return len(self._by_name)
311
+
312
+ def __getitem__(self, name: str) -> Source:
313
+ return self._by_name[name]
314
+
315
+ def __getattr__(self, name: str) -> Source:
316
+ if name.startswith("_"):
317
+ raise AttributeError(name)
318
+ try:
319
+ return self._by_name[name]
320
+ except KeyError:
321
+ raise AttributeError(f"no sources/{name}.py beside {self.folder.name}; have {', '.join(self._by_name)}") from None
322
+
323
+ def names(self) -> tuple[str, ...]:
324
+ return tuple(self._by_name)
325
+
326
+
327
+ def is_source(value: Any) -> bool:
328
+ return isinstance(value, Source)
@@ -0,0 +1,135 @@
1
+ """`Stated`: what one source states for one field, written the way the source writes it.
2
+
3
+ rated_torque = Stated(1.05, "N·m", "额定扭矩(Nominal Torque)")
4
+ peak_torque = Stated({"GDZ34": 3.82, "GDS34": 3.47}, "N·m", "堵转扭矩(Stall Torque)") # one value per column
5
+
6
+ WHY a class of its own and not robotparts' `Spec` or dataclass_values' `Value` (PEP 0003 §4): a `Spec` repeats its
7
+ source on every value (`source_url=`, `source_kind=`), which is the "no longer linked" Zach rejected; in a source file
8
+ the source is written once, in its header. A `Value` IS the number, for configs, and has no place for the source's
9
+ own label or a per-column value. `Stated` is the transcription; the catalogue's `Spec` is generated from it, never
10
+ typed twice.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import urllib.parse
16
+ from dataclasses import KW_ONLY, dataclass, field, replace
17
+ from typing import Any
18
+
19
+ from .units import to_si
20
+
21
+ SIDES = ("output", "rotor")
22
+ BOUNDS = ("max", "min")
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Stated:
27
+ """One value as one source states it.
28
+
29
+ - `value`: a number, a text, or `{column: value}` when the source has one column per variant (a driver board,
30
+ a winding). A value the same in every column is written once.
31
+ - `unit`: robotparts' registry spelling (`N·m`, `rpm`, `kg·cm²`; `""` for a count). The source's own spelling
32
+ goes in `as_written` or `note`.
33
+ - `as_written`: the source's own label for the value. It is also the anchor back into the raw file (a text quote),
34
+ so `where` is only needed when the label cannot find it (a drawing with no text layer, a repeated label).
35
+ - `where`: a source_msgs compact selector (`page=1&xywh=percent:18,76,7,2.6`, `table=1&row=7&col=3`).
36
+ - `at`: `"output"` when the source states a rotor-side quantity (Kv, Kt, rotor inertia) after the reducer.
37
+ - `basis`: how an estimate was made. `bound`: `"max"` for "< 60 dB".
38
+
39
+ `name`, `column` and `source` are set by the loader, never written by hand.
40
+ """
41
+
42
+ value: Any
43
+ unit: str | None = None
44
+ as_written: str | None = None
45
+ _: KW_ONLY
46
+ where: str | None = None
47
+ note: str | None = None
48
+ at: str | None = None
49
+ basis: str | None = None
50
+ bound: str | None = None
51
+ name: str | None = field(default=None, compare=False)
52
+ column: str | None = field(default=None, compare=False)
53
+ source: Any = field(default=None, compare=False, repr=False)
54
+ derived_from: Stated | None = field(default=None, compare=False, repr=False)
55
+
56
+ def __post_init__(self) -> None:
57
+ if self.at is not None and self.at not in SIDES:
58
+ raise ValueError(f"at={self.at!r}: say 'output' or 'rotor'")
59
+ if self.bound is not None and self.bound not in BOUNDS:
60
+ raise ValueError(f"bound={self.bound!r}: say 'max' or 'min'")
61
+ if isinstance(self.value, dict) and not self.value:
62
+ raise ValueError("a per-column value needs at least one column")
63
+
64
+ # --- columns ---------------------------------------------------------------------------------------------
65
+
66
+ @property
67
+ def by_column(self) -> bool:
68
+ """True when the source gives a different value per column (`{"GDZ34": 3.82, "GDS34": 3.47}`)."""
69
+ return isinstance(self.value, dict)
70
+
71
+ def for_column(self, column: str) -> Stated:
72
+ """This value as one column states it. A value written once holds for every column."""
73
+ if not self.by_column:
74
+ return replace(self, column=column)
75
+ if column not in self.value:
76
+ raise KeyError(f"{self.name or 'this value'} has no column {column!r}; it has {', '.join(self.value)}")
77
+ return replace(self, value=self.value[column], column=column)
78
+
79
+ # --- reading it ------------------------------------------------------------------------------------------
80
+
81
+ @property
82
+ def is_number(self) -> bool:
83
+ return isinstance(self.value, (int, float)) and not isinstance(self.value, bool)
84
+
85
+ @property
86
+ def si(self) -> float:
87
+ """The value in SI units (rated_torque in N·m, rotor_inertia in kg·m², speeds in rad/s)."""
88
+ if not self.is_number:
89
+ raise TypeError(f"{self.name or 'this value'} is {self.value!r}, not one number")
90
+ return to_si(self.value, self.unit)
91
+
92
+ @property
93
+ def anchor(self) -> str | None:
94
+ """Where the value is in its raw file, as a source_msgs compact selector: `where` if written, else the
95
+ source's own label as a text quote (Text Fragments syntax, `text=...`)."""
96
+ if self.where:
97
+ return self.where
98
+ if self.as_written:
99
+ return "text=" + urllib.parse.quote(self.as_written, safe="")
100
+ return None
101
+
102
+ @property
103
+ def is_derived(self) -> bool:
104
+ return self.derived_from is not None
105
+
106
+ def text(self) -> str:
107
+ """The value and its unit, compactly: `3.82 N·m`, `GDZ34 3.82 · GDS34 3.47`, `< 60 dB`."""
108
+ return self.value_text() + unit_text(self.unit)
109
+
110
+ def value_text(self) -> str:
111
+ """The value without its unit: `3.82`, `GDZ34 3.82 · GDS34 3.47`, `< 60`."""
112
+ if self.by_column:
113
+ return " · ".join(f"{column} {_number(value)}" for column, value in self.value.items())
114
+ mark = "< " if self.bound == "max" else "> " if self.bound == "min" else ""
115
+ return mark + _number(self.value)
116
+
117
+ def __str__(self) -> str:
118
+ return self.text()
119
+
120
+
121
+ def _number(value: Any) -> str:
122
+ if isinstance(value, bool):
123
+ return "yes" if value else "no"
124
+ if isinstance(value, float):
125
+ return f"{value:.6g}"
126
+ if isinstance(value, tuple):
127
+ return " – ".join(_number(item) for item in value)
128
+ return str(value)
129
+
130
+
131
+ def unit_text(unit: str | None) -> str:
132
+ """A unit as it follows a number: ` N·m`, `:1` (no space), nothing for a count."""
133
+ if not unit:
134
+ return ""
135
+ return unit if unit == ":1" else " " + unit
@@ -0,0 +1,57 @@
1
+ """The units a datasheet field accepts, each with its factor to SI, spelled as robotparts' registry spells them.
2
+ The first unit of a family is the one a datasheet usually quotes, which a table shows on a row nobody states.
3
+
4
+ WHY the registry's spellings and factors (PEP 0003): one vocabulary. robotparts' user tests check that every typed
5
+ field named like a registry key accepts only units that key lists, with the same factors.
6
+
7
+ A source's own spelling ("N.M", "RPM", "rpm/v", "Pairs") is normalised to these when it is transcribed; the source's
8
+ words stay in `Stated.as_written`.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+
15
+ RPM = 2 * math.pi / 60
16
+
17
+ TORQUE = {"N·m": 1.0, "mN·m": 1e-3}
18
+ SPEED = {"rpm": RPM, "rad/s": 1.0, "deg/s": math.pi / 180}
19
+ SMALL_ANGLE = {"arcmin": math.pi / 10800, "deg": math.pi / 180, "rad": 1.0, "mrad": 1e-3}
20
+ VOLTAGE = {"V": 1.0}
21
+ CURRENT = {"A": 1.0}
22
+ POWER = {"W": 1.0}
23
+ MASS = {"kg": 1.0, "g": 1e-3}
24
+ LENGTH = {"mm": 1e-3, "m": 1.0}
25
+ FORCE = {"N": 1.0}
26
+ INERTIA = {"kg·cm²": 1e-4, "kg·m²": 1.0, "kg·mm²": 1e-6, "g·cm²": 1e-7, "g·mm²": 1e-9}
27
+ VELOCITY_CONSTANT = {"rpm/V": RPM}
28
+ TORQUE_CONSTANT = {"N·m/A": 1.0, "mN·m/A": 1e-3}
29
+ # WHY V/krpm to V·s/rad: 1 V per 1000 rpm is 1 / (1000 · 2π/60) V·s/rad
30
+ BACK_EMF_CONSTANT = {"V/krpm": 1 / (1000 * RPM), "V·s/rad": 1.0}
31
+ RESISTANCE = {"Ω": 1.0, "mΩ": 1e-3}
32
+ INDUCTANCE = {"mH": 1e-3, "H": 1.0, "µH": 1e-6}
33
+ DAMPING = {"N·m·s/rad": 1.0, "mN·m·s/rad": 1e-3}
34
+ RATIO = {":1": 1.0, "": 1.0}
35
+ FRACTION = {"%": 0.01, "": 1.0}
36
+ COUNT = {"": 1.0}
37
+
38
+ FAMILIES = (TORQUE, SPEED, SMALL_ANGLE, VOLTAGE, CURRENT, POWER, MASS, LENGTH, FORCE, INERTIA, VELOCITY_CONSTANT,
39
+ TORQUE_CONSTANT, BACK_EMF_CONSTANT, RESISTANCE, INDUCTANCE, DAMPING, RATIO, FRACTION, COUNT)
40
+
41
+ # Every spelling above, once. A spelling in two families must mean the same factor ("" and ":1" are 1 everywhere;
42
+ # "%" is 0.01 only in FRACTION), so one table converts any stated value to SI.
43
+ FACTOR: dict[str, float] = {}
44
+ for _family in FAMILIES:
45
+ for _unit, _factor in _family.items():
46
+ if _unit in FACTOR and FACTOR[_unit] != _factor:
47
+ raise AssertionError(f"unit {_unit!r} has two factors: {FACTOR[_unit]} and {_factor}")
48
+ FACTOR[_unit] = _factor
49
+
50
+
51
+ def to_si(value: float, unit: str | None) -> float:
52
+ """`value` in `unit`, converted to SI. A unit this module does not know refuses (never a silent factor of 1)."""
53
+ if unit is None:
54
+ unit = ""
55
+ if unit not in FACTOR:
56
+ raise ValueError(f"unknown unit {unit!r}; known: {', '.join(sorted(u for u in FACTOR if u))}")
57
+ return value * FACTOR[unit]
@@ -0,0 +1 @@
1
+ """End-effector types by type folder (PEP 0004): gripper/."""