py-materials 3.4.0__tar.gz → 3.6.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.
Files changed (61) hide show
  1. {py_materials-3.4.0 → py_materials-3.6.0}/PKG-INFO +2 -2
  2. {py_materials-3.4.0 → py_materials-3.6.0}/pyproject.toml +2 -2
  3. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/__init__.py +1 -1
  4. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/vis/__init__.py +27 -50
  5. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/vis/_model.py +72 -0
  6. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_e2e_vis.py +86 -0
  7. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_vis.py +62 -114
  8. py_materials-3.6.0/tests/test_vis_override.py +261 -0
  9. {py_materials-3.4.0 → py_materials-3.6.0}/.gitignore +0 -0
  10. {py_materials-3.4.0 → py_materials-3.6.0}/LICENSE +0 -0
  11. {py_materials-3.4.0 → py_materials-3.6.0}/README.md +0 -0
  12. {py_materials-3.4.0 → py_materials-3.6.0}/docs/catalog/README.md +0 -0
  13. {py_materials-3.4.0 → py_materials-3.6.0}/docs/catalog/ceramics/README.md +0 -0
  14. {py_materials-3.4.0 → py_materials-3.6.0}/docs/catalog/electronics/README.md +0 -0
  15. {py_materials-3.4.0 → py_materials-3.6.0}/docs/catalog/gases/README.md +0 -0
  16. {py_materials-3.4.0 → py_materials-3.6.0}/docs/catalog/liquids/README.md +0 -0
  17. {py_materials-3.4.0 → py_materials-3.6.0}/docs/catalog/metals/README.md +0 -0
  18. {py_materials-3.4.0 → py_materials-3.6.0}/docs/catalog/plastics/README.md +0 -0
  19. {py_materials-3.4.0 → py_materials-3.6.0}/docs/catalog/scintillators/README.md +0 -0
  20. {py_materials-3.4.0 → py_materials-3.6.0}/docs/decisions/README.md +0 -0
  21. {py_materials-3.4.0 → py_materials-3.6.0}/mat-rs/data/README.md +0 -0
  22. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/core.py +0 -0
  23. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/data/ceramics.toml +0 -0
  24. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/data/electronics.toml +0 -0
  25. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/data/gases.toml +0 -0
  26. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/data/liquids.toml +0 -0
  27. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/data/metals.toml +0 -0
  28. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/data/plastics.toml +0 -0
  29. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/data/scintillators.toml +0 -0
  30. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/elements.py +0 -0
  31. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/enrichers.py +0 -0
  32. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/factories.py +0 -0
  33. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/loader.py +0 -0
  34. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/properties.py +0 -0
  35. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/registry.py +0 -0
  36. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/search.py +0 -0
  37. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/units.py +0 -0
  38. {py_materials-3.4.0 → py_materials-3.6.0}/src/pymat/vis/adapters.py +0 -0
  39. {py_materials-3.4.0 → py_materials-3.6.0}/tests/__init__.py +0 -0
  40. {py_materials-3.4.0 → py_materials-3.6.0}/tests/_visual_compare.py +0 -0
  41. {py_materials-3.4.0 → py_materials-3.6.0}/tests/baselines/README.md +0 -0
  42. {py_materials-3.4.0 → py_materials-3.6.0}/tests/conftest.py +0 -0
  43. {py_materials-3.4.0 → py_materials-3.6.0}/tests/material_preview.html +0 -0
  44. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_adapters.py +0 -0
  45. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_apply_to.py +0 -0
  46. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_build123d_integration_examples.py +0 -0
  47. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_catalog.py +0 -0
  48. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_core.py +0 -0
  49. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_enrichers.py +0 -0
  50. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_integration.py +0 -0
  51. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_loader.py +0 -0
  52. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_lookup.py +0 -0
  53. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_properties.py +0 -0
  54. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_readme_examples.py +0 -0
  55. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_search.py +0 -0
  56. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_toml_integrity.py +0 -0
  57. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_uncertainties.py +0 -0
  58. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_vis_inheritance.py +0 -0
  59. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_visual_compare.py +0 -0
  60. {py_materials-3.4.0 → py_materials-3.6.0}/tests/test_visual_regression.py +0 -0
  61. {py_materials-3.4.0 → py_materials-3.6.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.4.0
3
+ Version: 3.6.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
@@ -21,7 +21,7 @@ Classifier: Programming Language :: Python :: 3.13
21
21
  Classifier: Topic :: Scientific/Engineering
22
22
  Classifier: Topic :: Scientific/Engineering :: Physics
23
23
  Requires-Python: >=3.10
24
- Requires-Dist: mat-vis-client>=0.5.0
24
+ Requires-Dist: mat-vis-client>=0.6.3
25
25
  Requires-Dist: periodictable>=1.6.0
26
26
  Requires-Dist: pint>=0.20
27
27
  Requires-Dist: tomli>=1.0.0; python_version == '3.10'
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "py-materials"
7
- version = "3.4.0"
7
+ version = "3.6.0"
8
8
  description = "Hierarchical material library for CAD applications with build123d integration"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -31,7 +31,7 @@ dependencies = [
31
31
  "pint>=0.20",
32
32
  "periodictable>=1.6.0",
33
33
  "uncertainties>=3.2",
34
- "mat-vis-client>=0.5.0",
34
+ "mat-vis-client>=0.6.3",
35
35
  "tomli>=1.0.0; python_version == '3.10'",
36
36
  ]
37
37
 
@@ -57,7 +57,7 @@ from .properties import (
57
57
  from .search import search
58
58
  from .units import ureg
59
59
 
60
- __version__ = "3.4.0" # x-release-please-version
60
+ __version__ = "3.6.0" # x-release-please-version
61
61
  __all__ = [
62
62
  "Material",
63
63
  "AllProperties",
@@ -39,6 +39,7 @@ from mat_vis_client import (
39
39
  # Shared-singleton accessor: ``get_client`` became public in
40
40
  # mat-vis-client 0.5.0 (see mat-vis#84). Pinned in pyproject.toml.
41
41
  from mat_vis_client import get_client as _shared_client
42
+ from mat_vis_client import search as _client_search
42
43
 
43
44
  # Material-accepting adapters: Three.js / glTF / MaterialX.
44
45
  # Re-exported at top level so ``from pymat.vis import to_threejs`` works
@@ -71,6 +72,7 @@ def search(
71
72
  roughness: float | None = None,
72
73
  metalness: float | None = None,
73
74
  source: str | None = None,
75
+ tier: str = "1k",
74
76
  limit: int = 20,
75
77
  ) -> list[dict[str, Any]]:
76
78
  """Search the mat-vis index by category, tags, and scalar similarity.
@@ -78,60 +80,35 @@ def search(
78
80
  Args:
79
81
  category: filter by canonical category (metal, wood, stone, ...)
80
82
  tags: require ALL these tags to be present in the entry's tags list
81
- roughness / metalness: score by scalar distance (if set in index)
83
+ roughness / metalness: score by scalar distance (widened ±0.2)
82
84
  source: limit to one source
85
+ tier: only return entries that have this tier available (default 1k);
86
+ scalar-only sources (e.g. physicallybased) are tier-independent
83
87
  limit: max results
84
88
 
85
- Does NOT filter by tier — search is for finding materials,
86
- tier is a fetch-time concern.
89
+ Thin forwarder to ``mat_vis_client.search`` for the category / scalar /
90
+ tier / scoring path; adds the ``tags`` post-filter (not in upstream).
91
+
92
+ Index entries follow the mat-vis 0.6.x schema: scalars and category
93
+ live under ``entry["mat_vis"]["category"]`` / ``["pbr"]["roughness"]``.
87
94
  """
88
- client = _shared_client()
89
-
90
- roughness_range = None
91
- if roughness is not None:
92
- roughness_range = (max(0.0, roughness - 0.2), min(1.0, roughness + 0.2))
93
-
94
- metalness_range = None
95
- if metalness is not None:
96
- metalness_range = (max(0.0, metalness - 0.2), min(1.0, metalness + 0.2))
97
-
98
- required_tags = set(t.lower() for t in (tags or []))
99
-
100
- # Search all sources, no tier filter
101
- sources = [source] if source else client.sources()
102
- results: list[dict] = []
103
- for src in sources:
104
- try:
105
- for entry in client.index(src):
106
- if category and entry.get("category") != category:
107
- continue
108
- entry_tags = set(t.lower() for t in entry.get("tags", []))
109
- if required_tags and not required_tags.issubset(entry_tags):
110
- continue
111
- if roughness_range and not (
112
- entry.get("roughness") is not None
113
- and roughness_range[0] <= entry["roughness"] <= roughness_range[1]
114
- ):
115
- continue
116
- if metalness_range and not (
117
- entry.get("metalness") is not None
118
- and metalness_range[0] <= entry["metalness"] <= metalness_range[1]
119
- ):
120
- continue
121
- results.append(entry)
122
- except Exception:
123
- continue
124
-
125
- # Score by scalar distance
126
- for r in results:
127
- score = 0.0
128
- if roughness is not None and r.get("roughness") is not None:
129
- score += abs(r["roughness"] - roughness)
130
- if metalness is not None and r.get("metalness") is not None:
131
- score += abs(r["metalness"] - metalness)
132
- r["score"] = score
133
-
134
- results.sort(key=lambda r: r["score"])
95
+ results = _client_search(
96
+ category=category,
97
+ roughness=roughness,
98
+ metalness=metalness,
99
+ source=source,
100
+ tier=tier,
101
+ limit=None, # apply limit after tags post-filter
102
+ )
103
+
104
+ if tags:
105
+ required = {t.lower() for t in tags}
106
+ results = [
107
+ e
108
+ for e in results
109
+ if required.issubset({t.lower() for t in (e.get("mat_vis") or {}).get("tags") or []})
110
+ ]
111
+
135
112
  return results[:limit]
136
113
 
137
114
 
@@ -315,6 +315,78 @@ class Vis:
315
315
  super().__setattr__("_textures", {})
316
316
  super().__setattr__("_fetched", False)
317
317
 
318
+ def override(self, **deltas: Any) -> Vis:
319
+ """Return a new ``Vis`` with the given deltas applied; ``self``
320
+ is unchanged.
321
+
322
+ Use this when deriving a tweaked variant from a base Vis —
323
+ typically the registry instance returned by ``pymat["..."]``.
324
+ The registry instance is shared across all callers, so direct
325
+ mutation corrupts every other consumer of the same material::
326
+
327
+ steel = pymat["Stainless Steel 304"]
328
+ polished = steel.vis.override(roughness=0.3, finish="polished")
329
+ # steel.vis is unchanged; polished is independent.
330
+
331
+ The ``finishes`` dict is deep-copied so child mutations don't
332
+ propagate to the parent (matches ``merge_from_toml`` semantics
333
+ and closes the registry-mutation hazard that motivated this
334
+ method).
335
+
336
+ Identity deltas (``source`` / ``material_id`` / ``tier``) route
337
+ through :meth:`set_identity` for atomic invalidation. If
338
+ identity changes without an explicit ``finish=``, the inherited
339
+ ``_finish`` label is cleared — it would otherwise be stale,
340
+ pointing at a finish whose entry no longer matches the new
341
+ identity.
342
+
343
+ Unknown kwargs raise ``TypeError`` — catches typos like
344
+ ``roughnes=0.5`` that ``dataclasses.replace`` would accept
345
+ silently.
346
+ """
347
+ from copy import deepcopy
348
+ from dataclasses import fields
349
+
350
+ # Public dataclass fields (excludes _textures, _fetched, _finish)
351
+ # plus the ``finish`` property — the canonical override surface.
352
+ valid_fields = {f.name for f in fields(self) if not f.name.startswith("_")}
353
+ valid_keys = valid_fields | {"finish"}
354
+ unknown = set(deltas) - valid_keys
355
+ if unknown:
356
+ raise TypeError(
357
+ f"Vis.override() got unexpected kwargs: {sorted(unknown)}. "
358
+ f"Valid keys: {sorted(valid_keys)}"
359
+ )
360
+
361
+ new = deepcopy(self)
362
+
363
+ # ``finish`` is a property setter (not a field) and must be
364
+ # applied LAST so it resolves against the new instance's
365
+ # (deep-copied) finishes map.
366
+ finish_delta = deltas.pop("finish", None)
367
+
368
+ # Identity-pair updates: route through set_identity for atomic
369
+ # cache invalidation. Compute "changing" from the original
370
+ # values before pop so a no-op (same value) doesn't trigger
371
+ # the stale-_finish clear below.
372
+ identity_keys = {"source", "material_id", "tier"} & deltas.keys()
373
+ identity_changing = any(deltas[k] != getattr(new, k) for k in identity_keys)
374
+ if identity_keys:
375
+ new.set_identity(**{k: deltas.pop(k) for k in list(identity_keys)})
376
+
377
+ for k, v in deltas.items():
378
+ setattr(new, k, v)
379
+
380
+ # Identity moved without an explicit finish= → the inherited
381
+ # _finish label is now stale.
382
+ if identity_changing and finish_delta is None:
383
+ super(Vis, new).__setattr__("_finish", None)
384
+
385
+ if finish_delta is not None:
386
+ new.finish = finish_delta
387
+
388
+ return new
389
+
318
390
  @property
319
391
  def client(self) -> MatVisClient:
320
392
  """The shared ``mat-vis-client`` singleton.
@@ -277,6 +277,92 @@ class TestEndToEnd:
277
277
  assert rc.texture[:4] == b"\x89PNG"
278
278
 
279
279
 
280
+ @pytest.mark.skipif(SKIP_LIVE, reason="MAT_VIS_SKIP_LIVE=1")
281
+ class TestGpuopenNameLookup:
282
+ """Human-readable name access for gpuopen materials.
283
+
284
+ Bernhard (build123d#1270) flagged gpuopen UX as UUID-only — see
285
+ mat-vis#143. mat-vis-client 0.6.3 fixed this upstream:
286
+ ``MatVisClient._resolve_material_id`` accepts either canonical id
287
+ (UUID for gpuopen) or a normalized human-readable name from
288
+ ``mat_vis.name`` in the index, and ``fetch_all_textures`` / ``mtlx``
289
+ call into it.
290
+
291
+ These tests pin: ``Vis.material_id`` set to a human-readable name
292
+ flows through to fetch + mtlx without py-mat needing to know about
293
+ the resolution. If mat-vis-client ever drops name-based lookup,
294
+ these go red and we know the consumer-facing UX regressed.
295
+ """
296
+
297
+ PORTORO_NAME = "Portoro Green Marble"
298
+ PORTORO_UUID = "1f95c1cc-b0db-40b8-928c-775c0fc1228c"
299
+
300
+ def test_resolve_via_client(self):
301
+ """Direct upstream check — proves the index has the name."""
302
+ from mat_vis_client import get_client
303
+
304
+ c = get_client()
305
+ with _skip_on_upstream_outage():
306
+ canonical = c._resolve_material_id("gpuopen", self.PORTORO_NAME, "1k")
307
+ assert canonical == self.PORTORO_UUID
308
+
309
+ def test_vis_fetch_textures_by_name(self):
310
+ """Set ``vis.material_id`` to the human-readable name; texture
311
+ fetch resolves it transparently."""
312
+ from pymat import Material
313
+
314
+ m = Material(name="Portoro probe")
315
+ m.vis.source = "gpuopen"
316
+ m.vis.material_id = self.PORTORO_NAME
317
+ m.vis.tier = "1k"
318
+
319
+ with _skip_on_upstream_outage():
320
+ tx = m.vis.textures
321
+
322
+ assert tx, "no textures returned for gpuopen name lookup"
323
+ assert all(v[:4] == b"\x89PNG" for v in tx.values()), "non-PNG bytes"
324
+
325
+ def test_vis_mtlx_by_name(self):
326
+ """``Vis.mtlx`` resolves the name → MaterialX XML."""
327
+ from pymat import Material
328
+
329
+ m = Material(name="Portoro mtlx probe")
330
+ m.vis.source = "gpuopen"
331
+ m.vis.material_id = self.PORTORO_NAME
332
+ m.vis.tier = "1k"
333
+
334
+ with _skip_on_upstream_outage():
335
+ xml = m.vis.mtlx.xml()
336
+
337
+ assert isinstance(xml, str)
338
+ assert len(xml) > 200, f"suspiciously short MaterialX ({len(xml)} chars)"
339
+ assert "<materialx" in xml.lower() or xml.startswith("<?xml")
340
+
341
+ def test_unknown_name_raises_typed_error(self):
342
+ """Bad name → ``UnknownMaterialError``, not silent garbage."""
343
+ from mat_vis_client import UnknownMaterialError, get_client
344
+
345
+ c = get_client()
346
+ with _skip_on_upstream_outage():
347
+ with pytest.raises(UnknownMaterialError):
348
+ c._resolve_material_id("gpuopen", "Definitely Not A Material", "1k")
349
+
350
+ def test_canonical_uuid_still_works(self):
351
+ """Backwards-compat: existing UUID-based callers (and our TOML)
352
+ keep working unchanged."""
353
+ from pymat import Material
354
+
355
+ m = Material(name="Portoro UUID probe")
356
+ m.vis.source = "gpuopen"
357
+ m.vis.material_id = self.PORTORO_UUID
358
+ m.vis.tier = "1k"
359
+
360
+ with _skip_on_upstream_outage():
361
+ tx = m.vis.textures
362
+
363
+ assert tx, "UUID lookup broke"
364
+
365
+
280
366
  class TestSkipOnUpstreamOutage:
281
367
  """The flake-guard itself — tested without hitting the network."""
282
368
 
@@ -752,46 +752,45 @@ class TestVisModuleApi:
752
752
 
753
753
  manifest = vis.get_manifest()
754
754
  assert "release_tag" in manifest
755
- assert "tiers" in manifest
755
+ # mat-vis 0.6.x manifest: schema_version=3, top-level "sources" map
756
+ # (tier coverage moved under sources[*].tiers)
757
+ assert "sources" in manifest
756
758
 
757
759
  def test_search_with_mock(self, monkeypatch):
758
- """Search against a mock client (no network)."""
759
- import mat_vis_client as _client
760
+ """Search delegates to mat_vis_client.search (forwarder).
760
761
 
762
+ Patches the imported ``_client_search`` reference inside
763
+ ``pymat.vis`` so we don't need a real client / network.
764
+ """
761
765
  from pymat import vis
762
766
 
763
767
  mock_results = [
764
768
  {
765
769
  "id": "Metal001",
766
770
  "source": "ambientcg",
767
- "category": "metal",
768
- "roughness": 0.3,
769
- "metalness": 1.0,
771
+ "mat_vis": {
772
+ "category": "metal",
773
+ "tags": ["brushed", "silver"],
774
+ "pbr": {"roughness": 0.3, "metalness": 1.0},
775
+ },
770
776
  },
771
777
  ]
772
778
 
773
- class MockClient:
774
- def __init__(self, **kw):
775
- pass
779
+ captured: dict = {}
776
780
 
777
- @property
778
- def manifest(self):
779
- return {"release_tag": "mock", "tiers": {}}
780
-
781
- def sources(self, tier="1k"):
782
- return ["ambientcg"]
783
-
784
- def index(self, source):
785
- return mock_results
781
+ def fake_search(**kw):
782
+ captured.update(kw)
783
+ return mock_results
786
784
 
787
- def search(self, **kw):
788
- return mock_results
789
-
790
- monkeypatch.setattr(_client, "_client", MockClient())
785
+ monkeypatch.setattr(vis, "_client_search", fake_search)
791
786
 
792
787
  results = vis.search(category="metal")
793
- assert len(results) >= 1
788
+ assert len(results) == 1
794
789
  assert results[0]["id"] == "Metal001"
790
+ # Forwarder must request unbounded results then apply our limit
791
+ # locally, so the tags post-filter sees the full set.
792
+ assert captured["category"] == "metal"
793
+ assert captured["limit"] is None
795
794
 
796
795
  def test_rowmap_entry_missing_material_raises(self, monkeypatch):
797
796
  import mat_vis_client as _client
@@ -814,125 +813,74 @@ class TestVisModuleApi:
814
813
  with pytest.raises(KeyError, match="NotExist"):
815
814
  vis.rowmap_entry("ambientcg", "NotExist")
816
815
 
817
- def test_search_filters_and_scores(self, monkeypatch):
818
- """Exercises tag-subset, roughness-range, metalness-range, scoring."""
819
- import mat_vis_client as _client
816
+ def test_search_tags_post_filter(self, monkeypatch):
817
+ """Tags filter is applied locally on top of upstream search.
820
818
 
819
+ Category / scalar / tier filtering and scoring are upstream's job
820
+ (covered in mat-vis-client's own test suite). All we need to
821
+ verify here is the ``tags`` AND-subset post-filter and that the
822
+ ``limit`` is applied AFTER filtering — not before.
823
+ """
821
824
  from pymat import vis
822
825
 
826
+ # Mock returns 3 metal entries; only one has both required tags.
823
827
  rows = [
824
- # matches all filters (brushed + silver tags, rough 0.3, met 1.0)
825
828
  {
826
829
  "id": "A",
827
830
  "source": "ambientcg",
828
- "category": "metal",
829
- "tags": ["brushed", "silver", "steel"],
830
- "roughness": 0.3,
831
- "metalness": 1.0,
831
+ "mat_vis": {"category": "metal", "tags": ["brushed", "silver", "steel"]},
832
832
  },
833
- # wrong tags (missing brushed) → filtered out
834
833
  {
835
834
  "id": "B",
836
835
  "source": "ambientcg",
837
- "category": "metal",
838
- "tags": ["silver"],
839
- "roughness": 0.3,
840
- "metalness": 1.0,
836
+ "mat_vis": {"category": "metal", "tags": ["silver"]}, # no brushed
841
837
  },
842
- # roughness out of range → filtered out
843
838
  {
844
839
  "id": "C",
845
840
  "source": "ambientcg",
846
- "category": "metal",
847
- "tags": ["brushed", "silver"],
848
- "roughness": 0.9,
849
- "metalness": 1.0,
850
- },
851
- # metalness out of range → filtered out
852
- {
853
- "id": "D",
854
- "source": "ambientcg",
855
- "category": "metal",
856
- "tags": ["brushed", "silver"],
857
- "roughness": 0.3,
858
- "metalness": 0.0,
859
- },
860
- # wrong category → filtered out
861
- {
862
- "id": "E",
863
- "source": "ambientcg",
864
- "category": "wood",
865
- "tags": ["brushed", "silver"],
866
- "roughness": 0.3,
867
- "metalness": 1.0,
868
- },
869
- # matches but scores higher (roughness distance > A's)
870
- {
871
- "id": "F",
872
- "source": "ambientcg",
873
- "category": "metal",
874
- "tags": ["brushed", "silver"],
875
- "roughness": 0.45,
876
- "metalness": 1.0,
841
+ "mat_vis": {"category": "metal", "tags": ["brushed", "silver"]},
877
842
  },
878
843
  ]
879
844
 
880
- class MockClient:
881
- def __init__(self, **kw):
882
- pass
883
-
884
- @property
885
- def manifest(self):
886
- return {"release_tag": "mock", "tiers": {}}
887
-
888
- def sources(self, tier="1k"):
889
- return ["ambientcg"]
890
-
891
- def index(self, source):
892
- return rows
893
-
894
- monkeypatch.setattr(_client, "_client", MockClient())
845
+ monkeypatch.setattr(vis, "_client_search", lambda **kw: rows)
895
846
 
896
- results = vis.search(
897
- category="metal",
898
- tags=["brushed", "silver"],
899
- roughness=0.3,
900
- metalness=1.0,
901
- )
847
+ results = vis.search(category="metal", tags=["brushed", "silver"])
902
848
  ids = [r["id"] for r in results]
903
- assert ids[0] == "A" # perfect-score entry sorts first
904
- assert "F" in ids # matches filters, ranks lower
905
- assert "B" not in ids # missing brushed tag
906
- assert "C" not in ids # roughness out of ±0.2 range
907
- assert "D" not in ids # metalness out of ±0.2 range
908
- assert "E" not in ids # wrong category
909
-
910
- def test_search_source_iteration_swallows_index_errors(self, monkeypatch):
911
- """A broken source is skipped instead of failing the whole query."""
912
- import mat_vis_client as _client
849
+ assert ids == ["A", "C"] # B filtered out (missing brushed)
913
850
 
851
+ def test_search_tags_missing_key_excluded(self, monkeypatch):
852
+ """Entry with no tags key never satisfies a tags requirement."""
914
853
  from pymat import vis
915
854
 
916
- class MockClient:
917
- def __init__(self, **kw):
918
- pass
855
+ rows = [
856
+ {"id": "A", "source": "ambientcg", "mat_vis": {"category": "metal"}},
857
+ {
858
+ "id": "B",
859
+ "source": "ambientcg",
860
+ "mat_vis": {"category": "metal", "tags": ["matte"]},
861
+ },
862
+ ]
863
+ monkeypatch.setattr(vis, "_client_search", lambda **kw: rows)
919
864
 
920
- @property
921
- def manifest(self):
922
- return {"release_tag": "mock", "tiers": {}}
865
+ results = vis.search(tags=["matte"])
866
+ assert [r["id"] for r in results] == ["B"]
867
+
868
+ def test_search_limit_applied_after_tags(self, monkeypatch):
869
+ """Limit must clamp the final list, not the upstream call."""
870
+ from pymat import vis
923
871
 
924
- def sources(self, tier="1k"):
925
- return ["ambientcg", "broken"]
872
+ rows = [{"id": str(i), "source": "x", "mat_vis": {"tags": ["t"]}} for i in range(50)]
873
+ captured: dict = {}
926
874
 
927
- def index(self, source):
928
- if source == "broken":
929
- raise RuntimeError("source index missing")
930
- return [{"id": "ok", "source": "ambientcg", "category": "metal"}]
875
+ def fake_search(**kw):
876
+ captured.update(kw)
877
+ return rows
931
878
 
932
- monkeypatch.setattr(_client, "_client", MockClient())
879
+ monkeypatch.setattr(vis, "_client_search", fake_search)
933
880
 
934
- results = vis.search(category="metal")
935
- assert [r["id"] for r in results] == ["ok"]
881
+ results = vis.search(tags=["t"], limit=5)
882
+ assert len(results) == 5
883
+ assert captured["limit"] is None # we pass None upstream
936
884
 
937
885
  def test_client_factory(self, monkeypatch):
938
886
  """vis.client() returns the lazy-initialized shared client."""
@@ -0,0 +1,261 @@
1
+ """Tests for ``Vis.override(**deltas)`` — immutable derive helper.
2
+
3
+ The motivating bug: ``pymat["Stainless Steel 304"]`` returns the
4
+ *registry singleton*, so ``m.vis.roughness = 0.6`` in one caller is
5
+ visible to every other caller of the same key. ``override`` returns a
6
+ deep-copied variant so consumers can derive tweaked Vis instances
7
+ without corrupting the shared registry entry.
8
+
9
+ Pinned semantics:
10
+
11
+ - Returns a new instance; original unchanged in every field.
12
+ - ``finishes`` dict deep-copied (no shared-reference hazard).
13
+ - Identity deltas route through ``set_identity`` (atomic invalidation).
14
+ - ``finish=`` is special-cased (it's a property, not a field) and
15
+ applied LAST against the deep-copied finishes map.
16
+ - Identity change without ``finish=`` clears stale ``_finish`` label.
17
+ - Unknown kwargs raise ``TypeError`` (typo protection).
18
+ - Cache state preserved when identity unchanged; cleared otherwise.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import pytest
24
+
25
+ from pymat.vis._model import Vis
26
+
27
+
28
+ def _base() -> Vis:
29
+ return Vis(
30
+ source="ambientcg",
31
+ material_id="Metal012",
32
+ tier="1k",
33
+ finishes={
34
+ "brushed": {"source": "ambientcg", "id": "Metal012"},
35
+ "polished": {"source": "ambientcg", "id": "Metal049A"},
36
+ },
37
+ roughness=0.3,
38
+ metallic=1.0,
39
+ base_color=(0.75, 0.75, 0.77, 1.0),
40
+ )
41
+
42
+
43
+ class TestOverrideReturnsNewInstance:
44
+ def test_returns_new_object(self):
45
+ v = _base()
46
+ v2 = v.override(roughness=0.6)
47
+ assert v2 is not v
48
+
49
+ def test_original_scalars_unchanged(self):
50
+ v = _base()
51
+ v.override(roughness=0.6, metallic=0.0)
52
+ assert v.roughness == 0.3
53
+ assert v.metallic == 1.0
54
+
55
+ def test_original_identity_unchanged(self):
56
+ v = _base()
57
+ v.override(source="polyhaven", material_id="custom_01")
58
+ assert v.source == "ambientcg"
59
+ assert v.material_id == "Metal012"
60
+
61
+ def test_no_deltas_returns_independent_copy(self):
62
+ """``override()`` with no kwargs is still a deep-copy."""
63
+ v = _base()
64
+ v2 = v.override()
65
+ assert v2 is not v
66
+ assert v2 == v
67
+ assert v2.finishes is not v.finishes
68
+
69
+
70
+ class TestFinishesDeepCopy:
71
+ """The headline correctness fix — finishes must not share a dict."""
72
+
73
+ def test_finishes_is_independent(self):
74
+ v = _base()
75
+ v2 = v.override(roughness=0.6)
76
+ assert v.finishes is not v2.finishes
77
+
78
+ def test_child_mutates_finishes_parent_unaffected(self):
79
+ v = _base()
80
+ v2 = v.override()
81
+ v2.finishes["matte"] = {"source": "ambientcg", "id": "Metal099"}
82
+ assert "matte" in v2.finishes
83
+ assert "matte" not in v.finishes
84
+
85
+ def test_child_mutates_finish_entry_parent_unaffected(self):
86
+ """Even nested dict values are deep-copied."""
87
+ v = _base()
88
+ v2 = v.override()
89
+ v2.finishes["brushed"]["source"] = "polyhaven"
90
+ assert v.finishes["brushed"]["source"] == "ambientcg"
91
+
92
+
93
+ class TestScalarOverride:
94
+ def test_single_scalar(self):
95
+ v = _base()
96
+ v2 = v.override(roughness=0.6)
97
+ assert v2.roughness == 0.6
98
+
99
+ def test_multiple_scalars(self):
100
+ v = _base()
101
+ v2 = v.override(roughness=0.6, metallic=0.5, ior=1.4)
102
+ assert (v2.roughness, v2.metallic, v2.ior) == (0.6, 0.5, 1.4)
103
+
104
+ def test_identity_preserved_on_scalar_override(self):
105
+ v = _base()
106
+ v2 = v.override(roughness=0.6)
107
+ assert v2.source == "ambientcg"
108
+ assert v2.material_id == "Metal012"
109
+ assert v2.tier == "1k"
110
+
111
+ def test_finish_label_preserved_on_scalar_override(self):
112
+ """Pure scalar tweak should not clear the inherited finish."""
113
+ v = _base()
114
+ v.finish = "polished"
115
+ v2 = v.override(roughness=0.6)
116
+ assert v2._finish == "polished"
117
+
118
+
119
+ class TestIdentityOverride:
120
+ def test_source_change(self):
121
+ v = _base()
122
+ v2 = v.override(source="polyhaven")
123
+ assert v2.source == "polyhaven"
124
+ assert v2.material_id == "Metal012" # unchanged
125
+
126
+ def test_full_identity_swap(self):
127
+ v = _base()
128
+ v2 = v.override(source="polyhaven", material_id="metal_01", tier="2k")
129
+ assert (v2.source, v2.material_id, v2.tier) == ("polyhaven", "metal_01", "2k")
130
+
131
+ def test_identity_change_clears_stale_finish(self):
132
+ """If user moves identity without specifying a finish, the
133
+ inherited ``_finish`` label is now meaningless — clear it."""
134
+ v = _base()
135
+ v.finish = "polished"
136
+ assert v._finish == "polished"
137
+ v2 = v.override(source="polyhaven", material_id="custom_01")
138
+ assert v2._finish is None
139
+
140
+ def test_identity_no_op_preserves_finish(self):
141
+ """If identity 'change' is actually a no-op, don't clear finish."""
142
+ v = _base()
143
+ v.finish = "polished"
144
+ v2 = v.override(source="ambientcg") # same value
145
+ assert v2._finish == "polished"
146
+
147
+ def test_identity_change_invalidates_cache(self):
148
+ """Cache must be empty/unfetched after identity change."""
149
+ v = _base()
150
+ v._textures = {"color": b"\x89PNG_fake"}
151
+ v._fetched = True
152
+ v2 = v.override(source="polyhaven")
153
+ assert v2._textures == {}
154
+ assert v2._fetched is False
155
+
156
+ def test_no_identity_change_preserves_cache(self):
157
+ """Pure scalar override → cache is still valid for the same
158
+ identity, so deep-copy preserves it (deepcopy doesn't trip
159
+ ``__post_init__``)."""
160
+ v = _base()
161
+ v._textures = {"color": b"\x89PNG_fake"}
162
+ v._fetched = True
163
+ v2 = v.override(roughness=0.6)
164
+ assert v2._textures == {"color": b"\x89PNG_fake"}
165
+ assert v2._fetched is True
166
+
167
+
168
+ class TestFinishDelta:
169
+ def test_finish_applied(self):
170
+ v = _base()
171
+ v2 = v.override(finish="polished")
172
+ assert v2._finish == "polished"
173
+ assert v2.material_id == "Metal049A"
174
+ assert v2.source == "ambientcg"
175
+
176
+ def test_finish_against_deep_copied_map(self):
177
+ """Mutating child finishes after override doesn't affect parent's
178
+ finish lookup."""
179
+ v = _base()
180
+ v2 = v.override(finish="polished")
181
+ v2.finishes["polished"]["id"] = "TamperedID"
182
+ # Parent's polished entry still untouched
183
+ assert v.finishes["polished"]["id"] == "Metal049A"
184
+
185
+ def test_unknown_finish_raises(self):
186
+ v = _base()
187
+ with pytest.raises(ValueError, match="Unknown finish"):
188
+ v.override(finish="mirror")
189
+
190
+ def test_finish_combined_with_scalars(self):
191
+ v = _base()
192
+ v2 = v.override(finish="polished", roughness=0.1)
193
+ assert v2._finish == "polished"
194
+ assert v2.roughness == 0.1
195
+ assert v2.material_id == "Metal049A"
196
+
197
+ def test_finish_wins_over_explicit_identity(self):
198
+ """If user passes both ``source=`` and ``finish=``, finish runs
199
+ last and wins. Documented behavior — same as merge_from_toml."""
200
+ v = _base()
201
+ v2 = v.override(source="polyhaven", finish="polished")
202
+ # finish=polished is from finishes map (ambientcg/Metal049A)
203
+ assert v2.source == "ambientcg"
204
+ assert v2.material_id == "Metal049A"
205
+ assert v2._finish == "polished"
206
+
207
+
208
+ class TestUnknownKwargs:
209
+ def test_typo_raises_typeerror(self):
210
+ v = _base()
211
+ with pytest.raises(TypeError, match="roughnes"):
212
+ v.override(roughnes=0.5)
213
+
214
+ def test_internal_field_rejected(self):
215
+ """Don't let consumers reach into private state."""
216
+ v = _base()
217
+ with pytest.raises(TypeError):
218
+ v.override(_textures={})
219
+
220
+ def test_error_lists_valid_keys(self):
221
+ v = _base()
222
+ with pytest.raises(TypeError, match="Valid keys"):
223
+ v.override(unknown_field=42)
224
+
225
+
226
+ class TestRegistryMutationHazardFixed:
227
+ """The motivating user story: derive a polished steel without
228
+ corrupting the registry instance other callers see."""
229
+
230
+ def test_polished_variant_does_not_touch_registry(self):
231
+ import pymat
232
+
233
+ steel = pymat["Stainless Steel 304"]
234
+ original_finish = steel.vis._finish
235
+ original_roughness = steel.vis.roughness
236
+ original_mid = steel.vis.material_id
237
+
238
+ polished = steel.vis.override(finish="polished", roughness=0.1)
239
+
240
+ # Variant has the changes
241
+ assert polished._finish == "polished"
242
+ assert polished.roughness == 0.1
243
+ assert polished.material_id != original_mid
244
+
245
+ # Registry instance unchanged
246
+ assert steel.vis._finish == original_finish
247
+ assert steel.vis.roughness == original_roughness
248
+ assert steel.vis.material_id == original_mid
249
+
250
+ def test_two_variants_dont_cross_contaminate(self):
251
+ import pymat
252
+
253
+ steel = pymat["Stainless Steel 304"]
254
+ a = steel.vis.override(roughness=0.2)
255
+ b = steel.vis.override(roughness=0.8)
256
+ a.finishes["custom_a"] = {"source": "x", "id": "a"}
257
+ b.finishes["custom_b"] = {"source": "x", "id": "b"}
258
+ assert "custom_a" in a.finishes and "custom_a" not in b.finishes
259
+ assert "custom_b" in b.finishes and "custom_b" not in a.finishes
260
+ assert "custom_a" not in steel.vis.finishes
261
+ assert "custom_b" not in steel.vis.finishes
File without changes
File without changes
File without changes