py-materials 2.0.5__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.
pymat/core.py ADDED
@@ -0,0 +1,521 @@
1
+ """
2
+ Core Material class with hierarchy, chaining, and properties.
3
+
4
+ Supports:
5
+ - Hierarchical inheritance (parents -> children)
6
+ - Chainable syntax: stainless.s316L.electropolished.apply_to(part)
7
+ - Direct access: s316L.apply_to(part) (auto-registered if no collision)
8
+ - Property inheritance (children inherit parent properties unless overridden)
9
+ """
10
+
11
+ from __future__ import annotations
12
+ from dataclasses import dataclass, field
13
+ from typing import Dict, Optional, Any, TYPE_CHECKING, TypeVar
14
+
15
+ if TYPE_CHECKING:
16
+ from build123d import Shape
17
+
18
+ from .properties import AllProperties, MechanicalProperties, OpticalProperties, PBRProperties
19
+
20
+ # Type variable for generic object application
21
+ T = TypeVar('T')
22
+
23
+
24
+ def _make_material(
25
+ name: str,
26
+ *,
27
+ density: Optional[float] = None,
28
+ formula: Optional[str] = None,
29
+ composition: Optional[Dict[str, float]] = None,
30
+ color: Optional[tuple] = None,
31
+ grade: Optional[str] = None,
32
+ temper: Optional[str] = None,
33
+ treatment: Optional[str] = None,
34
+ vendor: Optional[str] = None,
35
+ mechanical: Optional[Dict[str, Any]] = None,
36
+ thermal: Optional[Dict[str, Any]] = None,
37
+ electrical: Optional[Dict[str, Any]] = None,
38
+ optical: Optional[Dict[str, Any]] = None,
39
+ pbr: Optional[Dict[str, Any]] = None,
40
+ manufacturing: Optional[Dict[str, Any]] = None,
41
+ compliance: Optional[Dict[str, Any]] = None,
42
+ sourcing: Optional[Dict[str, Any]] = None,
43
+ properties: Optional[AllProperties] = None,
44
+ parent: Optional['Material'] = None,
45
+ _key: Optional[str] = None,
46
+ ) -> 'Material':
47
+ """Factory function to create Material with density convenience param."""
48
+ # Create the internal material object
49
+ mat = _MaterialInternal(
50
+ name=name,
51
+ formula=formula,
52
+ composition=composition,
53
+ color=color,
54
+ grade=grade,
55
+ temper=temper,
56
+ treatment=treatment,
57
+ vendor=vendor,
58
+ mechanical=mechanical,
59
+ thermal=thermal,
60
+ electrical=electrical,
61
+ optical=optical,
62
+ pbr=pbr,
63
+ manufacturing=manufacturing,
64
+ compliance=compliance,
65
+ sourcing=sourcing,
66
+ properties=properties or AllProperties(),
67
+ parent=parent,
68
+ _key=_key,
69
+ )
70
+
71
+ # Apply density convenience param
72
+ if density is not None:
73
+ mat.properties.mechanical.density = density
74
+
75
+ return mat
76
+
77
+
78
+ @dataclass
79
+ class _MaterialInternal:
80
+ """
81
+ Internal Material implementation. Use Material() constructor.
82
+
83
+ A hierarchical, chainable material node.
84
+
85
+ Properties cascade down the chain - children inherit from parents
86
+ but can override any property at any level.
87
+ """
88
+
89
+ # Identity
90
+ name: str
91
+ formula: Optional[str] = None # Chemical formula (e.g., "Al2O3")
92
+ composition: Optional[Dict[str, float]] = None # element -> fraction
93
+
94
+ # Convenience parameters (backward compatibility)
95
+ color: Optional[tuple] = None # RGB or RGBA for visualization
96
+
97
+ # Hierarchy metadata
98
+ grade: Optional[str] = None # e.g., "304", "6061"
99
+ temper: Optional[str] = None # e.g., "T6", "annealed"
100
+ treatment: Optional[str] = None # e.g., "passivated", "anodized"
101
+ vendor: Optional[str] = None # e.g., "saint_gobain", "hamamatsu"
102
+
103
+ # Property groups as kwargs
104
+ mechanical: Optional[Dict[str, Any]] = None
105
+ thermal: Optional[Dict[str, Any]] = None
106
+ electrical: Optional[Dict[str, Any]] = None
107
+ optical: Optional[Dict[str, Any]] = None # Physics properties, NOT visualization
108
+ pbr: Optional[Dict[str, Any]] = None # Visualization properties, NOT physics
109
+ manufacturing: Optional[Dict[str, Any]] = None
110
+ compliance: Optional[Dict[str, Any]] = None
111
+ sourcing: Optional[Dict[str, Any]] = None
112
+
113
+ # Properties (all domains)
114
+ properties: AllProperties = field(default_factory=AllProperties)
115
+
116
+ # Hierarchy (not shown in repr)
117
+ parent: Optional[_MaterialInternal] = field(default=None, repr=False)
118
+ _children: Dict[str, _MaterialInternal] = field(default_factory=dict, repr=False)
119
+ _key: Optional[str] = field(default=None, repr=False) # for registry
120
+
121
+ def __post_init__(self):
122
+ """Apply convenience parameters and property groups to properties object."""
123
+ # Apply color if provided
124
+ if self.color is not None:
125
+ if len(self.color) == 3:
126
+ # RGB provided, add full opacity
127
+ self.properties.pbr.base_color = (*self.color, 1.0)
128
+ elif len(self.color) == 4:
129
+ # RGBA provided
130
+ self.properties.pbr.base_color = self.color
131
+ else:
132
+ raise ValueError(f"color must be RGB (3 values) or RGBA (4 values), got {len(self.color)}")
133
+
134
+ # Apply property groups
135
+ if self.mechanical:
136
+ for key, value in self.mechanical.items():
137
+ if hasattr(self.properties.mechanical, key):
138
+ setattr(self.properties.mechanical, key, value)
139
+
140
+ if self.thermal:
141
+ for key, value in self.thermal.items():
142
+ if hasattr(self.properties.thermal, key):
143
+ setattr(self.properties.thermal, key, value)
144
+
145
+ if self.electrical:
146
+ for key, value in self.electrical.items():
147
+ if hasattr(self.properties.electrical, key):
148
+ setattr(self.properties.electrical, key, value)
149
+
150
+ if self.optical:
151
+ for key, value in self.optical.items():
152
+ if hasattr(self.properties.optical, key):
153
+ setattr(self.properties.optical, key, value)
154
+
155
+ if self.pbr:
156
+ for key, value in self.pbr.items():
157
+ if hasattr(self.properties.pbr, key):
158
+ setattr(self.properties.pbr, key, value)
159
+
160
+ if self.manufacturing:
161
+ for key, value in self.manufacturing.items():
162
+ if hasattr(self.properties.manufacturing, key):
163
+ setattr(self.properties.manufacturing, key, value)
164
+
165
+ if self.compliance:
166
+ for key, value in self.compliance.items():
167
+ if hasattr(self.properties.compliance, key):
168
+ setattr(self.properties.compliance, key, value)
169
+
170
+ if self.sourcing:
171
+ for key, value in self.sourcing.items():
172
+ if hasattr(self.properties.sourcing, key):
173
+ setattr(self.properties.sourcing, key, value)
174
+
175
+ # Apply PBR defaults from optical properties (DRY principle)
176
+ # Allow physics properties to drive rendering defaults, but preserve explicit overrides
177
+
178
+ # If ior wasn't explicitly set (still at default 1.5) and optical.refractive_index exists,
179
+ # use optical.refractive_index as the PBR ior
180
+ if (self.properties.pbr.ior == 1.5 and
181
+ self.properties.optical.refractive_index is not None):
182
+ self.properties.pbr.ior = self.properties.optical.refractive_index
183
+
184
+ # If transmission wasn't explicitly set (still at default 0.0) and optical.transparency exists,
185
+ # convert transparency (0-100%) to transmission (0-1)
186
+ if (self.properties.pbr.transmission == 0.0 and
187
+ self.properties.optical.transparency is not None):
188
+ self.properties.pbr.transmission = self.properties.optical.transparency / 100.0
189
+
190
+ # =========================================================================
191
+ # Chaining API
192
+ # =========================================================================
193
+
194
+ def __getattr__(self, name: str) -> _MaterialInternal:
195
+ """
196
+ Access child variants by attribute.
197
+
198
+ Usage:
199
+ stainless.s316L -> accesses s316L grade
200
+ s316L.electropolished -> accesses treatment
201
+
202
+ Note: This is only called when normal attribute lookup fails.
203
+ """
204
+ # For private/protected attributes that don't exist, raise immediately
205
+ if name.startswith("_"):
206
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
207
+
208
+ # For public attributes, try to find in children
209
+ try:
210
+ children = object.__getattribute__(self, "_children")
211
+ if name in children:
212
+ return children[name]
213
+ except AttributeError:
214
+ pass
215
+
216
+ # Not found in children either
217
+ try:
218
+ children = object.__getattribute__(self, "_children")
219
+ available = list(children.keys())
220
+ except AttributeError:
221
+ available = []
222
+
223
+ raise AttributeError(
224
+ f"'{self.name}' has no variant '{name}'. "
225
+ f"Available: {available if available else 'none'}"
226
+ )
227
+
228
+ def _add_child(self, key: str, **overrides) -> _MaterialInternal:
229
+ """
230
+ Internal: add a child node with inherited properties.
231
+
232
+ Child inherits all properties from parent unless explicitly overridden.
233
+ """
234
+ # Inherit property objects (deep copy to avoid mutation)
235
+ from copy import deepcopy
236
+ inherited_props = deepcopy(self.properties)
237
+
238
+ # Handle property group overrides (mechanical, thermal, etc.)
239
+ # These are dicts that should be applied to the inherited properties
240
+ property_groups = [
241
+ ("mechanical", inherited_props.mechanical),
242
+ ("thermal", inherited_props.thermal),
243
+ ("electrical", inherited_props.electrical),
244
+ ("optical", inherited_props.optical),
245
+ ("pbr", inherited_props.pbr),
246
+ ("manufacturing", inherited_props.manufacturing),
247
+ ("compliance", inherited_props.compliance),
248
+ ("sourcing", inherited_props.sourcing),
249
+ ]
250
+
251
+ for group_name, prop_obj in property_groups:
252
+ if group_name in overrides:
253
+ group_dict = overrides.pop(group_name)
254
+ if isinstance(group_dict, dict):
255
+ for k, v in group_dict.items():
256
+ if v is not None and hasattr(prop_obj, k):
257
+ setattr(prop_obj, k, v)
258
+
259
+ # Build child properties
260
+ child_props = {
261
+ "name": overrides.get("name", f"{self.name} {key}"),
262
+ "formula": overrides.get("formula", self.formula),
263
+ "composition": overrides.get("composition", self.composition),
264
+ "properties": inherited_props,
265
+ "parent": self,
266
+ "_key": key,
267
+ }
268
+
269
+ # Carry forward metadata unless overridden
270
+ for meta in ("grade", "temper", "treatment", "vendor"):
271
+ child_props[meta] = overrides.get(meta, getattr(self, meta))
272
+
273
+ # Remove used overrides
274
+ for k in list(overrides.keys()):
275
+ if k in ("name", "formula", "composition", "grade", "temper", "treatment", "vendor"):
276
+ overrides.pop(k)
277
+
278
+ # Store any remaining overrides in custom properties
279
+ if overrides:
280
+ child_props["properties"].custom.update(overrides)
281
+
282
+ child = Material(**child_props)
283
+ self._children[key] = child
284
+ return child
285
+
286
+ # =========================================================================
287
+ # Chainable Methods
288
+ # =========================================================================
289
+
290
+ def grade_(self, key: str, **props) -> _MaterialInternal:
291
+ """Add a grade variant (e.g., 304, 316L, 6061, a7075)."""
292
+ return self._add_child(key, grade=key, **props)
293
+
294
+ def temper_(self, key: str, **props) -> _MaterialInternal:
295
+ """Add a temper/heat treatment (e.g., T6, O, annealed)."""
296
+ return self._add_child(key, temper=key, **props)
297
+
298
+ def treatment_(self, key: str, **props) -> _MaterialInternal:
299
+ """Add a surface treatment (e.g., passivated, anodized, electropolished)."""
300
+ return self._add_child(key, treatment=key, **props)
301
+
302
+ def vendor_(self, key: str, **props) -> _MaterialInternal:
303
+ """Add a vendor-specific variant."""
304
+ return self._add_child(key, vendor=key, **props)
305
+
306
+ def variant_(self, key: str, **props) -> _MaterialInternal:
307
+ """Add a generic variant (dopant, alloy composition, etc.)."""
308
+ return self._add_child(key, **props)
309
+
310
+ # =========================================================================
311
+ # Application to Shapes
312
+ # =========================================================================
313
+
314
+ def apply_to(self, obj):
315
+ """
316
+ Apply this material to an object.
317
+
318
+ For build123d Shapes: sets material, color, and calculates mass
319
+ For other objects: sets obj.material = self
320
+
321
+ Args:
322
+ obj: Object to apply material to (build123d Shape or any object)
323
+
324
+ Returns:
325
+ The modified object
326
+
327
+ Raises:
328
+ TypeError: If obj doesn't support attribute assignment
329
+
330
+ Example:
331
+ # build123d Shape - full features
332
+ crystal = Box(10, 10, 10)
333
+ lyso.apply_to(crystal) # Sets: material, color, mass
334
+
335
+ # Custom object - just material attribute
336
+ class MyPart:
337
+ pass
338
+ part = MyPart()
339
+ stainless.apply_to(part) # Sets: part.material = stainless
340
+ """
341
+ # Check if object supports attribute assignment
342
+ try:
343
+ obj.material = self
344
+ except (AttributeError, TypeError) as e:
345
+ raise TypeError(
346
+ f"Cannot apply material to {type(obj).__name__}: "
347
+ f"object doesn't support attribute assignment ({e})"
348
+ )
349
+
350
+ # Try build123d-specific features (color, mass calculation)
351
+ # Check for build123d Shape characteristics: has volume and color attributes
352
+ try:
353
+ if hasattr(obj, 'volume') and hasattr(obj, 'color'):
354
+ # Set color from PBR with alpha derived from transmission
355
+ # Alpha = 1 - transmission (transmission=1 → fully transparent, alpha=0)
356
+ color = self.properties.pbr.base_color
357
+ transmission = self.properties.pbr.transmission
358
+ alpha = 1.0 - transmission
359
+ obj.color = (*color[:3], alpha)
360
+
361
+ # Calculate mass if density is available
362
+ if self.properties.mechanical.density and self.properties.mechanical.density > 0:
363
+ # build123d volume is in mm³, density is g/cm³
364
+ # 1 cm³ = 1000 mm³, so g/mm³ = g/cm³ / 1000
365
+ density_g_mm3 = self.properties.mechanical.density / 1000
366
+ obj.mass = obj.volume * density_g_mm3
367
+
368
+ except (AttributeError, TypeError):
369
+ # If build123d-specific features fail, that's fine
370
+ # The material attribute is already set, which is the minimum requirement
371
+ pass
372
+
373
+ return obj
374
+
375
+ # =========================================================================
376
+ # Information & Inspection
377
+ # =========================================================================
378
+
379
+ @property
380
+ def path(self) -> str:
381
+ """Full hierarchical path from root (e.g., 'aluminum.a7075.T6')."""
382
+ parts = []
383
+ node = self
384
+ while node:
385
+ part_key = node._key or node.name.lower().replace(" ", "_")
386
+ parts.append(part_key)
387
+ node = node.parent
388
+ return ".".join(reversed(parts))
389
+
390
+ @property
391
+ def density(self) -> Optional[float]:
392
+ """Density in g/cm³ (convenience property for mechanical.density)."""
393
+ return self.properties.mechanical.density
394
+
395
+ @density.setter
396
+ def density(self, value: Optional[float]) -> None:
397
+ """Set density in g/cm³."""
398
+ self.properties.mechanical.density = value
399
+
400
+ @property
401
+ def density_g_mm3(self) -> float:
402
+ """Density in g/mm³ (for build123d calculations)."""
403
+ mech_density = self.properties.mechanical.density
404
+ if not mech_density:
405
+ return 0.0
406
+ return mech_density / 1000
407
+
408
+ def mass_from_volume_mm3(self, volume_mm3: float) -> float:
409
+ """Calculate mass in grams from volume in mm³."""
410
+ return volume_mm3 * self.density_g_mm3
411
+
412
+ def __repr__(self) -> str:
413
+ """String representation showing path and density."""
414
+ density_str = f"ρ={self.density} g/cm³" if self.density else "ρ=?"
415
+ return f"Material({self.path!r}, {density_str})"
416
+
417
+ def __str__(self) -> str:
418
+ """Human-readable string."""
419
+ return f"{self.name} ({self.path})"
420
+
421
+ def info(self) -> str:
422
+ """Detailed information about this material."""
423
+ lines = [
424
+ f"Material: {self.name}",
425
+ f"Path: {self.path}",
426
+ "",
427
+ "Mechanical Properties:",
428
+ f" Density: {self.density} g/cm³" if self.density else " Density: N/A",
429
+ f" Young's Modulus: {self.properties.mechanical.youngs_modulus} GPa"
430
+ if self.properties.mechanical.youngs_modulus else "",
431
+ f" Yield Strength: {self.properties.mechanical.yield_strength} MPa"
432
+ if self.properties.mechanical.yield_strength else "",
433
+ ]
434
+
435
+ if self.formula:
436
+ lines.append(f"Formula: {self.formula}")
437
+ if self.composition:
438
+ lines.append(f"Composition: {self.composition}")
439
+
440
+ return "\n".join(line for line in lines if line)
441
+
442
+
443
+ # Create the public Material class as an alias that accepts density param
444
+ class Material(_MaterialInternal):
445
+ """
446
+ A hierarchical, chainable material node.
447
+
448
+ Properties cascade down the chain - children inherit from parents
449
+ but can override any property at any level.
450
+
451
+ Constructor parameters:
452
+ - name: Material name (required)
453
+ - density: Density in g/cm³ (convenience parameter, sets mechanical.density)
454
+ - color: Visualization color - RGB tuple (r, g, b) or RGBA (r, g, b, alpha)
455
+ - formula: Chemical formula (e.g., "Al2O3")
456
+ - composition: Element fractions dict
457
+ - mechanical: Dict of mechanical properties (density, youngs_modulus, etc.)
458
+ - thermal: Dict of thermal properties (melting_point, conductivity, etc.)
459
+ - electrical: Dict of electrical properties (resistivity, dielectric_constant, etc.)
460
+ - optical: Dict of optical properties (refractive_index, transparency, etc.) - PHYSICS
461
+ - pbr: Dict of PBR visualization properties (base_color, metallic, roughness) - RENDERING
462
+ - manufacturing: Dict of manufacturing properties (machinability, weldability, etc.)
463
+ - compliance: Dict of compliance properties (rohs_compliant, food_safe, etc.)
464
+ - sourcing: Dict of sourcing properties (cost_per_kg, availability, etc.)
465
+
466
+ Example usage:
467
+ Material(name="Steel", density=7.8, color=(0.7, 0.7, 0.7))
468
+ Material(name="Steel", mechanical={"density": 7.8, "youngs_modulus": 200})
469
+ Material(name="LYSO", optical={"transparency": 92, "refractive_index": 1.82})
470
+ """
471
+
472
+ def __init__(
473
+ self,
474
+ name: str,
475
+ *,
476
+ density: Optional[float] = None,
477
+ formula: Optional[str] = None,
478
+ composition: Optional[Dict[str, float]] = None,
479
+ color: Optional[tuple] = None,
480
+ grade: Optional[str] = None,
481
+ temper: Optional[str] = None,
482
+ treatment: Optional[str] = None,
483
+ vendor: Optional[str] = None,
484
+ mechanical: Optional[Dict[str, Any]] = None,
485
+ thermal: Optional[Dict[str, Any]] = None,
486
+ electrical: Optional[Dict[str, Any]] = None,
487
+ optical: Optional[Dict[str, Any]] = None,
488
+ pbr: Optional[Dict[str, Any]] = None,
489
+ manufacturing: Optional[Dict[str, Any]] = None,
490
+ compliance: Optional[Dict[str, Any]] = None,
491
+ sourcing: Optional[Dict[str, Any]] = None,
492
+ properties: Optional[AllProperties] = None,
493
+ parent: Optional['Material'] = None,
494
+ _key: Optional[str] = None,
495
+ ):
496
+ # Call parent init without density
497
+ super().__init__(
498
+ name=name,
499
+ formula=formula,
500
+ composition=composition,
501
+ color=color,
502
+ grade=grade,
503
+ temper=temper,
504
+ treatment=treatment,
505
+ vendor=vendor,
506
+ mechanical=mechanical,
507
+ thermal=thermal,
508
+ electrical=electrical,
509
+ optical=optical,
510
+ pbr=pbr,
511
+ manufacturing=manufacturing,
512
+ compliance=compliance,
513
+ sourcing=sourcing,
514
+ properties=properties or AllProperties(),
515
+ parent=parent,
516
+ _key=_key,
517
+ )
518
+
519
+ # Apply density convenience param after parent init
520
+ if density is not None:
521
+ self.properties.mechanical.density = density