py-materials 3.2.1__tar.gz → 3.4.0__tar.gz
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.
- {py_materials-3.2.1 → py_materials-3.4.0}/PKG-INFO +1 -1
- {py_materials-3.2.1 → py_materials-3.4.0}/pyproject.toml +1 -1
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/__init__.py +68 -1
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/loader.py +11 -2
- py_materials-3.4.0/src/pymat/search.py +154 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/vis/_model.py +64 -0
- py_materials-3.4.0/tests/test_build123d_integration_examples.py +64 -0
- py_materials-3.4.0/tests/test_lookup.py +196 -0
- py_materials-3.4.0/tests/test_search.py +278 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_vis.py +13 -3
- py_materials-3.4.0/tests/test_vis_inheritance.py +309 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/.gitignore +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/LICENSE +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/README.md +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/docs/catalog/README.md +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/docs/catalog/ceramics/README.md +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/docs/catalog/electronics/README.md +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/docs/catalog/gases/README.md +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/docs/catalog/liquids/README.md +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/docs/catalog/metals/README.md +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/docs/catalog/plastics/README.md +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/docs/catalog/scintillators/README.md +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/docs/decisions/README.md +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/mat-rs/data/README.md +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/core.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/data/ceramics.toml +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/data/electronics.toml +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/data/gases.toml +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/data/liquids.toml +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/data/metals.toml +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/data/plastics.toml +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/data/scintillators.toml +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/elements.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/enrichers.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/factories.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/properties.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/registry.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/units.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/vis/__init__.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/src/pymat/vis/adapters.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/__init__.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/_visual_compare.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/baselines/README.md +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/conftest.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/material_preview.html +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_adapters.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_apply_to.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_catalog.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_core.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_e2e_vis.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_enrichers.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_integration.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_loader.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_properties.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_readme_examples.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_toml_integrity.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_uncertainties.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_visual_compare.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/test_visual_regression.py +0 -0
- {py_materials-3.2.1 → py_materials-3.4.0}/tests/visual_render.html +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: py-materials
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.4.0
|
|
4
4
|
Summary: Hierarchical material library for CAD applications with build123d integration
|
|
5
5
|
Project-URL: Homepage, https://github.com/MorePet/py-mat
|
|
6
6
|
Project-URL: Repository, https://github.com/MorePet/py-mat
|
|
@@ -54,9 +54,10 @@ from .properties import (
|
|
|
54
54
|
SourcingProperties,
|
|
55
55
|
ThermalProperties,
|
|
56
56
|
)
|
|
57
|
+
from .search import search
|
|
57
58
|
from .units import ureg
|
|
58
59
|
|
|
59
|
-
__version__ = "3.
|
|
60
|
+
__version__ = "3.4.0" # x-release-please-version
|
|
60
61
|
__all__ = [
|
|
61
62
|
"Material",
|
|
62
63
|
"AllProperties",
|
|
@@ -70,6 +71,7 @@ __all__ = [
|
|
|
70
71
|
"ureg",
|
|
71
72
|
"load_toml",
|
|
72
73
|
"load_category",
|
|
74
|
+
"search",
|
|
73
75
|
"enrich_from_periodictable",
|
|
74
76
|
"enrich_from_matproj",
|
|
75
77
|
"enrich_all",
|
|
@@ -180,6 +182,71 @@ def __getattr__(name: str) -> Material:
|
|
|
180
182
|
raise AttributeError(f"module 'pymat' has no attribute '{name}'")
|
|
181
183
|
|
|
182
184
|
|
|
185
|
+
def _lookup(name_or_key: str) -> Material:
|
|
186
|
+
"""Exact-lookup implementation for ``pymat["..."]``.
|
|
187
|
+
|
|
188
|
+
Resolves ``name_or_key`` against the registered material library via
|
|
189
|
+
``search(..., exact=True)``. Raises ``KeyError`` for empty queries,
|
|
190
|
+
misses, and ambiguous matches — the candidate list is attached to
|
|
191
|
+
the error message so the user can pick.
|
|
192
|
+
|
|
193
|
+
Backing the subscript form (``pymat["Stainless Steel 304"]``) is the
|
|
194
|
+
idiomatic Python-registry pattern (see ``os.environ``, ``sys.modules``,
|
|
195
|
+
``collections.ChainMap``) — raises on miss by convention, unlike
|
|
196
|
+
``dict.get`` which returns None.
|
|
197
|
+
"""
|
|
198
|
+
if not isinstance(name_or_key, str):
|
|
199
|
+
raise TypeError(f"pymat[...] takes a string key or name, got {type(name_or_key).__name__}")
|
|
200
|
+
if not name_or_key.strip():
|
|
201
|
+
raise KeyError("pymat[...] requires a non-empty material name or key; got empty/whitespace")
|
|
202
|
+
|
|
203
|
+
hits = search(name_or_key, exact=True, limit=50)
|
|
204
|
+
if not hits:
|
|
205
|
+
# Offer the closest fuzzy matches so the user can see what was
|
|
206
|
+
# close — far more useful than a bare KeyError.
|
|
207
|
+
fuzzy = search(name_or_key, limit=5)
|
|
208
|
+
if fuzzy:
|
|
209
|
+
suggestions = ", ".join(repr(m.name) for m in fuzzy)
|
|
210
|
+
raise KeyError(
|
|
211
|
+
f"No material matches {name_or_key!r} exactly. "
|
|
212
|
+
f"Close matches: {suggestions}. "
|
|
213
|
+
f"Use pymat.search({name_or_key!r}) for the full fuzzy list."
|
|
214
|
+
)
|
|
215
|
+
raise KeyError(f"No material matches {name_or_key!r}")
|
|
216
|
+
if len(hits) > 1:
|
|
217
|
+
names = ", ".join(repr(m.name) for m in hits[:8])
|
|
218
|
+
raise KeyError(
|
|
219
|
+
f"Ambiguous: {len(hits)} materials match {name_or_key!r} "
|
|
220
|
+
f"(key, name, or grade). Candidates: {names}"
|
|
221
|
+
f"{' …' if len(hits) > 8 else ''}. "
|
|
222
|
+
f"Use a more specific query or index by key."
|
|
223
|
+
)
|
|
224
|
+
return hits[0]
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
# Install module-level __getitem__ so ``pymat["Stainless Steel 304"]`` works.
|
|
228
|
+
# PEP 562 covers module-level __getattr__ but not __getitem__; the standard
|
|
229
|
+
# pattern is to swap the module's __class__ for a subtype of ModuleType that
|
|
230
|
+
# defines __getitem__. Python's import machinery is unaffected.
|
|
231
|
+
import sys as _sys # noqa: E402 — must run after _lookup / Material definitions
|
|
232
|
+
import types as _types # noqa: E402 — same reason
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class _PymatModule(_types.ModuleType):
|
|
236
|
+
def __getitem__(self, key: str) -> Material: # type: ignore[override]
|
|
237
|
+
return _lookup(key)
|
|
238
|
+
|
|
239
|
+
def __contains__(self, key: str) -> bool: # type: ignore[override]
|
|
240
|
+
try:
|
|
241
|
+
_lookup(key)
|
|
242
|
+
except KeyError:
|
|
243
|
+
return False
|
|
244
|
+
return True
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
_sys.modules[__name__].__class__ = _PymatModule
|
|
248
|
+
|
|
249
|
+
|
|
183
250
|
def __dir__() -> list[str]:
|
|
184
251
|
"""
|
|
185
252
|
Help IDE discover available materials.
|
|
@@ -256,12 +256,21 @@ def _resolve_material_node(
|
|
|
256
256
|
_key=key,
|
|
257
257
|
)
|
|
258
258
|
|
|
259
|
-
# Populate vis from
|
|
259
|
+
# Populate vis — inherit from parent, overlay any TOML overrides (#88).
|
|
260
|
+
# A grade TOML with no [vis] section gets a deep-copy of parent's vis;
|
|
261
|
+
# a partial [vis] table overrides individual fields on top of the copy.
|
|
262
|
+
# Root materials (no parent) always get a fresh Vis built from their
|
|
263
|
+
# own [vis] table (or an empty Vis when the table is absent).
|
|
260
264
|
vis_data = data.get("vis")
|
|
265
|
+
parent_vis = parent_material._vis if parent_material is not None else None
|
|
261
266
|
if vis_data and isinstance(vis_data, dict):
|
|
262
267
|
from pymat.vis._model import Vis
|
|
263
268
|
|
|
264
|
-
material._vis = Vis.
|
|
269
|
+
material._vis = Vis.merge_from_toml(parent_vis, vis_data)
|
|
270
|
+
elif parent_vis is not None:
|
|
271
|
+
from copy import deepcopy
|
|
272
|
+
|
|
273
|
+
material._vis = deepcopy(parent_vis)
|
|
265
274
|
|
|
266
275
|
# Register for direct access
|
|
267
276
|
registry.register(key, material)
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Fuzzy search over the py-mat domain library.
|
|
3
|
+
|
|
4
|
+
``pymat.search("stainless 316")`` returns a ranked list of ``Material``
|
|
5
|
+
instances whose registry key, name, grade, or hierarchy path matches
|
|
6
|
+
the query tokens. Complements ``pymat.vis.search(...)`` (visual
|
|
7
|
+
catalog): two axes, same verb, no namespace collision.
|
|
8
|
+
|
|
9
|
+
Algorithm: tokenize query on whitespace; every token must match at
|
|
10
|
+
least one weighted target on a candidate Material for it to be
|
|
11
|
+
included. Score is the sum of per-token best-target weights.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import unicodedata
|
|
17
|
+
from typing import TYPE_CHECKING
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from .core import Material
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _normalize(s: str) -> str:
|
|
24
|
+
"""Normalize a lookup/search input: NFKC + lowercase + collapse whitespace.
|
|
25
|
+
|
|
26
|
+
Picks up pasted curly quotes, em-dashes, non-breaking spaces, and other
|
|
27
|
+
lookalikes that users paste from browser UIs.
|
|
28
|
+
"""
|
|
29
|
+
return " ".join(unicodedata.normalize("NFKC", s).lower().split())
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# Target weights — higher is a stronger match. Order matters: when a
|
|
33
|
+
# query token matches multiple targets on the same Material, the
|
|
34
|
+
# highest-weight hit counts.
|
|
35
|
+
_WEIGHT_KEY = 10 # registry key — "s316L"
|
|
36
|
+
_WEIGHT_NAME = 5 # Material.name — "Stainless Steel 316L"
|
|
37
|
+
_WEIGHT_GRADE = 5 # Material.grade — "316L"
|
|
38
|
+
_WEIGHT_PATH = 3 # hierarchy parent names
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _targets(key: str, material: Material) -> list[tuple[str, int]]:
|
|
42
|
+
"""Return (lowered-target-string, weight) pairs for a Material.
|
|
43
|
+
|
|
44
|
+
Hierarchy path walks ``parent`` up; skips the material's own name
|
|
45
|
+
(already covered by the name target) and any None-named parents.
|
|
46
|
+
"""
|
|
47
|
+
pairs: list[tuple[str, int]] = [(key.lower(), _WEIGHT_KEY)]
|
|
48
|
+
|
|
49
|
+
if material.name:
|
|
50
|
+
pairs.append((material.name.lower(), _WEIGHT_NAME))
|
|
51
|
+
|
|
52
|
+
grade = getattr(material, "grade", None)
|
|
53
|
+
if grade:
|
|
54
|
+
pairs.append((str(grade).lower(), _WEIGHT_GRADE))
|
|
55
|
+
|
|
56
|
+
# Walk the parent chain; skip the material itself (starts from parent).
|
|
57
|
+
parent = getattr(material, "parent", None)
|
|
58
|
+
while parent is not None:
|
|
59
|
+
if parent.name:
|
|
60
|
+
pairs.append((parent.name.lower(), _WEIGHT_PATH))
|
|
61
|
+
parent = getattr(parent, "parent", None)
|
|
62
|
+
|
|
63
|
+
return pairs
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _score(tokens: list[str], targets: list[tuple[str, int]]) -> int:
|
|
67
|
+
"""Score a Material against the query tokens.
|
|
68
|
+
|
|
69
|
+
Every token must substring-match at least one target. Returns 0
|
|
70
|
+
(rejected) if any token misses. Otherwise returns the sum of
|
|
71
|
+
best-per-token weights — so a token matching the high-weight key
|
|
72
|
+
beats a token matching only the low-weight path.
|
|
73
|
+
"""
|
|
74
|
+
total = 0
|
|
75
|
+
for token in tokens:
|
|
76
|
+
best = 0
|
|
77
|
+
for target, weight in targets:
|
|
78
|
+
if token in target and weight > best:
|
|
79
|
+
best = weight
|
|
80
|
+
if best == 0:
|
|
81
|
+
return 0 # token didn't match anywhere → reject
|
|
82
|
+
total += best
|
|
83
|
+
return total
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def search(query: str, *, exact: bool = False, limit: int = 10) -> list[Material]:
|
|
87
|
+
"""Find Materials in the loaded library by name, key, or grade.
|
|
88
|
+
|
|
89
|
+
- **Fuzzy (default)**: tokenize ``query`` on whitespace; every token
|
|
90
|
+
must match somewhere (registry key, ``Material.name``, ``grade``,
|
|
91
|
+
or a hierarchy parent name). Ranked by summed target weight.
|
|
92
|
+
- **Exact** (``exact=True``): the whole normalized query must equal
|
|
93
|
+
the registry key OR ``Material.name`` OR ``Material.grade`` — same
|
|
94
|
+
three targets the fuzzy path uses, but full-string equality. Use
|
|
95
|
+
this to resolve a single known material without the list noise of
|
|
96
|
+
fuzzy mode.
|
|
97
|
+
|
|
98
|
+
Normalization: NFKC + case-fold + whitespace-collapse. Curly quotes,
|
|
99
|
+
em-dashes, non-breaking spaces, leading/trailing and internal-run
|
|
100
|
+
whitespace all fold away before comparison.
|
|
101
|
+
|
|
102
|
+
Returns an empty list for an empty / whitespace-only query.
|
|
103
|
+
|
|
104
|
+
Examples::
|
|
105
|
+
|
|
106
|
+
pymat.search("stainless")
|
|
107
|
+
# → [stainless, s304, s316L, s410, ...]
|
|
108
|
+
|
|
109
|
+
pymat.search("stainless 316")
|
|
110
|
+
# → [s316L] — all tokens must match
|
|
111
|
+
|
|
112
|
+
pymat.search("304", exact=True)
|
|
113
|
+
# → [s304] — grade match, no fuzz
|
|
114
|
+
|
|
115
|
+
pymat.search("Stainless Steel", exact=True)
|
|
116
|
+
# → [stainless] — exact parent name
|
|
117
|
+
|
|
118
|
+
Triggers ``load_all()`` on first call so results are exhaustive
|
|
119
|
+
across categories.
|
|
120
|
+
"""
|
|
121
|
+
normalized = _normalize(query)
|
|
122
|
+
if not normalized:
|
|
123
|
+
return []
|
|
124
|
+
|
|
125
|
+
# Import lazily to avoid circular import at module load: pymat's
|
|
126
|
+
# __init__.py hasn't finished initializing when this module loads.
|
|
127
|
+
from . import load_all, registry
|
|
128
|
+
|
|
129
|
+
load_all()
|
|
130
|
+
all_materials = registry.list_all()
|
|
131
|
+
|
|
132
|
+
scored: list[tuple[int, int, str, Material]] = []
|
|
133
|
+
|
|
134
|
+
if exact:
|
|
135
|
+
# Full-string equality against key / name / grade. Same three
|
|
136
|
+
# targets the fuzzy path cares about.
|
|
137
|
+
for key, material in all_materials.items():
|
|
138
|
+
candidates = [key, material.name or ""]
|
|
139
|
+
grade = getattr(material, "grade", None)
|
|
140
|
+
if grade:
|
|
141
|
+
candidates.append(str(grade))
|
|
142
|
+
if any(_normalize(c) == normalized for c in candidates):
|
|
143
|
+
# Single-match: tie-break by shorter key for determinism.
|
|
144
|
+
scored.append((0, len(key), key, material))
|
|
145
|
+
else:
|
|
146
|
+
tokens = normalized.split()
|
|
147
|
+
for key, material in all_materials.items():
|
|
148
|
+
targets = _targets(key, material)
|
|
149
|
+
s = _score(tokens, targets)
|
|
150
|
+
if s > 0:
|
|
151
|
+
scored.append((-s, len(key), key, material))
|
|
152
|
+
|
|
153
|
+
scored.sort()
|
|
154
|
+
return [m for _, _, _, m in scored[:limit]]
|
|
@@ -531,6 +531,70 @@ class Vis:
|
|
|
531
531
|
|
|
532
532
|
# ── TOML loader ──────────────────────────────────────────────
|
|
533
533
|
|
|
534
|
+
@classmethod
|
|
535
|
+
def merge_from_toml(cls, base: Vis | None, vis_data: dict[str, Any]) -> Vis:
|
|
536
|
+
"""Inherit from ``base`` (parent's Vis), then overlay TOML overrides.
|
|
537
|
+
|
|
538
|
+
Rules:
|
|
539
|
+
|
|
540
|
+
- If ``base`` is None and ``vis_data`` is empty → fresh ``Vis()``.
|
|
541
|
+
- If ``base`` is provided, start with ``deepcopy(base)`` so the child
|
|
542
|
+
inherits identity, finishes, scalars, and the ``_finish`` pick.
|
|
543
|
+
- If ``vis_data`` is provided, overlay its keys on top:
|
|
544
|
+
* ``finishes`` (if set) replaces the inherited map. This is the
|
|
545
|
+
semantically correct call: a grade that declares *any* finishes
|
|
546
|
+
wants its own set, not a concatenation.
|
|
547
|
+
* ``default`` (if set) picks a starting finish from the merged
|
|
548
|
+
map and writes ``source``/``material_id``/``_finish`` from it,
|
|
549
|
+
matching ``from_toml`` behavior.
|
|
550
|
+
* Any PBR scalar in ``vis_data`` overwrites the inherited value.
|
|
551
|
+
* Bare ``source`` / ``material_id`` / ``tier`` keys overwrite
|
|
552
|
+
directly (supports TOML that pins identity without finishes).
|
|
553
|
+
- Cache fields (``_textures``, ``_fetched``) are zeroed by
|
|
554
|
+
``Vis.__post_init__`` regardless.
|
|
555
|
+
|
|
556
|
+
Used by the TOML loader so grades inherit parent vis without needing
|
|
557
|
+
to re-declare identity + scalars. Closes #88.
|
|
558
|
+
"""
|
|
559
|
+
from copy import deepcopy
|
|
560
|
+
|
|
561
|
+
if base is None:
|
|
562
|
+
return cls.from_toml(vis_data or {})
|
|
563
|
+
|
|
564
|
+
merged = deepcopy(base)
|
|
565
|
+
|
|
566
|
+
if not vis_data:
|
|
567
|
+
return merged
|
|
568
|
+
|
|
569
|
+
if "finishes" in vis_data:
|
|
570
|
+
# Re-route through from_toml just for the finishes validation
|
|
571
|
+
# path — it raises on the 3.0 slashed-string form + malformed
|
|
572
|
+
# entries, and we want to keep that guard.
|
|
573
|
+
finishes_only = {"finishes": vis_data["finishes"]}
|
|
574
|
+
if "default" in vis_data:
|
|
575
|
+
finishes_only["default"] = vis_data["default"]
|
|
576
|
+
fresh = cls.from_toml(finishes_only)
|
|
577
|
+
merged.finishes = fresh.finishes
|
|
578
|
+
# If the TOML picked a new default finish, apply it (which will
|
|
579
|
+
# flip source/material_id/_finish through Vis's setters).
|
|
580
|
+
if fresh._finish is not None:
|
|
581
|
+
object.__setattr__(merged, "_finish", fresh._finish)
|
|
582
|
+
merged.source = fresh.source
|
|
583
|
+
merged.material_id = fresh.material_id
|
|
584
|
+
|
|
585
|
+
for field_name in ("source", "material_id", "tier"):
|
|
586
|
+
if field_name in vis_data:
|
|
587
|
+
setattr(merged, field_name, vis_data[field_name])
|
|
588
|
+
|
|
589
|
+
for fname in cls._PBR_SCALAR_FIELDS:
|
|
590
|
+
if fname in vis_data:
|
|
591
|
+
val = vis_data[fname]
|
|
592
|
+
if isinstance(val, list):
|
|
593
|
+
val = tuple(val)
|
|
594
|
+
setattr(merged, fname, val)
|
|
595
|
+
|
|
596
|
+
return merged
|
|
597
|
+
|
|
534
598
|
@classmethod
|
|
535
599
|
def from_toml(cls, vis_data: dict[str, Any]) -> Vis:
|
|
536
600
|
"""Construct from a TOML ``[vis]`` section.
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Execute ``examples/build123d_integration.py`` top-to-bottom as a test.
|
|
2
|
+
|
|
3
|
+
The examples file is a cell-style script (``# %%`` markers) mirroring
|
|
4
|
+
how build123d's author writes his own examples. Running the full script
|
|
5
|
+
in pytest keeps it honest: if any API drifts, the example — which is
|
|
6
|
+
what consumers are copy-pasting — goes red before they do.
|
|
7
|
+
|
|
8
|
+
We shell out via ``runpy.run_path`` rather than splitting cells because
|
|
9
|
+
cell-order matters (later cells use objects defined earlier). The
|
|
10
|
+
network-touching cells catch their own exceptions so a flaky mat-vis
|
|
11
|
+
CDN doesn't redline the whole example suite.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import runpy
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
EXAMPLE_PATH = Path(__file__).parent.parent / "examples" / "build123d_integration.py"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_example_script_runs_end_to_end(capsys):
|
|
23
|
+
"""Every cell in ``examples/build123d_integration.py`` must execute
|
|
24
|
+
without error. Assertions inside the cells are part of the contract
|
|
25
|
+
— this test fails the moment any of them regress."""
|
|
26
|
+
assert EXAMPLE_PATH.exists(), f"missing example: {EXAMPLE_PATH}"
|
|
27
|
+
|
|
28
|
+
# Execute as a fresh script (mimics user running it top-to-bottom).
|
|
29
|
+
# ``runpy.run_path`` gives us an isolated namespace and real exception
|
|
30
|
+
# propagation — unlike ``exec`` which can hide import errors.
|
|
31
|
+
result = runpy.run_path(str(EXAMPLE_PATH), run_name="__main__")
|
|
32
|
+
|
|
33
|
+
# Smoke: the script should have defined the key bindings used in
|
|
34
|
+
# cell 4 / 5 / 6. If a refactor silently drops one of these the
|
|
35
|
+
# test fails with a clean "missing name" rather than a stack trace
|
|
36
|
+
# buried inside runpy.
|
|
37
|
+
for name in ("s304", "housing_mat", "stainless"):
|
|
38
|
+
assert name in result, (
|
|
39
|
+
f"example script didn't define {name!r} — cell order may have drifted"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
# The completion line from the last cell should have reached stdout.
|
|
43
|
+
out = capsys.readouterr().out
|
|
44
|
+
assert "All cells completed." in out, (
|
|
45
|
+
"example script did not reach its final cell — a middle cell likely errored"
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_example_is_up_to_date_with_api():
|
|
50
|
+
"""Guard that the example file references APIs that actually exist.
|
|
51
|
+
Prevents stale copy-paste when module exports change."""
|
|
52
|
+
import pymat
|
|
53
|
+
from pymat import Material, search # noqa: F401 — shape assertions
|
|
54
|
+
|
|
55
|
+
# The cells touch these in order; if any is missing on the public
|
|
56
|
+
# surface the script will fail at import time.
|
|
57
|
+
assert hasattr(pymat, "search")
|
|
58
|
+
assert callable(pymat.search)
|
|
59
|
+
assert callable(getattr(pymat.__class__, "__getitem__", None))
|
|
60
|
+
|
|
61
|
+
# Method-form adapters the example exercises.
|
|
62
|
+
m = Material(name="probe")
|
|
63
|
+
for method in ("to_threejs", "to_gltf", "export_mtlx"):
|
|
64
|
+
assert callable(getattr(m.vis, method)), f"Vis.{method} missing — example will break"
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""Tests for ``pymat["..."]`` exact-lookup + normalization + ambiguity (#89).
|
|
2
|
+
|
|
3
|
+
Before 3.4, resolving an arbitrary user string to one Material required
|
|
4
|
+
handwritten glue (as in build123d#1270). This suite pins:
|
|
5
|
+
|
|
6
|
+
- Subscript access returns a single ``Material`` for exact matches on
|
|
7
|
+
key, ``Material.name``, or ``grade``.
|
|
8
|
+
- Normalization folds: whitespace collapsing, case, NFKC (curly quotes,
|
|
9
|
+
non-breaking space, em-dashes).
|
|
10
|
+
- Empty / whitespace-only / non-string inputs raise cleanly.
|
|
11
|
+
- Missing queries raise ``KeyError`` with fuzzy suggestions.
|
|
12
|
+
- Ambiguous queries raise ``KeyError`` with candidate list.
|
|
13
|
+
- ``in`` operator works (``__contains__``).
|
|
14
|
+
- ``search(..., exact=True)`` mirrors the matching rules.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import pytest
|
|
20
|
+
|
|
21
|
+
import pymat
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@pytest.fixture(autouse=True, scope="module")
|
|
25
|
+
def _load_all_categories():
|
|
26
|
+
"""Force lazy-load of every category so lookup sees the full library."""
|
|
27
|
+
pymat.load_all()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TestSubscriptBasic:
|
|
31
|
+
def test_lookup_by_name(self):
|
|
32
|
+
m = pymat["Stainless Steel 304"]
|
|
33
|
+
assert m.name == "Stainless Steel 304"
|
|
34
|
+
|
|
35
|
+
def test_lookup_by_registry_key(self):
|
|
36
|
+
m = pymat["s304"]
|
|
37
|
+
assert m.name == "Stainless Steel 304"
|
|
38
|
+
|
|
39
|
+
def test_lookup_by_grade(self):
|
|
40
|
+
"""``304`` isn't a registry key (``s304`` is) nor a substring
|
|
41
|
+
of the canonical name alone — but ``Material.grade == "304"``
|
|
42
|
+
makes it a valid exact target."""
|
|
43
|
+
m = pymat["304"]
|
|
44
|
+
assert m.grade == "304"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class TestNormalization:
|
|
48
|
+
def test_leading_trailing_whitespace(self):
|
|
49
|
+
assert pymat[" Stainless Steel 304 "].name == "Stainless Steel 304"
|
|
50
|
+
|
|
51
|
+
def test_internal_whitespace_collapse(self):
|
|
52
|
+
assert pymat["Stainless Steel 304"].name == "Stainless Steel 304"
|
|
53
|
+
|
|
54
|
+
def test_tabs_and_newlines(self):
|
|
55
|
+
assert pymat["Stainless\tSteel\n304"].name == "Stainless Steel 304"
|
|
56
|
+
|
|
57
|
+
def test_case_insensitive(self):
|
|
58
|
+
assert pymat["stainless steel 304"].name == "Stainless Steel 304"
|
|
59
|
+
assert pymat["STAINLESS STEEL 304"].name == "Stainless Steel 304"
|
|
60
|
+
assert pymat["StAiNlEsS sTeEl 304"].name == "Stainless Steel 304"
|
|
61
|
+
|
|
62
|
+
def test_unicode_nbsp(self):
|
|
63
|
+
"""Non-breaking space (U+00A0) folds to regular space via NFKC."""
|
|
64
|
+
assert pymat["Stainless\u00a0Steel\u00a0304"].name == "Stainless Steel 304"
|
|
65
|
+
|
|
66
|
+
def test_unicode_fullwidth_digits(self):
|
|
67
|
+
"""Full-width digits (U+FF10..U+FF19) fold to ASCII via NFKC."""
|
|
68
|
+
# "Stainless Steel 304" — U+FF13 U+FF10 U+FF14
|
|
69
|
+
assert pymat["Stainless Steel \uff13\uff10\uff14"].name == "Stainless Steel 304"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class TestMissingAndAmbiguous:
|
|
73
|
+
def test_missing_raises_key_error(self):
|
|
74
|
+
with pytest.raises(KeyError, match="No material matches"):
|
|
75
|
+
_ = pymat["totally_not_a_material_xyz"]
|
|
76
|
+
|
|
77
|
+
def test_missing_with_close_matches_suggests(self):
|
|
78
|
+
"""A typo-ish query that doesn't exact-match but has close
|
|
79
|
+
fuzzy matches should list them in the error."""
|
|
80
|
+
try:
|
|
81
|
+
_ = pymat["stainles stell 304"] # deliberate typos
|
|
82
|
+
except KeyError as e:
|
|
83
|
+
msg = str(e)
|
|
84
|
+
# Either zero close matches (plain error) or some close
|
|
85
|
+
# matches mentioned — both acceptable, just not silent.
|
|
86
|
+
assert "stainles stell 304" in msg or "No material" in msg
|
|
87
|
+
else:
|
|
88
|
+
pytest.fail("missing material should raise KeyError")
|
|
89
|
+
|
|
90
|
+
def test_unique_parent_returned(self):
|
|
91
|
+
"""``pymat["Stainless"]`` resolves to the parent because its
|
|
92
|
+
key is exactly ``"stainless"`` — that's unambiguous, not a bug."""
|
|
93
|
+
m = pymat["Stainless"]
|
|
94
|
+
assert m.name == "Stainless Steel"
|
|
95
|
+
|
|
96
|
+
def test_ambiguous_would_raise(self):
|
|
97
|
+
"""If a query matches multiple registry entries exactly, the
|
|
98
|
+
error must list candidates. We construct this scenario by
|
|
99
|
+
hand since the shipped library doesn't currently have natural
|
|
100
|
+
exact collisions."""
|
|
101
|
+
from pymat import Material, registry
|
|
102
|
+
|
|
103
|
+
m1 = Material(name="Duplicate Name")
|
|
104
|
+
m2 = Material(name="Duplicate Name")
|
|
105
|
+
try:
|
|
106
|
+
registry.register("dupe_a", m1)
|
|
107
|
+
registry.register("dupe_b", m2)
|
|
108
|
+
with pytest.raises(KeyError, match="Ambiguous.*match"):
|
|
109
|
+
_ = pymat["Duplicate Name"]
|
|
110
|
+
finally:
|
|
111
|
+
# Clean up: remove both to keep the fixture registry stable
|
|
112
|
+
registry._REGISTRY.pop("dupe_a", None)
|
|
113
|
+
registry._REGISTRY.pop("dupe_b", None)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class TestEdgeCases:
|
|
117
|
+
def test_empty_string_raises(self):
|
|
118
|
+
with pytest.raises(KeyError, match="non-empty"):
|
|
119
|
+
_ = pymat[""]
|
|
120
|
+
|
|
121
|
+
def test_whitespace_only_raises(self):
|
|
122
|
+
with pytest.raises(KeyError, match="non-empty"):
|
|
123
|
+
_ = pymat[" \t\n "]
|
|
124
|
+
|
|
125
|
+
def test_non_string_raises_type_error(self):
|
|
126
|
+
with pytest.raises(TypeError):
|
|
127
|
+
_ = pymat[42]
|
|
128
|
+
with pytest.raises(TypeError):
|
|
129
|
+
_ = pymat[None]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class TestContainsOperator:
|
|
133
|
+
def test_contains_true(self):
|
|
134
|
+
assert "Stainless Steel 304" in pymat
|
|
135
|
+
assert "s304" in pymat
|
|
136
|
+
assert "304" in pymat # grade match
|
|
137
|
+
|
|
138
|
+
def test_contains_false(self):
|
|
139
|
+
assert "not a real material xyz" not in pymat
|
|
140
|
+
assert "" not in pymat
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class TestExactSearch:
|
|
144
|
+
"""``search(query, exact=True)`` returns the same matches as the
|
|
145
|
+
subscript form, but as a list (for callers that want to handle
|
|
146
|
+
ambiguity themselves)."""
|
|
147
|
+
|
|
148
|
+
def test_exact_matches_key(self):
|
|
149
|
+
hits = pymat.search("s304", exact=True)
|
|
150
|
+
assert len(hits) == 1
|
|
151
|
+
assert hits[0].name == "Stainless Steel 304"
|
|
152
|
+
|
|
153
|
+
def test_exact_matches_name(self):
|
|
154
|
+
hits = pymat.search("Stainless Steel 304", exact=True)
|
|
155
|
+
assert len(hits) == 1
|
|
156
|
+
|
|
157
|
+
def test_exact_matches_grade(self):
|
|
158
|
+
"""The falsify review flagged that ``search("304", exact=True)``
|
|
159
|
+
used to return ``[]`` because grade wasn't in the exact-target
|
|
160
|
+
set. Fixed to include grade."""
|
|
161
|
+
hits = pymat.search("304", exact=True)
|
|
162
|
+
assert hits, "search('304', exact=True) should match via grade"
|
|
163
|
+
assert any(m.grade == "304" for m in hits)
|
|
164
|
+
|
|
165
|
+
def test_exact_empty_query_returns_empty_list(self):
|
|
166
|
+
assert pymat.search("", exact=True) == []
|
|
167
|
+
assert pymat.search(" ", exact=True) == []
|
|
168
|
+
|
|
169
|
+
def test_exact_normalization(self):
|
|
170
|
+
"""Case + whitespace folding same as subscript form."""
|
|
171
|
+
hits_a = pymat.search("stainless steel 304", exact=True)
|
|
172
|
+
hits_b = pymat.search(" Stainless Steel 304 ", exact=True)
|
|
173
|
+
assert [m.name for m in hits_a] == [m.name for m in hits_b]
|
|
174
|
+
|
|
175
|
+
def test_exact_vs_fuzzy_differ(self):
|
|
176
|
+
"""Exact mode returns ≤ results than fuzzy for the same query."""
|
|
177
|
+
exact = pymat.search("Stainless", exact=True)
|
|
178
|
+
fuzzy = pymat.search("Stainless")
|
|
179
|
+
assert len(exact) <= len(fuzzy)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class TestSearchFuzzyRegression:
|
|
183
|
+
"""The #89 fix adds normalization on the fuzzy path too. Verify
|
|
184
|
+
existing fuzzy tests still work + normalization applies."""
|
|
185
|
+
|
|
186
|
+
def test_fuzzy_whitespace_insensitive(self):
|
|
187
|
+
"""Fuzzy path now normalizes whitespace — extra spaces don't
|
|
188
|
+
break the tokenization."""
|
|
189
|
+
a = pymat.search("stainless 316")
|
|
190
|
+
b = pymat.search(" stainless 316 ")
|
|
191
|
+
assert [m.name for m in a] == [m.name for m in b]
|
|
192
|
+
|
|
193
|
+
def test_fuzzy_case_insensitive_via_normalization(self):
|
|
194
|
+
a = pymat.search("Stainless")
|
|
195
|
+
b = pymat.search("stainless")
|
|
196
|
+
assert [m.name for m in a] == [m.name for m in b]
|