vuer-sim 0.0.1__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.
vuer_sim/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """vuer-sim: simulation materials for MuJoCo and USD scenes.
2
+
3
+ The core needs only numpy. Optional extras: ``[mujoco]`` (apply tables to
4
+ models), ``[usd]`` (``pxr`` converters), ``[viewer]`` (the vuer editor events).
5
+ """
6
+
7
+ from .infer import CATEGORIES, Inferred, infer_physics, lookup_table
8
+ from .physics import (
9
+ PhysicsMaterial,
10
+ dampratio_to_restitution,
11
+ max_stable_timestep,
12
+ mjcf_defaults,
13
+ restitution_to_dampratio,
14
+ solref_restitution,
15
+ )
16
+ from .sensor import LidarReturns, SensorArrays, SensorMaterial, lidar_returns
17
+ from .table import ApplyReport, MaterialTable
18
+
19
+ try:
20
+ from importlib.metadata import version as _version
21
+
22
+ __version__ = _version("vuer-sim")
23
+ except Exception: # pragma: no cover - source tree without an install
24
+ __version__ = "0+unknown"
25
+
26
+ __all__ = [
27
+ "ApplyReport",
28
+ "CATEGORIES",
29
+ "Inferred",
30
+ "LidarReturns",
31
+ "MaterialTable",
32
+ "PhysicsMaterial",
33
+ "SensorArrays",
34
+ "SensorMaterial",
35
+ "dampratio_to_restitution",
36
+ "infer_physics",
37
+ "lidar_returns",
38
+ "lookup_table",
39
+ "max_stable_timestep",
40
+ "mjcf_defaults",
41
+ "restitution_to_dampratio",
42
+ "solref_restitution",
43
+ ]
vuer_sim/_fmt.py ADDED
@@ -0,0 +1,29 @@
1
+ """Number formatting and the stored JSON form shared by every vuer-sim file."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Iterable
7
+ from typing import Any
8
+
9
+
10
+ def num(v: float) -> str:
11
+ """Shortest text that parses back to the same float (``1.0`` -> ``"1"``)."""
12
+ v = float(v)
13
+ if v.is_integer() and abs(v) < 1e16:
14
+ return str(int(v))
15
+ return repr(v)
16
+
17
+
18
+ def nums(vs: Iterable[float]) -> str:
19
+ """Space-separated ``num`` values, as MJCF writes vectors."""
20
+ return " ".join(num(v) for v in vs)
21
+
22
+
23
+ def parse_nums(text: str) -> tuple[float, ...]:
24
+ return tuple(float(t) for t in str(text).split())
25
+
26
+
27
+ def dumps(obj: Any) -> str:
28
+ """Stored form of the DreamLake bundle contract: sorted keys, 2-space indent, trailing newline."""
29
+ return json.dumps(obj, sort_keys=True, indent=2, ensure_ascii=False) + "\n"
vuer_sim/infer.py ADDED
@@ -0,0 +1,408 @@
1
+ """Visual material -> physics material: a documented lookup table.
2
+
3
+ ``infer_physics("OakWood_02")`` or ``infer_physics({"name": ..., "metallic": 1.0})``
4
+ returns an ``Inferred`` with a ``PhysicsMaterial``, the matched category, the
5
+ match and a ``confidence`` in [0, 1].
6
+
7
+ The values are typical values for a dry contact of the material against a hard
8
+ surface, with the range that the sources give. They are a starting point for a
9
+ scene, not measurements of your objects. Sources (``SOURCES``):
10
+
11
+ * ``et-friction``: Engineering ToolBox, *Friction and Friction Coefficients for
12
+ some Common Materials*.
13
+ * ``et-density``: Engineering ToolBox, *Densities of Solids*.
14
+ * ``wiki-friction``: Wikipedia, *Friction*, table of approximate coefficients.
15
+ * ``wiki-cor``: Wikipedia, *Coefficient of restitution*, and R. Cross, *The
16
+ bounce of a ball*, Am. J. Phys. 67, 222 (1999). Restitution depends strongly
17
+ on the impact speed and on the other body, so its confidence is lower.
18
+
19
+ ``confidence`` is the confidence of the category values (``Category.confidence``)
20
+ times the quality of the match: 1.0 for a whole word of the name, 0.8 for a part
21
+ of a word, 0.6 for a guess from PBR parameters only. No match gives the MuJoCo
22
+ defaults with confidence 0.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import re
28
+ from collections.abc import Mapping
29
+ from dataclasses import dataclass, field
30
+ from typing import Any
31
+
32
+ from .physics import PhysicsMaterial
33
+ from .sensor import SensorMaterial
34
+
35
+ SOURCES = {
36
+ "et-friction": "https://www.engineeringtoolbox.com/friction-coefficients-d_778.html",
37
+ "et-density": "https://www.engineeringtoolbox.com/density-solids-d_1265.html",
38
+ "wiki-friction": "https://en.wikipedia.org/wiki/Friction#Approximate_coefficients_of_friction",
39
+ "wiki-cor": "https://en.wikipedia.org/wiki/Coefficient_of_restitution",
40
+ }
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Category:
45
+ """Typical values of one material category, with (low, high) ranges."""
46
+
47
+ name: str
48
+ keywords: tuple[str, ...]
49
+ friction: float
50
+ friction_range: tuple[float, float]
51
+ density: float
52
+ density_range: tuple[float, float]
53
+ restitution: float
54
+ restitution_range: tuple[float, float]
55
+ confidence: float
56
+ sources: tuple[str, ...] = ("et-friction", "et-density", "wiki-cor")
57
+ # Sensor assumptions (not from the sources above): diffuse reflectivity at
58
+ # 905 nm and whether LiDAR and depth cameras see through the surface.
59
+ lidar_reflectivity: float = 0.5
60
+ transparent: bool = False
61
+ note: str = ""
62
+
63
+
64
+ CATEGORIES: tuple[Category, ...] = (
65
+ Category(
66
+ "wood",
67
+ (
68
+ "wood",
69
+ "wooden",
70
+ "oak",
71
+ "pine",
72
+ "maple",
73
+ "walnut",
74
+ "birch",
75
+ "plywood",
76
+ "mdf",
77
+ "timber",
78
+ "parquet",
79
+ "bamboo",
80
+ "teak",
81
+ "cherry",
82
+ "ash",
83
+ ),
84
+ 0.4,
85
+ (0.25, 0.5),
86
+ 700,
87
+ (500, 900),
88
+ 0.5,
89
+ (0.4, 0.6),
90
+ 0.6,
91
+ lidar_reflectivity=0.5,
92
+ note="wood on wood, clean and dry; pine 500 to oak 900 kg/m^3",
93
+ ),
94
+ Category(
95
+ "metal",
96
+ (
97
+ "metal",
98
+ "metallic",
99
+ "steel",
100
+ "iron",
101
+ "chrome",
102
+ "stainless",
103
+ "brass",
104
+ "copper",
105
+ "nickel",
106
+ "bronze",
107
+ "tin",
108
+ ),
109
+ 0.6,
110
+ (0.5, 0.8),
111
+ 7850,
112
+ (7700, 8900),
113
+ 0.6,
114
+ (0.5, 0.8),
115
+ 0.6,
116
+ lidar_reflectivity=0.6,
117
+ note="steel on steel, dry; copper and brass reach 8900 kg/m^3",
118
+ ),
119
+ Category(
120
+ "aluminum",
121
+ ("aluminum", "aluminium", "alu", "anodized"),
122
+ 0.6,
123
+ (0.45, 1.05),
124
+ 2700,
125
+ (2640, 2810),
126
+ 0.5,
127
+ (0.4, 0.7),
128
+ 0.6,
129
+ lidar_reflectivity=0.6,
130
+ note="aluminium on steel 0.47-0.61, on aluminium up to 1.05",
131
+ ),
132
+ Category(
133
+ "plastic",
134
+ (
135
+ "plastic",
136
+ "abs",
137
+ "pvc",
138
+ "polypropylene",
139
+ "polyethylene",
140
+ "nylon",
141
+ "polymer",
142
+ "vinyl",
143
+ "pet",
144
+ "polycarbonate",
145
+ "pp",
146
+ "hdpe",
147
+ "pla",
148
+ ),
149
+ 0.35,
150
+ (0.2, 0.5),
151
+ 1050,
152
+ (900, 1400),
153
+ 0.5,
154
+ (0.3, 0.7),
155
+ 0.4,
156
+ lidar_reflectivity=0.4,
157
+ note="polyethylene on steel 0.2, ABS and nylon higher",
158
+ ),
159
+ Category(
160
+ "rubber",
161
+ ("rubber", "silicone", "latex", "tire", "tyre", "neoprene", "elastomer"),
162
+ 0.9,
163
+ (0.6, 1.2),
164
+ 1200,
165
+ (920, 1500),
166
+ 0.7,
167
+ (0.5, 0.9),
168
+ 0.5,
169
+ lidar_reflectivity=0.05,
170
+ note="rubber on dry concrete 0.6-0.85; soft rubber exceeds 1",
171
+ ),
172
+ Category(
173
+ "glass",
174
+ ("glass", "window", "glazing", "crystal", "pyrex"),
175
+ 0.5,
176
+ (0.4, 1.0),
177
+ 2500,
178
+ (2400, 2800),
179
+ 0.6,
180
+ (0.5, 0.7),
181
+ 0.5,
182
+ lidar_reflectivity=0.08,
183
+ transparent=True,
184
+ note="clean glass on glass is 0.9-1.0, any film lowers it; glass on metal 0.5-0.7",
185
+ ),
186
+ Category(
187
+ "fabric",
188
+ (
189
+ "fabric",
190
+ "cloth",
191
+ "textile",
192
+ "cotton",
193
+ "linen",
194
+ "wool",
195
+ "felt",
196
+ "carpet",
197
+ "rug",
198
+ "upholstery",
199
+ "velvet",
200
+ "denim",
201
+ "canvas",
202
+ "towel",
203
+ ),
204
+ 0.5,
205
+ (0.3, 0.7),
206
+ 300,
207
+ (100, 600),
208
+ 0.1,
209
+ (0.0, 0.2),
210
+ 0.3,
211
+ lidar_reflectivity=0.4,
212
+ note="bulk density of folded or padded cloth; the fibre is ~1500",
213
+ ),
214
+ Category(
215
+ "ceramic",
216
+ ("ceramic", "porcelain", "tile", "clay", "terracotta", "stoneware", "earthenware", "china", "mug"),
217
+ 0.5,
218
+ (0.4, 0.7),
219
+ 2400,
220
+ (2000, 2500),
221
+ 0.5,
222
+ (0.3, 0.6),
223
+ 0.5,
224
+ lidar_reflectivity=0.7,
225
+ ),
226
+ Category(
227
+ "stone",
228
+ ("stone", "concrete", "granite", "marble", "cement", "brick", "rock", "slate", "plaster", "asphalt"),
229
+ 0.6,
230
+ (0.5, 0.8),
231
+ 2400,
232
+ (1800, 2800),
233
+ 0.3,
234
+ (0.2, 0.5),
235
+ 0.5,
236
+ lidar_reflectivity=0.3,
237
+ note="concrete 2300-2400, granite and marble 2600-2800, brick 1800",
238
+ ),
239
+ Category(
240
+ "paper",
241
+ ("paper", "cardboard", "carton", "paperboard", "book"),
242
+ 0.4,
243
+ (0.3, 0.5),
244
+ 700,
245
+ (100, 1150),
246
+ 0.2,
247
+ (0.1, 0.4),
248
+ 0.3,
249
+ lidar_reflectivity=0.8,
250
+ note="sheet paper 700-1150; an empty cardboard box is far lighter",
251
+ ),
252
+ Category(
253
+ "foam",
254
+ ("foam", "sponge", "styrofoam", "polystyrene", "eva"),
255
+ 0.7,
256
+ (0.5, 1.0),
257
+ 50,
258
+ (20, 100),
259
+ 0.2,
260
+ (0.1, 0.4),
261
+ 0.3,
262
+ lidar_reflectivity=0.6,
263
+ ),
264
+ Category(
265
+ "leather",
266
+ ("leather", "suede"),
267
+ 0.6,
268
+ (0.4, 0.7),
269
+ 860,
270
+ (800, 950),
271
+ 0.3,
272
+ (0.2, 0.4),
273
+ 0.4,
274
+ lidar_reflectivity=0.2,
275
+ note="leather on wood about 0.6",
276
+ ),
277
+ )
278
+
279
+ # MuJoCo defaults: what an unknown material gets.
280
+ UNKNOWN = Category("unknown", (), 1.0, (0.0, 2.0), 1000, (1, 20000), 0.0, (0.0, 1.0), 0.0, sources=())
281
+
282
+ _WORD = re.compile(r"[A-Z]?[a-z]+|[A-Z]+(?![a-z])|\d+")
283
+
284
+
285
+ @dataclass
286
+ class Inferred:
287
+ """Result of ``infer_physics``."""
288
+
289
+ material: PhysicsMaterial
290
+ category: str
291
+ confidence: float
292
+ matched: str = "" # the keyword or rule that matched
293
+ sources: tuple[str, ...] = ()
294
+ ranges: dict[str, tuple[float, float]] = field(default_factory=dict)
295
+ sensor: SensorMaterial | None = None
296
+
297
+
298
+ def words(name: str) -> list[str]:
299
+ """Lower-case words of a name: ``"OakWood_02.001"`` -> ``["oak", "wood", "02", "001"]``."""
300
+ return [w.lower() for w in _WORD.findall(name or "")]
301
+
302
+
303
+ def match_category(name: str) -> tuple[Category, str, float]:
304
+ """(category, keyword, match quality) for a material name; ``UNKNOWN`` when nothing matches."""
305
+ ws = words(name)
306
+ for cat in CATEGORIES: # whole words first
307
+ for kw in cat.keywords:
308
+ if kw in ws:
309
+ return cat, kw, 1.0
310
+ joined = "".join(ws)
311
+ best: tuple[Category, str] | None = None
312
+ for cat in CATEGORIES: # then a long keyword inside a word ("oakwood")
313
+ for kw in cat.keywords:
314
+ if len(kw) >= 4 and kw in joined and (best is None or len(kw) > len(best[1])):
315
+ best = (cat, kw)
316
+ if best:
317
+ return best[0], best[1], 0.8
318
+ return UNKNOWN, "", 0.0
319
+
320
+
321
+ def _pbr(pbr: Any) -> dict[str, Any]:
322
+ if isinstance(pbr, str):
323
+ return {"name": pbr}
324
+ if isinstance(pbr, Mapping):
325
+ return dict(pbr)
326
+ return {k: getattr(pbr, k) for k in dir(pbr) if not k.startswith("_")}
327
+
328
+
329
+ def _luminance(color: Any) -> float | None:
330
+ if color is None:
331
+ return None
332
+ c = [float(v) for v in list(color)[:3]]
333
+ if max(c) > 1.0:
334
+ c = [v / 255.0 for v in c]
335
+ return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]
336
+
337
+
338
+ def infer_physics(pbr_or_name: Any, name: str | None = None) -> Inferred:
339
+ """Guess a ``PhysicsMaterial`` from a material name or PBR parameters.
340
+
341
+ ``pbr_or_name`` is a name, or a mapping or object with any of ``name``,
342
+ ``base_color`` (RGB or RGBA, 0-1 or 0-255), ``metallic``, ``roughness``,
343
+ ``opacity`` and ``transmission``. The name wins over the PBR rules.
344
+ ``name`` sets the name of the returned material.
345
+ """
346
+ p = _pbr(pbr_or_name)
347
+ cat, matched, quality = match_category(str(p.get("name", "")))
348
+ if cat is UNKNOWN:
349
+ metallic = float(p.get("metallic", 0.0) or 0.0)
350
+ transmission = float(p.get("transmission", 0.0) or 0.0)
351
+ opacity = p.get("opacity")
352
+ if opacity is None and p.get("base_color") is not None and len(list(p["base_color"])) == 4:
353
+ opacity = list(p["base_color"])[3]
354
+ if metallic >= 0.5:
355
+ cat, matched, quality = _cat("metal"), "metallic>=0.5", 0.6
356
+ elif transmission >= 0.5 or (opacity is not None and float(opacity) < 0.5):
357
+ cat, matched, quality = _cat("glass"), "transmission>=0.5 or opacity<0.5", 0.6
358
+ mat = PhysicsMaterial(
359
+ name=name or (cat.name if cat is not UNKNOWN else str(p.get("name") or "default")),
360
+ friction=(cat.friction, 0.005, 0.0001),
361
+ density=cat.density,
362
+ restitution=cat.restitution,
363
+ )
364
+ lum = _luminance(p.get("base_color"))
365
+ reflectivity = cat.lidar_reflectivity
366
+ if lum is not None and not cat.transparent:
367
+ # A dark albedo in the visible band is usually dark at 905 nm too.
368
+ reflectivity = round(min(reflectivity, 0.05 + 0.85 * lum), 3)
369
+ sensor = SensorMaterial(name=mat.name, lidar_reflectivity=reflectivity, transparent=cat.transparent)
370
+ return Inferred(
371
+ material=mat,
372
+ category=cat.name,
373
+ confidence=round(cat.confidence * quality, 3),
374
+ matched=matched,
375
+ sources=tuple(SOURCES[s] for s in cat.sources),
376
+ ranges={
377
+ "friction": cat.friction_range,
378
+ "density": cat.density_range,
379
+ "restitution": cat.restitution_range,
380
+ },
381
+ sensor=sensor,
382
+ )
383
+
384
+
385
+ def _cat(name: str) -> Category:
386
+ return next(c for c in CATEGORIES if c.name == name)
387
+
388
+
389
+ def lookup_table() -> list[dict[str, Any]]:
390
+ """The table as rows (for docs and the editor)."""
391
+ return [
392
+ {
393
+ "category": c.name,
394
+ "keywords": list(c.keywords),
395
+ "friction": c.friction,
396
+ "friction_range": list(c.friction_range),
397
+ "density": c.density,
398
+ "density_range": list(c.density_range),
399
+ "restitution": c.restitution,
400
+ "restitution_range": list(c.restitution_range),
401
+ "confidence": c.confidence,
402
+ "lidar_reflectivity": c.lidar_reflectivity,
403
+ "transparent": c.transparent,
404
+ "sources": [SOURCES[s] for s in c.sources],
405
+ "note": c.note,
406
+ }
407
+ for c in CATEGORIES
408
+ ]