From d61220d43a117d8408d0b5eee116b2eab7d1e82d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 23:22:19 +0000 Subject: [PATCH 01/13] TPMS: ten surfaces, the other network and graded TPMS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Six more nodal surfaces for the model tpms (theory notes §140, FR-G29, specification 1.254): Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P and I2-Y (Lord & Mackay 2003), their derivatives written out for the first-order distance; the network on the other side of the level (variant upper_network); graded TPMS (fraction_gradient along gradient_axis), each position at the level of its fraction, the slope of the level in the distance. The kernels take a table of levels; the calibration of the cell is cached. The public interface written again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MSrXEMpgnWPQNUwHwAgXHV --- CHANGELOG.md | 11 ++ docs/models.md | 2 +- docs/specification.md | 6 +- docs/theory.md | 81 ++++++++- src/morphogen/kernels/implicit.py | 266 +++++++++++++++++++++++------- src/morphogen/models/tpms.py | 208 ++++++++++++++++++----- tests/public_api.txt | 10 +- tests/test_models_cells_fields.py | 4 +- tests/test_tpms_surfaces.py | 180 ++++++++++++++++++++ 9 files changed, 656 insertions(+), 112 deletions(-) create mode 100644 tests/test_tpms_surfaces.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b506ed4..a649035 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ ## Unreleased +* TPMS (`tpms`, [docs/theory.md](docs/theory.md) §140): ten surfaces, with Schoen's I-WP + and F-RD, Fischer–Koch S, the lidinoid, split P and I2-Y (the nodal forms of Lord & + Mackay 2003) beside the gyroid, Schwarz P and D and Neovius; the network on the other side + of the surface (`variant: upper_network`), which differs from the network on the surfaces + that are not balanced; graded TPMS (`fraction_gradient: [0.15, 0.45]`, `gradient_axis`): + the volume fraction at equally spaced positions along an axis of a non-periodic domain, + interpolated linearly, each position at the level of its fraction, the slope of the level + in the distance of the surface. Public interface: `TPMS(fraction_gradient=..., + gradient_axis=...)`, `TPMS.graded_levels`, `TPMS.mean_fraction`, the keywords `levels` + and `gradient_axis` of `TPMSStructure`, and in `morphogen.models.tpms` `SURFACES`, + `VARIANTS`, `level_of_fraction` and `fraction_of_level`. * Forchheimer's law through OpenFOAM (`morphogen.io.forchheimer`, `morphogen openfoam forchheimer`, [docs/theory.md](docs/theory.md) §139): as the Reynolds number grows, inertia adds a drag to Darcy's and the apparent permeability of the pores falls. A case diff --git a/docs/models.md b/docs/models.md index 15f803d..919fd8c 100644 --- a/docs/models.md +++ b/docs/models.md @@ -72,7 +72,7 @@ What a realization is made of, and how it becomes images and meshes, is the subj | Model | Description | |---|---| -| `tpms` | Gyroid, Schwarz P, Schwarz D and Neovius, sheet or network | +| `tpms` | Ten surfaces: gyroid, Schwarz P and D, Neovius, Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P and I2-Y; the network on either side of the surface or the sheet, at a level, a volume fraction or a profile of the fraction along an axis (graded TPMS, [theory notes](theory.md) §140) | | `strut_lattice` | Cubic, BCC, FCC, octet, Kelvin, diamond and pyrochlore lattices, with solid or hollow struts; rotated and functionally graded lattices (non-periodic samples); their sections meshed in the plane by their exact contours | | `plate_lattice` | Plate lattices: closed cells walled by plates on the closest-packed planes of the cubic lattices, the {100} (`cubic`), {110} (`bcc`) and {111} (`fcc`, the octet plates) planes and their mixtures (Berger et al. 2017; Tancogne-Dejean et al. 2018), of a thickness or an exact relative density, in the ratio of an isotropic stiffness at low density (`isotropic`, which reaches the Hashin–Shtrikman bounds); turned, shifted and graded; the exact density and specific surface, the stiffness of the membranes at low density, exact meshes of their convex pieces ([below](#plate-lattices)) | | `random_lattice` | Strut lattices with missing struts and displaced nodes, with their rigidity (Maxwell–Calladine); their sections meshed in the plane by their exact contours | diff --git a/docs/specification.md b/docs/specification.md index 8beb61e..9e5274d 100644 --- a/docs/specification.md +++ b/docs/specification.md @@ -3,7 +3,7 @@ | | | |---|---| | Document | Software requirements specification | -| Version | 1.253 | +| Version | 1.254 | | Date | 2026-12-01 | | Author | @jdirr | | Status | Version 1.1 **validated** on 2026-10-21. The later versions, proposed, are listed in the change log (§13); changes go through pull requests that update this file and its change log. | @@ -358,6 +358,8 @@ centred on morphological modelling. |---|---| | Forchheimer's law through OpenFOAM (2026-12-01) | The inertia of the flow through the pores: periodic flows at finite Reynolds numbers, run by OpenFOAM, and the laws of the weak inertia and of Forchheimer fitted to them. | | Delivered | FR-E19 (`io.openfoam`, `morphogen openfoam forchheimer`, `outputs.openfoam.velocity`, [theory.md](theory.md) §139): the flow periodic along its axis too (a cyclic pair, the pressure fixed at one cell), driven to a filtration velocity by `meanVelocityForce` for both lines of OpenFOAM (OpenCFD's `fvOptions`, the Foundation's `fvConstraints`, put in place by `Allrun`), its pressure gradient read from the log of the solver, its apparent permeability and its convergence (the residuals, or a flow that no longer changes); the sweep `forchheimer`: a creeping flow (Darcy's permeability), periodic flows at the Reynolds numbers asked for, the failed and unsteady flows reported and left out, Forchheimer's law (`k_F`, `β`, `c_F = β √k`) and the weak inertia (`k / k_app − 1 = A Re²`) fitted, the exponents from flow to flow, `forchheimer.json` and `forchheimer.csv`; the scheme of the convection; the periodic flow in the tool *OpenFOAM case*; verified by laws standing in for OpenFOAM (10⁻⁹) and by OpenFOAM v2412 itself: the permeability of a slit at every Reynolds number (10⁻⁶), the weak inertia (exponent 2) and the stronger inertia of staggered rods | +| Additive manufacturing: TPMS (2026-12-01) | The surfaces of Schoen, Fischer–Koch and Lidin, the other network of a surface, graded TPMS. | +| Delivered | FR-G29 (`tpms`, [theory.md](theory.md) §140): six more nodal surfaces (Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P, I2-Y; Lord & Mackay 2003), their derivatives for the first-order distance; the network `upper_network` on the other side of the level; `fraction_gradient` along `gradient_axis`, the level of each position that of its fraction (any piecewise-linear profile, in non-periodic domains) | ## 4. Scope @@ -433,6 +435,7 @@ version, 0.1). | FR-G26 | Spinodal decomposition by the Cahn–Hilliard equation (semi-implicit spectral), at a fraction of the lever rule and an age of its coarsening | S | 3d | | FR-G27 | Grains grown from seeds (MicroStructPy): ellipsoidal seeds of laws of sizes and shapes, at random or aligned, the seeds of each phase of their own laws, broken down into spheres and placed within an overlap tolerance; the grain of a seed the union of the Laguerre cells of its spheres, meshed as one subdomain; amorphous phases merged into one region, voids left out of the meshes; ellipses in the plane (columnar grains); boxes and rectangles; the grains verified against their seeds on their exact cells, with their figures and a tool of the interface | S | 3d | | FR-G28 | Plate lattices: plates on the {100}, {110} and {111} planes of the cubic lattices and their mixtures, given by thicknesses or an exact relative density, the isotropic ratios of the mixtures; their exact density, specific surface and convex pieces; the stiffness of the membranes at low density | S | 3d | +| FR-G29 | TPMS: ten surfaces (gyroid, Schwarz P and D, Neovius, Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P, I2-Y), the networks on either side of a level and the sheet, at a level, a volume fraction or a profile of the volume fraction along an axis (graded TPMS) | S | 1d | ### 5.2 Representations @@ -1419,6 +1422,7 @@ Packages: `models`, `kernels`, `analysis`, `rve`, `mesh`, `homogenization`, `io` | 1.251 | 2026-12-01 | Micromagnetics: the magnetoelastic interaction of the domains (FR-H54, §3.11) | | 1.252 | 2026-12-01 | Micromagnetics: first-order reversal curves and their FORC diagrams (FR-H54, §3.11) | | 1.253 | 2026-12-01 | Forchheimer's law through OpenFOAM: periodic flows at finite Reynolds numbers, the weak inertia and Forchheimer's law fitted (FR-E19, §3.12) | +| 1.254 | 2026-12-01 | TPMS: ten surfaces, the other network and graded TPMS (FR-G29, §3.12) | ## 14. References diff --git a/docs/theory.md b/docs/theory.md index 5a47c0b..b09b789 100644 --- a/docs/theory.md +++ b/docs/theory.md @@ -12,7 +12,7 @@ them by these numbers (§75); by theme: | Theme | Sections | |---|---| | Models of random media | [§1](#1-boolean-models) Boolean models, [§2](#2-poisson-fibres-jeulin-1991-dirrenberger-et-al-2014) Poisson fibres (Jeulin 1991; Dirrenberger et al. 2014), [§3](#3-random-sequential-addition) Random sequential addition, [§4](#4-tessellations) Tessellations, [§5](#5-excursions-of-gaussian-random-fields) Excursions of Gaussian random fields, [§22](#22-combinations-of-models-and-grain-boundary-phases) Combinations of models and grain-boundary phases, [§23](#23-further-models) Further models, [§29](#29-nested-models) Nested models, [§38](#38-torquatos-approaches-dense-packings-cherry-pit-spheres-reconstruction-and-descriptors) Torquato's approaches: dense packings, cherry-pit spheres, reconstruction and descriptors, [§42](#42-foams-as-level-sets-of-distance-fields-level_set_foam) Foams as level sets of distance fields, [§56](#56-affine-anisotropy-of-the-models-modelsaffine) Affine anisotropy of the models, [§93](#93-scale-rich-networks-scale_rich_network) Scale-rich networks, [§95](#95-long-fibres-unidirectional-composites-parallel-or-misaligned-long_fibers) Long fibres: unidirectional composites, parallel or misaligned, [§97](#97-grains-with-subgrains-or-filled-with-another-structure-modelsnested_grains) Grains with subgrains, or filled with another structure, [§98](#98-monodisperse-and-polydisperse-objects) Monodisperse and polydisperse objects, [§107](#107-images-as-microstructures-segmentation-and-the-model-image-morphologysegmentation-modelsimage) Images as microstructures: segmentation and the model `image`, [§114](#114-reconstruction-from-descriptors-by-gradient-descent-morphologyreconstruction) Reconstruction from descriptors by gradient descent, [§115](#115-grains-grown-from-seeds-modelsseeded-kernelsseeds) Grains grown from seeds, [§116](#116-seeds-of-several-phases-and-the-verification-of-their-grains-modelsseeded-meshpolyhedra-kernelsseeds) Seeds of several phases and the verification of their grains, [§117](#117-seeds-of-the-plane-and-the-figures-of-the-verification-modelsseeded-vizfigures) Seeds of the plane and the figures of the verification, [§118](#118-seeds-of-boxes-and-of-rectangles-modelsseeded) Seeds of boxes and of rectangles | -| Architected and bio-inspired structures | [§6](#6-tpms) TPMS, [§7](#7-strut-lattices) Strut lattices, [§30](#30-bio-inspired-models) Bio-inspired models, [§71](#71-diamond-and-pyrochlore-lattices-of-struts-homogenizationframes-modelslattice) Diamond and pyrochlore lattices of struts, [§96](#96-woven-textile-composites-woven_textile) Woven textile composites, [§110](#110-woven-textiles-the-variability-of-the-tows-3d-architectures-the-tows-as-unidirectional-composites-woven_textile-homogenizationunidirectional) Woven textiles: the variability of the tows, 3D architectures, the tows as unidirectional composites, [§125](#125-plate-lattices-plate_lattice) Plate lattices | +| Architected and bio-inspired structures | [§6](#6-tpms) TPMS, [§7](#7-strut-lattices) Strut lattices, [§30](#30-bio-inspired-models) Bio-inspired models, [§71](#71-diamond-and-pyrochlore-lattices-of-struts-homogenizationframes-modelslattice) Diamond and pyrochlore lattices of struts, [§96](#96-woven-textile-composites-woven_textile) Woven textile composites, [§110](#110-woven-textiles-the-variability-of-the-tows-3d-architectures-the-tows-as-unidirectional-composites-woven_textile-homogenizationunidirectional) Woven textiles: the variability of the tows, 3D architectures, the tows as unidirectional composites, [§125](#125-plate-lattices-plate_lattice) Plate lattices, [§140](#140-tpms-ten-surfaces-their-two-networks-and-their-gradients-modelstpms) TPMS: ten surfaces, their two networks and their gradients | | Growth and design | [§14](#14-cellular-automata-automata) Cellular automata, [§15](#15-nucleation-and-growth-johnsonmehlavramikolmogorov) Nucleation and growth (Johnson–Mehl–Avrami–Kolmogorov), [§16](#16-aggregation) Aggregation, [§17](#17-combinatorial-design-design) Combinatorial design, [§18](#18-topology-optimization-of-periodic-cells-optimization) Topology optimization of periodic cells, [§78](#78-isogeometric-analysis-iga) Isogeometric analysis, [§79](#79-isogeometric-shape-optimization-igaoptimization) Isogeometric shape optimization, [§109](#109-inverse-design-of-active-structures-optimizationmorphing) Inverse design of active structures, [§113](#113-spinodal-decomposition-spinodal) Spinodal decomposition | | Geometry and meshes | [§19](#19-polycrystals-exact-cells-and-conforming-meshes-meshpolyhedra-meshpolycrystal) Polycrystals: exact cells and conforming meshes, [§24](#24-whole-periodic-grains-meshpolycrystal-cells-whole) Whole periodic grains, [§52](#52-views-and-measures-of-the-level-sets-vizsections) Views and measures of the level sets, [§75](#75-the-implicit-geometry-of-every-model-modelsimplicit-meshconforming) The implicit geometry of every model, [§76](#76-quadratic-tetrahedra-isoparametric-elements-and-curved-interfaces-meshcurved-homogenizationfe) Quadratic tetrahedra: isoparametric elements and curved interfaces, [§80](#80-sharp-edges-of-the-phases-meshes-that-follow-them-modelspieces-meshconforming-meshcurved) Sharp edges of the phases: meshes that follow them, [§94](#94-exact-meshes-without-a-background-grid-meshexact-meshoctree) Exact meshes without a background grid, [§119](#119-meshes-of-the-plane-and-their-finite-elements-meshtriangles-homogenizationplane) Meshes of the plane and their finite elements | | Measures | [§8](#8-specific-surface-by-cauchycrofton) Specific surface by Cauchy–Crofton, [§21](#21-morphological-measures-analysismorphology) Morphological measures, [§39](#39-random-sets-probed-by-structuring-elements-analysisrandom_sets-analysistopology) Random sets probed by structuring elements, [§55](#55-percolation-thresholds-analysispercolation) Percolation thresholds, [§70](#70-particles-of-a-phase-in-a-volume-analysisparticles) Particles of a phase in a volume, [§92](#92-crystallographic-textures-and-orientation-maps-texture-ioebsd-modelsebsd) Crystallographic textures and orientation maps, [§104](#104-measures-of-the-implicit-geometry-morphologymeasures) Measures of the implicit geometry, [§105](#105-unions-of-balls-and-of-discs-measured-exactly-morphologyballs) Unions of balls and of discs, measured exactly, [§106](#106-the-model-of-an-image-morphologyidentification) The model of an image | @@ -221,6 +221,9 @@ The solid is $\{\varphi \le t\}$ (network) or $\{|\varphi| \le t\}$ (sheet). translation by $(\pi,\pi,\pi)$ for Schwarz P). * The level-set field is the first-order distance $(\varphi - t)/|\nabla\varphi|$. +Six more surfaces (Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P, I2-Y), +the network on the other side of the surface and graded TPMS: §140. + ## 7. Strut lattices For the simple cubic lattice (three orthogonal cylinders of radius $r$ per cell of edge @@ -16570,6 +16573,72 @@ S. Whitaker, Transp. Porous Media 25 (1996) 27; M. Firdaouss, J.-L. Guermond, P. Le Quéré, J. Fluid Mech. 343 (1997) 331; D. Lasseux, A. A. Abbasian Arani, A. Ahmadi, Phys. Fluids 23 (2011) 073103. +## 140. TPMS: ten surfaces, their two networks and their gradients (`models.tpms`) + +**The surfaces.** Besides the four of §6, the nodal approximations of Lord & Mackay (2003) +(the zeros of truncated Fourier series, von Schnering & Nesper 1991), with +$A = \sin 2X\cos Y\sin Z + \sin X\sin 2Y\cos Z + \cos X\sin Y\sin 2Z$ and +$B = \cos 2X\cos 2Y + \cos 2Y\cos 2Z + \cos 2Z\cos 2X$: + +| surface | `surface` | $\varphi(X, Y, Z)$ | +|---|---|---| +| Schoen's I-WP (Schoen 1970) | `schoen_iwp` | $2(\cos X\cos Y + \cos Y\cos Z + \cos Z\cos X) - (\cos 2X + \cos 2Y + \cos 2Z)$ | +| Schoen's F-RD (Schoen 1970) | `schoen_frd` | $4\cos X\cos Y\cos Z - B$ | +| Fischer–Koch S (Fischer & Koch 1987) | `fischer_koch_s` | $\cos 2X\sin Y\cos Z + \cos X\cos 2Y\sin Z + \sin X\cos Y\cos 2Z$ | +| lidinoid (Lidin & Larsson 1990) | `lidinoid` | $\tfrac12 A - \tfrac12 B + 0.15$ | +| split P | `split_p` | $1.1A - 0.2B - 0.4(\cos 2X + \cos 2Y + \cos 2Z)$ | +| I2-Y (Schoen 1970) | `i2_y` | $-2A + B$ | + +Every function has the period $2\pi$ along each axis (one cubic cell of edge $a$) and the +cubic symmetry of the cyclic permutation of the axes; their derivatives, for the +first-order distance, are written out (`kernels.implicit`), checked against central +differences. They are approximations: the mean curvature $H$ of their zero sets, sampled on +the surfaces, vanishes on average for the balanced surfaces but not everywhere: its +root mean square, in units of $2\pi/a$, is about 0.02 (gyroid), 0.03 (D), 0.10 (P), 0.12 +(Neovius), 0.15 (Fischer–Koch S), 0.22 (I-WP), 0.33 (F-RD), 0.34 (split P), 0.45 (I2-Y) and +0.54 (lidinoid). The zero sets are those of the published forms, whose constants (the +0.15 of the lidinoid) place the surface; a solid given by its volume fraction is placed by +its level instead. + +**The two networks.** A level $t$ cuts space into the network $\{\varphi \le t\}$ +(`network`), the sheet $\{|\varphi| \le t\}$ (`sheet`) and the other network +$\{\varphi \ge t\}$ (`upper_network`: Top6Meta's exoskeletal, Microgen's upper skeletal). +With $F$ the distribution of $\varphi$ over the cell (sampled at $96^3$ points), a +fraction $f$ is the level $F^{-1}(f)$ of the network, $F^{-1}(1 - f)$ of the other one, +and the quantile $f$ of $|\varphi|$ for the sheet; the first-order distance is +$(\varphi - t)/|\nabla\varphi|$, $(|\varphi| - t)/|\nabla\varphi|$ or +$(t - \varphi)/|\nabla\varphi|$. The other network at $f$ is the complement of the network +at $1 - f$. On a balanced surface, $\varphi$ is odd under a symmetry of the lattice (the +translation by half a cell for Schwarz P, Neovius), $F$ is symmetric and the two networks +at a fraction are alike, at opposite levels (the network of Schwarz P moved by +$(a/2, a/2, a/2)$, voxel for voxel); I-WP, F-RD, the lidinoid, split P and I2-Y are not: +their two networks differ (the levels at a fraction are not opposite), and $\varphi \le 0$ +fills 0.469, 0.432, 0.385, 0.509 and 0.445 of their cells. + +**Graded TPMS.** `fraction_gradient` $(f_0, \dots, f_{m-1})$ gives the volume fraction at +$m$ equally spaced positions from the lower to the upper face of a non-periodic domain +along `gradient_axis`, interpolated linearly: $f(s)$, $s \in [0, 1]$ (two values: the +linear gradient of Top6Meta's FG type 1; more: any piecewise-linear profile). Each +position takes the level of its fraction, $t(s) = F^{-1}(f(s))$ (tabulated at 64 points per +interval of the profile and interpolated), so that a slab across the gradient, thin +before the length of the gradient but a cell or more thick, has the fraction $f(s)$ of its +position, and the sample the mean of the profile, +$\bar f = \sum_j (f_j + f_{j+1})/(2(m - 1))$. The function of the solid is +$\varphi - t(s)$ (or $|\varphi| - t(s)$, $t(s) - \varphi$), and its first-order distance +divides it by $|\nabla\varphi \mp t'(s)\,e_\text{axis}|$, the slope of the level +included. + +Validated in `tests/test_tpms_surfaces.py`: the published forms at a point; the derivatives +against central differences, the cyclic symmetry and the period; for each surface and +solid at a fraction 0.3, the fraction of the voxels (within 0.012 at 48 voxels per cell), +the level set negative exactly on the solid voxels, the points and the periodic tiles; the +other network the complement of the network at $1 - f$; Schwarz P's other network its +network moved by half a cell, the levels of I-WP and the lidinoid not opposite; the +fractions of slabs one cell thick within 0.02 of linear and tent profiles (sheet gyroid), +the mean fraction of the theory, an I-WP graded along $z$; the slope of the level set of a +graded split P, of median 1 within 5 % across its surface; a graded realization written +and read back, and run from a configuration to its STL surface. + ## References See [specification.md](specification.md#14-references). In addition: @@ -17723,3 +17792,13 @@ See [specification.md](specification.md#14-references). In addition: * Lasseux, D., Abbasian Arani, A. A., Ahmadi, A. (2011). On the stationary macroscopic inertial effects for one phase flow in ordered and disordered porous media. *Phys. Fluids* 23, 073103. +* Schoen, A. H. (1970). Infinite periodic minimal surfaces without self-intersections. + *NASA Technical Note* D-5541. +* von Schnering, H. G., Nesper, R. (1991). Nodal surfaces of Fourier series: fundamental + invariants of structured matter. *Z. Phys. B* 83, 407–412. +* Fischer, W., Koch, E. (1987). On 3-periodic minimal surfaces. *Z. Kristallogr.* 179, + 31–52. +* Lidin, S., Larsson, S. (1990). Bonnet transformation of infinite periodic minimal + surfaces with hexagonal symmetry. *J. Chem. Soc., Faraday Trans.* 86, 769–775. +* Lord, E. A., Mackay, A. L. (2003). Periodic minimal surfaces of cubic symmetry. *Curr. + Sci.* 85, 346–362. diff --git a/src/morphogen/kernels/implicit.py b/src/morphogen/kernels/implicit.py index 1762811..fa7f92d 100644 --- a/src/morphogen/kernels/implicit.py +++ b/src/morphogen/kernels/implicit.py @@ -1,4 +1,15 @@ -"""Evaluation of triply periodic minimal surface (TPMS) level-set functions.""" +"""Evaluation of triply periodic minimal surface (TPMS) level-set functions. + +The surfaces are the nodal approximations ``phi(X, Y, Z) = 0`` of their Fourier series +(von Schnering & Nesper 1991; Lord & Mackay 2003), ``X = 2 pi x / a`` (and ``Y``, ``Z``) +for a cubic cell of edge ``a``; every function has the period ``2 pi`` along each axis. + +A solid is a side of a level ``t`` of the function: ``phi <= t`` (the network), +``|phi| <= t`` (the sheet around the surface) or ``phi >= t`` (the other network). The +level may vary along an axis of the box: a table of levels at equally spaced positions +between two planes, interpolated linearly (graded TPMS); a table of one level is a +constant level. +""" from __future__ import annotations @@ -7,99 +18,235 @@ import numpy as np from numba import njit, prange -GYROID, SCHWARZ_P, SCHWARZ_D, NEOVIUS = 0, 1, 2, 3 -SURFACES = {"gyroid": GYROID, "schwarz_p": SCHWARZ_P, "schwarz_d": SCHWARZ_D, "neovius": NEOVIUS} +( + GYROID, + SCHWARZ_P, + SCHWARZ_D, + NEOVIUS, + SCHOEN_IWP, + SCHOEN_FRD, + FISCHER_KOCH_S, + LIDINOID, + SPLIT_P, + I2_Y, +) = range(10) +SURFACES = { + "gyroid": GYROID, + "schwarz_p": SCHWARZ_P, + "schwarz_d": SCHWARZ_D, + "neovius": NEOVIUS, + "schoen_iwp": SCHOEN_IWP, + "schoen_frd": SCHOEN_FRD, + "fischer_koch_s": FISCHER_KOCH_S, + "lidinoid": LIDINOID, + "split_p": SPLIT_P, + "i2_y": I2_Y, +} +#: The solids of a level: the network ``phi <= t``, the sheet ``|phi| <= t``, the other +#: network ``phi >= t``. +NETWORK, SHEET, UPPER_NETWORK = 0, 1, 2 +MODES = {"network": NETWORK, "sheet": SHEET, "upper_network": UPPER_NETWORK} @njit(cache=True, inline="always") -def tpms_value(code, X, Y, Z): - """phi(X, Y, Z) with X = 2 pi x / a (and similarly Y, Z).""" - if code == GYROID: - return math.sin(X) * math.cos(Y) + math.sin(Y) * math.cos(Z) + math.sin(Z) * math.cos(X) - if code == SCHWARZ_P: - return math.cos(X) + math.cos(Y) + math.cos(Z) - if code == SCHWARZ_D: - sx, sy, sz = math.sin(X), math.sin(Y), math.sin(Z) - cx, cy, cz = math.cos(X), math.cos(Y), math.cos(Z) - return sx * sy * sz + sx * cy * cz + cx * sy * cz + cx * cy * sz - # Neovius - cx, cy, cz = math.cos(X), math.cos(Y), math.cos(Z) - return 3.0 * (cx + cy + cz) + 4.0 * cx * cy * cz +def _cyclic(sx, sy, sz, cx, cy, cz, s2x, s2y, s2z, c2x, c2y, c2z): + """``A = sin2X cosY sinZ + sinX sin2Y cosZ + cosX sinY sin2Z`` and its derivatives, + ``B = cos2X cos2Y + cos2Y cos2Z + cos2Z cos2X`` and its derivatives (the brackets + of the lidinoid, split P and I2-Y).""" + a = s2x * cy * sz + sx * s2y * cz + cx * sy * s2z + ax = 2.0 * c2x * cy * sz + cx * s2y * cz - sx * sy * s2z + ay = -s2x * sy * sz + 2.0 * sx * c2y * cz + cx * cy * s2z + az = s2x * cy * cz - sx * s2y * sz + 2.0 * cx * sy * c2z + b = c2x * c2y + c2y * c2z + c2z * c2x + bx = -2.0 * s2x * (c2y + c2z) + by = -2.0 * s2y * (c2x + c2z) + bz = -2.0 * s2z * (c2x + c2y) + return a, ax, ay, az, b, bx, by, bz @njit(cache=True, inline="always") -def tpms_gradient_norm(code, X, Y, Z, kx, ky, kz): - """|grad phi| with respect to physical coordinates (k = 2 pi / a).""" +def tpms_value_gradient(code, X, Y, Z): + """``phi`` and its derivatives with respect to ``X``, ``Y``, ``Z``.""" sx, sy, sz = math.sin(X), math.sin(Y), math.sin(Z) cx, cy, cz = math.cos(X), math.cos(Y), math.cos(Z) if code == GYROID: - gx = cx * cy - sz * sx - gy = -sx * sy + cy * cz - gz = -sy * sz + cz * cx - elif code == SCHWARZ_P: - gx, gy, gz = -sx, -sy, -sz - elif code == SCHWARZ_D: + v = sx * cy + sy * cz + sz * cx + return v, cx * cy - sz * sx, -sx * sy + cy * cz, -sy * sz + cz * cx + if code == SCHWARZ_P: + return cx + cy + cz, -sx, -sy, -sz + if code == SCHWARZ_D: + v = sx * sy * sz + sx * cy * cz + cx * sy * cz + cx * cy * sz gx = cx * sy * sz + cx * cy * cz - sx * sy * cz - sx * cy * sz gy = sx * cy * sz - sx * sy * cz + cx * cy * cz - cx * sy * sz gz = sx * sy * cz - sx * cy * sz - cx * sy * sz + cx * cy * cz - else: - gx = -3.0 * sx - 4.0 * sx * cy * cz - gy = -3.0 * sy - 4.0 * cx * sy * cz - gz = -3.0 * sz - 4.0 * cx * cy * sz - return math.sqrt((kx * gx) ** 2 + (ky * gy) ** 2 + (kz * gz) ** 2) + return v, gx, gy, gz + if code == NEOVIUS: + v = 3.0 * (cx + cy + cz) + 4.0 * cx * cy * cz + return ( + v, + -3.0 * sx - 4.0 * sx * cy * cz, + -3.0 * sy - 4.0 * cx * sy * cz, + (-3.0 * sz - 4.0 * cx * cy * sz), + ) + s2x, s2y, s2z = 2.0 * sx * cx, 2.0 * sy * cy, 2.0 * sz * cz + c2x, c2y, c2z = cx * cx - sx * sx, cy * cy - sy * sy, cz * cz - sz * sz + if code == SCHOEN_IWP: + v = 2.0 * (cx * cy + cy * cz + cz * cx) - (c2x + c2y + c2z) + gx = -2.0 * sx * (cy + cz) + 2.0 * s2x + gy = -2.0 * sy * (cx + cz) + 2.0 * s2y + gz = -2.0 * sz * (cx + cy) + 2.0 * s2z + return v, gx, gy, gz + if code == SCHOEN_FRD: + v = 4.0 * cx * cy * cz - (c2x * c2y + c2y * c2z + c2z * c2x) + gx = -4.0 * sx * cy * cz + 2.0 * s2x * (c2y + c2z) + gy = -4.0 * cx * sy * cz + 2.0 * s2y * (c2x + c2z) + gz = -4.0 * cx * cy * sz + 2.0 * s2z * (c2x + c2y) + return v, gx, gy, gz + if code == FISCHER_KOCH_S: + v = c2x * sy * cz + cx * c2y * sz + sx * cy * c2z + gx = -2.0 * s2x * sy * cz - sx * c2y * sz + cx * cy * c2z + gy = c2x * cy * cz - 2.0 * cx * s2y * sz - sx * sy * c2z + gz = -c2x * sy * sz + cx * c2y * cz - 2.0 * sx * cy * s2z + return v, gx, gy, gz + a, ax, ay, az, b, bx, by, bz = _cyclic(sx, sy, sz, cx, cy, cz, s2x, s2y, s2z, c2x, c2y, c2z) + if code == LIDINOID: + return 0.5 * (a - b) + 0.15, 0.5 * (ax - bx), 0.5 * (ay - by), 0.5 * (az - bz) + if code == SPLIT_P: + v = 1.1 * a - 0.2 * b - 0.4 * (c2x + c2y + c2z) + gx = 1.1 * ax - 0.2 * bx + 0.8 * s2x + gy = 1.1 * ay - 0.2 * by + 0.8 * s2y + gz = 1.1 * az - 0.2 * bz + 0.8 * s2z + return v, gx, gy, gz + # I2-Y + return -2.0 * a + b, -2.0 * ax + bx, -2.0 * ay + by, -2.0 * az + bz @njit(cache=True, inline="always") -def _signed(code, sheet, level, X, Y, Z): - """Negative inside the solid: phi - t (network) or |phi| - t (sheet).""" - v = tpms_value(code, X, Y, Z) - if sheet: - return abs(v) - level - return v - level +def tpms_value(code, X, Y, Z): + """phi(X, Y, Z) with X = 2 pi x / a (and similarly Y, Z).""" + if code == GYROID: + return math.sin(X) * math.cos(Y) + math.sin(Y) * math.cos(Z) + math.sin(Z) * math.cos(X) + if code == SCHWARZ_P: + return math.cos(X) + math.cos(Y) + math.cos(Z) + return tpms_value_gradient(code, X, Y, Z)[0] + + +@njit(cache=True, inline="always") +def _level(levels, axis, lo, length, x, y, z): + """The level at a point and its derivative along the axis of the table.""" + m = levels.shape[0] + if m == 1: + return levels[0], 0.0 + s = x if axis == 0 else (y if axis == 1 else z) + u = (s - lo) / length * (m - 1) + if u <= 0.0: + return levels[0], 0.0 + if u >= m - 1: + return levels[m - 1], 0.0 + j = int(u) + f = u - j + return levels[j] + f * (levels[j + 1] - levels[j]), (levels[j + 1] - levels[j]) * ( + m - 1 + ) / length + + +@njit(cache=True, inline="always") +def _inside(code, mode, levels, axis, lo, length, k, offset, x, y, z): + """Whether the point is in the solid.""" + v = tpms_value(code, k[0] * (x - offset[0]), k[1] * (y - offset[1]), k[2] * (z - offset[2])) + t = _level(levels, axis, lo, length, x, y, z)[0] + if mode == SHEET: + return abs(v) <= t + if mode == UPPER_NETWORK: + return v >= t + return v <= t + + +@njit(cache=True, inline="always") +def _distance(code, mode, levels, axis, lo, length, k, offset, x, y, z): + """First-order distance ``f / |grad f|`` of the function ``f`` of the solid + (negative inside): ``phi - t``, ``|phi| - t`` or ``t - phi``.""" + v, gx, gy, gz = tpms_value_gradient( + code, k[0] * (x - offset[0]), k[1] * (y - offset[1]), k[2] * (z - offset[2]) + ) + gx, gy, gz = k[0] * gx, k[1] * gy, k[2] * gz + t, dt = _level(levels, axis, lo, length, x, y, z) + if mode == SHEET: + if v < 0.0: + v, gx, gy, gz = -v, -gx, -gy, -gz + f = v - t + elif mode == UPPER_NETWORK: + f = t - v + else: + f = v - t + if axis == 0: + gx -= dt + elif axis == 1: + gy -= dt + else: + gz -= dt + return f / max(math.sqrt(gx * gx + gy * gy + gz * gz), 1e-12) @njit(parallel=True, cache=True) -def tpms_count(code, sheet, level, k, offset, grid_lo, spacing, shape, ss, out): +def tpms_count(code, mode, levels, axis, lo, length, k, offset, grid_lo, spacing, shape, ss, out): + """The number of the ``ss^3`` samples of each voxel in the solid.""" inv = 1.0 / ss for i in prange(shape[0]): for j in range(shape[1]): for kk in range(shape[2]): cnt = 0 for a in range(ss): - X = k[0] * (grid_lo[0] + (i + (a + 0.5) * inv) * spacing[0] - offset[0]) + x = grid_lo[0] + (i + (a + 0.5) * inv) * spacing[0] for b in range(ss): - Y = k[1] * (grid_lo[1] + (j + (b + 0.5) * inv) * spacing[1] - offset[1]) + y = grid_lo[1] + (j + (b + 0.5) * inv) * spacing[1] for c in range(ss): - Z = k[2] * ( - grid_lo[2] + (kk + (c + 0.5) * inv) * spacing[2] - offset[2] - ) - if _signed(code, sheet, level, X, Y, Z) <= 0.0: + z = grid_lo[2] + (kk + (c + 0.5) * inv) * spacing[2] + if _inside(code, mode, levels, axis, lo, length, k, offset, x, y, z): cnt += 1 out[i, j, kk] = cnt @njit(parallel=True, cache=True) -def tpms_level_set(code, sheet, level, k, offset, grid_lo, spacing, shape, out): - """First-order distance estimate (phi - t) / |grad phi| at voxel centres.""" +def tpms_level_set(code, mode, levels, axis, lo, length, k, offset, grid_lo, spacing, shape, out): + """First-order distance of the solid (:func:`_distance`) at voxel centres.""" for i in prange(shape[0]): - X = k[0] * (grid_lo[0] + (i + 0.5) * spacing[0] - offset[0]) + x = grid_lo[0] + (i + 0.5) * spacing[0] for j in range(shape[1]): - Y = k[1] * (grid_lo[1] + (j + 0.5) * spacing[1] - offset[1]) + y = grid_lo[1] + (j + 0.5) * spacing[1] for kk in range(shape[2]): - Z = k[2] * (grid_lo[2] + (kk + 0.5) * spacing[2] - offset[2]) - g = tpms_gradient_norm(code, X, Y, Z, k[0], k[1], k[2]) - out[i, j, kk] = _signed(code, sheet, level, X, Y, Z) / max(g, 1e-12) + z = grid_lo[2] + (kk + 0.5) * spacing[2] + out[i, j, kk] = _distance(code, mode, levels, axis, lo, length, k, offset, x, y, z) @njit(parallel=True, cache=True) -def tpms_level_points(code, sheet, level, k, offset, pts, out): +def tpms_level_points(code, mode, levels, axis, lo, length, k, offset, pts, out): """The first-order distance of :func:`tpms_level_set` at points.""" for p in prange(pts.shape[0]): - X = k[0] * (pts[p, 0] - offset[0]) - Y = k[1] * (pts[p, 1] - offset[1]) - Z = k[2] * (pts[p, 2] - offset[2]) - g = tpms_gradient_norm(code, X, Y, Z, k[0], k[1], k[2]) - out[p] = _signed(code, sheet, level, X, Y, Z) / max(g, 1e-12) + out[p] = _distance( + code, mode, levels, axis, lo, length, k, offset, pts[p, 0], pts[p, 1], pts[p, 2] + ) + + +@njit(parallel=True, cache=True) +def tpms_points(code, mode, levels, axis, lo, length, k, offset, pts, out): + """Whether the points are in the solid.""" + for p in prange(pts.shape[0]): + out[p] = _inside( + code, mode, levels, axis, lo, length, k, offset, pts[p, 0], pts[p, 1], pts[p, 2] + ) + + +@njit(parallel=True, cache=True) +def tpms_cell_values(code, n, out): + """``phi`` at the centres of an ``n^3`` grid of one period ``[0, 2 pi)^3``.""" + h = 2.0 * math.pi / n + for i in prange(n): + X = (i + 0.5) * h + for j in range(n): + Y = (j + 0.5) * h + for kk in range(n): + out[i, j, kk] = tpms_value(code, X, Y, (kk + 0.5) * h) @njit(parallel=True, cache=True) @@ -134,12 +281,3 @@ def fourier_points(modes, re, im, lengths, origin, pts, out): br, bi = ar * zr - ai * zi, ar * zi + ai * zr total += re[j] * br - im[j] * bi out[p] = total - - -@njit(parallel=True, cache=True) -def tpms_points(code, sheet, level, k, offset, pts, out): - for p in prange(pts.shape[0]): - X = k[0] * (pts[p, 0] - offset[0]) - Y = k[1] * (pts[p, 1] - offset[1]) - Z = k[2] * (pts[p, 2] - offset[2]) - out[p] = _signed(code, sheet, level, X, Y, Z) <= 0.0 diff --git a/src/morphogen/models/tpms.py b/src/morphogen/models/tpms.py index 9b12d74..d6323ac 100644 --- a/src/morphogen/models/tpms.py +++ b/src/morphogen/models/tpms.py @@ -1,8 +1,12 @@ -"""Triply periodic minimal surface (TPMS) architectures.""" +"""Triply periodic minimal surface (TPMS) architectures: ten surfaces (the nodal +approximations of :mod:`morphogen.kernels.implicit`), their networks on either side of a +level and their sheets, at a level, a volume fraction or a gradient of the volume +fraction along an axis (graded TPMS).""" from __future__ import annotations from dataclasses import dataclass +from functools import lru_cache from typing import ClassVar import numpy as np @@ -17,39 +21,89 @@ #: Samples per unit-cell edge used to relate the level to the volume fraction. _CALIBRATION_SAMPLES = 96 +#: Levels of a graded TPMS per interval of its fractions (the table the kernels interpolate). +_GRADED_SAMPLES = 64 +#: The surfaces of the model. +SURFACES = tuple(implicit.SURFACES) +#: The solids of a level: the network ``phi <= t``, the sheet ``|phi| <= t``, the other +#: network ``phi >= t``. +VARIANTS = tuple(implicit.MODES) +@lru_cache(maxsize=32) def _unit_cell_values(code: int, n: int = _CALIBRATION_SAMPLES) -> np.ndarray: - """phi at the centres of an n^3 grid of one unit cell.""" - t = 2.0 * np.pi * (np.arange(n) + 0.5) / n - X, Y, Z = np.meshgrid(t, t, t, indexing="ij") - sx, sy, sz, cx, cy, cz = np.sin(X), np.sin(Y), np.sin(Z), np.cos(X), np.cos(Y), np.cos(Z) - if code == implicit.GYROID: - return (sx * cy + sy * cz + sz * cx).ravel() - if code == implicit.SCHWARZ_P: - return (cx + cy + cz).ravel() - if code == implicit.SCHWARZ_D: - return (sx * sy * sz + sx * cy * cz + cx * sy * cz + cx * cy * sz).ravel() - return (3.0 * (cx + cy + cz) + 4.0 * cx * cy * cz).ravel() + """phi at the centres of an n^3 grid of one unit cell (read-only).""" + out = np.empty((n, n, n)) + implicit.tpms_cell_values(code, n, out) + values = out.ravel() + values.flags.writeable = False + return values + + +def _side(values: np.ndarray, variant: str) -> np.ndarray: + """The values whose lowest quantiles are the solid: phi, |phi| or -phi.""" + if variant == "sheet": + return np.abs(values) + if variant == "upper_network": + return -values + return values + + +def level_of_fraction(surface: str, variant: str, fraction, n: int = _CALIBRATION_SAMPLES): + """The level ``t`` whose solid has the volume fraction ``fraction`` (a number or an + array), on a fine sampling of the unit cell.""" + side = _side(_unit_cell_values(implicit.SURFACES[surface], n), variant) + t = np.quantile(side, fraction) + return -t if variant == "upper_network" else t + + +def fraction_of_level(surface: str, variant: str, level: float, n: int = 128) -> float: + """The volume fraction of the solid at the level ``level`` (numerical).""" + values = _unit_cell_values(implicit.SURFACES[surface], n) + if variant == "sheet": + return float(np.mean(np.abs(values) <= level)) + if variant == "upper_network": + return float(np.mean(values >= level)) + return float(np.mean(values <= level)) @register_kind class TPMSStructure(Microstructure): - """Solid ``{phi <= level}`` (network) or ``{|phi| <= level}`` (sheet).""" + """Solid ``{phi <= level}`` (network), ``{|phi| <= level}`` (sheet) or + ``{phi >= level}`` (the other network); with ``levels``, the level varies along + ``gradient_axis``, interpolated linearly in a table of levels at equally spaced + positions from the lower to the upper face of the domain (a graded TPMS).""" kind = "tpms" - def __init__(self, domain, surface, variant, level, cell_size, **kwargs): + def __init__( + self, domain, surface, variant, level, cell_size, *, levels=None, gradient_axis=0, + **kwargs, + ): # fmt: skip super().__init__(domain, **kwargs) self.surface = surface self.variant = variant self.level = float(level) self.cell_size = np.asarray(as_triplet(cell_size, "cell_size", positive=True)) + self.levels = None if levels is None else np.asarray(levels, dtype=float) + self.gradient_axis = int(gradient_axis) self._code = implicit.SURFACES[surface] + self._mode = implicit.MODES[variant] self._k = 2.0 * np.pi / self.cell_size + self._table = np.array([self.level]) if self.levels is None else self.levels def _args(self): - return self._code, self.variant == "sheet", self.level, self._k, self.domain.lower + axis = self.gradient_axis + return ( + self._code, + self._mode, + self._table, + axis, + float(self.domain.lower[axis]), + float(self.domain.lengths[axis]), + self._k, + self.domain.lower, + ) def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1): grid = self.grid(shape, voxel_size=voxel_size, grid=grid) @@ -66,7 +120,8 @@ def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, sup return VoxelImage.from_grid(data, grid, name="fraction", metadata=self.image_metadata()) def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage: - """First-order signed distance ``(phi - t) / |grad phi|`` (negative in the solid).""" + """First-order signed distance ``f / |grad f|`` of the function of the solid + (``phi - t``, ``|phi| - t`` or ``t - phi``; negative in the solid).""" grid = self.grid(shape, voxel_size=voxel_size, grid=grid) out = np.empty(grid.shape, dtype=np.float32) implicit.tpms_level_set( @@ -84,7 +139,7 @@ def contains(self, points) -> np.ndarray: lipschitz = 1.5 def level_set_at(self, points, reach: float = np.inf) -> np.ndarray: - """``(phi - t) / |grad phi|`` at the points, as :meth:`level_set`.""" + """The first-order distance of :meth:`level_set` at the points.""" pts = np.ascontiguousarray(points, dtype=float).reshape(-1, 3) out = np.empty(len(pts)) implicit.tpms_level_points(*self._args(), pts, out) @@ -92,15 +147,22 @@ def level_set_at(self, points, reach: float = np.inf) -> np.ndarray: def summary(self) -> dict: cells = self.domain.lengths / self.cell_size - return {"surface": self.surface, "cells": "x".join(f"{c:g}" for c in cells)} + out = {"surface": self.surface, "cells": "x".join(f"{c:g}" for c in cells)} + if self.levels is not None: + out["graded"] = "xyz"[self.gradient_axis] + return out def _geometry(self) -> dict: - return { + out = { "surface": self.surface, "variant": self.variant, "level": self.level, "cell_size": self.cell_size.tolist(), } + if self.levels is not None: + out["levels"] = self.levels.tolist() + out["gradient_axis"] = self.gradient_axis + return out @classmethod def _from_geometry(cls, domain, geometry, **kwargs): @@ -110,6 +172,8 @@ def _from_geometry(cls, domain, geometry, **kwargs): geometry["variant"], geometry["level"], geometry["cell_size"], + levels=geometry.get("levels"), + gradient_axis=geometry.get("gradient_axis", 0), **kwargs, ) @@ -118,60 +182,118 @@ def _from_geometry(cls, domain, geometry, **kwargs): @anisotropic @dataclass(frozen=True) class TPMS(Model): - """TPMS lattice: gyroid, Schwarz P (primitive), Schwarz D (diamond) or Neovius. + """TPMS lattice: gyroid, Schwarz P (primitive) and D (diamond), Neovius, Schoen's I-WP + and F-RD, Fischer–Koch S, the lidinoid, split P or I2-Y (nodal approximations). - ``network``: solid ``{phi <= level}``; ``sheet``: solid ``{|phi| <= level}`` (walls around - the minimal surface). Give the level or the target volume fraction (solid fraction), - from which the level is computed on a fine sampling of the unit cell. + ``network``: solid ``{phi <= level}``; ``sheet``: solid ``{|phi| <= level}`` (walls + around the minimal surface); ``upper_network``: the network on the other side of the + surface, ``{phi >= level}`` (the image of the network by a symmetry of the lattice for + the balanced surfaces: gyroid, Schwarz P and D, Neovius, Fischer–Koch S). Give the + level, the target volume fraction (solid fraction), from which the level is computed + on a fine sampling of the unit cell, or the fractions of a graded TPMS: + ``fraction_gradient`` lists the volume fractions at equally spaced positions from the + lower to the upper face of the domain along ``gradient_axis`` (two values: a linear + gradient), interpolated linearly, each position at the level of its fraction (in a + non-periodic domain). """ name = "tpms" phases: ClassVar[dict[int, str]] = {0: "void", 1: "solid"} count_label = "unit cells" - surface: str = param("gyroid", doc="gyroid, schwarz_p, schwarz_d or neovius", kind="str") + surface: str = param( + "gyroid", + doc="gyroid, schwarz_p, schwarz_d, neovius, schoen_iwp, schoen_frd, fischer_koch_s, " + "lidinoid, split_p or i2_y", + kind="str", + ) cell_size: float | tuple = param( 1.0, doc="Edge of the unit cell (one value or three)", kind="vector", unit="length" ) - variant: str = param("network", doc="'network' (solid skeleton) or 'sheet' (walls)", kind="str") + variant: str = param( + "network", + doc="'network' (solid skeleton, phi <= level), 'sheet' (walls, |phi| <= level) or " + "'upper_network' (the other skeleton, phi >= level)", + kind="str", + ) level: float | None = param(None, doc="Level t of the iso-surface") volume_fraction: float | None = param(None, doc="Target solid volume fraction", kind="fraction") + fraction_gradient: tuple[float, ...] | None = param( + None, + doc="Solid volume fractions at equally spaced positions from the lower to the upper " + "face of the domain along gradient_axis, interpolated linearly: a graded TPMS " + "(non-periodic domains)", + kind="floats", + ) + gradient_axis: int = param( + 0, doc="Axis of the gradient of the volume fraction: 0, 1 or 2", kind="int" + ) anisotropy: Anisotropy | None = param(None, doc=ANISOTROPY, kind="anisotropy", kw_only=True) def _validate(self) -> None: if self.surface not in implicit.SURFACES: + raise ValueError(f"surface: expected one of {list(SURFACES)}, got {self.surface!r}") + if self.variant not in implicit.MODES: + raise ValueError(f"variant: expected one of {list(VARIANTS)}, got {self.variant!r}") + as_triplet(self.cell_size, "cell_size", positive=True) + given = [v is not None for v in (self.level, self.volume_fraction, self.fraction_gradient)] + if sum(given) != 1: raise ValueError( - f"surface: expected one of {sorted(implicit.SURFACES)}, got {self.surface!r}" + "give exactly one of 'level', 'volume_fraction' and 'fraction_gradient'" ) - if self.variant not in ("network", "sheet"): - raise ValueError(f"variant: expected 'network' or 'sheet', got {self.variant!r}") - as_triplet(self.cell_size, "cell_size", positive=True) - if (self.level is None) == (self.volume_fraction is None): - raise ValueError("give exactly one of 'level' and 'volume_fraction'") if self.volume_fraction is not None: check_fraction(self.volume_fraction, "volume_fraction") + if self.fraction_gradient is not None: + if len(self.fraction_gradient) < 2: + raise ValueError( + "fraction_gradient: the fractions at two positions at least (the lower " + "and upper faces)" + ) + for f in self.fraction_gradient: + check_fraction(f, "fraction_gradient") + if self.gradient_axis not in (0, 1, 2): + raise ValueError("gradient_axis: 0, 1 or 2") if self.variant == "sheet" and self.level is not None and self.level < 0: raise ValueError("level: must be non-negative for sheet TPMS") @property def iso_level(self) -> float: + """The level of the solid (of the mean fraction of a graded TPMS).""" if self.level is not None: return float(self.level) - values = _unit_cell_values(implicit.SURFACES[self.surface]) - if self.variant == "sheet": - values = np.abs(values) - return float(np.quantile(values, self.volume_fraction)) + return float(level_of_fraction(self.surface, self.variant, self.mean_fraction())) + + def mean_fraction(self) -> float: + """The target volume fraction, or the mean of the profile of a graded TPMS.""" + if self.fraction_gradient is not None: + f = np.asarray(self.fraction_gradient, dtype=float) + return float(np.mean(0.5 * (f[1:] + f[:-1]))) + if self.volume_fraction is not None: + return float(self.volume_fraction) + return self.solid_fraction() + + def graded_levels(self) -> np.ndarray | None: + """The table of the levels of a graded TPMS, at ``_GRADED_SAMPLES`` positions per + interval of its fractions (None for a constant level).""" + if self.fraction_gradient is None: + return None + f = np.asarray(self.fraction_gradient, dtype=float) + s = np.linspace(0.0, 1.0, _GRADED_SAMPLES * (len(f) - 1) + 1) + fractions = np.interp(s, np.linspace(0.0, 1.0, len(f)), f) + return np.asarray(level_of_fraction(self.surface, self.variant, fractions), dtype=float) def solid_fraction(self) -> float: - """Volume fraction of the solid for the current level (numerical).""" - values = _unit_cell_values(implicit.SURFACES[self.surface], 128) - if self.variant == "sheet": - values = np.abs(values) - return float(np.mean(values <= self.iso_level)) + """Volume fraction of the solid (numerical; the mean of a graded profile).""" + if self.fraction_gradient is not None: + return self.mean_fraction() + return fraction_of_level(self.surface, self.variant, self.iso_level) def generate(self, domain: Domain, seed: SeedLike = None) -> TPMSStructure: _, seed_info = make_rng(seed) cell = np.array(as_triplet(self.cell_size, "cell_size", positive=True)) + levels = self.graded_levels() + if levels is not None and domain.periodic: + raise ValueError("tpms: a graded TPMS needs a non-periodic domain") if domain.periodic: ratio = domain.lengths / cell if np.any(np.abs(ratio - np.rint(ratio)) > 1e-6 * np.maximum(ratio, 1.0)): @@ -183,8 +305,10 @@ def generate(self, domain: Domain, seed: SeedLike = None) -> TPMSStructure: domain, self.surface, self.variant, - self.iso_level, + self.iso_level if levels is None else float(np.mean(levels)), tuple(cell), + levels=levels, + gradient_axis=self.gradient_axis, model=self, seed=seed_info, ) @@ -194,4 +318,6 @@ def expected_count(self, domain: Domain) -> float: return domain.volume / float(np.prod(np.broadcast_to(self.cell_size, 3))) def theory(self, domain: Domain | None = None) -> dict[str, float]: + if self.fraction_gradient is not None: + return {"volume_fraction": self.mean_fraction()} return {"level": self.iso_level, "volume_fraction": self.solid_fraction()} diff --git a/tests/public_api.txt b/tests/public_api.txt index 3801343..6218e4c 100644 --- a/tests/public_api.txt +++ b/tests/public_api.txt @@ -4621,18 +4621,24 @@ morphogen.models.tiling_field.TilingField.summary(self) morphogen.models.tiling_field.TilingField.voxelize(self, shape=None, *, voxel_size=None, grid=None, supersampling=1) morphogen.models.tiling_field.VOXELS_PER_CELL morphogen.models.tiling_field.default_grid(domain, tiling) -morphogen.models.tpms.TPMS(surface='gyroid', cell_size=1.0, variant='network', level=None, volume_fraction=None, *, anisotropy=None) +morphogen.models.tpms.SURFACES +morphogen.models.tpms.TPMS(surface='gyroid', cell_size=1.0, variant='network', level=None, volume_fraction=None, fraction_gradient=None, gradient_axis=0, *, anisotropy=None) morphogen.models.tpms.TPMS.expected_count(self, domain) morphogen.models.tpms.TPMS.generate(self, domain, seed=None) +morphogen.models.tpms.TPMS.graded_levels(self) morphogen.models.tpms.TPMS.iso_level +morphogen.models.tpms.TPMS.mean_fraction(self) morphogen.models.tpms.TPMS.solid_fraction(self) morphogen.models.tpms.TPMS.theory(self, domain=None) -morphogen.models.tpms.TPMSStructure(domain, surface, variant, level, cell_size, **kwargs) +morphogen.models.tpms.TPMSStructure(domain, surface, variant, level, cell_size, *, levels=None, gradient_axis=0, **kwargs) morphogen.models.tpms.TPMSStructure.contains(self, points) morphogen.models.tpms.TPMSStructure.level_set(self, shape=None, *, voxel_size=None, grid=None) morphogen.models.tpms.TPMSStructure.level_set_at(self, points, reach=inf) morphogen.models.tpms.TPMSStructure.summary(self) morphogen.models.tpms.TPMSStructure.voxelize(self, shape=None, *, voxel_size=None, grid=None, supersampling=1) +morphogen.models.tpms.VARIANTS +morphogen.models.tpms.fraction_of_level(surface, variant, level, n=128) +morphogen.models.tpms.level_of_fraction(surface, variant, fraction, n=96) morphogen.models.transparent.TransparentDeadLeaves(domain, centers, radii, values, *, alpha, threshold, mean_value, **kwargs) morphogen.models.transparent.TransparentDeadLeaves.contains(self, points) morphogen.models.transparent.TransparentDeadLeaves.field(self, shape=None, *, voxel_size=None, grid=None) diff --git a/tests/test_models_cells_fields.py b/tests/test_models_cells_fields.py index 3120128..16d8332 100644 --- a/tests/test_models_cells_fields.py +++ b/tests/test_models_cells_fields.py @@ -170,8 +170,8 @@ def test_tpms_level_set_and_errors(): assert np.array_equal(micro.contains(pts).reshape(img.shape), img.data == 1) with pytest.raises(ValueError, match="whole number"): TPMS(cell_size=0.7, level=0.0).generate(mg.Domain.cube(1.0)) - with pytest.raises(ValueError): - TPMS(surface="lidinoid", level=0.0) + with pytest.raises(ValueError, match="surface"): + TPMS(surface="schwarz_h", level=0.0) # -- strut lattices --------------------------------------------------------------------------- diff --git a/tests/test_tpms_surfaces.py b/tests/test_tpms_surfaces.py new file mode 100644 index 0000000..9fff845 --- /dev/null +++ b/tests/test_tpms_surfaces.py @@ -0,0 +1,180 @@ +"""The ten TPMS surfaces, their three solids and the graded TPMS (theory.md §6, §140).""" + +import numpy as np +import pytest + +import morphogen as mg +from morphogen import analysis, io, pipeline +from morphogen.config import load_config +from morphogen.kernels import implicit +from morphogen.models.base import Microstructure +from morphogen.models.tpms import TPMS, level_of_fraction + +SURFACES = list(implicit.SURFACES) + + +def test_gradients_symmetry_and_period(): + """The derivatives of every surface are those of its function (central differences); + every function has the cubic symmetry of the cyclic permutation of the axes and the + period 2 pi.""" + rng = np.random.default_rng(0) + h = 1e-6 + for name, code in implicit.SURFACES.items(): + for X, Y, Z in rng.uniform(0.0, 2.0 * np.pi, (40, 3)): + v, *g = implicit.tpms_value_gradient(code, X, Y, Z) + assert implicit.tpms_value(code, X, Y, Z) == pytest.approx(v, abs=1e-12) + for a in range(3): + e = np.zeros(3) + e[a] = h + up = implicit.tpms_value(code, *(np.array([X, Y, Z]) + e)) + down = implicit.tpms_value(code, *(np.array([X, Y, Z]) - e)) + assert g[a] == pytest.approx((up - down) / (2 * h), abs=1e-6), name + assert implicit.tpms_value(code, Y, Z, X) == pytest.approx(v, abs=1e-12), name + shifted = implicit.tpms_value(code, X + 2 * np.pi, Y - 2 * np.pi, Z + 4 * np.pi) + assert shifted == pytest.approx(v, abs=1e-9), name + + +def test_published_forms(): + """The nodal forms at a point, against their published expressions (Lord & Mackay + 2003): Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P and I2-Y.""" + X, Y, Z = 0.3, 1.1, -0.7 + s, c = np.sin, np.cos + cyclic = s(2 * X) * c(Y) * s(Z) + s(X) * s(2 * Y) * c(Z) + c(X) * s(Y) * s(2 * Z) + pairs = c(2 * X) * c(2 * Y) + c(2 * Y) * c(2 * Z) + c(2 * Z) * c(2 * X) + expected = { + "schoen_iwp": 2 * (c(X) * c(Y) + c(Y) * c(Z) + c(Z) * c(X)) + - (c(2 * X) + c(2 * Y) + c(2 * Z)), + "schoen_frd": 4 * c(X) * c(Y) * c(Z) - pairs, + "fischer_koch_s": c(2 * X) * s(Y) * c(Z) + c(X) * c(2 * Y) * s(Z) + s(X) * c(Y) * c(2 * Z), + "lidinoid": 0.5 * cyclic - 0.5 * pairs + 0.15, + "split_p": 1.1 * cyclic - 0.2 * pairs - 0.4 * (c(2 * X) + c(2 * Y) + c(2 * Z)), + "i2_y": -2 * cyclic + pairs, + } + for name, value in expected.items(): + assert implicit.tpms_value(implicit.SURFACES[name], X, Y, Z) == pytest.approx(value) + + +@pytest.mark.parametrize("surface", SURFACES) +@pytest.mark.parametrize("variant", ["network", "sheet", "upper_network"]) +def test_fraction_level_set_and_points(surface, variant): + """Each solid at a target fraction: the fraction of its voxels, its level set negative + exactly where its voxels are solid, its points, and periodic tiles.""" + model = TPMS(surface=surface, cell_size=1.0, variant=variant, volume_fraction=0.3) + assert model.theory()["volume_fraction"] == pytest.approx(0.3, abs=5e-3) + micro = model.generate(mg.Domain.cube(1.0)) + img = micro.voxelize(shape=48) + assert analysis.volume_fraction(img) == pytest.approx(0.3, abs=0.012) + assert np.array_equal(micro.level_set(shape=48).data <= 0, img.data == 1) + pts = img.grid().center_points() + assert np.array_equal(micro.contains(pts).reshape(img.shape), img.data == 1) + two = model.generate(mg.Domain.cube(2.0)).voxelize(shape=96).data + assert np.array_equal(np.tile(img.data, (2, 2, 2)), two) + + +@pytest.mark.parametrize("surface", ["schoen_iwp", "lidinoid", "gyroid"]) +def test_upper_network_is_the_complement(surface): + """The other network at the fraction f is the complement of the network at 1 - f: + the same level, the other side.""" + upper = TPMS(surface=surface, variant="upper_network", volume_fraction=0.35) + lower = TPMS(surface=surface, variant="network", volume_fraction=0.65) + assert upper.iso_level == pytest.approx(lower.iso_level, abs=1e-9) + a = upper.generate(mg.Domain.cube(1.0)).voxelize(shape=32).data + b = lower.generate(mg.Domain.cube(1.0)).voxelize(shape=32).data + assert np.mean(a + b == 1) > 0.999 + + +def test_balanced_networks_are_alike(): + """Schwarz P is balanced: its other network is its network moved by half a cell, at + the opposite level; the I-WP is not: the levels of its two networks at a fraction are + not opposite (its function is skewed).""" + p = mg.Domain.cube(1.0) + lower = TPMS(surface="schwarz_p", volume_fraction=0.25).generate(p).voxelize(shape=32).data + upper = TPMS(surface="schwarz_p", variant="upper_network", volume_fraction=0.25) + moved = np.roll(upper.generate(p).voxelize(shape=32).data, (16, 16, 16), axis=(0, 1, 2)) + assert np.array_equal(lower, moved) + for surface, balanced in (("schwarz_p", True), ("schoen_iwp", False), ("lidinoid", False)): + t = level_of_fraction(surface, "network", 0.25) + u = level_of_fraction(surface, "upper_network", 0.25) + assert (abs(t + u) < 1e-3) == balanced, surface + + +def test_graded_fraction_profile(): + """A graded TPMS: the fraction of each slab of one cell follows the prescribed + profile (two and three fractions), and the mean fraction is the theory's.""" + domain = mg.Domain(size=(8.0, 2.0, 2.0), periodic=False) + for profile in ((0.15, 0.45), (0.2, 0.5, 0.2)): + model = TPMS(surface="gyroid", variant="sheet", fraction_gradient=profile) + micro = model.generate(domain) + img = micro.voxelize(shape=(256, 64, 64)) + slabs = img.data.reshape(8, 32, 64, 64).mean(axis=(1, 2, 3)) + x = (np.arange(8) + 0.5) / 8 + target = np.interp(x, np.linspace(0, 1, len(profile)), profile) + assert np.max(np.abs(slabs - target)) < 0.02 + assert img.data.mean() == pytest.approx(model.theory()["volume_fraction"], abs=0.01) + assert np.array_equal(micro.level_set(shape=(128, 32, 32)).data <= 0, + micro.voxelize(shape=(128, 32, 32)).data == 1) # fmt: skip + model = TPMS(surface="schoen_iwp", fraction_gradient=(0.1, 0.4), gradient_axis=2) + micro = model.generate(mg.Domain(size=(2.0, 2.0, 6.0), periodic=False)) + data = micro.voxelize(shape=(32, 32, 96)).data + assert data[:, :, :16].mean() < 0.17 < 0.33 < data[:, :, -16:].mean() + + +def test_graded_distance_and_round_trip(tmp_path): + """The level set of a graded TPMS is a distance near its surface (its slope about 1 + across the surface), and the realization is written and read back.""" + model = TPMS(surface="split_p", fraction_gradient=(0.2, 0.4), cell_size=1.0) + domain = mg.Domain(size=(4.0, 1.0, 1.0), periodic=False) + micro = model.generate(domain) + rng = np.random.default_rng(3) + pts = rng.uniform(domain.lower, domain.upper, (4000, 3)) + phi = micro.level_set_at(pts) + near = pts[np.abs(phi) < 0.01] + g = [] + for p in near[:200]: + grad = [ + (micro.level_set_at(p + e)[0] - micro.level_set_at(p - e)[0]) / 2e-5 + for e in 1e-5 * np.eye(3) + ] + g.append(np.linalg.norm(grad)) + assert np.median(g) == pytest.approx(1.0, abs=0.05) + path = tmp_path / "graded.json" + io.save_microstructure(micro, path) + back = io.load_microstructure(path) + assert isinstance(back, Microstructure) + assert np.array_equal(back.voxelize(shape=(64, 16, 16)).data, + micro.voxelize(shape=(64, 16, 16)).data) # fmt: skip + + +def test_graded_levels_and_errors(): + """The levels of a graded TPMS are those of its fractions; errors.""" + model = TPMS(surface="gyroid", fraction_gradient=(0.2, 0.6)) + levels = model.graded_levels() + assert levels[0] == pytest.approx(level_of_fraction("gyroid", "network", 0.2)) + assert levels[-1] == pytest.approx(level_of_fraction("gyroid", "network", 0.6)) + assert np.all(np.diff(levels) > 0) + with pytest.raises(ValueError, match="non-periodic"): + model.generate(mg.Domain.cube(1.0)) + with pytest.raises(ValueError, match="exactly one"): + TPMS(volume_fraction=0.3, fraction_gradient=(0.2, 0.4)) + with pytest.raises(ValueError, match="two positions"): + TPMS(fraction_gradient=(0.2,)) + with pytest.raises(ValueError, match="fraction_gradient"): + TPMS(fraction_gradient=(0.2, 1.2)) + with pytest.raises(ValueError, match="gradient_axis"): + TPMS(fraction_gradient=(0.2, 0.4), gradient_axis=3) + with pytest.raises(ValueError, match="variant"): + TPMS(variant="exoskeletal", volume_fraction=0.3) + + +def test_graded_in_a_configuration(tmp_path): + """A graded TPMS from a configuration, its surface written as STL.""" + config = { + "model": {"type": "tpms", "surface": "schoen_frd", "variant": "sheet", + "fraction_gradient": [0.15, 0.35], "gradient_axis": 0}, + "domain": {"size": [4.0, 1.0, 1.0], "periodic": False}, + "voxels": {"shape": [64, 16, 16]}, + "outputs": {"directory": str(tmp_path), "name": "frd", "surface": ["stl"]}, + } # fmt: skip + outdir = pipeline.run(load_config(config)) + stl = list(outdir.rglob("frd*.stl")) + assert stl and stl[0].stat().st_size > 1000 From e95583dbe92ca0ad517b2180c1a8fb6e9d7cdfa8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 23:28:37 +0000 Subject: [PATCH 02/13] Spinodoids: levels of sums of waves of one wavelength MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The model spinodoid (theory notes §141, FR-G30, specification 1.255): the level of a sum of waves of one wavelength and random phases (Cahn 1965; Soyarslan et al. 2018; Kumar et al. 2020), their directions uniform on the sphere or within cones about the axes (lamellar, columnar, cubic); the network, the sheet or the other network at a level of the normal law, a volume fraction or a profile of fractions along an axis (graded); in periodic boxes the modes of a shell about the wavelength. The specific surface of Rice's formula in the theory; grids evaluated plane by plane as products of complex matrices. The model in the registry, the interface, the sections and the per-model tests; the count of the models (50) in the documentation; the public interface written again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MSrXEMpgnWPQNUwHwAgXHV --- CHANGELOG.md | 10 + README.md | 2 +- docs/api.md | 2 +- docs/architecture.md | 2 +- docs/guide.md | 2 +- docs/index.md | 2 +- docs/models.md | 3 +- docs/specification.md | 6 +- docs/theory.md | 75 ++++- docs/tutorial_geometry.md | 2 +- docs/tutorial_interface.md | 2 +- src/morphogen/gui/api.py | 2 +- src/morphogen/models/__init__.py | 8 +- src/morphogen/models/spinodoid.py | 518 ++++++++++++++++++++++++++++++ src/morphogen/viz/sections.py | 2 + tests/public_api.txt | 25 ++ tests/test_models_base.py | 1 + tests/test_spinodoid.py | 167 ++++++++++ 18 files changed, 819 insertions(+), 12 deletions(-) create mode 100644 src/morphogen/models/spinodoid.py create mode 100644 tests/test_spinodoid.py diff --git a/CHANGELOG.md b/CHANGELOG.md index a649035..a64a30f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +* Spinodoids (`spinodoid`, [docs/theory.md](docs/theory.md) §141): the level of a sum of + waves of one wavelength (Cahn 1965; Soyarslan et al. 2018; Kumar et al. 2020), their + directions uniform on the sphere or within cones about the axes (`cone_angles`: + isotropic, lamellar, columnar, cubic), the network, the sheet or the other network at a + level of the normal law, a volume fraction or a profile of fractions (graded); in a + periodic box the modes of a shell about the wavelength (a periodic realization). The + theory gives the specific surface of Rice's formula, which the realizations meet within + 1 to 2 %. Public interface: `Spinodoid`, `SpinodoidStructure` and, in + `morphogen.models.spinodoid`, `level_of_fraction`, `in_cones`, `cone_moments` and + `rice_surface`. * TPMS (`tpms`, [docs/theory.md](docs/theory.md) §140): ten surfaces, with Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P and I2-Y (the nodal forms of Lord & Mackay 2003) beside the gyroid, Schwarz P and D and Neovius; the network on the other side diff --git a/README.md b/README.md index 2ba8095..06e28a6 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ A study follows one chain, and each step is a part of the package: | Step | What morphoGen does | |---|---| -| **Generate** | 49 models: Boolean models, packings, fibres, tessellations, Gaussian fields, dead leaves, automata and growths, spinodal decomposition, strut and plate lattices, foams, triply periodic surfaces, woven textiles, bio-inspired structures, images segmented into their phases; monodisperse or polydisperse; periodic or not, combined, nested; hierarchical structures of any models four or five levels deep, chains or trees (lattices of lattices or of tubes, tows of fibres in a porous resin, grains of lamellae); and the shapes of Microgen (3MAH) | +| **Generate** | 50 models: Boolean models, packings, fibres, tessellations, Gaussian fields, dead leaves, automata and growths, spinodal decomposition, strut and plate lattices, foams, triply periodic surfaces, woven textiles, bio-inspired structures, images segmented into their phases; monodisperse or polydisperse; periodic or not, combined, nested; hierarchical structures of any models four or five levels deep, chains or trees (lattices of lattices or of tubes, tows of fibres in a porous resin, grains of lamellae); and the shapes of Microgen (3MAH) | | **Describe** | an exact description of each realization (centres, axes, cells) and an implicit function for each phase, from which voxel images, surfaces and conforming meshes are cut at any resolution | | **Measure** | fractions, specific surface, covariance, chords, tortuosity, percolation thresholds, stereology..., each beside the closed form of its model when there is one; on the implicit geometry itself, exactly: the probes of mathematical morphology and the Minkowski functionals of unions of spheres; the model of an image or of a section identified among candidates | | **Compute** | elastic, thermal, electrical, dielectric, magnetic and diffusive properties, their couplings, harmonic regimes, the magnetization curves of saturating phases and the magnetostriction and stiffening in a field of magnetorheological elastomers, the magnetic domains of ferromagnets (micromagnetics: hysteresis loops and first-order reversal curves, their dynamics, their thermal fluctuations and their magnetostriction under stress), hierarchical structures homogenized level by level and the buckling of their levels (the walls of their tubes too), waves, flow and sound, thermo-chemo-elastic fields in time, periodic plates through their thickness (their stiffness of Kirchhoff and Love, their transverse shear by the bending gradient, their conductance and their bowing, the permeance and the inertance of perforated panels, the sound that panels let through, their guided waves and band gaps, prestressed too, the wrinkling and the dimpling of their faces, compressed or heated between fixed edges, their elastic limits and their collapse, and the panels of diff --git a/docs/api.md b/docs/api.md index 16f70dc..b6c25eb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -20,7 +20,7 @@ the steps of a study: | Step | Package | What it holds | |---|---|---| -| Generate | [`morphogen.models`](api/morphogen.models.rst) | the 49 models of microstructures and the shapes of Microgen (3MAH), their realizations and their theory | +| Generate | [`morphogen.models`](api/morphogen.models.rst) | the 50 models of microstructures and the shapes of Microgen (3MAH), their realizations and their theory | | | [`morphogen.automata`](api/morphogen.automata.rst) | cellular automata and lattice growth processes, on grids and tilings | | | [`morphogen.design`](api/morphogen.design.rst) | tile assemblies, strut frameworks and their rigidity, searches of design spaces | | | [`morphogen.optimization`](api/morphogen.optimization.rst) | topology optimization of periodic cells by inverse homogenization, and the inverse design of active structures | diff --git a/docs/architecture.md b/docs/architecture.md index b38d1f1..6181d0e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1362,7 +1362,7 @@ style. | `test_conforming.py` | MMG meshes: tiling, mirrored meshes of symmetric cells (exact symmetries, matching faces, the group of a 2 x 2 array of holes), volume fractions, exact faces, matching periodic faces and exact PBC, porous lattices, exports (VTU, INP, MSH, Medit) and readers | | `test_iga.py` | B-spline functions against the recurrence of Cox and de Boor, their derivatives and the embeddings of their refinements; exact arcs, refined patches and assemblies; the patch test (plane strain, plane stress, a solid); Lamé's thick-walled cylinder (orders 3 and 2, 4 and 3) and Kirsch's plate with a hole; the effective tensors of a homogeneous cell, of a laminate (elasticity, conduction) and of a cell with a hole, against the curved finite elements of the solid (slow); cells of any lattice (other cuts of the same cell, strips with gaps, a cell and its neighbour), the square and hexagonal arrays of holes against the series of Perrins et al. and the isotropy of the hexagonal one, the sheet with alternating holes (exact fraction, symmetries of the square, the square array with circles, Poisson's ratio against the ligaments; against the FFT solver, slow) | | `test_iga_optimization.py` | the design and its geometries (linear maps, symmetric radial variables); the analytical shape derivatives of the tensor and of the fraction of a cell (elasticity, conduction) and of the compliance and the area of a structure against central differences; the hole of largest bulk modulus against the bound of Hashin and Shtrikman (Vigdergauz; SLSQP and MMA); the hole of a plate under biaxial tension against the ellipse (slow); folded designs and the history of the kept iterates; variables linked by the symmetries of a pattern (images and directions, periods, derivatives, errors); the holes of an auxetic sheet found again from their effective constants; its lowest Poisson's ratio at a given stiffness, with linear constraints | -| `test_implicit.py` | the implicit geometry of every model: for the 49 models, the shapes of Microgen and 19 other configurations of several phases, an implicit function of each phase whose sign is that of the voxel image on two grids and which partition the points; the Menger sponge on the grid of its cubes, two cells and their boundary layer against their planes, leaves and a transparent leaf against their spheres; the interpolation on the background mesh; the conforming mesh of a coated sphere (three phases cut one after the other: volumes, matching faces, the phases kept, finite elements against the FFT solver), cells of three phases meshed by their grains, coated hard spheres (slow) | +| `test_implicit.py` | the implicit geometry of every model: for the 50 models, the shapes of Microgen and 19 other configurations of several phases, an implicit function of each phase whose sign is that of the voxel image on two grids and which partition the points; the Menger sponge on the grid of its cubes, two cells and their boundary layer against their planes, leaves and a transparent leaf against their spheres; the interpolation on the background mesh; the conforming mesh of a coated sphere (three phases cut one after the other: volumes, matching faces, the phases kept, finite elements against the FFT solver), cells of three phases meshed by their grains, coated hard spheres (slow) | | `test_radioss.py` | the inputs of OpenRadioss read back card by card against the columns of the Radioss Reference Guide (units, nodes, bricks and tetrahedra oriented for Radioss, their mid-side nodes on their edges, parts, the solid property, LAW1, LAW36 with its yield curves at the rates of Norton's viscosity, LAW2, node groups, held and driven faces, the anchor of free faces, a shear, an impact on a rigid wall, the self contact, the time histories and their sampling, the Engine input, the length scale); the model (units, materials, loadings, time steps); the listings, time histories and legacy VTK grids (ASCII and binary, classic and VTK 5.1) | | `test_dynamics.py` | the installation of OpenRadioss found (the paths, the environment, the permissions restored), runs with a stand-in of OpenRadioss (`fake_openradioss.py`): the curves of a bar against its modulus, the forces from the time history or the animations, the frames for the 3D view, a shear, an impact, the failures of the Starter, the stops, the conversions; a release installed from a GitHub API served locally (the archive of each system, no member leaving its folder); the command line | | `test_gui_tools_dynamics.py` | the tab Explicit dynamics: the inputs written without OpenRadioss (engineering units, the materials of the fields and of the JSON), the errors, a dynamic test with the stand-in (its summary in MPa and MJ/m³, the curves in morphoGen's components compared with another run, the 3D view of its last frame), the results read back, the installation found, an impact | diff --git a/docs/guide.md b/docs/guide.md index f56895f..e8550d0 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -10,7 +10,7 @@ questions. | Step | Page | What it covers | |---|---|---| -| Generate | [Models of microstructures](models.md) | the 49 models by family and the shapes of Microgen, their anisotropy, their sizes (monodisperse or polydisperse), automata and growth, nested and bio-inspired models | +| Generate | [Models of microstructures](models.md) | the 50 models by family and the shapes of Microgen, their anisotropy, their sizes (monodisperse or polydisperse), automata and growth, nested and bio-inspired models | | Describe | [Geometry, voxels and meshes](geometry.md) | exact descriptions, implicit functions, voxel images, conforming meshes, symmetric cells | | Measure | [Measures and theory](measures.md) | the closed forms of the models, the measures of images, percolation, crystallographic textures | | Compute | [The library of materials](library.md) | the materials of the phases by their names — metals, crystals, ceramics, glasses, polymers, elastomers, fibres, fluids —, their values, sources and units; materials of one's own | diff --git a/docs/index.md b/docs/index.md index b2fae84..7404ddb 100644 --- a/docs/index.md +++ b/docs/index.md @@ -39,7 +39,7 @@ package, a command line and a graphical interface in the web browser; free softw ::::{container} card **[Generate](models.md)** -49 models of random and architected media: Boolean models, packings, fibres, +50 models of random and architected media: Boolean models, packings, fibres, tessellations, Gaussian fields, dead leaves, automata and growths, spinodal decomposition, strut and plate lattices, foams, triply periodic surfaces, woven textiles, bio-inspired structures, images segmented into their phases; periodic or not, combined, nested; diff --git a/docs/models.md b/docs/models.md index 919fd8c..62df1ef 100644 --- a/docs/models.md +++ b/docs/models.md @@ -4,7 +4,7 @@ A model holds the parameters of a random set or of a deterministic architecture, closed-form characteristics of the set when they exist (`model.theory()`: volume fraction, specific surface, covariance, integral range...). `model.generate(domain, seed)` draws one realization of it in a box, periodic or not; the same seed gives the -same realization. morphoGen has 49 models, listed below by family, and takes the shapes of +same realization. morphoGen has 50 models, listed below by family, and takes the shapes of [Microgen](https://github.com/3MAH/microgen) (3MAH) through the model `microgen` ([below](#shapes-of-microgen)): `morphogen models` lists them, `morphogen models ` gives the parameters of one, and the @@ -73,6 +73,7 @@ What a realization is made of, and how it becomes images and meshes, is the subj | Model | Description | |---|---| | `tpms` | Ten surfaces: gyroid, Schwarz P and D, Neovius, Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P and I2-Y; the network on either side of the surface or the sheet, at a level, a volume fraction or a profile of the fraction along an axis (graded TPMS, [theory notes](theory.md) §140) | +| `spinodoid` | Spinodoids (Kumar et al. 2020): the level of a sum of waves of one wavelength in random directions, isotropic or within cones about the axes (lamellar, columnar, cubic), network, sheet or the other network, at a fraction or graded; periodic in periodic boxes; their specific surface by Rice's formula ([theory notes](theory.md) §141) | | `strut_lattice` | Cubic, BCC, FCC, octet, Kelvin, diamond and pyrochlore lattices, with solid or hollow struts; rotated and functionally graded lattices (non-periodic samples); their sections meshed in the plane by their exact contours | | `plate_lattice` | Plate lattices: closed cells walled by plates on the closest-packed planes of the cubic lattices, the {100} (`cubic`), {110} (`bcc`) and {111} (`fcc`, the octet plates) planes and their mixtures (Berger et al. 2017; Tancogne-Dejean et al. 2018), of a thickness or an exact relative density, in the ratio of an isotropic stiffness at low density (`isotropic`, which reaches the Hashin–Shtrikman bounds); turned, shifted and graded; the exact density and specific surface, the stiffness of the membranes at low density, exact meshes of their convex pieces ([below](#plate-lattices)) | | `random_lattice` | Strut lattices with missing struts and displaced nodes, with their rigidity (Maxwell–Calladine); their sections meshed in the plane by their exact contours | diff --git a/docs/specification.md b/docs/specification.md index 9e5274d..acd1932 100644 --- a/docs/specification.md +++ b/docs/specification.md @@ -3,7 +3,7 @@ | | | |---|---| | Document | Software requirements specification | -| Version | 1.254 | +| Version | 1.255 | | Date | 2026-12-01 | | Author | @jdirr | | Status | Version 1.1 **validated** on 2026-10-21. The later versions, proposed, are listed in the change log (§13); changes go through pull requests that update this file and its change log. | @@ -360,6 +360,8 @@ centred on morphological modelling. | Delivered | FR-E19 (`io.openfoam`, `morphogen openfoam forchheimer`, `outputs.openfoam.velocity`, [theory.md](theory.md) §139): the flow periodic along its axis too (a cyclic pair, the pressure fixed at one cell), driven to a filtration velocity by `meanVelocityForce` for both lines of OpenFOAM (OpenCFD's `fvOptions`, the Foundation's `fvConstraints`, put in place by `Allrun`), its pressure gradient read from the log of the solver, its apparent permeability and its convergence (the residuals, or a flow that no longer changes); the sweep `forchheimer`: a creeping flow (Darcy's permeability), periodic flows at the Reynolds numbers asked for, the failed and unsteady flows reported and left out, Forchheimer's law (`k_F`, `β`, `c_F = β √k`) and the weak inertia (`k / k_app − 1 = A Re²`) fitted, the exponents from flow to flow, `forchheimer.json` and `forchheimer.csv`; the scheme of the convection; the periodic flow in the tool *OpenFOAM case*; verified by laws standing in for OpenFOAM (10⁻⁹) and by OpenFOAM v2412 itself: the permeability of a slit at every Reynolds number (10⁻⁶), the weak inertia (exponent 2) and the stronger inertia of staggered rods | | Additive manufacturing: TPMS (2026-12-01) | The surfaces of Schoen, Fischer–Koch and Lidin, the other network of a surface, graded TPMS. | | Delivered | FR-G29 (`tpms`, [theory.md](theory.md) §140): six more nodal surfaces (Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P, I2-Y; Lord & Mackay 2003), their derivatives for the first-order distance; the network `upper_network` on the other side of the level; `fraction_gradient` along `gradient_axis`, the level of each position that of its fraction (any piecewise-linear profile, in non-periodic domains) | +| Additive manufacturing: spinodoids (2026-12-01) | The stochastic architectures of Kumar et al. (2020) and of Top6Meta's spinodal module. | +| Delivered | FR-G30 (`spinodoid`, [theory.md](theory.md) §141): `n_waves` waves of a `wavelength`, directions uniform or within `cone_angles` (lamellar, columnar, cubic), random phases; the three solids at a level of the normal law, graded by `fraction_gradient`; the modes of a shell of `bandwidth` in periodic boxes; the specific surface by Rice's formula; grids by products of complex matrices | ## 4. Scope @@ -436,6 +438,7 @@ version, 0.1). | FR-G27 | Grains grown from seeds (MicroStructPy): ellipsoidal seeds of laws of sizes and shapes, at random or aligned, the seeds of each phase of their own laws, broken down into spheres and placed within an overlap tolerance; the grain of a seed the union of the Laguerre cells of its spheres, meshed as one subdomain; amorphous phases merged into one region, voids left out of the meshes; ellipses in the plane (columnar grains); boxes and rectangles; the grains verified against their seeds on their exact cells, with their figures and a tool of the interface | S | 3d | | FR-G28 | Plate lattices: plates on the {100}, {110} and {111} planes of the cubic lattices and their mixtures, given by thicknesses or an exact relative density, the isotropic ratios of the mixtures; their exact density, specific surface and convex pieces; the stiffness of the membranes at low density | S | 3d | | FR-G29 | TPMS: ten surfaces (gyroid, Schwarz P and D, Neovius, Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P, I2-Y), the networks on either side of a level and the sheet, at a level, a volume fraction or a profile of the volume fraction along an axis (graded TPMS) | S | 1d | +| FR-G30 | Spinodoids: the levels of sums of waves of one wavelength in random directions, on the sphere or within cones about the axes, the network, the sheet or the other network at a level, a fraction or a profile of fractions, periodic in periodic boxes; their specific surface by Rice's formula | S | 1d | ### 5.2 Representations @@ -1423,6 +1426,7 @@ Packages: `models`, `kernels`, `analysis`, `rve`, `mesh`, `homogenization`, `io` | 1.252 | 2026-12-01 | Micromagnetics: first-order reversal curves and their FORC diagrams (FR-H54, §3.11) | | 1.253 | 2026-12-01 | Forchheimer's law through OpenFOAM: periodic flows at finite Reynolds numbers, the weak inertia and Forchheimer's law fitted (FR-E19, §3.12) | | 1.254 | 2026-12-01 | TPMS: ten surfaces, the other network and graded TPMS (FR-G29, §3.12) | +| 1.255 | 2026-12-01 | Spinodoids: sums of waves of one wavelength, cones, grading, Rice's surface (FR-G30, §3.12) | ## 14. References diff --git a/docs/theory.md b/docs/theory.md index b09b789..220e863 100644 --- a/docs/theory.md +++ b/docs/theory.md @@ -12,7 +12,7 @@ them by these numbers (§75); by theme: | Theme | Sections | |---|---| | Models of random media | [§1](#1-boolean-models) Boolean models, [§2](#2-poisson-fibres-jeulin-1991-dirrenberger-et-al-2014) Poisson fibres (Jeulin 1991; Dirrenberger et al. 2014), [§3](#3-random-sequential-addition) Random sequential addition, [§4](#4-tessellations) Tessellations, [§5](#5-excursions-of-gaussian-random-fields) Excursions of Gaussian random fields, [§22](#22-combinations-of-models-and-grain-boundary-phases) Combinations of models and grain-boundary phases, [§23](#23-further-models) Further models, [§29](#29-nested-models) Nested models, [§38](#38-torquatos-approaches-dense-packings-cherry-pit-spheres-reconstruction-and-descriptors) Torquato's approaches: dense packings, cherry-pit spheres, reconstruction and descriptors, [§42](#42-foams-as-level-sets-of-distance-fields-level_set_foam) Foams as level sets of distance fields, [§56](#56-affine-anisotropy-of-the-models-modelsaffine) Affine anisotropy of the models, [§93](#93-scale-rich-networks-scale_rich_network) Scale-rich networks, [§95](#95-long-fibres-unidirectional-composites-parallel-or-misaligned-long_fibers) Long fibres: unidirectional composites, parallel or misaligned, [§97](#97-grains-with-subgrains-or-filled-with-another-structure-modelsnested_grains) Grains with subgrains, or filled with another structure, [§98](#98-monodisperse-and-polydisperse-objects) Monodisperse and polydisperse objects, [§107](#107-images-as-microstructures-segmentation-and-the-model-image-morphologysegmentation-modelsimage) Images as microstructures: segmentation and the model `image`, [§114](#114-reconstruction-from-descriptors-by-gradient-descent-morphologyreconstruction) Reconstruction from descriptors by gradient descent, [§115](#115-grains-grown-from-seeds-modelsseeded-kernelsseeds) Grains grown from seeds, [§116](#116-seeds-of-several-phases-and-the-verification-of-their-grains-modelsseeded-meshpolyhedra-kernelsseeds) Seeds of several phases and the verification of their grains, [§117](#117-seeds-of-the-plane-and-the-figures-of-the-verification-modelsseeded-vizfigures) Seeds of the plane and the figures of the verification, [§118](#118-seeds-of-boxes-and-of-rectangles-modelsseeded) Seeds of boxes and of rectangles | -| Architected and bio-inspired structures | [§6](#6-tpms) TPMS, [§7](#7-strut-lattices) Strut lattices, [§30](#30-bio-inspired-models) Bio-inspired models, [§71](#71-diamond-and-pyrochlore-lattices-of-struts-homogenizationframes-modelslattice) Diamond and pyrochlore lattices of struts, [§96](#96-woven-textile-composites-woven_textile) Woven textile composites, [§110](#110-woven-textiles-the-variability-of-the-tows-3d-architectures-the-tows-as-unidirectional-composites-woven_textile-homogenizationunidirectional) Woven textiles: the variability of the tows, 3D architectures, the tows as unidirectional composites, [§125](#125-plate-lattices-plate_lattice) Plate lattices, [§140](#140-tpms-ten-surfaces-their-two-networks-and-their-gradients-modelstpms) TPMS: ten surfaces, their two networks and their gradients | +| Architected and bio-inspired structures | [§6](#6-tpms) TPMS, [§7](#7-strut-lattices) Strut lattices, [§30](#30-bio-inspired-models) Bio-inspired models, [§71](#71-diamond-and-pyrochlore-lattices-of-struts-homogenizationframes-modelslattice) Diamond and pyrochlore lattices of struts, [§96](#96-woven-textile-composites-woven_textile) Woven textile composites, [§110](#110-woven-textiles-the-variability-of-the-tows-3d-architectures-the-tows-as-unidirectional-composites-woven_textile-homogenizationunidirectional) Woven textiles: the variability of the tows, 3D architectures, the tows as unidirectional composites, [§125](#125-plate-lattices-plate_lattice) Plate lattices, [§140](#140-tpms-ten-surfaces-their-two-networks-and-their-gradients-modelstpms) TPMS: ten surfaces, their two networks and their gradients, [§141](#141-spinodoids-levels-of-sums-of-waves-of-one-wavelength-modelsspinodoid) Spinodoids: levels of sums of waves of one wavelength | | Growth and design | [§14](#14-cellular-automata-automata) Cellular automata, [§15](#15-nucleation-and-growth-johnsonmehlavramikolmogorov) Nucleation and growth (Johnson–Mehl–Avrami–Kolmogorov), [§16](#16-aggregation) Aggregation, [§17](#17-combinatorial-design-design) Combinatorial design, [§18](#18-topology-optimization-of-periodic-cells-optimization) Topology optimization of periodic cells, [§78](#78-isogeometric-analysis-iga) Isogeometric analysis, [§79](#79-isogeometric-shape-optimization-igaoptimization) Isogeometric shape optimization, [§109](#109-inverse-design-of-active-structures-optimizationmorphing) Inverse design of active structures, [§113](#113-spinodal-decomposition-spinodal) Spinodal decomposition | | Geometry and meshes | [§19](#19-polycrystals-exact-cells-and-conforming-meshes-meshpolyhedra-meshpolycrystal) Polycrystals: exact cells and conforming meshes, [§24](#24-whole-periodic-grains-meshpolycrystal-cells-whole) Whole periodic grains, [§52](#52-views-and-measures-of-the-level-sets-vizsections) Views and measures of the level sets, [§75](#75-the-implicit-geometry-of-every-model-modelsimplicit-meshconforming) The implicit geometry of every model, [§76](#76-quadratic-tetrahedra-isoparametric-elements-and-curved-interfaces-meshcurved-homogenizationfe) Quadratic tetrahedra: isoparametric elements and curved interfaces, [§80](#80-sharp-edges-of-the-phases-meshes-that-follow-them-modelspieces-meshconforming-meshcurved) Sharp edges of the phases: meshes that follow them, [§94](#94-exact-meshes-without-a-background-grid-meshexact-meshoctree) Exact meshes without a background grid, [§119](#119-meshes-of-the-plane-and-their-finite-elements-meshtriangles-homogenizationplane) Meshes of the plane and their finite elements | | Measures | [§8](#8-specific-surface-by-cauchycrofton) Specific surface by Cauchy–Crofton, [§21](#21-morphological-measures-analysismorphology) Morphological measures, [§39](#39-random-sets-probed-by-structuring-elements-analysisrandom_sets-analysistopology) Random sets probed by structuring elements, [§55](#55-percolation-thresholds-analysispercolation) Percolation thresholds, [§70](#70-particles-of-a-phase-in-a-volume-analysisparticles) Particles of a phase in a volume, [§92](#92-crystallographic-textures-and-orientation-maps-texture-ioebsd-modelsebsd) Crystallographic textures and orientation maps, [§104](#104-measures-of-the-implicit-geometry-morphologymeasures) Measures of the implicit geometry, [§105](#105-unions-of-balls-and-of-discs-measured-exactly-morphologyballs) Unions of balls and of discs, measured exactly, [§106](#106-the-model-of-an-image-morphologyidentification) The model of an image | @@ -16639,6 +16639,70 @@ the mean fraction of the theory, an I-WP graded along $z$; the slope of the leve graded split P, of median 1 within 5 % across its surface; a graded realization written and read back, and run from a configuration to its STL surface. +## 141. Spinodoids: levels of sums of waves of one wavelength (`models.spinodoid`) + +Cahn (1965) described the early spinodal decomposition by a Gaussian random field whose +spectrum is concentrated on the fastest wavelength; Soyarslan et al. (2018) and Kumar et +al. (2020) made it a family of architected materials, the spinodoids: + +$$ +\varphi(x) = \sqrt{2/N}\sum_{i=1}^N \cos(k_i\cdot x + \gamma_i), \qquad +|k_i| = \beta = 2\pi/\lambda, +$$ + +$N$ waves (`n_waves`, 1000 by default) of wavelength $\lambda$ (`wavelength`), of phases +$\gamma_i$ uniform in $[0, 2\pi)$ and of directions $n_i = k_i/\beta$ uniform on the unit +sphere, or within cones of half-angles $(\theta_1, \theta_2, \theta_3)$ about the axes +(`cone_angles`, degrees: a direction within the cone of one axis at least, +$|n\cdot e_a| \ge \cos\theta_a$; $(90, 90, 90)$ isotropic, $(15, 0, 0)$ lamellar, +$(0, 15, 15)$ columnar, $(15, 15, 15)$ cubic; Kumar et al. 2020). The field has the mean 0 +and the variance 1 ($2/N \cdot N \cdot \tfrac12$), its values are nearly normal for many +waves, and the solid is a side of a level as for the TPMS (§140): the network +$\{\varphi \le t\}$, the sheet $\{|\varphi| \le t\}$, the other network +$\{\varphi \ge t\}$, at $t = \Phi^{-1}(f)$, $\Phi^{-1}((1 + f)/2)$ or $\Phi^{-1}(1 - f)$ +for a volume fraction $f$ ($\Phi$ the normal law); `fraction_gradient` grades the level +along an axis as in §140, with the slope of the level in the first-order distance +$f/|\nabla f|$. + +**Rice's formula.** The gradient of the field has the second moments +$\Lambda = E[\nabla\varphi\,\nabla\varphi^T] = \frac1N\sum_i k_i k_i^T$ ($\beta^2 E[n n^T]$, +$\beta^2/3$ times the identity for isotropic waves). The mean number of crossings of the +level $t$ per unit length along a direction $d$ is +$\pi^{-1}\sqrt{d^T\Lambda d}\,e^{-t^2/2}$ (Rice 1944), and by Cauchy–Crofton (§8) the +specific surface of the level is twice its mean over the directions: + +$$ +S_V(t) = \frac{2}{\pi}\,e^{-t^2/2}\,\big\langle\sqrt{d^T\Lambda d}\big\rangle_d +\qquad\Big(= \frac{2\beta}{\pi\sqrt3}\,e^{-t^2/2}\ \text{for isotropic waves}\Big), +$$ + +and a sheet has two such surfaces, at $\pm t$. `theory()` gives it with the moments of the +cones (on 20 000 directions of a Fibonacci sphere). + +**Periodic boxes.** The waves are then modes of the box, $k = 2\pi m/L$, those whose length +lies in the shell $|k|/\beta \in [1 - w/2, 1 + w/2]$ (`bandwidth` $w$, 0.2) and whose +direction lies in the cones, one of each pair $\pm m$, $N$ of them at most drawn at random: +93 modes in a box of 4 wavelengths, 261 in a box of 6. The realization is periodic and +its moments $\Lambda$ those of its modes. + +**Evaluation.** On a grid, each plane of voxels across $x$ is +$\mathrm{Re}\,[(E_y\,\mathrm{diag}(u))\,E_z^T]$, $u_i = \sqrt{2/N}\,e^{i(k_{i,x}x + +\gamma_i)}$ and $E_y$, $E_z$ the factors $e^{ik_{i,y}y}$, $e^{ik_{i,z}z}$ of the waves at the +rows and columns of voxels: a product of complex matrices (a 96³ grid of 1000 waves in +0.1 s), the gradient by $ik_a$. At points, the sum of the waves and of their gradients. + +Validated in `tests/test_spinodoid.py`: for the three solids of isotropic waves at a +fraction 0.3, the fraction of the voxels (within 0.015) and the specific surface of Rice's +formula (within 4 %; 1 to 2 % measured), the level set negative exactly on the solid voxels +and equal to its values at points; the mean 0, variance 1 and moments $\beta^2/3$ of the +field and of its gradient, the slope of the level set of median 1 within 5 % across its +surface; the modes of a periodic box in the shell, the field periodic, the fraction and +the surface of the theory; lamellar waves (thin chords along $x$: less than 0.3 of the +others) and columnar ones (long chords along $x$: more than 3 times), Rice's surface of +their cones within 5 %, the moments of isotropic and narrow cones, Rice's closed form; a +graded sheet whose slabs follow the profile within 0.025, written and read back; the +levels of the normal law and the errors; a run from a configuration to its STL surface. + ## References See [specification.md](specification.md#14-references). In addition: @@ -17802,3 +17866,12 @@ See [specification.md](specification.md#14-references). In addition: surfaces with hexagonal symmetry. *J. Chem. Soc., Faraday Trans.* 86, 769–775. * Lord, E. A., Mackay, A. L. (2003). Periodic minimal surfaces of cubic symmetry. *Curr. Sci.* 85, 346–362. +* Cahn, J. W. (1965). Phase separation by spinodal decomposition in isotropic systems. + *J. Chem. Phys.* 42, 93–99. +* Rice, S. O. (1944). Mathematical analysis of random noise. *Bell Syst. Tech. J.* 23, + 282–332. +* Soyarslan, C., Bargmann, S., Pradas, M., Weissmüller, J. (2018). 3D stochastic + bicontinuous microstructures: generation, topology and elasticity. *Acta Mater.* 149, + 326–340. +* Kumar, S., Tan, S., Zheng, L., Kochmann, D. M. (2020). Inverse-designed spinodoid + metamaterials. *npj Comput. Mater.* 6, 73. diff --git a/docs/tutorial_geometry.md b/docs/tutorial_geometry.md index a43bd5f..6d134a4 100644 --- a/docs/tutorial_geometry.md +++ b/docs/tutorial_geometry.md @@ -63,7 +63,7 @@ print(level.data.dtype, bool(((level.data < 0) == (image.data == 2)).all())) mg.io.save_image(level, "interphase.vti") # for ParaView: its zero level is the interface ``` -Every model has such functions — the 49 models, the shapes of Microgen, their combinations, coatings, nested and +Every model has such functions — the 50 models, the shapes of Microgen, their combinations, coatings, nested and transformed structures: distances to unions of spheres and segments, differences of power distances to the germs of cells, the rings of osteons, the leaves of a dead-leaves model outside those that cover them ([theory notes](theory.md), §75). A structure of two diff --git a/docs/tutorial_interface.md b/docs/tutorial_interface.md index be564be..a45ab25 100644 --- a/docs/tutorial_interface.md +++ b/docs/tutorial_interface.md @@ -23,7 +23,7 @@ opens its menu (where to send it, its 3D view, a new title), its cross **×** (o middle click) closes it — **Undo** beside the strip brings it back for a few seconds; its files stay in the folder of the session either way. -In *Create › Generate*, the menu lists the 49 models and the shapes of Microgen by family (the filter above it +In *Create › Generate*, the menu lists the 50 models and the shapes of Microgen by family (the filter above it finds one by a word of its name or of its summary). Choose `boolean_spheres`: its form opens filled with its template; set the radius to 1, the volume fraction to 0.2, the size of the domain to 10 and the seed to 1, then **Generate** (or `Ctrl + Enter`, which diff --git a/src/morphogen/gui/api.py b/src/morphogen/gui/api.py index 9e342f9..57eda33 100644 --- a/src/morphogen/gui/api.py +++ b/src/morphogen/gui/api.py @@ -196,7 +196,7 @@ def examples() -> dict[str, dict]: ), "Lattices and TPMS": ( "strut_lattice", "plate_lattice", "random_lattice", "hierarchical_lattice", - "scale_rich_network", "tpms", "fractal_sponge", "microgen", + "scale_rich_network", "tpms", "spinodoid", "fractal_sponge", "microgen", ), "Bio-inspired": ("nacre", "bouligand", "osteons"), "Growth and patterns": ( diff --git a/src/morphogen/models/__init__.py b/src/morphogen/models/__init__.py index db479bf..a3669a8 100644 --- a/src/morphogen/models/__init__.py +++ b/src/morphogen/models/__init__.py @@ -22,7 +22,10 @@ ``seeded_laguerre`` Grains grown from ellipsoidal seeds (MicroStructPy): the Laguerre cells of the spheres of each seed gathered into its grain ``gaussian_excursion`` Excursion set of a Gaussian random field -``tpms`` Gyroid, Schwarz P/D, Neovius sheet or network lattices +``tpms`` TPMS of ten surfaces (gyroid, Schwarz P/D, Neovius, I-WP, F-RD, + Fischer-Koch S, lidinoid, split P, I2-Y): sheets, networks, graded +``spinodoid`` Spinodoids: levels of sums of waves of one wavelength in random + directions or cones (Kumar et al. 2020), graded ``strut_lattice`` Cubic, BCC, FCC and octet strut lattices ``plate_lattice`` Plate lattices: closed cells of plates on the {100}, {110} and {111} planes (cubic, bcc, fcc) and their isotropic mixtures @@ -146,6 +149,7 @@ from morphogen.models.scale_rich_3d import ScaleRichBeams, ScaleRichPlates from morphogen.models.seeded import SeededLaguerre, SeededTessellation from morphogen.models.spinodal import Spinodal, SpinodalStructure +from morphogen.models.spinodoid import Spinodoid, SpinodoidStructure from morphogen.models.tessellation import Laguerre, Tessellation, Voronoi from morphogen.models.textile import TextileStructure, WovenTextile from morphogen.models.tiling_field import TilingField @@ -229,6 +233,8 @@ "SphereChains", "Spinodal", "SpinodalStructure", + "Spinodoid", + "SpinodoidStructure", "StrutLattice", "TPMSStructure", "Tessellation", diff --git a/src/morphogen/models/spinodoid.py b/src/morphogen/models/spinodoid.py new file mode 100644 index 0000000..bf1a731 --- /dev/null +++ b/src/morphogen/models/spinodoid.py @@ -0,0 +1,518 @@ +"""Spinodoids: the level sets of a sum of waves of one wavelength (Cahn 1965; Soyarslan et +al. 2018; Kumar, Tan, Zheng & Kochmann 2020). + +The field + + phi(x) = sqrt(2 / N) sum_i cos(k_i . x + gamma_i), |k_i| = beta = 2 pi / lambda, + +of ``N`` waves of directions ``k_i / beta`` drawn uniformly on the unit sphere, or within +cones of half-angles ``theta_1``, ``theta_2``, ``theta_3`` about the axes (Kumar et al. +2020: a direction within the cone of one axis at least), and of phases ``gamma_i`` +uniform in ``[0, 2 pi)``, has the mean 0 and the variance 1; for many waves its values are +normal (Cahn's approximation of the early spinodal decomposition by a Gaussian random +field). The solid is a side of a level ``t`` (network ``phi <= t``, sheet ``|phi| <= t``, +other network ``phi >= t``), placed for a volume fraction ``f`` by the normal law: +``t = Phi^-1(f)``, ``Phi^-1((1 + f) / 2)`` or ``Phi^-1(1 - f)``; a profile of fractions +along an axis grades the level as in :mod:`morphogen.models.tpms`. + +In a periodic box the waves are the modes of the box ``k = 2 pi m / L`` whose length lies +within a shell ``|k| / beta in [1 - w/2, 1 + w/2]`` (``bandwidth`` ``w``) and whose direction +lies in the cones, ``N`` of them at most drawn at random (one of each pair ``+-m``): the +realization is periodic. In a box that is not periodic the directions are drawn on the +sphere. + +Rice's formula gives the specific surface of a level ``t`` of a Gaussian field, +``S_V = (2 / pi) exp(-t^2 / 2) ``, the mean over the directions ``d`` +of the root mean square of the derivative of ``phi`` along ``d``, ``Lambda = E[grad phi +grad phi] = beta^2 E[n n]`` (``beta^2 / 3`` times the identity for isotropic waves); a +sheet has two such surfaces. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from functools import lru_cache +from typing import ClassVar + +import numpy as np +from numba import njit, prange +from scipy import stats + +from morphogen._utils import check_fraction, check_positive +from morphogen.domain import Domain, Grid +from morphogen.image import VoxelImage +from morphogen.models.affine import ANISOTROPY, Anisotropy, anisotropic +from morphogen.models.base import Microstructure, Model, param, register, register_kind +from morphogen.seeding import SeedLike, make_rng, seed_from_description + +#: Relative width of the shell of the modes of a periodic box. +BANDWIDTH = 0.2 +#: Levels of a graded spinodoid per interval of its fractions. +_GRADED_SAMPLES = 64 +VARIANTS = ("network", "sheet", "upper_network") + + +def level_of_fraction(variant: str, fraction): + """The level of the normal law whose solid has the volume fraction ``fraction``.""" + f = np.asarray(fraction, dtype=float) + if variant == "sheet": + t = stats.norm.ppf(0.5 * (1.0 + f)) + elif variant == "upper_network": + t = stats.norm.ppf(1.0 - f) + else: + t = stats.norm.ppf(f) + return float(t) if np.ndim(t) == 0 else t + + +def in_cones(n: np.ndarray, angles) -> np.ndarray: + """Whether the unit vectors ``n`` lie within the cone of half-angle ``angles[a]`` + (degrees) about the axis ``a`` of at least one axis (``0``: no cone about that axis).""" + n = np.asarray(n, dtype=float).reshape(-1, 3) + out = np.zeros(len(n), dtype=bool) + for a, theta in enumerate(angles): + if theta > 0.0: + out |= np.abs(n[:, a]) >= math.cos(math.radians(theta)) - 1e-12 + return out + + +@lru_cache(maxsize=16) +def _sphere(n: int = 20000) -> np.ndarray: + """``n`` nearly uniform directions (a Fibonacci sphere).""" + i = np.arange(n) + 0.5 + z = 1.0 - 2.0 * i / n + r = np.sqrt(1.0 - z * z) + a = math.pi * (3.0 - math.sqrt(5.0)) * i + return np.column_stack([r * np.cos(a), r * np.sin(a), z]) + + +def rice_surface(second_moments: np.ndarray, level: float) -> float: + """Specific surface of the level ``level`` of a unit-variance Gaussian field whose + gradient has the second moments ``Lambda`` (Rice's formula, averaged over the + directions).""" + d = _sphere() + rms = np.sqrt(np.maximum(np.einsum("ij,jk,ik->i", d, second_moments, d), 0.0)) + return float(2.0 / math.pi * math.exp(-0.5 * level * level) * rms.mean()) + + +def cone_moments(angles) -> np.ndarray: + """``E[n n]`` of the directions uniform within the cones (on a fine sphere).""" + d = _sphere() + d = d[in_cones(d, angles)] + return d.T @ d / len(d) + + +@njit(parallel=True, cache=True) +def _waves_at(k, phase, amp, pts, grad, phi, dphi): + """``phi`` (and its gradient) at points: the sum of the waves.""" + for p in prange(pts.shape[0]): + x, y, z = pts[p, 0], pts[p, 1], pts[p, 2] + s = 0.0 + gx = 0.0 + gy = 0.0 + gz = 0.0 + for i in range(k.shape[0]): + a = k[i, 0] * x + k[i, 1] * y + k[i, 2] * z + phase[i] + s += math.cos(a) + if grad: + sn = math.sin(a) + gx -= k[i, 0] * sn + gy -= k[i, 1] * sn + gz -= k[i, 2] * sn + phi[p] = amp * s + if grad: + dphi[p, 0] = amp * gx + dphi[p, 1] = amp * gy + dphi[p, 2] = amp * gz + + +@register_kind +class SpinodoidStructure(Microstructure): + """The solid of a level of a sum of waves (see the module): the network, the sheet + or the other network, at a level or at a table of levels along an axis (graded).""" + + kind = "spinodoid" + + def __init__( + self, + domain, + wavelength, + n_waves, + cone_angles, + variant, + level, + wave_seed, + *, + bandwidth=BANDWIDTH, + levels=None, + gradient_axis=0, + **kwargs, + ): + super().__init__(domain, **kwargs) + self.wavelength = float(wavelength) + self.n_waves = int(n_waves) + self.cone_angles = tuple(float(a) for a in cone_angles) + self.variant = variant + self.level = float(level) + self.wave_seed = wave_seed + self.bandwidth = float(bandwidth) + self.levels = None if levels is None else np.asarray(levels, dtype=float) + self.gradient_axis = int(gradient_axis) + self._waves = None + + # -- the waves --------------------------------------------------------------------------- + + def waves(self) -> tuple[np.ndarray, np.ndarray]: + """The wave vectors ``k_i`` (rows) and phases ``gamma_i`` (the phase of each wave + at the lower corner of the domain).""" + if self._waves is None: + rng = np.random.default_rng(seed_from_description(self.wave_seed)) + beta = 2.0 * math.pi / self.wavelength + if self.domain.periodic: + k = self._modes(beta, rng) + else: + k = self._directions(rng) * beta + phase = rng.uniform(0.0, 2.0 * math.pi, len(k)) + self._waves = (np.ascontiguousarray(k), phase) + return self._waves + + def _directions(self, rng) -> np.ndarray: + out = [] + count = 0 + while count < self.n_waves: + n = rng.standard_normal((max(4 * self.n_waves, 1000), 3)) + n /= np.linalg.norm(n, axis=1)[:, None] + n = n[in_cones(n, self.cone_angles)] + out.append(n) + count += len(n) + return np.concatenate(out)[: self.n_waves] + + def _modes(self, beta, rng) -> np.ndarray: + lengths = self.domain.lengths + hi = beta * (1.0 + 0.5 * self.bandwidth) + lo = beta * (1.0 - 0.5 * self.bandwidth) + n_max = np.floor(hi * lengths / (2.0 * math.pi)).astype(int) + axes = [np.arange(-n, n + 1) for n in n_max] + m = np.stack(np.meshgrid(*axes, indexing="ij"), axis=-1).reshape(-1, 3) + half = (m[:, 0] > 0) | ((m[:, 0] == 0) & (m[:, 1] > 0)) + half |= (m[:, 0] == 0) & (m[:, 1] == 0) & (m[:, 2] > 0) + k = 2.0 * math.pi * m[half] / lengths + size = np.linalg.norm(k, axis=1) + keep = (size >= lo) & (size <= hi) + k, size = k[keep], size[keep] + k = k[in_cones(k / size[:, None], self.cone_angles)] + if len(k) == 0: + raise ValueError( + "spinodoid: no mode of the periodic box in the shell and the cones; widen the " + "box, the bandwidth or the cones" + ) + if len(k) > self.n_waves: + k = k[rng.choice(len(k), self.n_waves, replace=False)] + return k + + @property + def amplitude(self) -> float: + return math.sqrt(2.0 / len(self.waves()[0])) + + def second_moments(self) -> np.ndarray: + """``Lambda = E[grad phi grad phi]`` of the realization: ``(1 / N) sum k k``.""" + k = self.waves()[0] + return k.T @ k / len(k) + + # -- the field --------------------------------------------------------------------------- + + def values_at(self, points, gradient: bool = False): + """``phi`` at points (rows), and its gradient with ``gradient``.""" + k, phase = self.waves() + pts = np.ascontiguousarray(points, dtype=float).reshape(-1, 3) - self.domain.lower + phi = np.empty(len(pts)) + dphi = np.empty((len(pts), 3) if gradient else (1, 3)) + _waves_at(k, phase, self.amplitude, np.ascontiguousarray(pts), gradient, phi, dphi) + return (phi, dphi) if gradient else phi + + def field(self, grid: Grid, gradient: bool = False): + """``phi`` at the voxel centres of a grid (and its gradient, ``(3, nx, ny, nz)``): + each plane of voxels a product of the factors of its waves along ``y`` and ``z``.""" + k, phase = self.waves() + amp = self.amplitude + nx, ny, nz = grid.shape + x0 = grid.origin + 0.5 * grid.spacing - self.domain.lower + xs = x0[0] + grid.spacing[0] * np.arange(nx) + ey = np.exp(1j * np.outer(x0[1] + grid.spacing[1] * np.arange(ny), k[:, 1])) + ezt = np.exp(1j * np.outer(k[:, 2], x0[2] + grid.spacing[2] * np.arange(nz))) + phi = np.empty((nx, ny, nz)) + dphi = np.empty((3, nx, ny, nz)) if gradient else None + for i, x in enumerate(xs): + u = amp * np.exp(1j * (k[:, 0] * x + phase)) + phi[i] = ((ey * u) @ ezt).real + if gradient: + for a in range(3): # d/dx_a Re(u e) = Re(i k_a u e) + dphi[a, i] = ((ey * (1j * k[:, a] * u)) @ ezt).real + return (phi, dphi) if gradient else phi + + # -- the levels -------------------------------------------------------------------------- + + def _level_at(self, coordinate): + """The level at coordinates along the gradient axis, and its slope.""" + if self.levels is None: + return self.level, 0.0 + axis = self.gradient_axis + lo, length = self.domain.lower[axis], self.domain.lengths[axis] + m = len(self.levels) + s = np.clip((np.asarray(coordinate, dtype=float) - lo) / length, 0.0, 1.0) + positions = np.linspace(0.0, 1.0, m) + t = np.interp(s, positions, self.levels) + j = np.clip((s * (m - 1)).astype(int), 0, m - 2) + slope = (self.levels[j + 1] - self.levels[j]) * (m - 1) / length + return t, slope + + def _function(self, phi, t): + if self.variant == "sheet": + return np.abs(phi) - t + if self.variant == "upper_network": + return t - phi + return phi - t + + def _distance(self, phi, dphi, coordinate, axis_first: bool): + """``f / |grad f|`` with the gradient of ``phi`` (components first or last).""" + t, slope = self._level_at(coordinate) + f = self._function(phi, t) + g = [dphi[a] if axis_first else dphi[:, a] for a in range(3)] + sign = np.sign(phi) if self.variant == "sheet" else 1.0 + g = [sign * c for c in g] + g[self.gradient_axis] = g[self.gradient_axis] - slope + norm = np.sqrt(g[0] ** 2 + g[1] ** 2 + g[2] ** 2) + return f / np.maximum(norm, 1e-12 * 2.0 * math.pi / self.wavelength) + + def _grid_coordinate(self, grid: Grid) -> np.ndarray: + axis = self.gradient_axis + c = grid.origin[axis] + (np.arange(grid.shape[axis]) + 0.5) * grid.spacing[axis] + shape = [1, 1, 1] + shape[axis] = -1 + return c.reshape(shape) + + # -- the interface of the structures ----------------------------------------------------- + + def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1): + grid = self.grid(shape, voxel_size=voxel_size, grid=grid) + ss = int(supersampling) + if not 1 <= ss <= 6: + raise ValueError("supersampling must be an integer between 1 and 6") + fine = grid if ss == 1 else Grid(grid.domain, tuple(n * ss for n in grid.shape)) + phi = self.field(fine) + t, _ = self._level_at(self._grid_coordinate(fine)) + inside = self._function(phi, t) <= 0.0 + if ss == 1: + data = inside.astype(np.uint8) + return VoxelImage.from_grid(data, grid, name="phase", metadata=self.image_metadata()) + nx, ny, nz = grid.shape + data = inside.reshape(nx, ss, ny, ss, nz, ss).mean(axis=(1, 3, 5), dtype=np.float32) + return VoxelImage.from_grid(data, grid, name="fraction", metadata=self.image_metadata()) + + def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage: + """First-order distance ``f / |grad f|`` of the function of the solid (``phi - t``, + ``|phi| - t`` or ``t - phi``; negative in the solid).""" + grid = self.grid(shape, voxel_size=voxel_size, grid=grid) + phi, dphi = self.field(grid, gradient=True) + data = self._distance(phi, dphi, self._grid_coordinate(grid), True) + return VoxelImage.from_grid( + data.astype(np.float32), grid, name="level_set", metadata=self.image_metadata() + ) + + def contains(self, points) -> np.ndarray: + pts = np.asarray(points, dtype=float).reshape(-1, 3) + t, _ = self._level_at(pts[:, self.gradient_axis]) + return self._function(self.values_at(pts), t) <= 0.0 + + #: The first-order distance is a distance near the surface; margin for its curvature + lipschitz = 1.5 + + def level_set_at(self, points, reach: float = np.inf) -> np.ndarray: + """The first-order distance of :meth:`level_set` at the points.""" + pts = np.asarray(points, dtype=float).reshape(-1, 3) + phi, dphi = self.values_at(pts, gradient=True) + return self._distance(phi, dphi, pts[:, self.gradient_axis], False) + + def summary(self) -> dict: + out = {"waves": len(self.waves()[0]), "wavelength": self.wavelength} + if self.levels is not None: + out["graded"] = "xyz"[self.gradient_axis] + return out + + def _geometry(self) -> dict: + out = { + "wavelength": self.wavelength, + "n_waves": self.n_waves, + "cone_angles": list(self.cone_angles), + "variant": self.variant, + "level": self.level, + "wave_seed": self.wave_seed, + "bandwidth": self.bandwidth, + } + if self.levels is not None: + out["levels"] = self.levels.tolist() + out["gradient_axis"] = self.gradient_axis + return out + + @classmethod + def _from_geometry(cls, domain, geometry, **kwargs): + return cls( + domain, + geometry["wavelength"], + geometry["n_waves"], + geometry["cone_angles"], + geometry["variant"], + geometry["level"], + geometry["wave_seed"], + bandwidth=geometry.get("bandwidth", BANDWIDTH), + levels=geometry.get("levels"), + gradient_axis=geometry.get("gradient_axis", 0), + **kwargs, + ) + + +@register +@anisotropic +@dataclass(frozen=True) +class Spinodoid(Model): + """Spinodoid: a level of a sum of waves of one wavelength in random directions, on the + sphere or within cones about the axes (see the module): the network, the sheet or the + other network, at a level, a volume fraction or a profile of the fraction along an + axis (graded, in a non-periodic domain).""" + + name = "spinodoid" + phases: ClassVar[dict[int, str]] = {0: "void", 1: "solid"} + + wavelength: float = param(1.0, doc="Wavelength 2 pi / |k| of the waves", unit="length") + n_waves: int = param( + 1000, + doc="Number of waves (in a periodic box: at most, among the modes of the shell)", + kind="int", + ) + cone_angles: tuple[float, ...] = param( + (90.0, 90.0, 90.0), + doc="Half-angles (degrees) of the cones of the directions about x, y and z (0: no " + "cone; 90, 90, 90: isotropic; 15, 0, 0: lamellar; 0, 15, 15: columnar)", + kind="floats", + ) + variant: str = param( + "network", + doc="'network' (phi <= level), 'sheet' (|phi| <= level) or 'upper_network' (phi >= level)", + kind="str", + ) + volume_fraction: float | None = param(None, doc="Target solid volume fraction", kind="fraction") + level: float | None = param(None, doc="Level t of the field (of unit variance)") + fraction_gradient: tuple[float, ...] | None = param( + None, + doc="Solid volume fractions at equally spaced positions from the lower to the upper " + "face of the domain along gradient_axis, interpolated linearly: a graded spinodoid " + "(non-periodic domains)", + kind="floats", + ) + gradient_axis: int = param( + 0, doc="Axis of the gradient of the volume fraction: 0, 1 or 2", kind="int" + ) + bandwidth: float = param( + BANDWIDTH, + doc="Periodic boxes: relative width of the shell of the modes about the wavelength", + ) + anisotropy: Anisotropy | None = param(None, doc=ANISOTROPY, kind="anisotropy", kw_only=True) + + def _validate(self) -> None: + check_positive(self.wavelength, "wavelength") + if int(self.n_waves) != self.n_waves or self.n_waves < 10: + raise ValueError("n_waves: an integer, at least 10") + if len(self.cone_angles) != 3: + raise ValueError("cone_angles: three half-angles (degrees)") + if not all(0.0 <= a <= 90.0 for a in self.cone_angles): + raise ValueError("cone_angles: between 0 and 90 degrees") + if not any(a > 0.0 for a in self.cone_angles): + raise ValueError("cone_angles: one cone at least") + if self.variant not in VARIANTS: + raise ValueError(f"variant: expected one of {list(VARIANTS)}, got {self.variant!r}") + given = [v is not None for v in (self.level, self.volume_fraction, self.fraction_gradient)] + if sum(given) != 1: + raise ValueError( + "give exactly one of 'level', 'volume_fraction' and 'fraction_gradient'" + ) + if self.volume_fraction is not None: + check_fraction(self.volume_fraction, "volume_fraction") + if self.fraction_gradient is not None: + if len(self.fraction_gradient) < 2: + raise ValueError( + "fraction_gradient: the fractions at two positions at least (the lower " + "and upper faces)" + ) + for f in self.fraction_gradient: + check_fraction(f, "fraction_gradient") + if self.gradient_axis not in (0, 1, 2): + raise ValueError("gradient_axis: 0, 1 or 2") + if self.variant == "sheet" and self.level is not None and self.level < 0: + raise ValueError("level: must be non-negative for a sheet") + if not 0.0 < self.bandwidth < 1.0: + raise ValueError("bandwidth: between 0 and 1") + + def mean_fraction(self) -> float: + """The target volume fraction, or the mean of a graded profile.""" + if self.fraction_gradient is not None: + f = np.asarray(self.fraction_gradient, dtype=float) + return float(np.mean(0.5 * (f[1:] + f[:-1]))) + if self.volume_fraction is not None: + return float(self.volume_fraction) + t = float(self.level) + if self.variant == "sheet": + return float(2.0 * stats.norm.cdf(t) - 1.0) + if self.variant == "upper_network": + return float(stats.norm.sf(t)) + return float(stats.norm.cdf(t)) + + @property + def iso_level(self) -> float: + if self.level is not None: + return float(self.level) + return level_of_fraction(self.variant, self.mean_fraction()) + + def graded_levels(self) -> np.ndarray | None: + """The table of the levels of a graded spinodoid (None for a constant level).""" + if self.fraction_gradient is None: + return None + f = np.asarray(self.fraction_gradient, dtype=float) + s = np.linspace(0.0, 1.0, _GRADED_SAMPLES * (len(f) - 1) + 1) + fractions = np.interp(s, np.linspace(0.0, 1.0, len(f)), f) + return np.asarray(level_of_fraction(self.variant, fractions), dtype=float) + + def generate(self, domain: Domain, seed: SeedLike = None) -> SpinodoidStructure: + rng, seed_info = make_rng(seed) + levels = self.graded_levels() + if levels is not None and domain.periodic: + raise ValueError("spinodoid: a graded spinodoid needs a non-periodic domain") + # the waves are drawn from a child seed so that they can be regenerated lazily + wave_seed = {"entropy": int(rng.integers(0, 2**63)), "spawn_key": []} + return SpinodoidStructure( + domain, + self.wavelength, + self.n_waves, + self.cone_angles, + self.variant, + self.iso_level if levels is None else float(np.mean(levels)), + wave_seed, + bandwidth=self.bandwidth, + levels=levels, + gradient_axis=self.gradient_axis, + model=self, + seed=seed_info, + ) + + def theory(self, domain: Domain | None = None) -> dict[str, float]: + """The volume fraction; for a constant level, the specific surface of Rice's + formula for Gaussian waves of the directions of the cones.""" + out = {"volume_fraction": self.mean_fraction()} + if self.fraction_gradient is not None: + return out + t = self.iso_level + beta = 2.0 * math.pi / self.wavelength + moments = beta * beta * cone_moments(self.cone_angles) + surface = rice_surface(moments, t) + out["level"] = t + out["specific_surface"] = 2.0 * surface if self.variant == "sheet" else surface + return out diff --git a/src/morphogen/viz/sections.py b/src/morphogen/viz/sections.py index 6f1c3ab..e836858 100644 --- a/src/morphogen/viz/sections.py +++ b/src/morphogen/viz/sections.py @@ -92,6 +92,7 @@ from morphogen.models.plate_lattice import PlateLatticeStructure from morphogen.models.scale_rich import ScaleRichStructure from morphogen.models.scale_rich_3d import ScaleRichBeams, ScaleRichPlates +from morphogen.models.spinodoid import SpinodoidStructure from morphogen.models.tessellation import Tessellation from morphogen.models.textile import TextileStructure from morphogen.models.tpms import TPMSStructure @@ -132,6 +133,7 @@ _POINTWISE = ( PrimitiveUnion, TPMSStructure, + SpinodoidStructure, Tessellation, GaussianField, LatticeField, diff --git a/tests/public_api.txt b/tests/public_api.txt index 6218e4c..fd6144d 100644 --- a/tests/public_api.txt +++ b/tests/public_api.txt @@ -3676,6 +3676,8 @@ morphogen.models: SeededTessellation morphogen.models: SphereChains morphogen.models: Spinodal morphogen.models: SpinodalStructure +morphogen.models: Spinodoid +morphogen.models: SpinodoidStructure morphogen.models: StrutLattice morphogen.models: TPMSStructure morphogen.models: Tessellation @@ -4512,6 +4514,29 @@ morphogen.models.spinodal.cahn_hilliard(c, kappa, time, *, steps=None, energy=Fa morphogen.models.spinodal.free_energy(c, kappa) morphogen.models.spinodal.structure_peak(c) morphogen.models.spinodal.wave_numbers(shape) +morphogen.models.spinodoid.BANDWIDTH +morphogen.models.spinodoid.Spinodoid(wavelength=1.0, n_waves=1000, cone_angles=(90.0, 90.0, 90.0), variant='network', volume_fraction=None, level=None, fraction_gradient=None, gradient_axis=0, bandwidth=0.2, *, anisotropy=None) +morphogen.models.spinodoid.Spinodoid.generate(self, domain, seed=None) +morphogen.models.spinodoid.Spinodoid.graded_levels(self) +morphogen.models.spinodoid.Spinodoid.iso_level +morphogen.models.spinodoid.Spinodoid.mean_fraction(self) +morphogen.models.spinodoid.Spinodoid.theory(self, domain=None) +morphogen.models.spinodoid.SpinodoidStructure(domain, wavelength, n_waves, cone_angles, variant, level, wave_seed, *, bandwidth=0.2, levels=None, gradient_axis=0, **kwargs) +morphogen.models.spinodoid.SpinodoidStructure.amplitude +morphogen.models.spinodoid.SpinodoidStructure.contains(self, points) +morphogen.models.spinodoid.SpinodoidStructure.field(self, grid, gradient=False) +morphogen.models.spinodoid.SpinodoidStructure.level_set(self, shape=None, *, voxel_size=None, grid=None) +morphogen.models.spinodoid.SpinodoidStructure.level_set_at(self, points, reach=inf) +morphogen.models.spinodoid.SpinodoidStructure.second_moments(self) +morphogen.models.spinodoid.SpinodoidStructure.summary(self) +morphogen.models.spinodoid.SpinodoidStructure.values_at(self, points, gradient=False) +morphogen.models.spinodoid.SpinodoidStructure.voxelize(self, shape=None, *, voxel_size=None, grid=None, supersampling=1) +morphogen.models.spinodoid.SpinodoidStructure.waves(self) +morphogen.models.spinodoid.VARIANTS +morphogen.models.spinodoid.cone_moments(angles) +morphogen.models.spinodoid.in_cones(n, angles) +morphogen.models.spinodoid.level_of_fraction(variant, fraction) +morphogen.models.spinodoid.rice_surface(second_moments, level) morphogen.models.tessellation.Laguerre(n_cells=None, intensity=None, phase_fractions=None, crystal_orientations=False, boundary_thickness=0.0, boundary_phase=None, radius=Constant(value=1.0), germs='poisson', packing_fraction=0.3, *, texture=None, anisotropy=None) morphogen.models.tessellation.Laguerre.generate(self, domain, seed=None) morphogen.models.tessellation.Laguerre.theory(self, domain=None) diff --git a/tests/test_models_base.py b/tests/test_models_base.py index 1a5e527..8cdd8d4 100644 --- a/tests/test_models_base.py +++ b/tests/test_models_base.py @@ -65,6 +65,7 @@ {"surface": "gyroid", "cell_size": 4.0, "variant": "sheet", "volume_fraction": 0.2}, True, ), + "spinodoid": ({"wavelength": 2.0, "volume_fraction": 0.4, "n_waves": 200}, True), "strut_lattice": ({"cell": "bcc", "cell_size": 4.0, "strut_radius": 0.4}, True), "plate_lattice": ( {"cell": "cubic+fcc", "cell_size": 4.0, "volume_fraction": 0.2, "isotropic": True}, diff --git a/tests/test_spinodoid.py b/tests/test_spinodoid.py new file mode 100644 index 0000000..42d3782 --- /dev/null +++ b/tests/test_spinodoid.py @@ -0,0 +1,167 @@ +"""Spinodoids: levels of sums of waves of one wavelength (theory.md §141).""" + +import math + +import numpy as np +import pytest + +import morphogen as mg +from morphogen import analysis +from morphogen.analysis import morphology +from morphogen.models.base import Microstructure +from morphogen.models.spinodoid import ( + Spinodoid, + SpinodoidStructure, + cone_moments, + in_cones, + level_of_fraction, + rice_surface, +) + +CUBE = mg.Domain(size=(6.0, 6.0, 6.0), periodic=False) + + +@pytest.mark.parametrize("variant", ["network", "sheet", "upper_network"]) +def test_fraction_and_rice_surface(variant): + """Isotropic waves: the fraction of the normal law, the specific surface of Rice's + formula (twice for a sheet), the level set negative exactly on the solid voxels and the + points of the solid.""" + model = Spinodoid(wavelength=1.0, volume_fraction=0.3, variant=variant) + micro = model.generate(CUBE, seed=1) + img = micro.voxelize(shape=96) + theory = model.theory() + assert img.data.mean() == pytest.approx(0.3, abs=0.015) + assert analysis.specific_surface(img) == pytest.approx(theory["specific_surface"], rel=0.04) + coarse = micro.voxelize(shape=40) + assert np.array_equal(micro.level_set(shape=40).data <= 0, coarse.data == 1) + pts = coarse.grid().center_points() + assert np.array_equal(micro.contains(pts).reshape(coarse.shape), coarse.data == 1) + values = micro.level_set_at(pts).reshape(coarse.shape) + assert np.abs(values - micro.level_set(shape=40).data).max() < 1e-4 + + +def test_field_statistics_and_distance(): + """The field has the mean 0, the variance 1 and the gradient of second moments + beta^2 / 3; its level set is a distance across the surface (slope about 1).""" + micro = Spinodoid(wavelength=1.0, volume_fraction=0.5).generate(CUBE, seed=2) + rng = np.random.default_rng(0) + pts = rng.uniform(CUBE.lower, CUBE.upper, (20000, 3)) + phi, grad = micro.values_at(pts, gradient=True) + assert phi.mean() == pytest.approx(0.0, abs=0.03) + assert phi.var() == pytest.approx(1.0, abs=0.05) + beta = 2.0 * math.pi + assert np.mean(grad**2, axis=0) == pytest.approx([beta**2 / 3] * 3, rel=0.1) + assert np.allclose(micro.second_moments(), beta**2 / 3 * np.eye(3), atol=0.08 * beta**2) + near = pts[np.abs(micro.level_set_at(pts)) < 0.005][:200] + slopes = [] + for p in near: + g = [(micro.level_set_at(p + e)[0] - micro.level_set_at(p - e)[0]) / 2e-5 + for e in 1e-5 * np.eye(3)] # fmt: skip + slopes.append(np.linalg.norm(g)) + assert np.median(slopes) == pytest.approx(1.0, abs=0.05) + + +def test_periodic_modes(): + """In a periodic box the waves are modes of the box in the shell: the field is + periodic, a realization tiles, and the fraction and surface are those of the theory.""" + model = Spinodoid(wavelength=1.0, volume_fraction=0.4) + micro = model.generate(mg.Domain.cube(4.0), seed=2) + k = micro.waves()[0] + m = k * 4.0 / (2.0 * math.pi) + assert np.allclose(m, np.rint(m)) + size = np.linalg.norm(k, axis=1) / (2.0 * math.pi) + assert np.all((size >= 0.9 - 1e-12) & (size <= 1.1 + 1e-12)) + assert 50 < len(k) <= 1000 + pts = np.random.default_rng(1).uniform(0.0, 4.0, (50, 3)) + shift = np.array([4.0, -4.0, 8.0]) + assert np.allclose(micro.values_at(pts), micro.values_at(pts + shift)) + img = micro.voxelize(shape=64) + assert img.data.mean() == pytest.approx(0.4, abs=0.02) + surface = analysis.specific_surface(img) + assert surface == pytest.approx(model.theory()["specific_surface"], rel=0.05) + with pytest.raises(ValueError, match="no mode"): + Spinodoid(wavelength=10.0, volume_fraction=0.4).generate(mg.Domain.cube(1.0)).waves() + + +def test_cones(): + """Waves within cones: lamellar structures (a cone about x: thin along x), columnar + ones (cones about y and z: long along x), and Rice's surface of their directions.""" + lamellar = Spinodoid(wavelength=1.0, volume_fraction=0.5, cone_angles=(15.0, 0.0, 0.0)) + micro = lamellar.generate(CUBE, seed=3) + k = micro.waves()[0] + assert in_cones(k / np.linalg.norm(k, axis=1)[:, None], (15.0, 0.0, 0.0)).all() + img = micro.voxelize(shape=96) + chords = [np.mean(morphology.chord_lengths(img, axis=a)) for a in range(3)] + assert chords[0] < 0.3 * min(chords[1], chords[2]) + expected = lamellar.theory()["specific_surface"] + assert analysis.specific_surface(img) == pytest.approx(expected, rel=0.05) + columnar = Spinodoid(wavelength=1.0, volume_fraction=0.5, cone_angles=(0.0, 15.0, 15.0)) + img = columnar.generate(CUBE, seed=3).voxelize(shape=96) + chords = [np.mean(morphology.chord_lengths(img, axis=a)) for a in range(3)] + assert chords[0] > 3.0 * max(chords[1], chords[2]) + # the moments of the directions: isotropic, and all along x for a narrow cone + assert np.allclose(cone_moments((90.0, 90.0, 90.0)), np.eye(3) / 3, atol=1e-3) + narrow = cone_moments((5.0, 0.0, 0.0)) + assert narrow[0, 0] > 0.99 + # Rice: S_V of an isotropic Gaussian field at level t, 2 beta exp(-t^2/2) / (pi sqrt 3) + beta = 2.0 * math.pi + exact = 2.0 * beta * math.exp(-0.5 * 0.7**2) / (math.pi * math.sqrt(3.0)) + assert rice_surface(beta**2 / 3 * np.eye(3), 0.7) == pytest.approx(exact, rel=1e-3) + + +def test_graded(): + """A graded sheet: the fraction of each slab follows the profile; the realization is + written and read back.""" + domain = mg.Domain(size=(8.0, 3.0, 3.0), periodic=False) + model = Spinodoid(wavelength=0.5, fraction_gradient=(0.2, 0.6), variant="sheet") + micro = model.generate(domain, seed=4) + img = micro.voxelize(shape=(256, 96, 96)) + slabs = img.data.reshape(8, 32, 96, 96).mean(axis=(1, 2, 3)) + target = 0.2 + 0.4 * (np.arange(8) + 0.5) / 8 + assert np.max(np.abs(slabs - target)) < 0.025 + assert model.theory() == {"volume_fraction": pytest.approx(0.4)} + small = (64, 24, 24) + assert np.array_equal(micro.level_set(shape=small).data <= 0, + micro.voxelize(shape=small).data == 1) # fmt: skip + back = Microstructure.from_dict(micro.to_dict()) + assert isinstance(back, SpinodoidStructure) + assert np.array_equal(back.voxelize(shape=small).data, micro.voxelize(shape=small).data) + + +def test_levels_and_errors(): + """The levels of the normal law, the theory at a level, and errors.""" + assert level_of_fraction("network", 0.5) == pytest.approx(0.0, abs=1e-12) + assert level_of_fraction("sheet", 0.6827) == pytest.approx(1.0, abs=1e-3) + assert level_of_fraction("upper_network", 0.3) == pytest.approx(-level_of_fraction( + "network", 0.3)) # fmt: skip + assert Spinodoid(level=0.0).theory()["volume_fraction"] == pytest.approx(0.5) + with pytest.raises(ValueError, match="exactly one"): + Spinodoid() + with pytest.raises(ValueError, match="cone_angles"): + Spinodoid(volume_fraction=0.3, cone_angles=(0.0, 0.0, 0.0)) + with pytest.raises(ValueError, match="cone_angles"): + Spinodoid(volume_fraction=0.3, cone_angles=(100.0, 0.0, 0.0)) + with pytest.raises(ValueError, match="n_waves"): + Spinodoid(volume_fraction=0.3, n_waves=3) + with pytest.raises(ValueError, match="non-periodic"): + Spinodoid(fraction_gradient=(0.2, 0.4)).generate(mg.Domain.cube(2.0)) + with pytest.raises(ValueError, match="variant"): + Spinodoid(volume_fraction=0.3, variant="skeletal") + + +def test_in_a_configuration(tmp_path): + """A spinodoid from a configuration: the run and its STL surface.""" + from morphogen import pipeline + from morphogen.config import load_config + + config = { + "model": {"type": "spinodoid", "wavelength": 0.5, "volume_fraction": 0.35, + "cone_angles": [30, 30, 30], "n_waves": 300}, + "domain": {"size": 2.0, "periodic": False}, + "voxels": {"shape": 32}, + "seed": 5, + "outputs": {"directory": str(tmp_path), "name": "spin", "surface": ["stl"]}, + "analysis": ["volume_fraction"], + } # fmt: skip + outdir = pipeline.run(load_config(config)) + assert list(outdir.rglob("spin*.stl")) From 9b01adad52f4a2144dda120d085dc63d540737a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 23:33:12 +0000 Subject: [PATCH 03/13] Hybrid architectures: two models blended across a transition MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The model hybrid (theory notes §142, FR-G31, specification 1.256): two models blended across a plane, a cylinder or a sphere by a sigmoid of the distance to it (Yang et al. 2014; Top6Meta's hybrids), the first below the plane or inside, the second beyond. Any two models with implicit functions: their functions bounded by D tanh(phi / D) before they are blended, so that a first-order distance that grows far from its surface does not outweigh the other model; the slope of the blend bounded by max(L_1, L_2) + D / 2w. In the registry, the interface, the sections and the per-model tests; 51 models in the documentation; the public interface written again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MSrXEMpgnWPQNUwHwAgXHV --- CHANGELOG.md | 9 + README.md | 2 +- docs/api.md | 2 +- docs/architecture.md | 2 +- docs/guide.md | 2 +- docs/index.md | 2 +- docs/models.md | 3 +- docs/specification.md | 6 +- docs/theory.md | 55 +++++- docs/tutorial_geometry.md | 2 +- docs/tutorial_interface.md | 2 +- src/morphogen/gui/api.py | 4 +- src/morphogen/models/__init__.py | 5 + src/morphogen/models/hybrid.py | 302 +++++++++++++++++++++++++++++++ src/morphogen/viz/sections.py | 2 + tests/public_api.txt | 15 ++ tests/test_hybrid.py | 112 ++++++++++++ tests/test_models_base.py | 10 + 18 files changed, 526 insertions(+), 11 deletions(-) create mode 100644 src/morphogen/models/hybrid.py create mode 100644 tests/test_hybrid.py diff --git a/CHANGELOG.md b/CHANGELOG.md index a64a30f..b087edc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +* Hybrid architectures (`hybrid`, [docs/theory.md](docs/theory.md) §142): two models blended + across a plane, a cylinder or a sphere (`transition`, `position`, `radius`, `center`), the + first below the plane or inside, the second beyond, by a sigmoid of the distance to the + surface of width `width` (Yang et al. 2014): a gyroid into a Schwarz P along a beam, a + strut lattice at the core of a cylinder in a TPMS. Any two models with implicit + functions: their functions bounded by `scale` (`D tanh(phi / D)`) before they are + blended, so that a first-order distance that grows far from its surface does not + outweigh the other model; the slope of the blend bounded for the exact measures and + meshes. Public interface: `Hybrid`, `HybridStructure`. * Spinodoids (`spinodoid`, [docs/theory.md](docs/theory.md) §141): the level of a sum of waves of one wavelength (Cahn 1965; Soyarslan et al. 2018; Kumar et al. 2020), their directions uniform on the sphere or within cones about the axes (`cone_angles`: diff --git a/README.md b/README.md index 06e28a6..ea01e51 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ A study follows one chain, and each step is a part of the package: | Step | What morphoGen does | |---|---| -| **Generate** | 50 models: Boolean models, packings, fibres, tessellations, Gaussian fields, dead leaves, automata and growths, spinodal decomposition, strut and plate lattices, foams, triply periodic surfaces, woven textiles, bio-inspired structures, images segmented into their phases; monodisperse or polydisperse; periodic or not, combined, nested; hierarchical structures of any models four or five levels deep, chains or trees (lattices of lattices or of tubes, tows of fibres in a porous resin, grains of lamellae); and the shapes of Microgen (3MAH) | +| **Generate** | 51 models: Boolean models, packings, fibres, tessellations, Gaussian fields, dead leaves, automata and growths, spinodal decomposition, strut and plate lattices, foams, triply periodic surfaces, woven textiles, bio-inspired structures, images segmented into their phases; monodisperse or polydisperse; periodic or not, combined, nested; hierarchical structures of any models four or five levels deep, chains or trees (lattices of lattices or of tubes, tows of fibres in a porous resin, grains of lamellae); and the shapes of Microgen (3MAH) | | **Describe** | an exact description of each realization (centres, axes, cells) and an implicit function for each phase, from which voxel images, surfaces and conforming meshes are cut at any resolution | | **Measure** | fractions, specific surface, covariance, chords, tortuosity, percolation thresholds, stereology..., each beside the closed form of its model when there is one; on the implicit geometry itself, exactly: the probes of mathematical morphology and the Minkowski functionals of unions of spheres; the model of an image or of a section identified among candidates | | **Compute** | elastic, thermal, electrical, dielectric, magnetic and diffusive properties, their couplings, harmonic regimes, the magnetization curves of saturating phases and the magnetostriction and stiffening in a field of magnetorheological elastomers, the magnetic domains of ferromagnets (micromagnetics: hysteresis loops and first-order reversal curves, their dynamics, their thermal fluctuations and their magnetostriction under stress), hierarchical structures homogenized level by level and the buckling of their levels (the walls of their tubes too), waves, flow and sound, thermo-chemo-elastic fields in time, periodic plates through their thickness (their stiffness of Kirchhoff and Love, their transverse shear by the bending gradient, their conductance and their bowing, the permeance and the inertance of perforated panels, the sound that panels let through, their guided waves and band gaps, prestressed too, the wrinkling and the dimpling of their faces, compressed or heated between fixed edges, their elastic limits and their collapse, and the panels of diff --git a/docs/api.md b/docs/api.md index b6c25eb..59f7dd4 100644 --- a/docs/api.md +++ b/docs/api.md @@ -20,7 +20,7 @@ the steps of a study: | Step | Package | What it holds | |---|---|---| -| Generate | [`morphogen.models`](api/morphogen.models.rst) | the 50 models of microstructures and the shapes of Microgen (3MAH), their realizations and their theory | +| Generate | [`morphogen.models`](api/morphogen.models.rst) | the 51 models of microstructures and the shapes of Microgen (3MAH), their realizations and their theory | | | [`morphogen.automata`](api/morphogen.automata.rst) | cellular automata and lattice growth processes, on grids and tilings | | | [`morphogen.design`](api/morphogen.design.rst) | tile assemblies, strut frameworks and their rigidity, searches of design spaces | | | [`morphogen.optimization`](api/morphogen.optimization.rst) | topology optimization of periodic cells by inverse homogenization, and the inverse design of active structures | diff --git a/docs/architecture.md b/docs/architecture.md index 6181d0e..67a849c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1362,7 +1362,7 @@ style. | `test_conforming.py` | MMG meshes: tiling, mirrored meshes of symmetric cells (exact symmetries, matching faces, the group of a 2 x 2 array of holes), volume fractions, exact faces, matching periodic faces and exact PBC, porous lattices, exports (VTU, INP, MSH, Medit) and readers | | `test_iga.py` | B-spline functions against the recurrence of Cox and de Boor, their derivatives and the embeddings of their refinements; exact arcs, refined patches and assemblies; the patch test (plane strain, plane stress, a solid); Lamé's thick-walled cylinder (orders 3 and 2, 4 and 3) and Kirsch's plate with a hole; the effective tensors of a homogeneous cell, of a laminate (elasticity, conduction) and of a cell with a hole, against the curved finite elements of the solid (slow); cells of any lattice (other cuts of the same cell, strips with gaps, a cell and its neighbour), the square and hexagonal arrays of holes against the series of Perrins et al. and the isotropy of the hexagonal one, the sheet with alternating holes (exact fraction, symmetries of the square, the square array with circles, Poisson's ratio against the ligaments; against the FFT solver, slow) | | `test_iga_optimization.py` | the design and its geometries (linear maps, symmetric radial variables); the analytical shape derivatives of the tensor and of the fraction of a cell (elasticity, conduction) and of the compliance and the area of a structure against central differences; the hole of largest bulk modulus against the bound of Hashin and Shtrikman (Vigdergauz; SLSQP and MMA); the hole of a plate under biaxial tension against the ellipse (slow); folded designs and the history of the kept iterates; variables linked by the symmetries of a pattern (images and directions, periods, derivatives, errors); the holes of an auxetic sheet found again from their effective constants; its lowest Poisson's ratio at a given stiffness, with linear constraints | -| `test_implicit.py` | the implicit geometry of every model: for the 50 models, the shapes of Microgen and 19 other configurations of several phases, an implicit function of each phase whose sign is that of the voxel image on two grids and which partition the points; the Menger sponge on the grid of its cubes, two cells and their boundary layer against their planes, leaves and a transparent leaf against their spheres; the interpolation on the background mesh; the conforming mesh of a coated sphere (three phases cut one after the other: volumes, matching faces, the phases kept, finite elements against the FFT solver), cells of three phases meshed by their grains, coated hard spheres (slow) | +| `test_implicit.py` | the implicit geometry of every model: for the 51 models, the shapes of Microgen and 19 other configurations of several phases, an implicit function of each phase whose sign is that of the voxel image on two grids and which partition the points; the Menger sponge on the grid of its cubes, two cells and their boundary layer against their planes, leaves and a transparent leaf against their spheres; the interpolation on the background mesh; the conforming mesh of a coated sphere (three phases cut one after the other: volumes, matching faces, the phases kept, finite elements against the FFT solver), cells of three phases meshed by their grains, coated hard spheres (slow) | | `test_radioss.py` | the inputs of OpenRadioss read back card by card against the columns of the Radioss Reference Guide (units, nodes, bricks and tetrahedra oriented for Radioss, their mid-side nodes on their edges, parts, the solid property, LAW1, LAW36 with its yield curves at the rates of Norton's viscosity, LAW2, node groups, held and driven faces, the anchor of free faces, a shear, an impact on a rigid wall, the self contact, the time histories and their sampling, the Engine input, the length scale); the model (units, materials, loadings, time steps); the listings, time histories and legacy VTK grids (ASCII and binary, classic and VTK 5.1) | | `test_dynamics.py` | the installation of OpenRadioss found (the paths, the environment, the permissions restored), runs with a stand-in of OpenRadioss (`fake_openradioss.py`): the curves of a bar against its modulus, the forces from the time history or the animations, the frames for the 3D view, a shear, an impact, the failures of the Starter, the stops, the conversions; a release installed from a GitHub API served locally (the archive of each system, no member leaving its folder); the command line | | `test_gui_tools_dynamics.py` | the tab Explicit dynamics: the inputs written without OpenRadioss (engineering units, the materials of the fields and of the JSON), the errors, a dynamic test with the stand-in (its summary in MPa and MJ/m³, the curves in morphoGen's components compared with another run, the 3D view of its last frame), the results read back, the installation found, an impact | diff --git a/docs/guide.md b/docs/guide.md index e8550d0..90d3577 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -10,7 +10,7 @@ questions. | Step | Page | What it covers | |---|---|---| -| Generate | [Models of microstructures](models.md) | the 50 models by family and the shapes of Microgen, their anisotropy, their sizes (monodisperse or polydisperse), automata and growth, nested and bio-inspired models | +| Generate | [Models of microstructures](models.md) | the 51 models by family and the shapes of Microgen, their anisotropy, their sizes (monodisperse or polydisperse), automata and growth, nested and bio-inspired models | | Describe | [Geometry, voxels and meshes](geometry.md) | exact descriptions, implicit functions, voxel images, conforming meshes, symmetric cells | | Measure | [Measures and theory](measures.md) | the closed forms of the models, the measures of images, percolation, crystallographic textures | | Compute | [The library of materials](library.md) | the materials of the phases by their names — metals, crystals, ceramics, glasses, polymers, elastomers, fibres, fluids —, their values, sources and units; materials of one's own | diff --git a/docs/index.md b/docs/index.md index 7404ddb..e4316a9 100644 --- a/docs/index.md +++ b/docs/index.md @@ -39,7 +39,7 @@ package, a command line and a graphical interface in the web browser; free softw ::::{container} card **[Generate](models.md)** -50 models of random and architected media: Boolean models, packings, fibres, +51 models of random and architected media: Boolean models, packings, fibres, tessellations, Gaussian fields, dead leaves, automata and growths, spinodal decomposition, strut and plate lattices, foams, triply periodic surfaces, woven textiles, bio-inspired structures, images segmented into their phases; periodic or not, combined, nested; diff --git a/docs/models.md b/docs/models.md index 62df1ef..389e305 100644 --- a/docs/models.md +++ b/docs/models.md @@ -4,7 +4,7 @@ A model holds the parameters of a random set or of a deterministic architecture, closed-form characteristics of the set when they exist (`model.theory()`: volume fraction, specific surface, covariance, integral range...). `model.generate(domain, seed)` draws one realization of it in a box, periodic or not; the same seed gives the -same realization. morphoGen has 50 models, listed below by family, and takes the shapes of +same realization. morphoGen has 51 models, listed below by family, and takes the shapes of [Microgen](https://github.com/3MAH/microgen) (3MAH) through the model `microgen` ([below](#shapes-of-microgen)): `morphogen models` lists them, `morphogen models ` gives the parameters of one, and the @@ -110,6 +110,7 @@ What a realization is made of, and how it becomes images and meshes, is the subj | Model | Description | |---|---| | `combination` | Union, intersection, difference and complement of models; inclusions in a matrix, e.g. a polycrystal; nested models (each fills the phase 1 of the previous one); the unions of unions of spheres and segments, and their differences where those removed lie within the first, meshed in the plane by their exact contours | +| `hybrid` | Two models blended across a plane, a cylinder or a sphere (multi-morphology architectures, Yang et al. 2014): a gyroid into a Schwarz P, a strut lattice at the core of a TPMS; any two models with implicit functions, bounded before they are blended ([theory notes](theory.md) §142) | | `cox_spheres` | Spheres clustered in the phase 1 of another model: Cox models of nanocomposites (particles in aggregates), hard-core or not | | `coating` | A coating (interphase) around the phase 1 of any model, or a shell inside it: hollow spheres, fibres and struts, core–shell particles | | `hierarchy` | Models nested in the phases of others at any number of scales, four or five deep: lattices whose struts are lattices, porous walls, fibres of fibrils, grains of lamellae; each level any model, in the frame of the members or grains of the level above; homogenized level by level | diff --git a/docs/specification.md b/docs/specification.md index acd1932..d55b41a 100644 --- a/docs/specification.md +++ b/docs/specification.md @@ -3,7 +3,7 @@ | | | |---|---| | Document | Software requirements specification | -| Version | 1.255 | +| Version | 1.256 | | Date | 2026-12-01 | | Author | @jdirr | | Status | Version 1.1 **validated** on 2026-10-21. The later versions, proposed, are listed in the change log (§13); changes go through pull requests that update this file and its change log. | @@ -362,6 +362,8 @@ centred on morphological modelling. | Delivered | FR-G29 (`tpms`, [theory.md](theory.md) §140): six more nodal surfaces (Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P, I2-Y; Lord & Mackay 2003), their derivatives for the first-order distance; the network `upper_network` on the other side of the level; `fraction_gradient` along `gradient_axis`, the level of each position that of its fraction (any piecewise-linear profile, in non-periodic domains) | | Additive manufacturing: spinodoids (2026-12-01) | The stochastic architectures of Kumar et al. (2020) and of Top6Meta's spinodal module. | | Delivered | FR-G30 (`spinodoid`, [theory.md](theory.md) §141): `n_waves` waves of a `wavelength`, directions uniform or within `cone_angles` (lamellar, columnar, cubic), random phases; the three solids at a level of the normal law, graded by `fraction_gradient`; the modes of a shell of `bandwidth` in periodic boxes; the specific surface by Rice's formula; grids by products of complex matrices | +| Additive manufacturing: hybrids (2026-12-01) | Multi-morphology architectures, as Top6Meta's hybrids, for any two models. | +| Delivered | FR-G31 (`hybrid`, [theory.md](theory.md) §142): `transition` linear, cylindrical or spherical, `position`, `radius`, `center` and `width` (the sigmoid of Yang et al. 2014), the functions bounded by `scale` before they are blended, each model where the weight is 0 or 1, the slope bounded by `max(L_1, L_2) + D / 2w` | ## 4. Scope @@ -439,6 +441,7 @@ version, 0.1). | FR-G28 | Plate lattices: plates on the {100}, {110} and {111} planes of the cubic lattices and their mixtures, given by thicknesses or an exact relative density, the isotropic ratios of the mixtures; their exact density, specific surface and convex pieces; the stiffness of the membranes at low density | S | 3d | | FR-G29 | TPMS: ten surfaces (gyroid, Schwarz P and D, Neovius, Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P, I2-Y), the networks on either side of a level and the sheet, at a level, a volume fraction or a profile of the volume fraction along an axis (graded TPMS) | S | 1d | | FR-G30 | Spinodoids: the levels of sums of waves of one wavelength in random directions, on the sphere or within cones about the axes, the network, the sheet or the other network at a level, a fraction or a profile of fractions, periodic in periodic boxes; their specific surface by Rice's formula | S | 1d | +| FR-G31 | Hybrid architectures: two models with implicit functions blended across a plane, a cylinder or a sphere by a sigmoid of the distance to it, their bounded functions mixed continuously; a bound of the slope of the blend | S | 1d | ### 5.2 Representations @@ -1427,6 +1430,7 @@ Packages: `models`, `kernels`, `analysis`, `rve`, `mesh`, `homogenization`, `io` | 1.253 | 2026-12-01 | Forchheimer's law through OpenFOAM: periodic flows at finite Reynolds numbers, the weak inertia and Forchheimer's law fitted (FR-E19, §3.12) | | 1.254 | 2026-12-01 | TPMS: ten surfaces, the other network and graded TPMS (FR-G29, §3.12) | | 1.255 | 2026-12-01 | Spinodoids: sums of waves of one wavelength, cones, grading, Rice's surface (FR-G30, §3.12) | +| 1.256 | 2026-12-01 | Hybrid architectures: two models blended across a plane, a cylinder or a sphere (FR-G31, §3.12) | ## 14. References diff --git a/docs/theory.md b/docs/theory.md index 220e863..95e47de 100644 --- a/docs/theory.md +++ b/docs/theory.md @@ -12,7 +12,7 @@ them by these numbers (§75); by theme: | Theme | Sections | |---|---| | Models of random media | [§1](#1-boolean-models) Boolean models, [§2](#2-poisson-fibres-jeulin-1991-dirrenberger-et-al-2014) Poisson fibres (Jeulin 1991; Dirrenberger et al. 2014), [§3](#3-random-sequential-addition) Random sequential addition, [§4](#4-tessellations) Tessellations, [§5](#5-excursions-of-gaussian-random-fields) Excursions of Gaussian random fields, [§22](#22-combinations-of-models-and-grain-boundary-phases) Combinations of models and grain-boundary phases, [§23](#23-further-models) Further models, [§29](#29-nested-models) Nested models, [§38](#38-torquatos-approaches-dense-packings-cherry-pit-spheres-reconstruction-and-descriptors) Torquato's approaches: dense packings, cherry-pit spheres, reconstruction and descriptors, [§42](#42-foams-as-level-sets-of-distance-fields-level_set_foam) Foams as level sets of distance fields, [§56](#56-affine-anisotropy-of-the-models-modelsaffine) Affine anisotropy of the models, [§93](#93-scale-rich-networks-scale_rich_network) Scale-rich networks, [§95](#95-long-fibres-unidirectional-composites-parallel-or-misaligned-long_fibers) Long fibres: unidirectional composites, parallel or misaligned, [§97](#97-grains-with-subgrains-or-filled-with-another-structure-modelsnested_grains) Grains with subgrains, or filled with another structure, [§98](#98-monodisperse-and-polydisperse-objects) Monodisperse and polydisperse objects, [§107](#107-images-as-microstructures-segmentation-and-the-model-image-morphologysegmentation-modelsimage) Images as microstructures: segmentation and the model `image`, [§114](#114-reconstruction-from-descriptors-by-gradient-descent-morphologyreconstruction) Reconstruction from descriptors by gradient descent, [§115](#115-grains-grown-from-seeds-modelsseeded-kernelsseeds) Grains grown from seeds, [§116](#116-seeds-of-several-phases-and-the-verification-of-their-grains-modelsseeded-meshpolyhedra-kernelsseeds) Seeds of several phases and the verification of their grains, [§117](#117-seeds-of-the-plane-and-the-figures-of-the-verification-modelsseeded-vizfigures) Seeds of the plane and the figures of the verification, [§118](#118-seeds-of-boxes-and-of-rectangles-modelsseeded) Seeds of boxes and of rectangles | -| Architected and bio-inspired structures | [§6](#6-tpms) TPMS, [§7](#7-strut-lattices) Strut lattices, [§30](#30-bio-inspired-models) Bio-inspired models, [§71](#71-diamond-and-pyrochlore-lattices-of-struts-homogenizationframes-modelslattice) Diamond and pyrochlore lattices of struts, [§96](#96-woven-textile-composites-woven_textile) Woven textile composites, [§110](#110-woven-textiles-the-variability-of-the-tows-3d-architectures-the-tows-as-unidirectional-composites-woven_textile-homogenizationunidirectional) Woven textiles: the variability of the tows, 3D architectures, the tows as unidirectional composites, [§125](#125-plate-lattices-plate_lattice) Plate lattices, [§140](#140-tpms-ten-surfaces-their-two-networks-and-their-gradients-modelstpms) TPMS: ten surfaces, their two networks and their gradients, [§141](#141-spinodoids-levels-of-sums-of-waves-of-one-wavelength-modelsspinodoid) Spinodoids: levels of sums of waves of one wavelength | +| Architected and bio-inspired structures | [§6](#6-tpms) TPMS, [§7](#7-strut-lattices) Strut lattices, [§30](#30-bio-inspired-models) Bio-inspired models, [§71](#71-diamond-and-pyrochlore-lattices-of-struts-homogenizationframes-modelslattice) Diamond and pyrochlore lattices of struts, [§96](#96-woven-textile-composites-woven_textile) Woven textile composites, [§110](#110-woven-textiles-the-variability-of-the-tows-3d-architectures-the-tows-as-unidirectional-composites-woven_textile-homogenizationunidirectional) Woven textiles: the variability of the tows, 3D architectures, the tows as unidirectional composites, [§125](#125-plate-lattices-plate_lattice) Plate lattices, [§140](#140-tpms-ten-surfaces-their-two-networks-and-their-gradients-modelstpms) TPMS: ten surfaces, their two networks and their gradients, [§141](#141-spinodoids-levels-of-sums-of-waves-of-one-wavelength-modelsspinodoid) Spinodoids: levels of sums of waves of one wavelength, [§142](#142-hybrid-architectures-two-models-blended-across-a-transition-modelshybrid) Hybrid architectures: two models blended across a transition | | Growth and design | [§14](#14-cellular-automata-automata) Cellular automata, [§15](#15-nucleation-and-growth-johnsonmehlavramikolmogorov) Nucleation and growth (Johnson–Mehl–Avrami–Kolmogorov), [§16](#16-aggregation) Aggregation, [§17](#17-combinatorial-design-design) Combinatorial design, [§18](#18-topology-optimization-of-periodic-cells-optimization) Topology optimization of periodic cells, [§78](#78-isogeometric-analysis-iga) Isogeometric analysis, [§79](#79-isogeometric-shape-optimization-igaoptimization) Isogeometric shape optimization, [§109](#109-inverse-design-of-active-structures-optimizationmorphing) Inverse design of active structures, [§113](#113-spinodal-decomposition-spinodal) Spinodal decomposition | | Geometry and meshes | [§19](#19-polycrystals-exact-cells-and-conforming-meshes-meshpolyhedra-meshpolycrystal) Polycrystals: exact cells and conforming meshes, [§24](#24-whole-periodic-grains-meshpolycrystal-cells-whole) Whole periodic grains, [§52](#52-views-and-measures-of-the-level-sets-vizsections) Views and measures of the level sets, [§75](#75-the-implicit-geometry-of-every-model-modelsimplicit-meshconforming) The implicit geometry of every model, [§76](#76-quadratic-tetrahedra-isoparametric-elements-and-curved-interfaces-meshcurved-homogenizationfe) Quadratic tetrahedra: isoparametric elements and curved interfaces, [§80](#80-sharp-edges-of-the-phases-meshes-that-follow-them-modelspieces-meshconforming-meshcurved) Sharp edges of the phases: meshes that follow them, [§94](#94-exact-meshes-without-a-background-grid-meshexact-meshoctree) Exact meshes without a background grid, [§119](#119-meshes-of-the-plane-and-their-finite-elements-meshtriangles-homogenizationplane) Meshes of the plane and their finite elements | | Measures | [§8](#8-specific-surface-by-cauchycrofton) Specific surface by Cauchy–Crofton, [§21](#21-morphological-measures-analysismorphology) Morphological measures, [§39](#39-random-sets-probed-by-structuring-elements-analysisrandom_sets-analysistopology) Random sets probed by structuring elements, [§55](#55-percolation-thresholds-analysispercolation) Percolation thresholds, [§70](#70-particles-of-a-phase-in-a-volume-analysisparticles) Particles of a phase in a volume, [§92](#92-crystallographic-textures-and-orientation-maps-texture-ioebsd-modelsebsd) Crystallographic textures and orientation maps, [§104](#104-measures-of-the-implicit-geometry-morphologymeasures) Measures of the implicit geometry, [§105](#105-unions-of-balls-and-of-discs-measured-exactly-morphologyballs) Unions of balls and of discs, measured exactly, [§106](#106-the-model-of-an-image-morphologyidentification) The model of an image | @@ -16703,6 +16703,56 @@ their cones within 5 %, the moments of isotropic and narrow cones, Rice's closed graded sheet whose slabs follow the profile within 0.025, written and read back; the levels of the normal law and the errors; a run from a configuration to its STL surface. +## 142. Hybrid architectures: two models blended across a transition (`models.hybrid`) + +Multi-morphology architectures pass from one structure to another within a part: a +gyroid into a Schwarz P along a beam, a strut lattice at the core of a cylinder and a TPMS +around it. Yang et al. (2014) blend the functions of two TPMS with a sigmoid of the +position; `hybrid` blends any two models with implicit functions (§75), each solid the set +where its function $\varphi_i$ (negative inside, a signed or first-order distance) is +negative: + +$$ +\varphi = \alpha\,\tilde\varphi_1 + (1 - \alpha)\,\tilde\varphi_2, \qquad +\alpha = \frac{1}{1 + e^{G/w}}, \qquad \tilde\varphi_i = D\tanh(\varphi_i/D), +$$ + +$G$ the signed distance to the surface of the transition (`transition`): a plane across +an axis ($G = x_a - x_0$, `position`, by default the middle of the domain), a cylinder about +an axis ($G = r - R$) or a sphere ($G = |x - c| - R$; `radius` by default a quarter of the +smallest edge across the axis, `center` the centre of the domain); $w$ the `width` of the +transition ($\alpha$ goes from 0.9 to 0.1 over $4.4w$; Top6Meta's sharpness $k$ is $1/w$). +The first model lies below the plane, inside the cylinder or the sphere ($G < 0$, +$\alpha \to 1$), the second beyond. + +**Bounded functions.** Blending distances rather than the raw functions of the TPMS makes +the two terms comparable for any pair of models; but a first-order distance +$(\varphi - t)/|\nabla\varphi|$ grows without bound near the critical points of $\varphi$, +far from its surface (4 cells for a gyroid at a fraction 0.2), and would outweigh the +other model there. The bound $D\tanh(\varphi/D)$ keeps the zero set and the slope at the +surface ($D\tanh(x/D) = x - x^3/3D^2 + \dots$) and caps the values at $D$ (`scale`, by +default the larger median $|\varphi_i|$ of the two realizations on 4096 points of the +domain). The slope of the blend is then at most + +$$ +L \le \max(L_1, L_2) + \frac{D}{2w}, +$$ + +as $|\tilde\varphi_1 - \tilde\varphi_2| \le 2D$ and $|\nabla\alpha| \le 1/4w$: the bound +that the exact measures (§104) and meshes (§75) use. Where $\alpha$ is within $10^{-6}$ of 1 or 0, +the hybrid is the first or the second model, voxel for voxel. Within the transition the +blend of two sheets is thinner than either (their walls do not overlap): the fraction of a +gyroid sheet blended into a Schwarz P sheet, both at 0.25, falls to about 0.19 there; wider +transitions smooth it. The blend is not periodic. + +Validated in `tests/test_hybrid.py`: a gyroid sheet into a Schwarz P sheet along $z$, +equal to each model voxel for voxel far from the plane, the weight the sigmoid of the +distance, the level set negative exactly on the solid voxels and the points; an octet +lattice inside a cylinder and a sphere within a gyroid, the core the lattice, the bound of +the slope, a realization read back; the bounded functions (the same signs, the same values +near the surfaces, the blend within $D$); the default position, radius, centre and scale, +the errors; a run from a configuration to its STL surface. + ## References See [specification.md](specification.md#14-references). In addition: @@ -17875,3 +17925,6 @@ See [specification.md](specification.md#14-references). In addition: 326–340. * Kumar, S., Tan, S., Zheng, L., Kochmann, D. M. (2020). Inverse-designed spinodoid metamaterials. *npj Comput. Mater.* 6, 73. +* Yang, N., Quan, Z., Zhang, D., Tian, Y. (2014). Multi-morphology transition + hybridization CAD design of minimal surface porous structures for use in tissue + engineering. *Comput.-Aided Des.* 56, 11–21. diff --git a/docs/tutorial_geometry.md b/docs/tutorial_geometry.md index 6d134a4..e8fc534 100644 --- a/docs/tutorial_geometry.md +++ b/docs/tutorial_geometry.md @@ -63,7 +63,7 @@ print(level.data.dtype, bool(((level.data < 0) == (image.data == 2)).all())) mg.io.save_image(level, "interphase.vti") # for ParaView: its zero level is the interface ``` -Every model has such functions — the 50 models, the shapes of Microgen, their combinations, coatings, nested and +Every model has such functions — the 51 models, the shapes of Microgen, their combinations, coatings, nested and transformed structures: distances to unions of spheres and segments, differences of power distances to the germs of cells, the rings of osteons, the leaves of a dead-leaves model outside those that cover them ([theory notes](theory.md), §75). A structure of two diff --git a/docs/tutorial_interface.md b/docs/tutorial_interface.md index a45ab25..3e194b0 100644 --- a/docs/tutorial_interface.md +++ b/docs/tutorial_interface.md @@ -23,7 +23,7 @@ opens its menu (where to send it, its 3D view, a new title), its cross **×** (o middle click) closes it — **Undo** beside the strip brings it back for a few seconds; its files stay in the folder of the session either way. -In *Create › Generate*, the menu lists the 50 models and the shapes of Microgen by family (the filter above it +In *Create › Generate*, the menu lists the 51 models and the shapes of Microgen by family (the filter above it finds one by a word of its name or of its summary). Choose `boolean_spheres`: its form opens filled with its template; set the radius to 1, the volume fraction to 0.2, the size of the domain to 10 and the seed to 1, then **Generate** (or `Ctrl + Enter`, which diff --git a/src/morphogen/gui/api.py b/src/morphogen/gui/api.py index 57eda33..230d7ec 100644 --- a/src/morphogen/gui/api.py +++ b/src/morphogen/gui/api.py @@ -203,7 +203,9 @@ def examples() -> dict[str, dict]: "cellular_automaton", "activator_inhibitor", "reaction_diffusion", "nucleation_growth", "aggregation", "branching", "spinodal", ), - "Assemblies and combinations": ("tile_assembly", "combination", "coating", "hierarchy"), + "Assemblies and combinations": ( + "tile_assembly", "combination", "hybrid", "coating", "hierarchy", + ), } # fmt: skip diff --git a/src/morphogen/models/__init__.py b/src/morphogen/models/__init__.py index a3669a8..14410f7 100644 --- a/src/morphogen/models/__init__.py +++ b/src/morphogen/models/__init__.py @@ -26,6 +26,8 @@ Fischer-Koch S, lidinoid, split P, I2-Y): sheets, networks, graded ``spinodoid`` Spinodoids: levels of sums of waves of one wavelength in random directions or cones (Kumar et al. 2020), graded +``hybrid`` Two models blended across a plane, a cylinder or a sphere + (multi-morphology architectures) ``strut_lattice`` Cubic, BCC, FCC and octet strut lattices ``plate_lattice`` Plate lattices: closed cells of plates on the {100}, {110} and {111} planes (cubic, bcc, fcc) and their isotropic mixtures @@ -119,6 +121,7 @@ from morphogen.models.hierarchical import HierarchicalLattice from morphogen.models.hierarchy import HierarchicalStructure, Hierarchy from morphogen.models.honeycomb import Honeycomb, PrismaticCells +from morphogen.models.hybrid import Hybrid, HybridStructure from morphogen.models.image import ImageModel, ImageStructure from morphogen.models.laminate import Laminate, RandomLaminate from morphogen.models.lattice import StrutLattice @@ -192,6 +195,8 @@ "HierarchicalStructure", "Hierarchy", "Honeycomb", + "Hybrid", + "HybridStructure", "ImageModel", "ImageStructure", "Laguerre", diff --git a/src/morphogen/models/hybrid.py b/src/morphogen/models/hybrid.py new file mode 100644 index 0000000..0254e42 --- /dev/null +++ b/src/morphogen/models/hybrid.py @@ -0,0 +1,302 @@ +"""Hybrid architectures: two models blended across a transition (multi-morphology). + +The solid of each model is the set where its function ``phi_i`` (its level set: a signed +distance or a first-order distance, negative inside) is negative; the hybrid is the set +where + + phi = alpha phi_1 + (1 - alpha) phi_2, alpha = 1 / (1 + exp(G / w)), + +is negative, ``G`` the signed distance to the surface of the transition and ``w`` its +width: a plane across an axis (``linear``, ``G = x_a - position``), a cylinder about an +axis (``cylindrical``, ``G = r - radius``) or a sphere (``spherical``, ``G = |x - c| - +radius``). The first model lies below the plane, inside the cylinder or the sphere, the +second beyond; within a few widths of the surface the two functions mix and the two +architectures merge into each other continuously (Top6Meta's hybrids, after the blending +of level sets of Yang et al. 2014). Blending distances rather than raw functions makes any +two models with implicit functions mix alike, a gyroid with a strut lattice as well as two +TPMS. + +Before they are blended, the functions are bounded, ``D tanh(phi_i / D)``: their zero +sets and their slopes at the surfaces are kept, while their values far from the surfaces, +where first-order distances grow without bound near the critical points of a function, +stay within ``D`` (``scale``: by default the larger median ``|phi_i|`` of the two models +over the domain). The slope of the blend is then at most ``max(L_1, L_2) + D / 2w`` (the +slope of ``alpha`` is ``1 / 4w`` at most). The blend is not periodic. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import ClassVar + +import numpy as np +from scipy.special import expit + +from morphogen._utils import check_positive +from morphogen.domain import Domain, Grid +from morphogen.image import VoxelImage +from morphogen.models.base import Microstructure, Model, param, register, register_kind +from morphogen.seeding import SeedLike, make_rng, seed_from_description + +TRANSITIONS = ("linear", "cylindrical", "spherical") +#: Points sampled over the domain for the default scale of the functions. +_SCALE_SAMPLES = 4096 + + +def _median_scale(parts, domain: Domain) -> float: + """The larger median ``|phi|`` of the realizations over points of the domain.""" + rng = np.random.default_rng(0) + pts = rng.uniform(domain.lower, domain.upper, (_SCALE_SAMPLES, 3)) + return max(float(np.median(np.abs(p.level_set_at(pts, np.inf)))) for p in parts) + + +@register_kind +class HybridStructure(Microstructure): + """Two realizations blended across a transition (see the module).""" + + kind = "hybrid" + + def __init__( + self, domain, parts, transition, axis, position, radius, center, width, scale, **kw + ): + super().__init__(domain, **kw) + if transition not in TRANSITIONS: + raise ValueError(f"transition: one of {', '.join(TRANSITIONS)}") + self.parts = list(parts) + self.transition = transition + self.axis = int(axis) + self.position = float(position) + self.radius = float(radius) + self.center = np.asarray(center, dtype=float) + self.width = float(width) + self.scale = float(scale) + + # -- the transition ---------------------------------------------------------------------- + + def signed_distance(self, points) -> np.ndarray: + """``G``: the signed distance of the points to the surface of the transition + (negative on the side of the first model).""" + p = np.asarray(points, dtype=float).reshape(-1, 3) + if self.transition == "linear": + return p[:, self.axis] - self.position + d = p - self.center + if self.transition == "cylindrical": + d[:, self.axis] = 0.0 + return np.linalg.norm(d, axis=1) - self.radius + + def weight(self, points) -> np.ndarray: + """``alpha``: the weight of the first model at the points.""" + return expit(-self.signed_distance(points) / self.width) + + # -- the functions ----------------------------------------------------------------------- + + def _bounded(self, f: np.ndarray) -> np.ndarray: + return self.scale * np.tanh(np.asarray(f, dtype=float) / self.scale) + + def _functions_at(self, points) -> list[np.ndarray]: + return [self._bounded(part.level_set_at(points, np.inf)) for part in self.parts] + + def level_set_at(self, points, reach: float = np.inf) -> np.ndarray: + """``alpha phi_1 + (1 - alpha) phi_2`` at the points.""" + pts = np.asarray(points, dtype=float).reshape(-1, 3) + f1, f2 = self._functions_at(pts) + a = self.weight(pts) + return a * f1 + (1.0 - a) * f2 + + def _grid_functions(self, grid: Grid) -> list[np.ndarray]: + pts = grid.center_points() + out = [] + for part in self.parts: + try: + f = part.level_set_at(pts, np.inf).reshape(grid.shape) + except NotImplementedError: + f = part.level_set(grid=grid).data.astype(float) + out.append(self._bounded(f)) + return out + + def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage: + """The blend of the functions of the two models at the voxel centres.""" + grid = self.grid(shape, voxel_size=voxel_size, grid=grid) + f1, f2 = self._grid_functions(grid) + a = self.weight(grid.center_points()).reshape(grid.shape) + data = (a * f1 + (1.0 - a) * f2).astype(np.float32) + return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata()) + + def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1): + grid = self.grid(shape, voxel_size=voxel_size, grid=grid) + ss = int(supersampling) + if not 1 <= ss <= 6: + raise ValueError("supersampling must be an integer between 1 and 6") + fine = grid if ss == 1 else Grid(grid.domain, tuple(n * ss for n in grid.shape)) + inside = self.level_set(grid=fine).data <= 0.0 + if ss == 1: + data = inside.astype(np.uint8) + return VoxelImage.from_grid(data, grid, name="phase", metadata=self.image_metadata()) + nx, ny, nz = grid.shape + data = inside.reshape(nx, ss, ny, ss, nz, ss).mean(axis=(1, 3, 5), dtype=np.float32) + return VoxelImage.from_grid(data, grid, name="fraction", metadata=self.image_metadata()) + + def contains(self, points) -> np.ndarray: + return self.level_set_at(points) <= 0.0 + + @property + def lipschitz(self) -> float: + """``max(L_1, L_2) + D / 2w``: the slopes of the bounded functions and of the + weight.""" + own = max(float(getattr(p, "lipschitz", 1.0) or 1.0) for p in self.parts) + return own + self.scale / (2.0 * self.width) + + # -- description ------------------------------------------------------------------------- + + def summary(self) -> dict: + out = {"transition": self.transition} + for k, part in enumerate(self.parts): + out.update({f"c{k}_{key}": value for key, value in part.summary().items()}) + return out + + def _geometry(self) -> dict: + return { + "parts": [p.to_dict() for p in self.parts], + "transition": self.transition, + "axis": self.axis, + "position": self.position, + "radius": self.radius, + "center": self.center.tolist(), + "width": self.width, + "scale": self.scale, + } + + @classmethod + def _from_geometry(cls, domain, geometry, **kwargs): + parts = [Microstructure.from_dict(d) for d in geometry["parts"]] + return cls( + domain, + parts, + geometry["transition"], + geometry["axis"], + geometry["position"], + geometry["radius"], + geometry["center"], + geometry["width"], + geometry["scale"], + **kwargs, + ) + + +@register +@dataclass(frozen=True) +class Hybrid(Model): + """Two models blended across a plane, a cylinder or a sphere (multi-morphology + architectures, see the module): the first below the plane, inside the cylinder or the + sphere, the second beyond, merging into each other within a few widths.""" + + name = "hybrid" + phases: ClassVar[dict[int, str]] = {0: "void", 1: "solid"} + supports_periodic: ClassVar[bool] = False + + models: tuple = param( + (), doc="The two models blended: mappings with a 'type' key and their parameters", + kind="models", + ) # fmt: skip + transition: str = param( + "linear", + doc="linear (a plane across axis), cylindrical (a cylinder about axis) or spherical " + "(a sphere about center)", + kind="str", + ) + axis: int = param(2, doc="Axis across the plane, or of the cylinder: 0, 1 or 2", kind="int") + position: float | None = param( + None, + doc="Linear: the coordinate of the plane along axis (default: the middle of the domain)", + unit="length", + ) + radius: float | None = param( + None, + doc="Cylindrical and spherical: the radius of the surface (default: a quarter of the " + "smallest edge of the domain across the axis)", + unit="length", + ) + center: tuple[float, ...] | None = param( + None, + doc="Cylindrical and spherical: the centre (default: the centre of the domain)", + kind="floats", + unit="length", + ) + width: float = param( + 0.1, + doc="Width w of the transition: alpha = 1 / (1 + exp(G / w)), G the signed distance " + "to the surface (90 % of the change within 4.4 w)", + unit="length", + ) + + scale: float | None = param( + None, + doc="Length D that bounds the functions in the blend, D tanh(phi / D) (default: the " + "larger median |phi| of the two models over the domain)", + unit="length", + ) + + def _validate(self) -> None: + if len(self.models) != 2: + raise ValueError("models: exactly two models to blend") + for m in self.models: + if not m.has_level_set: + raise ValueError( + f"models: {m.name} has no level set of its phase 1 (several phases); " + "blend two-phase models" + ) + if self.transition not in TRANSITIONS: + raise ValueError(f"transition: one of {', '.join(TRANSITIONS)}") + if self.axis not in (0, 1, 2): + raise ValueError("axis: 0, 1 or 2") + check_positive(self.width, "width") + if self.scale is not None: + check_positive(self.scale, "scale") + if self.radius is not None: + check_positive(self.radius, "radius") + if self.center is not None and len(self.center) != 3: + raise ValueError("center: three coordinates") + + def _surface(self, domain: Domain) -> tuple[float, float, np.ndarray]: + """The position, radius and centre of the transition in a domain (their defaults).""" + a = self.axis + position = ( + float(domain.center[a]) if self.position is None else float(self.position) + ) # fmt: skip + center = domain.center if self.center is None else np.asarray(self.center, dtype=float) + if self.radius is not None: + radius = float(self.radius) + else: + edges = domain.lengths if self.transition == "spherical" else np.delete( + domain.lengths, a + ) # fmt: skip + radius = 0.25 * float(np.min(edges)) + return position, radius, center + + def generate(self, domain: Domain, seed: SeedLike = None) -> HybridStructure: + self._check_domain(domain) + rng, seed_info = make_rng(seed) + if seed_info is not None: # children of the seed sequence: reproducible + seeds = list(seed_from_description(seed_info).spawn(len(self.models))) + else: + seeds = list(rng.spawn(len(self.models))) + parts = [m.generate(domain, s) for m, s in zip(self.models, seeds, strict=True)] + position, radius, center = self._surface(domain) + scale = self.scale if self.scale is not None else _median_scale(parts, domain) + return HybridStructure( + domain, + parts, + self.transition, + self.axis, + position, + radius, + center, + self.width, + scale if scale > 0.0 else self.width, + model=self, + seed=seed_info, + ) + + def theory(self, domain: Domain | None = None) -> dict[str, float]: + """None in closed form: the transition mixes the two solids (see the module).""" + return {} diff --git a/src/morphogen/viz/sections.py b/src/morphogen/viz/sections.py index e836858..18085a1 100644 --- a/src/morphogen/viz/sections.py +++ b/src/morphogen/viz/sections.py @@ -79,6 +79,7 @@ from morphogen.models.gaussian import GaussianField from morphogen.models.hierarchy import HierarchicalStructure from morphogen.models.honeycomb import PrismaticCells +from morphogen.models.hybrid import HybridStructure from morphogen.models.image import ImageStructure from morphogen.models.laminate import Laminate from morphogen.models.lattice_field import LatticeField @@ -134,6 +135,7 @@ PrimitiveUnion, TPMSStructure, SpinodoidStructure, + HybridStructure, Tessellation, GaussianField, LatticeField, diff --git a/tests/public_api.txt b/tests/public_api.txt index fd6144d..e9a7f8b 100644 --- a/tests/public_api.txt +++ b/tests/public_api.txt @@ -3635,6 +3635,8 @@ morphogen.models: HierarchicalLattice morphogen.models: HierarchicalStructure morphogen.models: Hierarchy morphogen.models: Honeycomb +morphogen.models: Hybrid +morphogen.models: HybridStructure morphogen.models: ImageModel morphogen.models: ImageStructure morphogen.models: Laguerre @@ -4064,6 +4066,19 @@ morphogen.models.honeycomb.WoodRays(boundary, z, u, cells, width, height, cell_l morphogen.models.honeycomb.WoodRays.cell_distance(self, ray, u, rel, across) morphogen.models.honeycomb.WoodRays.locate(self, boundary, z) morphogen.models.honeycomb.WoodRays.to_dict(self) +morphogen.models.hybrid.Hybrid(models=(), transition='linear', axis=2, position=None, radius=None, center=None, width=0.1, scale=None) +morphogen.models.hybrid.Hybrid.generate(self, domain, seed=None) +morphogen.models.hybrid.Hybrid.theory(self, domain=None) +morphogen.models.hybrid.HybridStructure(domain, parts, transition, axis, position, radius, center, width, scale, **kw) +morphogen.models.hybrid.HybridStructure.contains(self, points) +morphogen.models.hybrid.HybridStructure.level_set(self, shape=None, *, voxel_size=None, grid=None) +morphogen.models.hybrid.HybridStructure.level_set_at(self, points, reach=inf) +morphogen.models.hybrid.HybridStructure.lipschitz +morphogen.models.hybrid.HybridStructure.signed_distance(self, points) +morphogen.models.hybrid.HybridStructure.summary(self) +morphogen.models.hybrid.HybridStructure.voxelize(self, shape=None, *, voxel_size=None, grid=None, supersampling=1) +morphogen.models.hybrid.HybridStructure.weight(self, points) +morphogen.models.hybrid.TRANSITIONS morphogen.models.image.EXAMPLE morphogen.models.image.ImageModel(file='example_image.npz', array=None, classes=2, thresholds=None, sigma=0.0, spacing=None, window='origin') morphogen.models.image.ImageModel.active_phases(self) diff --git a/tests/test_hybrid.py b/tests/test_hybrid.py new file mode 100644 index 0000000..3e2c8f2 --- /dev/null +++ b/tests/test_hybrid.py @@ -0,0 +1,112 @@ +"""Hybrid architectures: two models blended across a transition (theory.md §142).""" + +import numpy as np +import pytest + +import morphogen as mg +from morphogen.models.base import Microstructure +from morphogen.models.hybrid import Hybrid, HybridStructure + +GYROID = {"type": "tpms", "surface": "gyroid", "variant": "sheet", "volume_fraction": 0.25} +PRIMITIVE = {"type": "tpms", "surface": "schwarz_p", "variant": "sheet", "volume_fraction": 0.25} +OCTET = {"type": "strut_lattice", "cell": "octet", "cell_size": 1.0, "volume_fraction": 0.2} + + +def test_linear_transition(): + """Far from the plane the hybrid is each model, voxel for voxel; the weight is the + sigmoid of the distance to the plane; the level set is negative exactly on the solid + voxels, and the points agree.""" + domain = mg.Domain(size=(2.0, 2.0, 6.0), periodic=False) + model = Hybrid(models=(GYROID, PRIMITIVE), transition="linear", axis=2, width=0.2) + micro = model.generate(domain, seed=1) + shape = (32, 32, 96) + img = micro.voxelize(shape=shape) + first = model.models[0].generate(domain).voxelize(shape=shape) + second = model.models[1].generate(domain).voxelize(shape=shape) + assert np.array_equal(img.data[:, :, :24], first.data[:, :, :24]) + assert np.array_equal(img.data[:, :, -24:], second.data[:, :, -24:]) + z = np.array([[0.0, 0.0, 3.0], [0.0, 0.0, 3.2], [0.0, 0.0, 2.0]]) + assert micro.weight(z) == pytest.approx([0.5, 1.0 / (1.0 + np.e), 1.0 / (1.0 + np.exp(-5.0))]) + assert np.array_equal(micro.level_set(shape=shape).data <= 0, img.data == 1) + pts = img.grid().center_points() + assert np.array_equal(micro.contains(pts).reshape(shape), img.data == 1) + + +@pytest.mark.parametrize("transition", ["cylindrical", "spherical"]) +def test_core_and_shell(transition): + """A strut lattice inside a cylinder or a sphere, a gyroid outside: each model where + the weight is nearly 0 or 1; the bound of the slope; a realization read back.""" + domain = mg.Domain(size=(3.0, 3.0, 3.0), periodic=False) + model = Hybrid(models=(OCTET, GYROID), transition=transition, radius=0.8, width=0.05) + micro = model.generate(domain, seed=2) + shape = (48, 48, 48) + img = micro.voxelize(shape=shape) + pts = img.grid().center_points() + a = micro.weight(pts).reshape(shape) + inner = model.models[0].generate(domain, 0).voxelize(shape=shape).data + assert micro.signed_distance([[1.5, 1.5, 1.5]])[0] == pytest.approx(-0.8) + core = (a > 1 - 1e-6) & (inner == img.data) + assert core.sum() >= 0.99 * (a > 1 - 1e-6).sum() + assert micro.lipschitz == pytest.approx( + max(p.lipschitz for p in micro.parts) + micro.scale / (2 * 0.05) + ) + back = Microstructure.from_dict(micro.to_dict()) + assert isinstance(back, HybridStructure) + assert np.array_equal(back.voxelize(shape=24).data, micro.voxelize(shape=24).data) + + +def test_bounded_functions(): + """The functions are bounded by the scale before the blend: their zero sets are kept, + their slopes at the surfaces too, and the blend stays within the scale.""" + domain = mg.Domain(size=(2.0, 2.0, 4.0), periodic=False) + model = Hybrid(models=(GYROID, OCTET), width=0.1, scale=0.15) + micro = model.generate(domain, seed=3) + pts = np.random.default_rng(1).uniform(domain.lower, domain.upper, (5000, 3)) + raw = micro.parts[0].level_set_at(pts) + bounded = micro._functions_at(pts)[0] + assert np.array_equal(raw <= 0, bounded <= 0) + near = np.abs(raw) < 0.005 + assert np.allclose(bounded[near], raw[near], rtol=1e-3) + assert np.all(np.abs(micro.level_set_at(pts)) <= 0.15 + 1e-12) + assert micro.scale == 0.15 + + +def test_defaults_and_errors(): + """The default position, radius, centre and scale; errors.""" + domain = mg.Domain(size=(2.0, 4.0, 6.0), periodic=False) + model = Hybrid(models=(GYROID, PRIMITIVE), transition="cylindrical", axis=2) + micro = model.generate(domain, seed=4) + assert micro.radius == pytest.approx(0.5) # a quarter of the smaller edge across z + assert np.allclose(micro.center, [1.0, 2.0, 3.0]) + assert micro.scale > 0 + sphere = Hybrid(models=(GYROID, PRIMITIVE), transition="spherical").generate(domain, 0) + assert sphere.radius == pytest.approx(0.5) + plane = Hybrid(models=(GYROID, PRIMITIVE), axis=1).generate(domain, 0) + assert plane.position == pytest.approx(2.0) + with pytest.raises(ValueError, match="exactly two"): + Hybrid(models=(GYROID,)) + with pytest.raises(ValueError, match="transition"): + Hybrid(models=(GYROID, PRIMITIVE), transition="radial") + with pytest.raises(ValueError, match="width"): + Hybrid(models=(GYROID, PRIMITIVE), width=0.0) + with pytest.raises(ValueError, match="level set"): + Hybrid(models=(GYROID, {"type": "voronoi", "n_cells": 10})) + with pytest.raises(ValueError, match="periodic"): + Hybrid(models=(GYROID, PRIMITIVE)).generate(mg.Domain.cube(2.0)) + + +def test_in_a_configuration(tmp_path): + """A hybrid from a configuration: a gyroid graded into a Schwarz P, its STL surface.""" + from morphogen import pipeline + from morphogen.config import load_config + + config = { + "model": {"type": "hybrid", "transition": "linear", "axis": 0, "width": 0.25, + "models": [GYROID, PRIMITIVE]}, + "domain": {"size": [4.0, 1.0, 1.0], "periodic": False}, + "voxels": {"shape": [64, 16, 16]}, + "seed": 1, + "outputs": {"directory": str(tmp_path), "name": "hybrid", "surface": ["stl"]}, + } # fmt: skip + outdir = pipeline.run(load_config(config)) + assert list(outdir.rglob("hybrid*.stl")) diff --git a/tests/test_models_base.py b/tests/test_models_base.py index 8cdd8d4..1e19198 100644 --- a/tests/test_models_base.py +++ b/tests/test_models_base.py @@ -66,6 +66,16 @@ True, ), "spinodoid": ({"wavelength": 2.0, "volume_fraction": 0.4, "n_waves": 200}, True), + "hybrid": ( + { + "models": [ + {"type": "tpms", "cell_size": 4.0, "volume_fraction": 0.3}, + {"type": "tpms", "surface": "schwarz_p", "cell_size": 4.0, "volume_fraction": 0.3}, + ], + "width": 0.5, + }, + False, + ), "strut_lattice": ({"cell": "bcc", "cell_size": 4.0, "strut_radius": 0.4}, True), "plate_lattice": ( {"cell": "cubic+fcc", "cell_size": 4.0, "volume_fraction": 0.2, "isotropic": True}, From e9b67530e94919a484703359aeeb4d43fe0d893d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 23:40:15 +0000 Subject: [PATCH 04/13] Parts ready to print: shapes, shells, skins, supports, conformal TPMS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The model part (theory notes §143, FR-G32, specification 1.257): any two-phase model filling a box, a cylinder, a tube, a sphere or a closed surface read from a file (STL binary or ASCII, other formats by meshio, fitted into the domain on request), with a shell along the boundary, the skins of a sandwich and the supports of a beam; its function a maximum and minima of signed distances. mesh.distance: the signed distance to a closed triangle surface on a grid, exact within a band (the closest points of Ericson), its inside by the parity of crossings, interpolated trilinearly. Conformal TPMS: the cells of tpms wrapped around an axis (cells_around), in cylindrical coordinates, for tubes and columns. 52 models in the documentation; the public interface written again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MSrXEMpgnWPQNUwHwAgXHV --- CHANGELOG.md | 11 + README.md | 2 +- docs/api.md | 2 +- docs/architecture.md | 2 +- docs/guide.md | 2 +- docs/index.md | 2 +- docs/models.md | 3 +- docs/specification.md | 6 +- docs/theory.md | 64 ++++- docs/tutorial_geometry.md | 2 +- docs/tutorial_interface.md | 2 +- src/morphogen/gui/api.py | 2 +- src/morphogen/kernels/implicit.py | 87 +++++- src/morphogen/mesh/distance.py | 202 ++++++++++++++ src/morphogen/models/__init__.py | 5 + src/morphogen/models/part.py | 438 ++++++++++++++++++++++++++++++ src/morphogen/models/tpms.py | 50 +++- src/morphogen/viz/sections.py | 2 + tests/public_api.txt | 28 +- tests/test_models_base.py | 9 + tests/test_part.py | 204 ++++++++++++++ 21 files changed, 1095 insertions(+), 30 deletions(-) create mode 100644 src/morphogen/mesh/distance.py create mode 100644 src/morphogen/models/part.py create mode 100644 tests/test_part.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b087edc..213e50f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ ## Unreleased +* Parts ready to print (`part`, [docs/theory.md](docs/theory.md) §143): any two-phase model + filling a box, a cylinder, a tube, a sphere or a closed surface read from a file (STL, + binary or ASCII, or OBJ, PLY... through meshio; `fit` scales it into the domain), with a + solid shell along the boundary (`shell`), the skins of a sandwich panel (`skins`) and the + supports of a beam (`supports`). The signed distance to a closed triangle surface on a + grid (`morphogen.mesh.distance`): exact near the surface, its inside by the parity of + crossings. Conformal TPMS (`tpms` with `cells_around`, `cylinder_axis`, + `cylinder_center`): cells wrapped around an axis, for tubes and columns. Public + interface: `Part`, `PartStructure`, `morphogen.mesh.distance` (`read_surface`, + `signed_distance_grid`, `interpolate`, `fitted`, `merged`, `is_closed`), and the keywords + `cells_around`, `cylinder_axis` and `cylinder_center` of `TPMS` and `TPMSStructure`. * Hybrid architectures (`hybrid`, [docs/theory.md](docs/theory.md) §142): two models blended across a plane, a cylinder or a sphere (`transition`, `position`, `radius`, `center`), the first below the plane or inside, the second beyond, by a sigmoid of the distance to the diff --git a/README.md b/README.md index ea01e51..4e68b7e 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ A study follows one chain, and each step is a part of the package: | Step | What morphoGen does | |---|---| -| **Generate** | 51 models: Boolean models, packings, fibres, tessellations, Gaussian fields, dead leaves, automata and growths, spinodal decomposition, strut and plate lattices, foams, triply periodic surfaces, woven textiles, bio-inspired structures, images segmented into their phases; monodisperse or polydisperse; periodic or not, combined, nested; hierarchical structures of any models four or five levels deep, chains or trees (lattices of lattices or of tubes, tows of fibres in a porous resin, grains of lamellae); and the shapes of Microgen (3MAH) | +| **Generate** | 52 models: Boolean models, packings, fibres, tessellations, Gaussian fields, dead leaves, automata and growths, spinodal decomposition, strut and plate lattices, foams, triply periodic surfaces, woven textiles, bio-inspired structures, images segmented into their phases; monodisperse or polydisperse; periodic or not, combined, nested; hierarchical structures of any models four or five levels deep, chains or trees (lattices of lattices or of tubes, tows of fibres in a porous resin, grains of lamellae); and the shapes of Microgen (3MAH) | | **Describe** | an exact description of each realization (centres, axes, cells) and an implicit function for each phase, from which voxel images, surfaces and conforming meshes are cut at any resolution | | **Measure** | fractions, specific surface, covariance, chords, tortuosity, percolation thresholds, stereology..., each beside the closed form of its model when there is one; on the implicit geometry itself, exactly: the probes of mathematical morphology and the Minkowski functionals of unions of spheres; the model of an image or of a section identified among candidates | | **Compute** | elastic, thermal, electrical, dielectric, magnetic and diffusive properties, their couplings, harmonic regimes, the magnetization curves of saturating phases and the magnetostriction and stiffening in a field of magnetorheological elastomers, the magnetic domains of ferromagnets (micromagnetics: hysteresis loops and first-order reversal curves, their dynamics, their thermal fluctuations and their magnetostriction under stress), hierarchical structures homogenized level by level and the buckling of their levels (the walls of their tubes too), waves, flow and sound, thermo-chemo-elastic fields in time, periodic plates through their thickness (their stiffness of Kirchhoff and Love, their transverse shear by the bending gradient, their conductance and their bowing, the permeance and the inertance of perforated panels, the sound that panels let through, their guided waves and band gaps, prestressed too, the wrinkling and the dimpling of their faces, compressed or heated between fixed edges, their elastic limits and their collapse, and the panels of diff --git a/docs/api.md b/docs/api.md index 59f7dd4..6733c00 100644 --- a/docs/api.md +++ b/docs/api.md @@ -20,7 +20,7 @@ the steps of a study: | Step | Package | What it holds | |---|---|---| -| Generate | [`morphogen.models`](api/morphogen.models.rst) | the 51 models of microstructures and the shapes of Microgen (3MAH), their realizations and their theory | +| Generate | [`morphogen.models`](api/morphogen.models.rst) | the 52 models of microstructures and the shapes of Microgen (3MAH), their realizations and their theory | | | [`morphogen.automata`](api/morphogen.automata.rst) | cellular automata and lattice growth processes, on grids and tilings | | | [`morphogen.design`](api/morphogen.design.rst) | tile assemblies, strut frameworks and their rigidity, searches of design spaces | | | [`morphogen.optimization`](api/morphogen.optimization.rst) | topology optimization of periodic cells by inverse homogenization, and the inverse design of active structures | diff --git a/docs/architecture.md b/docs/architecture.md index 67a849c..cc1770a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1362,7 +1362,7 @@ style. | `test_conforming.py` | MMG meshes: tiling, mirrored meshes of symmetric cells (exact symmetries, matching faces, the group of a 2 x 2 array of holes), volume fractions, exact faces, matching periodic faces and exact PBC, porous lattices, exports (VTU, INP, MSH, Medit) and readers | | `test_iga.py` | B-spline functions against the recurrence of Cox and de Boor, their derivatives and the embeddings of their refinements; exact arcs, refined patches and assemblies; the patch test (plane strain, plane stress, a solid); Lamé's thick-walled cylinder (orders 3 and 2, 4 and 3) and Kirsch's plate with a hole; the effective tensors of a homogeneous cell, of a laminate (elasticity, conduction) and of a cell with a hole, against the curved finite elements of the solid (slow); cells of any lattice (other cuts of the same cell, strips with gaps, a cell and its neighbour), the square and hexagonal arrays of holes against the series of Perrins et al. and the isotropy of the hexagonal one, the sheet with alternating holes (exact fraction, symmetries of the square, the square array with circles, Poisson's ratio against the ligaments; against the FFT solver, slow) | | `test_iga_optimization.py` | the design and its geometries (linear maps, symmetric radial variables); the analytical shape derivatives of the tensor and of the fraction of a cell (elasticity, conduction) and of the compliance and the area of a structure against central differences; the hole of largest bulk modulus against the bound of Hashin and Shtrikman (Vigdergauz; SLSQP and MMA); the hole of a plate under biaxial tension against the ellipse (slow); folded designs and the history of the kept iterates; variables linked by the symmetries of a pattern (images and directions, periods, derivatives, errors); the holes of an auxetic sheet found again from their effective constants; its lowest Poisson's ratio at a given stiffness, with linear constraints | -| `test_implicit.py` | the implicit geometry of every model: for the 51 models, the shapes of Microgen and 19 other configurations of several phases, an implicit function of each phase whose sign is that of the voxel image on two grids and which partition the points; the Menger sponge on the grid of its cubes, two cells and their boundary layer against their planes, leaves and a transparent leaf against their spheres; the interpolation on the background mesh; the conforming mesh of a coated sphere (three phases cut one after the other: volumes, matching faces, the phases kept, finite elements against the FFT solver), cells of three phases meshed by their grains, coated hard spheres (slow) | +| `test_implicit.py` | the implicit geometry of every model: for the 52 models, the shapes of Microgen and 19 other configurations of several phases, an implicit function of each phase whose sign is that of the voxel image on two grids and which partition the points; the Menger sponge on the grid of its cubes, two cells and their boundary layer against their planes, leaves and a transparent leaf against their spheres; the interpolation on the background mesh; the conforming mesh of a coated sphere (three phases cut one after the other: volumes, matching faces, the phases kept, finite elements against the FFT solver), cells of three phases meshed by their grains, coated hard spheres (slow) | | `test_radioss.py` | the inputs of OpenRadioss read back card by card against the columns of the Radioss Reference Guide (units, nodes, bricks and tetrahedra oriented for Radioss, their mid-side nodes on their edges, parts, the solid property, LAW1, LAW36 with its yield curves at the rates of Norton's viscosity, LAW2, node groups, held and driven faces, the anchor of free faces, a shear, an impact on a rigid wall, the self contact, the time histories and their sampling, the Engine input, the length scale); the model (units, materials, loadings, time steps); the listings, time histories and legacy VTK grids (ASCII and binary, classic and VTK 5.1) | | `test_dynamics.py` | the installation of OpenRadioss found (the paths, the environment, the permissions restored), runs with a stand-in of OpenRadioss (`fake_openradioss.py`): the curves of a bar against its modulus, the forces from the time history or the animations, the frames for the 3D view, a shear, an impact, the failures of the Starter, the stops, the conversions; a release installed from a GitHub API served locally (the archive of each system, no member leaving its folder); the command line | | `test_gui_tools_dynamics.py` | the tab Explicit dynamics: the inputs written without OpenRadioss (engineering units, the materials of the fields and of the JSON), the errors, a dynamic test with the stand-in (its summary in MPa and MJ/m³, the curves in morphoGen's components compared with another run, the 3D view of its last frame), the results read back, the installation found, an impact | diff --git a/docs/guide.md b/docs/guide.md index 90d3577..0377503 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -10,7 +10,7 @@ questions. | Step | Page | What it covers | |---|---|---| -| Generate | [Models of microstructures](models.md) | the 51 models by family and the shapes of Microgen, their anisotropy, their sizes (monodisperse or polydisperse), automata and growth, nested and bio-inspired models | +| Generate | [Models of microstructures](models.md) | the 52 models by family and the shapes of Microgen, their anisotropy, their sizes (monodisperse or polydisperse), automata and growth, nested and bio-inspired models | | Describe | [Geometry, voxels and meshes](geometry.md) | exact descriptions, implicit functions, voxel images, conforming meshes, symmetric cells | | Measure | [Measures and theory](measures.md) | the closed forms of the models, the measures of images, percolation, crystallographic textures | | Compute | [The library of materials](library.md) | the materials of the phases by their names — metals, crystals, ceramics, glasses, polymers, elastomers, fibres, fluids —, their values, sources and units; materials of one's own | diff --git a/docs/index.md b/docs/index.md index e4316a9..70a0bb5 100644 --- a/docs/index.md +++ b/docs/index.md @@ -39,7 +39,7 @@ package, a command line and a graphical interface in the web browser; free softw ::::{container} card **[Generate](models.md)** -51 models of random and architected media: Boolean models, packings, fibres, +52 models of random and architected media: Boolean models, packings, fibres, tessellations, Gaussian fields, dead leaves, automata and growths, spinodal decomposition, strut and plate lattices, foams, triply periodic surfaces, woven textiles, bio-inspired structures, images segmented into their phases; periodic or not, combined, nested; diff --git a/docs/models.md b/docs/models.md index 389e305..3e23967 100644 --- a/docs/models.md +++ b/docs/models.md @@ -4,7 +4,7 @@ A model holds the parameters of a random set or of a deterministic architecture, closed-form characteristics of the set when they exist (`model.theory()`: volume fraction, specific surface, covariance, integral range...). `model.generate(domain, seed)` draws one realization of it in a box, periodic or not; the same seed gives the -same realization. morphoGen has 51 models, listed below by family, and takes the shapes of +same realization. morphoGen has 52 models, listed below by family, and takes the shapes of [Microgen](https://github.com/3MAH/microgen) (3MAH) through the model `microgen` ([below](#shapes-of-microgen)): `morphogen models` lists them, `morphogen models ` gives the parameters of one, and the @@ -111,6 +111,7 @@ What a realization is made of, and how it becomes images and meshes, is the subj |---|---| | `combination` | Union, intersection, difference and complement of models; inclusions in a matrix, e.g. a polycrystal; nested models (each fills the phase 1 of the previous one); the unions of unions of spheres and segments, and their differences where those removed lie within the first, meshed in the plane by their exact contours | | `hybrid` | Two models blended across a plane, a cylinder or a sphere (multi-morphology architectures, Yang et al. 2014): a gyroid into a Schwarz P, a strut lattice at the core of a TPMS; any two models with implicit functions, bounded before they are blended ([theory notes](theory.md) §142) | +| `part` | A part ready to print: any two-phase model filling a box, a cylinder, a tube, a sphere or a closed surface read from a file (STL, OBJ, PLY), with a shell along its boundary, the skins of a sandwich and the supports of a beam; TPMS whose cells wrap around the axis of a tube (`cells_around`) ([theory notes](theory.md) §143) | | `cox_spheres` | Spheres clustered in the phase 1 of another model: Cox models of nanocomposites (particles in aggregates), hard-core or not | | `coating` | A coating (interphase) around the phase 1 of any model, or a shell inside it: hollow spheres, fibres and struts, core–shell particles | | `hierarchy` | Models nested in the phases of others at any number of scales, four or five deep: lattices whose struts are lattices, porous walls, fibres of fibrils, grains of lamellae; each level any model, in the frame of the members or grains of the level above; homogenized level by level | diff --git a/docs/specification.md b/docs/specification.md index d55b41a..8bf39a5 100644 --- a/docs/specification.md +++ b/docs/specification.md @@ -3,7 +3,7 @@ | | | |---|---| | Document | Software requirements specification | -| Version | 1.256 | +| Version | 1.257 | | Date | 2026-12-01 | | Author | @jdirr | | Status | Version 1.1 **validated** on 2026-10-21. The later versions, proposed, are listed in the change log (§13); changes go through pull requests that update this file and its change log. | @@ -364,6 +364,8 @@ centred on morphological modelling. | Delivered | FR-G30 (`spinodoid`, [theory.md](theory.md) §141): `n_waves` waves of a `wavelength`, directions uniform or within `cone_angles` (lamellar, columnar, cubic), random phases; the three solids at a level of the normal law, graded by `fraction_gradient`; the modes of a shell of `bandwidth` in periodic boxes; the specific surface by Rice's formula; grids by products of complex matrices | | Additive manufacturing: hybrids (2026-12-01) | Multi-morphology architectures, as Top6Meta's hybrids, for any two models. | | Delivered | FR-G31 (`hybrid`, [theory.md](theory.md) §142): `transition` linear, cylindrical or spherical, `position`, `radius`, `center` and `width` (the sigmoid of Yang et al. 2014), the functions bounded by `scale` before they are blended, each model where the weight is 0 or 1, the slope bounded by `max(L_1, L_2) + D / 2w` | +| Additive manufacturing: parts (2026-12-01) | Specimens and components rather than boxes: Top6Meta's sandwiches, beams and cylinders, and the infill of any part. | +| Delivered | FR-G32 (`part`, `mesh.distance`, `tpms` `cells_around`, [theory.md](theory.md) §143): `shape` box, cylinder, tube, sphere or mesh (`mesh`, `fit`, `resolution`), `shell`, `skins` and `supports` along their axes, the function of the part a maximum and minima of signed distances; the distance to a closed surface exact near it (Ericson's closest points), its inside by the parity of the columns; the cells of a TPMS wrapped around an axis | ## 4. Scope @@ -442,6 +444,7 @@ version, 0.1). | FR-G29 | TPMS: ten surfaces (gyroid, Schwarz P and D, Neovius, Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P, I2-Y), the networks on either side of a level and the sheet, at a level, a volume fraction or a profile of the volume fraction along an axis (graded TPMS) | S | 1d | | FR-G30 | Spinodoids: the levels of sums of waves of one wavelength in random directions, on the sphere or within cones about the axes, the network, the sheet or the other network at a level, a fraction or a profile of fractions, periodic in periodic boxes; their specific surface by Rice's formula | S | 1d | | FR-G31 | Hybrid architectures: two models with implicit functions blended across a plane, a cylinder or a sphere by a sigmoid of the distance to it, their bounded functions mixed continuously; a bound of the slope of the blend | S | 1d | +| FR-G32 | Parts ready to print: any two-phase model filling a box, a cylinder, a tube, a sphere or a closed surface read from a file, with a shell along its boundary, the skins of a sandwich and the supports of a beam; the signed distance to closed triangle surfaces; TPMS whose cells wrap around an axis (conformal TPMS) | S | 1d | ### 5.2 Representations @@ -1431,6 +1434,7 @@ Packages: `models`, `kernels`, `analysis`, `rve`, `mesh`, `homogenization`, `io` | 1.254 | 2026-12-01 | TPMS: ten surfaces, the other network and graded TPMS (FR-G29, §3.12) | | 1.255 | 2026-12-01 | Spinodoids: sums of waves of one wavelength, cones, grading, Rice's surface (FR-G30, §3.12) | | 1.256 | 2026-12-01 | Hybrid architectures: two models blended across a plane, a cylinder or a sphere (FR-G31, §3.12) | +| 1.257 | 2026-12-01 | Parts ready to print: shapes, shells, skins, supports, closed surfaces from files, conformal TPMS (FR-G32, §3.12) | ## 14. References diff --git a/docs/theory.md b/docs/theory.md index 95e47de..efb0def 100644 --- a/docs/theory.md +++ b/docs/theory.md @@ -12,7 +12,7 @@ them by these numbers (§75); by theme: | Theme | Sections | |---|---| | Models of random media | [§1](#1-boolean-models) Boolean models, [§2](#2-poisson-fibres-jeulin-1991-dirrenberger-et-al-2014) Poisson fibres (Jeulin 1991; Dirrenberger et al. 2014), [§3](#3-random-sequential-addition) Random sequential addition, [§4](#4-tessellations) Tessellations, [§5](#5-excursions-of-gaussian-random-fields) Excursions of Gaussian random fields, [§22](#22-combinations-of-models-and-grain-boundary-phases) Combinations of models and grain-boundary phases, [§23](#23-further-models) Further models, [§29](#29-nested-models) Nested models, [§38](#38-torquatos-approaches-dense-packings-cherry-pit-spheres-reconstruction-and-descriptors) Torquato's approaches: dense packings, cherry-pit spheres, reconstruction and descriptors, [§42](#42-foams-as-level-sets-of-distance-fields-level_set_foam) Foams as level sets of distance fields, [§56](#56-affine-anisotropy-of-the-models-modelsaffine) Affine anisotropy of the models, [§93](#93-scale-rich-networks-scale_rich_network) Scale-rich networks, [§95](#95-long-fibres-unidirectional-composites-parallel-or-misaligned-long_fibers) Long fibres: unidirectional composites, parallel or misaligned, [§97](#97-grains-with-subgrains-or-filled-with-another-structure-modelsnested_grains) Grains with subgrains, or filled with another structure, [§98](#98-monodisperse-and-polydisperse-objects) Monodisperse and polydisperse objects, [§107](#107-images-as-microstructures-segmentation-and-the-model-image-morphologysegmentation-modelsimage) Images as microstructures: segmentation and the model `image`, [§114](#114-reconstruction-from-descriptors-by-gradient-descent-morphologyreconstruction) Reconstruction from descriptors by gradient descent, [§115](#115-grains-grown-from-seeds-modelsseeded-kernelsseeds) Grains grown from seeds, [§116](#116-seeds-of-several-phases-and-the-verification-of-their-grains-modelsseeded-meshpolyhedra-kernelsseeds) Seeds of several phases and the verification of their grains, [§117](#117-seeds-of-the-plane-and-the-figures-of-the-verification-modelsseeded-vizfigures) Seeds of the plane and the figures of the verification, [§118](#118-seeds-of-boxes-and-of-rectangles-modelsseeded) Seeds of boxes and of rectangles | -| Architected and bio-inspired structures | [§6](#6-tpms) TPMS, [§7](#7-strut-lattices) Strut lattices, [§30](#30-bio-inspired-models) Bio-inspired models, [§71](#71-diamond-and-pyrochlore-lattices-of-struts-homogenizationframes-modelslattice) Diamond and pyrochlore lattices of struts, [§96](#96-woven-textile-composites-woven_textile) Woven textile composites, [§110](#110-woven-textiles-the-variability-of-the-tows-3d-architectures-the-tows-as-unidirectional-composites-woven_textile-homogenizationunidirectional) Woven textiles: the variability of the tows, 3D architectures, the tows as unidirectional composites, [§125](#125-plate-lattices-plate_lattice) Plate lattices, [§140](#140-tpms-ten-surfaces-their-two-networks-and-their-gradients-modelstpms) TPMS: ten surfaces, their two networks and their gradients, [§141](#141-spinodoids-levels-of-sums-of-waves-of-one-wavelength-modelsspinodoid) Spinodoids: levels of sums of waves of one wavelength, [§142](#142-hybrid-architectures-two-models-blended-across-a-transition-modelshybrid) Hybrid architectures: two models blended across a transition | +| Architected and bio-inspired structures | [§6](#6-tpms) TPMS, [§7](#7-strut-lattices) Strut lattices, [§30](#30-bio-inspired-models) Bio-inspired models, [§71](#71-diamond-and-pyrochlore-lattices-of-struts-homogenizationframes-modelslattice) Diamond and pyrochlore lattices of struts, [§96](#96-woven-textile-composites-woven_textile) Woven textile composites, [§110](#110-woven-textiles-the-variability-of-the-tows-3d-architectures-the-tows-as-unidirectional-composites-woven_textile-homogenizationunidirectional) Woven textiles: the variability of the tows, 3D architectures, the tows as unidirectional composites, [§125](#125-plate-lattices-plate_lattice) Plate lattices, [§140](#140-tpms-ten-surfaces-their-two-networks-and-their-gradients-modelstpms) TPMS: ten surfaces, their two networks and their gradients, [§141](#141-spinodoids-levels-of-sums-of-waves-of-one-wavelength-modelsspinodoid) Spinodoids: levels of sums of waves of one wavelength, [§142](#142-hybrid-architectures-two-models-blended-across-a-transition-modelshybrid) Hybrid architectures: two models blended across a transition, [§143](#143-parts-ready-to-print-infills-in-shapes-with-shells-skins-and-supports-modelspart) Parts ready to print: infills in shapes, with shells, skins and supports | | Growth and design | [§14](#14-cellular-automata-automata) Cellular automata, [§15](#15-nucleation-and-growth-johnsonmehlavramikolmogorov) Nucleation and growth (Johnson–Mehl–Avrami–Kolmogorov), [§16](#16-aggregation) Aggregation, [§17](#17-combinatorial-design-design) Combinatorial design, [§18](#18-topology-optimization-of-periodic-cells-optimization) Topology optimization of periodic cells, [§78](#78-isogeometric-analysis-iga) Isogeometric analysis, [§79](#79-isogeometric-shape-optimization-igaoptimization) Isogeometric shape optimization, [§109](#109-inverse-design-of-active-structures-optimizationmorphing) Inverse design of active structures, [§113](#113-spinodal-decomposition-spinodal) Spinodal decomposition | | Geometry and meshes | [§19](#19-polycrystals-exact-cells-and-conforming-meshes-meshpolyhedra-meshpolycrystal) Polycrystals: exact cells and conforming meshes, [§24](#24-whole-periodic-grains-meshpolycrystal-cells-whole) Whole periodic grains, [§52](#52-views-and-measures-of-the-level-sets-vizsections) Views and measures of the level sets, [§75](#75-the-implicit-geometry-of-every-model-modelsimplicit-meshconforming) The implicit geometry of every model, [§76](#76-quadratic-tetrahedra-isoparametric-elements-and-curved-interfaces-meshcurved-homogenizationfe) Quadratic tetrahedra: isoparametric elements and curved interfaces, [§80](#80-sharp-edges-of-the-phases-meshes-that-follow-them-modelspieces-meshconforming-meshcurved) Sharp edges of the phases: meshes that follow them, [§94](#94-exact-meshes-without-a-background-grid-meshexact-meshoctree) Exact meshes without a background grid, [§119](#119-meshes-of-the-plane-and-their-finite-elements-meshtriangles-homogenizationplane) Meshes of the plane and their finite elements | | Measures | [§8](#8-specific-surface-by-cauchycrofton) Specific surface by Cauchy–Crofton, [§21](#21-morphological-measures-analysismorphology) Morphological measures, [§39](#39-random-sets-probed-by-structuring-elements-analysisrandom_sets-analysistopology) Random sets probed by structuring elements, [§55](#55-percolation-thresholds-analysispercolation) Percolation thresholds, [§70](#70-particles-of-a-phase-in-a-volume-analysisparticles) Particles of a phase in a volume, [§92](#92-crystallographic-textures-and-orientation-maps-texture-ioebsd-modelsebsd) Crystallographic textures and orientation maps, [§104](#104-measures-of-the-implicit-geometry-morphologymeasures) Measures of the implicit geometry, [§105](#105-unions-of-balls-and-of-discs-measured-exactly-morphologyballs) Unions of balls and of discs, measured exactly, [§106](#106-the-model-of-an-image-morphologyidentification) The model of an image | @@ -16753,6 +16753,67 @@ the slope, a realization read back; the bounded functions (the same signs, the s near the surfaces, the blend within $D$); the default position, radius, centre and scale, the errors; a run from a configuration to its STL surface. +## 143. Parts ready to print: infills in shapes, with shells, skins and supports (`models.part`) + +The other models fill boxes; a part fills a shape, with the solid walls that make it a +specimen or a component (Top6Meta's sandwiches, beams and cylinders): with $s$ the signed +distance to the shape (negative inside) and $\varphi$ the function of the infill (any +model with a level set of its phase 1, generated in the domain), the function of the part +is + +$$ +\psi = \max\big(s,\ \min(\varphi,\ -s - e,\ \pi_\text{skins},\ \pi_\text{supports})\big), +$$ + +the infill, the shell of thickness $e$ along the boundary of the shape ($-e \le s \le 0$, +`shell`), the skins of a sandwich (plates of thicknesses $(t_-, t_+)$ at the faces of the +domain along `skin_axis`, $\pi = \min(x_a - (a_- + t_-),\ (a_+ - t_+) - x_a)$) and the +supports of a beam (the same along `support_axis`), all cut by the shape. Maxima and +minima of signed distances are signed distances where the closest points do not change +sides, and bounds of the distance elsewhere: the slope of $\psi$ is at most +$\max(1, L_\varphi)$. + +**The shapes.** `box` (the domain), `cylinder` and `tube` about `axis` between the faces +of the domain along it ($s$ the distance to a capped cylinder: with $\rho = r - R$, or +$\max(r - R, R_i - r)$ for the tube, and $\zeta = |x_a - c_a| - H/2$, +$s = |(\rho, \zeta)^+| + \min(\max(\rho, \zeta), 0)$, exact), `sphere` +($|x - c| - R$), all of radius $R$ inscribed in the domain by default (the inner radius of +a tube half of it), and `mesh`, a closed triangle surface from a file (STL, binary or +ASCII; OBJ, PLY, OFF... through meshio), its coincident vertices merged, scaled and +centred into the domain with `fit` (its largest extent 96 % of the domain's). + +**The distance to a surface** (`mesh.distance`) is tabulated on a grid of `resolution` +nodes along the longest edge of the domain (with a margin of two nodes): the inside is the +parity of the crossings of the columns of nodes with the triangles (§100, the columns off +the nodes by $10^{-6}$ of a cell, so that none meets an edge), the distance exact within a +band of three nodes of each triangle (or the thickness of the shell, and two more) — the +closest point of a triangle by its Voronoi regions (Ericson 2005) — and the Euclidean +distance transform of the inside beyond. Between the nodes it is interpolated +trilinearly: within $10^{-2}$ of the exact distance to a torus near its surface for nodes +an eighth of its tube radius apart, the error of the surface itself included. A surface +whose edges are not each shared by two triangles draws a warning (its inside may be +wrong). + +**Conformal TPMS.** A tube or a column is better filled by cells that wrap around its +axis than by cells cut by its wall. With `cells_around` $n$, the TPMS of §140 is evaluated +in the cylindrical coordinates $(r, \theta, s)$ about `cylinder_axis` through +`cylinder_center`: $X = 2\pi r/a_1$, $Y = n\theta$, $Z = 2\pi s/a_3$. The function is +invariant by the rotation of $2\pi/n$ about the axis; its gradient, for the first-order +distance, is $\varphi_X\,(2\pi/a_1)\,e_r + \varphi_Y\,(n/r)\,e_\theta + +\varphi_Z\,(2\pi/a_3)\,e_s$, the cells growing with the radius along $e_\theta$ (their +fraction is that of the straight cell where the cell is thin before the radius). + +Validated in `tests/test_part.py`: a sandwich of plates of 0.25 and 0.125 with the +supports of a beam of 0.5, full where they lie, the infill between; a cylinder, a tube +and a sphere with shells of 0.1, nothing beyond the shape, the shell full, their exact +volumes (and on the grid within 3 %), the level set and the points; the distance to a torus +read from a binary STL, within $10^{-2}$ near its surface, of the right sign, interpolated; +an ASCII STL, a fitted surface, the warning of an open one; a torus filled with a gyroid +and a shell, its volume within 2 %; a gyroid of 16 cells around $z$ invariant by the +rotation of one cell, the slope of its level set of median 1 within 5 %, a Schwarz P +around $x$, a tube filled with them; the errors; a column with end plates from a +configuration to its STL surface. + ## References See [specification.md](specification.md#14-references). In addition: @@ -17928,3 +17989,4 @@ See [specification.md](specification.md#14-references). In addition: * Yang, N., Quan, Z., Zhang, D., Tian, Y. (2014). Multi-morphology transition hybridization CAD design of minimal surface porous structures for use in tissue engineering. *Comput.-Aided Des.* 56, 11–21. +* Ericson, C. (2005). *Real-Time Collision Detection*. Morgan Kaufmann, San Francisco. diff --git a/docs/tutorial_geometry.md b/docs/tutorial_geometry.md index e8fc534..cd61ef6 100644 --- a/docs/tutorial_geometry.md +++ b/docs/tutorial_geometry.md @@ -63,7 +63,7 @@ print(level.data.dtype, bool(((level.data < 0) == (image.data == 2)).all())) mg.io.save_image(level, "interphase.vti") # for ParaView: its zero level is the interface ``` -Every model has such functions — the 51 models, the shapes of Microgen, their combinations, coatings, nested and +Every model has such functions — the 52 models, the shapes of Microgen, their combinations, coatings, nested and transformed structures: distances to unions of spheres and segments, differences of power distances to the germs of cells, the rings of osteons, the leaves of a dead-leaves model outside those that cover them ([theory notes](theory.md), §75). A structure of two diff --git a/docs/tutorial_interface.md b/docs/tutorial_interface.md index 3e194b0..155d234 100644 --- a/docs/tutorial_interface.md +++ b/docs/tutorial_interface.md @@ -23,7 +23,7 @@ opens its menu (where to send it, its 3D view, a new title), its cross **×** (o middle click) closes it — **Undo** beside the strip brings it back for a few seconds; its files stay in the folder of the session either way. -In *Create › Generate*, the menu lists the 51 models and the shapes of Microgen by family (the filter above it +In *Create › Generate*, the menu lists the 52 models and the shapes of Microgen by family (the filter above it finds one by a word of its name or of its summary). Choose `boolean_spheres`: its form opens filled with its template; set the radius to 1, the volume fraction to 0.2, the size of the domain to 10 and the seed to 1, then **Generate** (or `Ctrl + Enter`, which diff --git a/src/morphogen/gui/api.py b/src/morphogen/gui/api.py index 230d7ec..1a615d4 100644 --- a/src/morphogen/gui/api.py +++ b/src/morphogen/gui/api.py @@ -204,7 +204,7 @@ def examples() -> dict[str, dict]: "aggregation", "branching", "spinodal", ), "Assemblies and combinations": ( - "tile_assembly", "combination", "hybrid", "coating", "hierarchy", + "tile_assembly", "combination", "hybrid", "part", "coating", "hierarchy", ), } # fmt: skip diff --git a/src/morphogen/kernels/implicit.py b/src/morphogen/kernels/implicit.py index fa7f92d..6b39fee 100644 --- a/src/morphogen/kernels/implicit.py +++ b/src/morphogen/kernels/implicit.py @@ -9,6 +9,11 @@ level may vary along an axis of the box: a table of levels at equally spaced positions between two planes, interpolated linearly (graded TPMS); a table of one level is a constant level. + +The cells may also wrap around an axis (conformal TPMS of tubes and columns): in the +cylindrical coordinates ``(r, theta, s)`` about the axis through a centre, ``X = k_1 r``, +``Y = n theta`` (``n`` cells around) and ``Z = k_3 s``. The array ``frame`` gives +``(1, n, axis, centre)`` for cylindrical coordinates, ``(0, ...)`` for Cartesian ones. """ from __future__ import annotations @@ -151,9 +156,56 @@ def _level(levels, axis, lo, length, x, y, z): @njit(cache=True, inline="always") -def _inside(code, mode, levels, axis, lo, length, k, offset, x, y, z): +def _cylindrical(frame, x, y, z): + """The radius, angle and axial coordinate of a point about the axis of ``frame``, and + the unit vectors ``e_r`` and ``e_theta`` (Cartesian components).""" + a = int(frame[2]) + b, c = (a + 1) % 3, (a + 2) % 3 + q = (x - frame[3], y - frame[4], z - frame[5]) + u, v = q[b], q[c] + r = math.sqrt(u * u + v * v) + rr = max(r, 1e-300) + er = np.zeros(3) + et = np.zeros(3) + er[b], er[c] = u / rr, v / rr + et[b], et[c] = -v / rr, u / rr + s = x if a == 0 else (y if a == 1 else z) + return r, math.atan2(v, u), s, er, et + + +@njit(cache=True, inline="always") +def _mapped(k, offset, frame, x, y, z): + """The arguments ``X, Y, Z`` of the function at a point.""" + if frame[0] > 0.5: + r, theta, s, _, _ = _cylindrical(frame, x, y, z) + return k[0] * r, frame[1] * theta, k[2] * (s - offset[int(frame[2])]) + return k[0] * (x - offset[0]), k[1] * (y - offset[1]), k[2] * (z - offset[2]) + + +@njit(cache=True, inline="always") +def _value_gradient(code, k, offset, frame, x, y, z): + """``phi`` at a point and its gradient in Cartesian coordinates.""" + if frame[0] > 0.5: + r, theta, s, er, et = _cylindrical(frame, x, y, z) + a = int(frame[2]) + v, gX, gY, gZ = tpms_value_gradient( + code, k[0] * r, frame[1] * theta, k[2] * (s - offset[a]) + ) + cr, ct = k[0] * gX, frame[1] * gY / max(r, 1e-12) + g = cr * er + ct * et + g[a] += k[2] * gZ + return v, g[0], g[1], g[2] + v, gX, gY, gZ = tpms_value_gradient( + code, k[0] * (x - offset[0]), k[1] * (y - offset[1]), k[2] * (z - offset[2]) + ) + return v, k[0] * gX, k[1] * gY, k[2] * gZ + + +@njit(cache=True, inline="always") +def _inside(code, mode, levels, axis, lo, length, k, offset, frame, x, y, z): """Whether the point is in the solid.""" - v = tpms_value(code, k[0] * (x - offset[0]), k[1] * (y - offset[1]), k[2] * (z - offset[2])) + X, Y, Z = _mapped(k, offset, frame, x, y, z) + v = tpms_value(code, X, Y, Z) t = _level(levels, axis, lo, length, x, y, z)[0] if mode == SHEET: return abs(v) <= t @@ -163,13 +215,10 @@ def _inside(code, mode, levels, axis, lo, length, k, offset, x, y, z): @njit(cache=True, inline="always") -def _distance(code, mode, levels, axis, lo, length, k, offset, x, y, z): +def _distance(code, mode, levels, axis, lo, length, k, offset, frame, x, y, z): """First-order distance ``f / |grad f|`` of the function ``f`` of the solid (negative inside): ``phi - t``, ``|phi| - t`` or ``t - phi``.""" - v, gx, gy, gz = tpms_value_gradient( - code, k[0] * (x - offset[0]), k[1] * (y - offset[1]), k[2] * (z - offset[2]) - ) - gx, gy, gz = k[0] * gx, k[1] * gy, k[2] * gz + v, gx, gy, gz = _value_gradient(code, k, offset, frame, x, y, z) t, dt = _level(levels, axis, lo, length, x, y, z) if mode == SHEET: if v < 0.0: @@ -189,7 +238,9 @@ def _distance(code, mode, levels, axis, lo, length, k, offset, x, y, z): @njit(parallel=True, cache=True) -def tpms_count(code, mode, levels, axis, lo, length, k, offset, grid_lo, spacing, shape, ss, out): +def tpms_count( + code, mode, levels, axis, lo, length, k, offset, frame, grid_lo, spacing, shape, ss, out +): """The number of the ``ss^3`` samples of each voxel in the solid.""" inv = 1.0 / ss for i in prange(shape[0]): @@ -202,13 +253,17 @@ def tpms_count(code, mode, levels, axis, lo, length, k, offset, grid_lo, spacing y = grid_lo[1] + (j + (b + 0.5) * inv) * spacing[1] for c in range(ss): z = grid_lo[2] + (kk + (c + 0.5) * inv) * spacing[2] - if _inside(code, mode, levels, axis, lo, length, k, offset, x, y, z): + if _inside( + code, mode, levels, axis, lo, length, k, offset, frame, x, y, z + ): cnt += 1 out[i, j, kk] = cnt @njit(parallel=True, cache=True) -def tpms_level_set(code, mode, levels, axis, lo, length, k, offset, grid_lo, spacing, shape, out): +def tpms_level_set( + code, mode, levels, axis, lo, length, k, offset, frame, grid_lo, spacing, shape, out +): """First-order distance of the solid (:func:`_distance`) at voxel centres.""" for i in prange(shape[0]): x = grid_lo[0] + (i + 0.5) * spacing[0] @@ -216,24 +271,26 @@ def tpms_level_set(code, mode, levels, axis, lo, length, k, offset, grid_lo, spa y = grid_lo[1] + (j + 0.5) * spacing[1] for kk in range(shape[2]): z = grid_lo[2] + (kk + 0.5) * spacing[2] - out[i, j, kk] = _distance(code, mode, levels, axis, lo, length, k, offset, x, y, z) + out[i, j, kk] = _distance( + code, mode, levels, axis, lo, length, k, offset, frame, x, y, z + ) @njit(parallel=True, cache=True) -def tpms_level_points(code, mode, levels, axis, lo, length, k, offset, pts, out): +def tpms_level_points(code, mode, levels, axis, lo, length, k, offset, frame, pts, out): """The first-order distance of :func:`tpms_level_set` at points.""" for p in prange(pts.shape[0]): out[p] = _distance( - code, mode, levels, axis, lo, length, k, offset, pts[p, 0], pts[p, 1], pts[p, 2] + code, mode, levels, axis, lo, length, k, offset, frame, pts[p, 0], pts[p, 1], pts[p, 2] ) @njit(parallel=True, cache=True) -def tpms_points(code, mode, levels, axis, lo, length, k, offset, pts, out): +def tpms_points(code, mode, levels, axis, lo, length, k, offset, frame, pts, out): """Whether the points are in the solid.""" for p in prange(pts.shape[0]): out[p] = _inside( - code, mode, levels, axis, lo, length, k, offset, pts[p, 0], pts[p, 1], pts[p, 2] + code, mode, levels, axis, lo, length, k, offset, frame, pts[p, 0], pts[p, 1], pts[p, 2] ) diff --git a/src/morphogen/mesh/distance.py b/src/morphogen/mesh/distance.py new file mode 100644 index 0000000..9e71a41 --- /dev/null +++ b/src/morphogen/mesh/distance.py @@ -0,0 +1,202 @@ +"""Signed distances to closed triangle surfaces on grids, and the surfaces of files. + +The inside of a surface is the parity of the crossings of the columns of the grid +(:func:`morphogen.kernels.meshes.surface_parity`); the distance is exact (the closest +point of each triangle, Ericson 2005) within a band of nodes about the surface, and the +Euclidean distance transform of the inside beyond it. Between the nodes, the distance is +interpolated trilinearly: a signed distance within a fraction of a cell of the exact one +near smooth surfaces. +""" + +from __future__ import annotations + +import math +import warnings +from pathlib import Path + +import numpy as np +from numba import njit +from scipy import ndimage + +from morphogen.domain import Grid +from morphogen.kernels.meshes import surface_parity +from morphogen.mesh.surface import SurfaceMesh + +#: Nodes about each triangle whose distance is exact. +BAND = 3 + + +@njit(cache=True, inline="always") +def _closest(px, py, pz, a, b, c): + """The squared distance from the point ``p`` to the triangle ``abc`` (Ericson, + *Real-Time Collision Detection*, 5.1.5), in scalars.""" + abx, aby, abz = b[0] - a[0], b[1] - a[1], b[2] - a[2] + acx, acy, acz = c[0] - a[0], c[1] - a[1], c[2] - a[2] + apx, apy, apz = px - a[0], py - a[1], pz - a[2] + d1 = abx * apx + aby * apy + abz * apz + d2 = acx * apx + acy * apy + acz * apz + if d1 <= 0.0 and d2 <= 0.0: + qx, qy, qz = a[0], a[1], a[2] + else: + bpx, bpy, bpz = px - b[0], py - b[1], pz - b[2] + d3 = abx * bpx + aby * bpy + abz * bpz + d4 = acx * bpx + acy * bpy + acz * bpz + vc = d1 * d4 - d3 * d2 + cpx, cpy, cpz = px - c[0], py - c[1], pz - c[2] + d5 = abx * cpx + aby * cpy + abz * cpz + d6 = acx * cpx + acy * cpy + acz * cpz + vb = d5 * d2 - d1 * d6 + va = d3 * d6 - d5 * d4 + if d3 >= 0.0 and d4 <= d3: + qx, qy, qz = b[0], b[1], b[2] + elif vc <= 0.0 and d1 >= 0.0 and d3 <= 0.0: + t = d1 / (d1 - d3) + qx, qy, qz = a[0] + t * abx, a[1] + t * aby, a[2] + t * abz + elif d6 >= 0.0 and d5 <= d6: + qx, qy, qz = c[0], c[1], c[2] + elif vb <= 0.0 and d2 >= 0.0 and d6 <= 0.0: + t = d2 / (d2 - d6) + qx, qy, qz = a[0] + t * acx, a[1] + t * acy, a[2] + t * acz + elif va <= 0.0 and (d4 - d3) >= 0.0 and (d5 - d6) >= 0.0: + t = (d4 - d3) / ((d4 - d3) + (d5 - d6)) + qx, qy, qz = ( + b[0] + t * (c[0] - b[0]), + b[1] + t * (c[1] - b[1]), + b[2] + t * (c[2] - b[2]), + ) + else: + denom = 1.0 / (va + vb + vc) + v, w = vb * denom, vc * denom + qx = a[0] + abx * v + acx * w + qy = a[1] + aby * v + acy * w + qz = a[2] + abz * v + acz * w + dx, dy, dz = px - qx, py - qy, pz - qz + return dx * dx + dy * dy + dz * dz + + +@njit(cache=True) +def _band_distances(vertices, faces, origin, spacing, band, out): + """The squared distances of the nodes (voxel centres) within ``band`` nodes of each + triangle to the nearest triangle (``out`` starts at infinity).""" + lo = np.empty(3, dtype=np.int64) + hi = np.empty(3, dtype=np.int64) + for f in range(faces.shape[0]): + a = vertices[faces[f, 0]] + b = vertices[faces[f, 1]] + c = vertices[faces[f, 2]] + for d in range(3): + m0 = min(a[d], b[d], c[d]) + m1 = max(a[d], b[d], c[d]) + lo[d] = max(0, math.floor((m0 - origin[d]) / spacing[d] - 0.5) - band) + hi[d] = min(out.shape[d] - 1, math.ceil((m1 - origin[d]) / spacing[d] - 0.5) + band) + for i in range(lo[0], hi[0] + 1): + px = origin[0] + (i + 0.5) * spacing[0] + for j in range(lo[1], hi[1] + 1): + py = origin[1] + (j + 0.5) * spacing[1] + for k in range(lo[2], hi[2] + 1): + pz = origin[2] + (k + 0.5) * spacing[2] + d2 = _closest(px, py, pz, a, b, c) + if d2 < out[i, j, k]: + out[i, j, k] = d2 + + +def merged(surface: SurfaceMesh, tolerance: float = 1e-9) -> SurfaceMesh: + """The surface with its coincident vertices merged (within ``tolerance`` of the size + of its box) and its degenerate faces removed.""" + v = np.asarray(surface.vertices, dtype=float) + size = float(np.ptp(v, axis=0).max()) if len(v) else 1.0 + keys = np.round(v / (tolerance * max(size, 1e-300))).astype(np.int64) + _, first, inverse = np.unique(keys, axis=0, return_index=True, return_inverse=True) + faces = inverse.reshape(-1)[np.asarray(surface.faces, dtype=np.int64)] + a, b, c = faces[:, 0], faces[:, 1], faces[:, 2] + good = (a != b) & (b != c) & (a != c) + return SurfaceMesh(v[first], faces[good]) + + +def is_closed(surface: SurfaceMesh) -> bool: + """Whether every edge of the (merged) surface is shared by exactly two faces.""" + f = np.asarray(surface.faces, dtype=np.int64) + edges = np.sort(np.concatenate([f[:, [0, 1]], f[:, [1, 2]], f[:, [2, 0]]]), axis=1) + _, counts = np.unique(edges, axis=0, return_counts=True) + return bool(len(counts)) and bool(np.all(counts == 2)) + + +def read_surface(path) -> SurfaceMesh: + """A triangle surface from a file: STL (binary or ASCII) by morphoGen, other formats + (OBJ, PLY, OFF...) by meshio; merged (:func:`merged`).""" + path = Path(path) + if path.suffix.lower() == ".stl": + raw = path.read_bytes() + n = int(np.frombuffer(raw, dtype="= 84 else -1 + if len(raw) == 84 + 50 * n: + from morphogen.io.meshes import read_stl + + return merged(read_stl(path)) + text = raw.decode("ascii", errors="replace").split() + values = [ + [float(text[i + 1]), float(text[i + 2]), float(text[i + 3])] + for i, w in enumerate(text[:-3]) + if w == "vertex" + ] + verts = np.asarray(values, dtype=float).reshape(-1, 3) + if len(verts) == 0 or len(verts) % 3: + raise ValueError(f"{path}: not an STL surface") + return merged(SurfaceMesh(verts, np.arange(len(verts)).reshape(-1, 3))) + try: + import meshio + except ImportError: # pragma: no cover - depends on the environment + raise ImportError( + f"{path}: reading this format needs the optional 'meshio' package: " + "pip install 'morphogen[io]'" + ) from None + m = meshio.read(str(path)) + tri = [c.data for c in m.cells if c.type == "triangle"] + if not tri: + raise ValueError(f"{path}: no triangles") + return merged(SurfaceMesh(np.asarray(m.points[:, :3], dtype=float), np.concatenate(tri))) + + +def signed_distance_grid(surface: SurfaceMesh, grid: Grid, band: int = BAND) -> np.ndarray: + """The signed distance (negative inside) to a closed surface at the voxel centres of + a grid: exact within ``band`` nodes of the surface, the distance transform of the + inside beyond (see the module).""" + if not is_closed(surface): + warnings.warn( + "the surface is not closed: its inside, the parity of crossings, may be wrong", + stacklevel=2, + ) + origin = np.asarray(grid.origin, dtype=float) + spacing = np.asarray(grid.spacing, dtype=float) + vertices = np.ascontiguousarray(surface.vertices, dtype=float) + faces = np.ascontiguousarray(surface.faces, dtype=np.int64) + index = (vertices - origin) / spacing - 0.5 # the centre of voxel i at i + inside = surface_parity(index, faces, tuple(int(n) for n in grid.shape)).astype(bool) + near = np.full(grid.shape, np.inf) + _band_distances(vertices, faces, origin, spacing, int(band), near) + near = np.sqrt(near) + half = 0.5 * float(spacing.min()) + outer = ndimage.distance_transform_edt(~inside, sampling=spacing) - half + inner = ndimage.distance_transform_edt(inside, sampling=spacing) - half + far = np.where(inside, inner, outer) + d = np.where(np.isfinite(near), near, np.maximum(far, band * float(spacing.min()))) + return np.where(inside, -d, d) + + +def interpolate(values: np.ndarray, grid: Grid, points) -> np.ndarray: + """Trilinear interpolation of values at the voxel centres of a grid (the nearest + values beyond its centres).""" + pts = np.asarray(points, dtype=float).reshape(-1, 3) + index = (pts - np.asarray(grid.origin)) / np.asarray(grid.spacing) - 0.5 + return ndimage.map_coordinates(values, index.T, order=1, mode="nearest") + + +def fitted(surface: SurfaceMesh, lower, upper, margin: float = 0.02) -> SurfaceMesh: + """The surface scaled (uniformly) and moved to the centre of the box ``[lower, + upper]``, its largest extent ``1 - 2 margin`` of the box along that axis.""" + v = np.asarray(surface.vertices, dtype=float) + lo, hi = v.min(axis=0), v.max(axis=0) + lower, upper = np.asarray(lower, dtype=float), np.asarray(upper, dtype=float) + size = np.maximum(hi - lo, 1e-300) + scale = float(np.min((1.0 - 2.0 * margin) * (upper - lower) / size)) + centre = 0.5 * (lo + hi) + return SurfaceMesh((v - centre) * scale + 0.5 * (lower + upper), surface.faces) diff --git a/src/morphogen/models/__init__.py b/src/morphogen/models/__init__.py index 14410f7..ee926ab 100644 --- a/src/morphogen/models/__init__.py +++ b/src/morphogen/models/__init__.py @@ -28,6 +28,8 @@ directions or cones (Kumar et al. 2020), graded ``hybrid`` Two models blended across a plane, a cylinder or a sphere (multi-morphology architectures) +``part`` A part ready to print: an infill in a box, cylinder, tube, + sphere or closed surface, with shell, skins and supports ``strut_lattice`` Cubic, BCC, FCC and octet strut lattices ``plate_lattice`` Plate lattices: closed cells of plates on the {100}, {110} and {111} planes (cubic, bcc, fcc) and their isotropic mixtures @@ -146,6 +148,7 @@ ) from morphogen.models.nested_grains import NestedGrains, NestedGrainStructure from morphogen.models.osteons import Osteons, OsteonStructure +from morphogen.models.part import Part, PartStructure from morphogen.models.plate_lattice import PlateLattice, PlateLatticeStructure from morphogen.models.reconstruction import Reconstruction from morphogen.models.scale_rich import ScaleRichNetwork, ScaleRichStructure @@ -217,6 +220,8 @@ "OpenFoam", "OsteonStructure", "Osteons", + "Part", + "PartStructure", "PenetrableSpheres", "PlateLattice", "PlateLatticeStructure", diff --git a/src/morphogen/models/part.py b/src/morphogen/models/part.py new file mode 100644 index 0000000..c30dd13 --- /dev/null +++ b/src/morphogen/models/part.py @@ -0,0 +1,438 @@ +"""Parts ready to print: an architecture filling a shape, with walls, skins and supports. + +A part is the solid + + (infill U shell U skins U supports) inside the shape, + +the shape a box (the domain), a cylinder or a tube about an axis (between the faces of the +domain along it), a sphere, or any closed triangle surface read from a file (STL, OBJ, +PLY...; the part to fill), and + +* the infill any model with a level set of its phase 1 (a TPMS, a strut or plate + lattice, a spinodoid, a hybrid...), generated in the domain; +* the shell a solid wall of thickness ``shell`` along the boundary of the shape, inside it; +* the skins the face sheets of a sandwich panel: solid plates of thicknesses + ``(lower, upper)`` at the faces of the domain along ``skin_axis``; +* the supports the solid blocks at the ends of a beam: thicknesses ``(lower, upper)`` at + the faces of the domain along ``support_axis``. + +With ``s`` the signed distance to the shape (negative inside) and ``phi`` the function of +the infill, the function of the part is + + max(s, min(phi, -s - shell, skins, supports)), + +an intersection and unions of signed distances, exact where theirs are: those of the box, +the cylinder, the tube and the sphere are exact; that of a surface is exact within a band +of nodes about it and interpolated trilinearly between the nodes of a grid +(:mod:`morphogen.mesh.distance`). +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from typing import ClassVar + +import numpy as np + +from morphogen._utils import check_positive +from morphogen.domain import Domain, Grid +from morphogen.image import VoxelImage +from morphogen.mesh.surface import SurfaceMesh +from morphogen.models.base import Microstructure, Model, param, register, register_kind +from morphogen.seeding import SeedLike, make_rng, seed_from_description + +SHAPES = ("box", "cylinder", "tube", "sphere", "mesh") +#: Nodes along the longest edge of the grid of the distance to a surface. +MESH_RESOLUTION = 128 + + +def _box_distance(p, lower, upper) -> np.ndarray: + """The signed distance to an axis-aligned box.""" + centre, half = 0.5 * (lower + upper), 0.5 * (upper - lower) + q = np.abs(p - centre) - half + outside = np.linalg.norm(np.maximum(q, 0.0), axis=1) + return outside + np.minimum(q.max(axis=1), 0.0) + + +def _capped(radial, axial) -> np.ndarray: + """The signed distance of the intersection of a radial and an axial condition (a + capped cylinder): exact where both are distances in orthogonal directions.""" + outside = np.hypot(np.maximum(radial, 0.0), np.maximum(axial, 0.0)) + return outside + np.minimum(np.maximum(radial, axial), 0.0) + + +@register_kind +class PartStructure(Microstructure): + """An infill in a shape, with its shell, skins and supports (see the module).""" + + kind = "part" + + def __init__( + self, + domain, + infill, + shape, + *, + axis=2, + radius=0.0, + inner_radius=0.0, + center=None, + surface=None, + resolution=MESH_RESOLUTION, + shell=0.0, + skins=None, + skin_axis=2, + supports=None, + support_axis=0, + **kwargs, + ): + super().__init__(domain, **kwargs) + if shape not in SHAPES: + raise ValueError(f"shape: one of {', '.join(SHAPES)}") + self.infill = infill + self.shape = shape + self.axis = int(axis) + self.radius = float(radius) + self.inner_radius = float(inner_radius) + self.center = domain.center if center is None else np.asarray(center, dtype=float) + self.surface = surface + self.resolution = int(resolution) + self.shell = float(shell) + self.skins = None if skins is None else tuple(float(t) for t in skins) + self.skin_axis = int(skin_axis) + self.supports = None if supports is None else tuple(float(t) for t in supports) + self.support_axis = int(support_axis) + self._sdf = None + + # -- the shape ----------------------------------------------------------------------------- + + def _mesh_grid(self) -> tuple[Grid, np.ndarray]: + """The grid of the distance to the surface and its values (computed once).""" + if self._sdf is None: + from morphogen.mesh.distance import BAND, signed_distance_grid + + lengths = self.domain.lengths + h = float(lengths.max()) / self.resolution + margin = 2.0 * h + lower = self.domain.lower - margin + size = lengths + 2.0 * margin + n = tuple(math.ceil(s / h) for s in size) + grid = Grid(Domain(size=tuple(n_ * h for n_ in n), origin=tuple(lower), + periodic=False), n) # fmt: skip + band = max(BAND, math.ceil(self.shell / h) + 2) + self._sdf = (grid, signed_distance_grid(self.surface, grid, band)) + return self._sdf + + def shape_distance(self, points) -> np.ndarray: + """``s``: the signed distance of the points to the shape (negative inside).""" + p = np.asarray(points, dtype=float).reshape(-1, 3) + lower, upper = self.domain.lower, self.domain.upper + if self.shape == "box": + return _box_distance(p, lower, upper) + if self.shape == "mesh": + from morphogen.mesh.distance import interpolate + + grid, values = self._mesh_grid() + return interpolate(values, grid, p) + a = self.axis + d = p - self.center + if self.shape == "sphere": + return np.linalg.norm(d, axis=1) - self.radius + d[:, a] = 0.0 + r = np.linalg.norm(d, axis=1) + radial = r - self.radius + if self.shape == "tube": + radial = np.maximum(radial, self.inner_radius - r) + axial = np.abs(p[:, a] - 0.5 * (lower[a] + upper[a])) - 0.5 * (upper[a] - lower[a]) + return _capped(radial, axial) + + def _plates(self, p, thicknesses, axis) -> np.ndarray | None: + """The signed distance to the plates at the faces of the domain along an axis.""" + if thicknesses is None: + return None + lo, hi = self.domain.lower[axis], self.domain.upper[axis] + out = np.full(len(p), np.inf) + if thicknesses[0] > 0.0: + out = np.minimum(out, p[:, axis] - (lo + thicknesses[0])) + if thicknesses[1] > 0.0: + out = np.minimum(out, (hi - thicknesses[1]) - p[:, axis]) + return out + + def _combine(self, p, s, phi) -> np.ndarray: + solid = phi + if self.shell > 0.0: + solid = np.minimum(solid, -s - self.shell) + for plates in ( + self._plates(p, self.skins, self.skin_axis), + self._plates(p, self.supports, self.support_axis), + ): + if plates is not None: + solid = np.minimum(solid, plates) + return np.maximum(s, solid) + + # -- the functions --------------------------------------------------------------------------- + + def level_set_at(self, points, reach: float = np.inf) -> np.ndarray: + p = np.asarray(points, dtype=float).reshape(-1, 3) + return self._combine(p, self.shape_distance(p), self.infill.level_set_at(p, reach)) + + def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage: + """The function of the part at the voxel centres.""" + grid = self.grid(shape, voxel_size=voxel_size, grid=grid) + p = grid.center_points() + try: + phi = self.infill.level_set_at(p, np.inf) + except NotImplementedError: + phi = self.infill.level_set(grid=grid).data.astype(float).ravel() + data = self._combine(p, self.shape_distance(p), phi).reshape(grid.shape) + return VoxelImage.from_grid( + data.astype(np.float32), grid, name="level_set", metadata=self.image_metadata() + ) + + def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1): + grid = self.grid(shape, voxel_size=voxel_size, grid=grid) + ss = int(supersampling) + if not 1 <= ss <= 6: + raise ValueError("supersampling must be an integer between 1 and 6") + fine = grid if ss == 1 else Grid(grid.domain, tuple(n * ss for n in grid.shape)) + inside = self.level_set(grid=fine).data <= 0.0 + if ss == 1: + data = inside.astype(np.uint8) + return VoxelImage.from_grid(data, grid, name="phase", metadata=self.image_metadata()) + nx, ny, nz = grid.shape + data = inside.reshape(nx, ss, ny, ss, nz, ss).mean(axis=(1, 3, 5), dtype=np.float32) + return VoxelImage.from_grid(data, grid, name="fraction", metadata=self.image_metadata()) + + def contains(self, points) -> np.ndarray: + return self.level_set_at(points) <= 0.0 + + @property + def lipschitz(self) -> float: + """The slopes of the distances (1) and of the function of the infill.""" + return max(1.0, float(getattr(self.infill, "lipschitz", 1.0) or 1.0)) + + def shape_volume(self) -> float: + """The volume of the shape within the domain: exact for the box, the cylinder, + the tube and the sphere inside the domain; counted on the grid of a surface.""" + lengths = self.domain.lengths + if self.shape == "box": + return self.domain.volume + if self.shape == "mesh": + grid, values = self._mesh_grid() + inside = self.domain.contains(grid.center_points()) & (values.ravel() <= 0.0) + return float(inside.sum() * np.prod(grid.spacing)) + if self.shape == "sphere": + return 4.0 / 3.0 * math.pi * self.radius**3 + area = math.pi * (self.radius**2 - (self.inner_radius**2 if self.shape == "tube" else 0)) + return area * float(lengths[self.axis]) + + # -- description --------------------------------------------------------------------------- + + def summary(self) -> dict: + out = {"shape": self.shape} + out.update({f"infill_{k}": v for k, v in self.infill.summary().items()}) + return out + + def _geometry(self) -> dict: + out = { + "infill": self.infill.to_dict(), + "shape": self.shape, + "axis": self.axis, + "radius": self.radius, + "inner_radius": self.inner_radius, + "center": np.asarray(self.center).tolist(), + "resolution": self.resolution, + "shell": self.shell, + "skins": None if self.skins is None else list(self.skins), + "skin_axis": self.skin_axis, + "supports": None if self.supports is None else list(self.supports), + "support_axis": self.support_axis, + } + if self.surface is not None: + out["surface"] = { + "vertices": np.asarray(self.surface.vertices).tolist(), + "faces": np.asarray(self.surface.faces).tolist(), + } + return out + + @classmethod + def _from_geometry(cls, domain, geometry, **kwargs): + surface = geometry.get("surface") + if surface is not None: + surface = SurfaceMesh( + np.asarray(surface["vertices"], dtype=float), + np.asarray(surface["faces"], dtype=np.int64), + ) + return cls( + domain, + Microstructure.from_dict(geometry["infill"]), + geometry["shape"], + axis=geometry["axis"], + radius=geometry["radius"], + inner_radius=geometry["inner_radius"], + center=geometry["center"], + surface=surface, + resolution=geometry["resolution"], + shell=geometry["shell"], + skins=geometry["skins"], + skin_axis=geometry["skin_axis"], + supports=geometry["supports"], + support_axis=geometry["support_axis"], + **kwargs, + ) + + +@register +@dataclass(frozen=True) +class Part(Model): + """A part ready to print: an infill model in a shape (a box, a cylinder, a tube, a + sphere or a closed surface from a file), with a shell along its boundary, the skins of + a sandwich and the supports of a beam (see the module).""" + + name = "part" + phases: ClassVar[dict[int, str]] = {0: "void", 1: "solid"} + supports_periodic: ClassVar[bool] = False + path_parameters: ClassVar[tuple[str, ...]] = ("mesh",) + + infill: Model | None = param( + None, doc="The model filling the shape (a mapping with a 'type' key)", kind="model" + ) + shape: str = param("box", doc="box, cylinder, tube, sphere or mesh", kind="str") + axis: int = param(2, doc="Axis of the cylinder or the tube: 0, 1 or 2", kind="int") + radius: float | None = param( + None, + doc="Radius of the cylinder, tube or sphere (default: inscribed in the domain)", + unit="length", + ) + inner_radius: float | None = param( + None, doc="Inner radius of the tube (default: half the radius)", unit="length" + ) + center: tuple[float, ...] | None = param( + None, + doc="Centre of the cylinder, tube or sphere (default: the centre of the domain)", + kind="floats", + unit="length", + ) + mesh: str | None = param( + None, doc="The closed surface of the part (STL, or OBJ, PLY... by meshio)", kind="str" + ) + fit: bool = param( + False, + doc="Scale and centre the surface into the domain (its largest extent 96 % of the " + "domain's along that axis)", + kind="bool", + ) + resolution: int = param( + MESH_RESOLUTION, + doc="Nodes along the longest edge of the grid of the distance to the surface", + kind="int", + ) + shell: float = param( + 0.0, doc="Thickness of the solid wall along the boundary of the shape", unit="length" + ) + skins: tuple[float, ...] | None = param( + None, + doc="Thicknesses of the solid plates at the lower and upper faces of the domain along " + "skin_axis (the face sheets of a sandwich)", + kind="floats", + unit="length", + ) + skin_axis: int = param(2, doc="Axis across the skins: 0, 1 or 2", kind="int") + supports: tuple[float, ...] | None = param( + None, + doc="Thicknesses of the solid blocks at the lower and upper faces of the domain along " + "support_axis (the supports of a beam)", + kind="floats", + unit="length", + ) + support_axis: int = param(0, doc="Axis of the supports: 0, 1 or 2", kind="int") + + def _validate(self) -> None: + if self.infill is None: + raise ValueError("infill: the model filling the part") + if not self.infill.has_level_set: + raise ValueError( + f"infill: {self.infill.name} has no level set of its phase 1 (several " + "phases); fill the part with a two-phase model" + ) + if self.shape not in SHAPES: + raise ValueError(f"shape: one of {', '.join(SHAPES)}") + for name in ("axis", "skin_axis", "support_axis"): + if getattr(self, name) not in (0, 1, 2): + raise ValueError(f"{name}: 0, 1 or 2") + if self.radius is not None: + check_positive(self.radius, "radius") + if self.inner_radius is not None: + check_positive(self.inner_radius, "inner_radius") + if self.radius is not None and self.inner_radius >= self.radius: + raise ValueError("inner_radius: smaller than the radius") + if self.center is not None and len(self.center) != 3: + raise ValueError("center: three coordinates") + if self.shape == "mesh" and not self.mesh: + raise ValueError("mesh: the file of the surface of the part") + if self.resolution < 8: + raise ValueError("resolution: at least 8 nodes") + check_positive(self.shell, "shell", allow_zero=True) + for name in ("skins", "supports"): + value = getattr(self, name) + if value is not None: + if len(value) != 2: + raise ValueError(f"{name}: the thicknesses at the lower and upper faces") + for t in value: + check_positive(t, name, allow_zero=True) + + def _dimensions(self, domain: Domain) -> tuple[float, float]: + """The radius and inner radius of the shape in a domain (their defaults).""" + if self.radius is not None: + radius = float(self.radius) + elif self.shape == "sphere": + radius = 0.5 * float(domain.lengths.min()) + else: + radius = 0.5 * float(np.delete(domain.lengths, self.axis).min()) + inner = 0.5 * radius if self.inner_radius is None else float(self.inner_radius) + if self.shape == "tube" and inner >= radius: + raise ValueError("inner_radius: smaller than the radius") + return radius, inner + + def surface(self, domain: Domain | None = None) -> SurfaceMesh | None: + """The surface of the part read from its file (fitted into the domain).""" + if self.shape != "mesh": + return None + from morphogen.mesh.distance import fitted, read_surface + + surface = read_surface(self.mesh) + if self.fit: + if domain is None: + raise ValueError("fit: the surface is fitted into a domain") + surface = fitted(surface, domain.lower, domain.upper) + return surface + + def generate(self, domain: Domain, seed: SeedLike = None) -> PartStructure: + self._check_domain(domain) + rng, seed_info = make_rng(seed) + child = seed_from_description(seed_info).spawn(1)[0] if seed_info else rng.spawn(1)[0] + infill = self.infill.generate(domain, child) + radius, inner = self._dimensions(domain) + return PartStructure( + domain, + infill, + self.shape, + axis=self.axis, + radius=radius, + inner_radius=inner, + center=None if self.center is None else self.center, + surface=self.surface(domain), + resolution=self.resolution, + shell=self.shell, + skins=self.skins, + skin_axis=self.skin_axis, + supports=self.supports, + support_axis=self.support_axis, + model=self, + seed=seed_info, + ) + + def theory(self, domain: Domain | None = None) -> dict[str, float]: + """None in closed form (the infill cut by the shape, with walls).""" + return {} diff --git a/src/morphogen/models/tpms.py b/src/morphogen/models/tpms.py index d6323ac..1efbc37 100644 --- a/src/morphogen/models/tpms.py +++ b/src/morphogen/models/tpms.py @@ -78,7 +78,7 @@ class TPMSStructure(Microstructure): def __init__( self, domain, surface, variant, level, cell_size, *, levels=None, gradient_axis=0, - **kwargs, + cells_around=None, cylinder_axis=2, cylinder_center=None, **kwargs, ): # fmt: skip super().__init__(domain, **kwargs) self.surface = surface @@ -91,6 +91,15 @@ def __init__( self._mode = implicit.MODES[variant] self._k = 2.0 * np.pi / self.cell_size self._table = np.array([self.level]) if self.levels is None else self.levels + #: Cylindrical coordinates: the number of cells around the axis (None: Cartesian) + self.cells_around = None if cells_around is None else int(cells_around) + self.cylinder_axis = int(cylinder_axis) + self.cylinder_center = ( + domain.center if cylinder_center is None else np.asarray(cylinder_center, float) + ) + self._frame = np.zeros(6) + if self.cells_around is not None: + self._frame[:] = [1.0, self.cells_around, self.cylinder_axis, *self.cylinder_center] def _args(self): axis = self.gradient_axis @@ -103,6 +112,7 @@ def _args(self): float(self.domain.lengths[axis]), self._k, self.domain.lower, + self._frame, ) def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1): @@ -150,6 +160,8 @@ def summary(self) -> dict: out = {"surface": self.surface, "cells": "x".join(f"{c:g}" for c in cells)} if self.levels is not None: out["graded"] = "xyz"[self.gradient_axis] + if self.cells_around is not None: + out["around"] = self.cells_around return out def _geometry(self) -> dict: @@ -162,6 +174,10 @@ def _geometry(self) -> dict: if self.levels is not None: out["levels"] = self.levels.tolist() out["gradient_axis"] = self.gradient_axis + if self.cells_around is not None: + out["cells_around"] = self.cells_around + out["cylinder_axis"] = self.cylinder_axis + out["cylinder_center"] = np.asarray(self.cylinder_center).tolist() return out @classmethod @@ -174,6 +190,9 @@ def _from_geometry(cls, domain, geometry, **kwargs): geometry["cell_size"], levels=geometry.get("levels"), gradient_axis=geometry.get("gradient_axis", 0), + cells_around=geometry.get("cells_around"), + cylinder_axis=geometry.get("cylinder_axis", 2), + cylinder_center=geometry.get("cylinder_center"), **kwargs, ) @@ -194,7 +213,9 @@ class TPMS(Model): ``fraction_gradient`` lists the volume fractions at equally spaced positions from the lower to the upper face of the domain along ``gradient_axis`` (two values: a linear gradient), interpolated linearly, each position at the level of its fraction (in a - non-periodic domain). + non-periodic domain). With ``cells_around``, the cells wrap around ``cylinder_axis`` + (conformal TPMS of tubes and columns): ``X = 2 pi r / a_1``, ``Y = n theta``, + ``Z = 2 pi s / a_3`` in the cylindrical coordinates about the axis. """ name = "tpms" @@ -228,6 +249,20 @@ class TPMS(Model): gradient_axis: int = param( 0, doc="Axis of the gradient of the volume fraction: 0, 1 or 2", kind="int" ) + cells_around: int | None = param( + None, + doc="Conformal TPMS: the number of cells around cylinder_axis (cylindrical " + "coordinates r, theta, s: cell_size along r and s; non-periodic domains)", + kind="int", + ) + cylinder_axis: int = param(2, doc="Axis of the cylindrical coordinates: 0, 1 or 2", kind="int") + cylinder_center: tuple[float, ...] | None = param( + None, + doc="A point of the axis of the cylindrical coordinates (default: the centre of the " + "domain)", + kind="floats", + unit="length", + ) anisotropy: Anisotropy | None = param(None, doc=ANISOTROPY, kind="anisotropy", kw_only=True) def _validate(self) -> None: @@ -255,6 +290,12 @@ def _validate(self) -> None: raise ValueError("gradient_axis: 0, 1 or 2") if self.variant == "sheet" and self.level is not None and self.level < 0: raise ValueError("level: must be non-negative for sheet TPMS") + if self.cells_around is not None and self.cells_around < 1: + raise ValueError("cells_around: at least one cell around the axis") + if self.cylinder_axis not in (0, 1, 2): + raise ValueError("cylinder_axis: 0, 1 or 2") + if self.cylinder_center is not None and len(self.cylinder_center) != 3: + raise ValueError("cylinder_center: three coordinates") @property def iso_level(self) -> float: @@ -294,6 +335,8 @@ def generate(self, domain: Domain, seed: SeedLike = None) -> TPMSStructure: levels = self.graded_levels() if levels is not None and domain.periodic: raise ValueError("tpms: a graded TPMS needs a non-periodic domain") + if self.cells_around is not None and domain.periodic: + raise ValueError("tpms: a conformal (cylindrical) TPMS needs a non-periodic domain") if domain.periodic: ratio = domain.lengths / cell if np.any(np.abs(ratio - np.rint(ratio)) > 1e-6 * np.maximum(ratio, 1.0)): @@ -309,6 +352,9 @@ def generate(self, domain: Domain, seed: SeedLike = None) -> TPMSStructure: tuple(cell), levels=levels, gradient_axis=self.gradient_axis, + cells_around=self.cells_around, + cylinder_axis=self.cylinder_axis, + cylinder_center=self.cylinder_center, model=self, seed=seed_info, ) diff --git a/src/morphogen/viz/sections.py b/src/morphogen/viz/sections.py index 18085a1..4a78a74 100644 --- a/src/morphogen/viz/sections.py +++ b/src/morphogen/viz/sections.py @@ -89,6 +89,7 @@ from morphogen.models.nested import ClusteredSpheres, CoatedStructure, FractalStructure from morphogen.models.nested_grains import NestedGrainStructure from morphogen.models.osteons import OsteonStructure +from morphogen.models.part import PartStructure from morphogen.models.planar import plane_axes from morphogen.models.plate_lattice import PlateLatticeStructure from morphogen.models.scale_rich import ScaleRichStructure @@ -136,6 +137,7 @@ TPMSStructure, SpinodoidStructure, HybridStructure, + PartStructure, Tessellation, GaussianField, LatticeField, diff --git a/tests/public_api.txt b/tests/public_api.txt index e9a7f8b..ba3792f 100644 --- a/tests/public_api.txt +++ b/tests/public_api.txt @@ -3395,6 +3395,13 @@ morphogen.mesh.curved.MAX_SAMPLES morphogen.mesh.curved.SAMPLES_PER_ELEMENT morphogen.mesh.curved.curved_mesh(mesh, micro, *, sampling=None, corners=True, max_move=0.3, min_jacobian=0.3) morphogen.mesh.curved.curved_triangles(mesh, micro, *, sampling=None, corners=True, max_move=0.3, min_jacobian=0.3) +morphogen.mesh.distance.BAND +morphogen.mesh.distance.fitted(surface, lower, upper, margin=0.02) +morphogen.mesh.distance.interpolate(values, grid, points) +morphogen.mesh.distance.is_closed(surface) +morphogen.mesh.distance.merged(surface, tolerance=1e-09) +morphogen.mesh.distance.read_surface(path) +morphogen.mesh.distance.signed_distance_grid(surface, grid, band=3) morphogen.mesh.exact.TOLERANCE morphogen.mesh.exact.adaptive_mesh(micro, *, size, hausdorff=None, min_size=None, gradation=1.8, phases='all', order=1, periodic=None, lipschitz=None, project=True, remove_islands=None, ridges=False, sharp_edges=None, retries=2, executable=None, workdir=None, timeout=None) morphogen.mesh.exact.exact_mesh(micro, *, size, min_size=None, hausdorff=None, gradation=None, phases='all', order=1, periodic=None, grains=None, sharp_edges=None, executable=None, workdir=None, timeout=None, **options) @@ -3657,6 +3664,8 @@ morphogen.models: NucleationGrowthModel morphogen.models: OpenFoam morphogen.models: OsteonStructure morphogen.models: Osteons +morphogen.models: Part +morphogen.models: PartStructure morphogen.models: PenetrableSpheres morphogen.models: PlateLattice morphogen.models: PlateLatticeStructure @@ -4334,6 +4343,21 @@ morphogen.models.osteons.Osteons.expected_count(self, domain) morphogen.models.osteons.Osteons.generate(self, domain, seed=None) morphogen.models.osteons.Osteons.intensity morphogen.models.osteons.Osteons.theory(self, domain=None) +morphogen.models.part.MESH_RESOLUTION +morphogen.models.part.Part(infill=None, shape='box', axis=2, radius=None, inner_radius=None, center=None, mesh=None, fit=False, resolution=128, shell=0.0, skins=None, skin_axis=2, supports=None, support_axis=0) +morphogen.models.part.Part.generate(self, domain, seed=None) +morphogen.models.part.Part.surface(self, domain=None) +morphogen.models.part.Part.theory(self, domain=None) +morphogen.models.part.PartStructure(domain, infill, shape, *, axis=2, radius=0.0, inner_radius=0.0, center=None, surface=None, resolution=128, shell=0.0, skins=None, skin_axis=2, supports=None, support_axis=0, **kwargs) +morphogen.models.part.PartStructure.contains(self, points) +morphogen.models.part.PartStructure.level_set(self, shape=None, *, voxel_size=None, grid=None) +morphogen.models.part.PartStructure.level_set_at(self, points, reach=inf) +morphogen.models.part.PartStructure.lipschitz +morphogen.models.part.PartStructure.shape_distance(self, points) +morphogen.models.part.PartStructure.shape_volume(self) +morphogen.models.part.PartStructure.summary(self) +morphogen.models.part.PartStructure.voxelize(self, shape=None, *, voxel_size=None, grid=None, supersampling=1) +morphogen.models.part.SHAPES morphogen.models.pieces.Piece(phase, union) morphogen.models.pieces.Piece.at(self, points, band) morphogen.models.pieces.colours(n, pairs) @@ -4662,7 +4686,7 @@ morphogen.models.tiling_field.TilingField.voxelize(self, shape=None, *, voxel_si morphogen.models.tiling_field.VOXELS_PER_CELL morphogen.models.tiling_field.default_grid(domain, tiling) morphogen.models.tpms.SURFACES -morphogen.models.tpms.TPMS(surface='gyroid', cell_size=1.0, variant='network', level=None, volume_fraction=None, fraction_gradient=None, gradient_axis=0, *, anisotropy=None) +morphogen.models.tpms.TPMS(surface='gyroid', cell_size=1.0, variant='network', level=None, volume_fraction=None, fraction_gradient=None, gradient_axis=0, cells_around=None, cylinder_axis=2, cylinder_center=None, *, anisotropy=None) morphogen.models.tpms.TPMS.expected_count(self, domain) morphogen.models.tpms.TPMS.generate(self, domain, seed=None) morphogen.models.tpms.TPMS.graded_levels(self) @@ -4670,7 +4694,7 @@ morphogen.models.tpms.TPMS.iso_level morphogen.models.tpms.TPMS.mean_fraction(self) morphogen.models.tpms.TPMS.solid_fraction(self) morphogen.models.tpms.TPMS.theory(self, domain=None) -morphogen.models.tpms.TPMSStructure(domain, surface, variant, level, cell_size, *, levels=None, gradient_axis=0, **kwargs) +morphogen.models.tpms.TPMSStructure(domain, surface, variant, level, cell_size, *, levels=None, gradient_axis=0, cells_around=None, cylinder_axis=2, cylinder_center=None, **kwargs) morphogen.models.tpms.TPMSStructure.contains(self, points) morphogen.models.tpms.TPMSStructure.level_set(self, shape=None, *, voxel_size=None, grid=None) morphogen.models.tpms.TPMSStructure.level_set_at(self, points, reach=inf) diff --git a/tests/test_models_base.py b/tests/test_models_base.py index 1e19198..d5d1cb3 100644 --- a/tests/test_models_base.py +++ b/tests/test_models_base.py @@ -66,6 +66,15 @@ True, ), "spinodoid": ({"wavelength": 2.0, "volume_fraction": 0.4, "n_waves": 200}, True), + "part": ( + { + "infill": {"type": "tpms", "cell_size": 4.0, "volume_fraction": 0.3}, + "shape": "cylinder", + "shell": 0.5, + "skins": [0.5, 0.5], + }, + False, + ), "hybrid": ( { "models": [ diff --git a/tests/test_part.py b/tests/test_part.py new file mode 100644 index 0000000..d39c5e6 --- /dev/null +++ b/tests/test_part.py @@ -0,0 +1,204 @@ +"""Parts ready to print: infills in shapes, with shells, skins and supports, conformal +TPMS and the distance to closed surfaces (theory.md §143).""" + +import numpy as np +import pytest + +import morphogen as mg +from morphogen import io +from morphogen.image import VoxelImage +from morphogen.mesh.distance import ( + fitted, + interpolate, + is_closed, + merged, + read_surface, + signed_distance_grid, +) +from morphogen.mesh.surface import SurfaceMesh, surface_mesh +from morphogen.models.base import Microstructure +from morphogen.models.part import Part, PartStructure +from morphogen.models.tpms import TPMS + +GYROID = {"type": "tpms", "surface": "gyroid", "variant": "sheet", "volume_fraction": 0.2} + + +def _torus(path, shape=(100, 100, 40)): + """A closed torus surface (R = 3, r = 1, about z through the origin) written as STL.""" + domain = mg.Domain(size=(10.0, 10.0, 4.0), origin=(-5.0, -5.0, -2.0), periodic=False) + grid = domain.grid(shape=shape) + p = grid.center_points() + phi = np.hypot(np.hypot(p[:, 0], p[:, 1]) - 3.0, p[:, 2]) - 1.0 + image = VoxelImage.from_grid(phi.reshape(grid.shape).astype(np.float32), grid, + name="level_set") # fmt: skip + io.save_mesh(surface_mesh(image, closed=True), path) + return domain + + +def test_sandwich_and_beam(): + """The skins of a sandwich (full plates at the faces along z) and the supports of a + beam (full blocks at its ends along x), the infill between them.""" + domain = mg.Domain(size=(6.0, 3.0, 2.0), periodic=False) + model = Part(infill=GYROID, skins=(0.25, 0.125), supports=(0.5, 0.0)) + micro = model.generate(domain, seed=1) + img = micro.voxelize(shape=(96, 48, 32)) + assert img.data[:, :, :4].all() and img.data[:, :, -2:].all() + assert img.data[:8].all() and not img.data[-8:, :, 8:-8].all() + core = img.data[16:-16, :, 6:-4] + assert 0.12 < core.mean() < 0.3 + assert np.array_equal(micro.level_set(shape=(96, 48, 32)).data <= 0, img.data == 1) + + +@pytest.mark.parametrize("shape", ["cylinder", "tube", "sphere"]) +def test_shapes_and_shells(shape): + """Nothing outside the shape, a full shell along its boundary, the exact volume of + the shape, the level set and the points of the solid; a realization read back.""" + domain = mg.Domain(size=(2.0, 2.0, 4.0), periodic=False) + model = Part(infill=GYROID, shape=shape, shell=0.1, radius=0.9, inner_radius=0.5) + micro = model.generate(domain, seed=2) + grid_shape = (48, 48, 96) + img = micro.voxelize(shape=grid_shape) + pts = img.grid().center_points() + s = micro.shape_distance(pts).reshape(grid_shape) + assert img.data[s > 0].sum() == 0 + assert img.data[(s < -0.02) & (s > -0.08)].all() + expected = { + "cylinder": np.pi * 0.9**2 * 4.0, + "tube": np.pi * (0.9**2 - 0.5**2) * 4.0, + "sphere": 4.0 / 3.0 * np.pi * 0.9**3, + }[shape] + assert micro.shape_volume() == pytest.approx(expected) + assert np.mean(s <= 0) * 16.0 == pytest.approx(expected, rel=0.03) + assert np.array_equal(micro.level_set(shape=grid_shape).data <= 0, img.data == 1) + assert np.array_equal(micro.contains(pts).reshape(grid_shape), img.data == 1) + back = Microstructure.from_dict(micro.to_dict()) + assert isinstance(back, PartStructure) + assert np.array_equal(back.voxelize(shape=24).data, micro.voxelize(shape=24).data) + + +def test_distance_to_a_surface(tmp_path): + """The signed distance to a closed surface on a grid: exact near the surface (within + the error of the surface itself), of the right sign everywhere, interpolated between + the nodes; STL files binary and ASCII; a surface fitted into a box.""" + path = tmp_path / "torus.stl" + _torus(path) + surface = read_surface(path) + assert is_closed(surface) + domain = mg.Domain(size=(10.0, 10.0, 4.0), origin=(-5.0, -5.0, -2.0), periodic=False) + grid = domain.grid(shape=(80, 80, 32)) + sdf = signed_distance_grid(surface, grid) + p = grid.center_points() + exact = np.hypot(np.hypot(p[:, 0], p[:, 1]) - 3.0, p[:, 2]) - 1.0 + near = np.abs(exact) < 0.25 + assert np.abs(sdf.ravel() - exact)[near].max() < 0.01 + assert ( + np.array_equal(sdf.ravel() <= 0, exact <= 0) + or np.mean((sdf.ravel() <= 0) == (exact <= 0)) > 0.999 + ) + q = np.random.default_rng(0).uniform([-4, -4, -1], [4, 4, 1], (2000, 3)) + exact_q = np.hypot(np.hypot(q[:, 0], q[:, 1]) - 3.0, q[:, 2]) - 1.0 + band = np.abs(exact_q) < 0.2 + assert np.abs(interpolate(sdf, grid, q) - exact_q)[band].max() < 0.02 + # an ASCII STL of a tetrahedron + ascii_path = tmp_path / "tetra.stl" + v = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=float) + faces = [(0, 2, 1), (0, 1, 3), (0, 3, 2), (1, 2, 3)] + lines = ["solid t"] + for f in faces: + lines += ["facet normal 0 0 0", "outer loop"] + lines += [f"vertex {v[i][0]} {v[i][1]} {v[i][2]}" for i in f] + lines += ["endloop", "endfacet"] + ascii_path.write_text("\n".join([*lines, "endsolid t"])) + tetra = read_surface(ascii_path) + assert len(tetra.vertices) == 4 and len(tetra.faces) == 4 and is_closed(tetra) + box = fitted(tetra, [0, 0, 0], [2, 4, 2]) + assert np.allclose(box.vertices.min(axis=0), [0.04, 1.04, 0.04]) + assert np.allclose(box.vertices.max(axis=0), [1.96, 2.96, 1.96]) + open_surface = merged(SurfaceMesh(v, np.array(faces[:3]))) + assert not is_closed(open_surface) + with pytest.warns(UserWarning, match="not closed"): + signed_distance_grid(open_surface, mg.Domain.cube(1.0, periodic=False).grid(8)) + + +def test_infill_of_a_surface(tmp_path): + """A torus read from a file filled with a gyroid, with a shell: nothing beyond the + surface, a full shell, the volume of the torus; the surface fitted into a domain.""" + path = tmp_path / "torus.stl" + domain = _torus(path) + model = Part(infill={**GYROID, "cell_size": 0.5}, shape="mesh", mesh=str(path), shell=0.1) + micro = model.generate(domain, seed=1) + img = micro.voxelize(shape=(100, 100, 40)) + q = img.grid().center_points() + d = (np.hypot(np.hypot(q[:, 0], q[:, 1]) - 3.0, q[:, 2]) - 1.0).reshape(img.shape) + assert img.data[d > 0.05].sum() == 0 + assert img.data[(d < -0.03) & (d > -0.07)].all() + assert micro.shape_volume() == pytest.approx(2 * np.pi**2 * 3.0, rel=0.02) + small = mg.Domain(size=(2.0, 2.0, 1.0), periodic=False) + fit = Part(infill=GYROID, shape="mesh", mesh=str(path), fit=True).generate(small, 1) + assert np.allclose(fit.surface.vertices.min(axis=0)[:2], [0.04, 0.04], atol=0.01) + + +def test_conformal_tpms(): + """Cells wrapped around an axis: the solid invariant by the rotation of one cell + about the axis, the level set a distance across the surface (slope about 1), the + level set and the voxels alike; a tube filled with them.""" + domain = mg.Domain(size=(4.0, 4.0, 4.0), periodic=False) + model = TPMS(surface="gyroid", variant="sheet", volume_fraction=0.25, cell_size=0.5, + cells_around=16) # fmt: skip + micro = model.generate(domain) + q = np.random.default_rng(0).uniform(0.5, 3.5, (2000, 3)) + t = 2.0 * np.pi / 16 + rot = np.array([[np.cos(t), -np.sin(t), 0.0], [np.sin(t), np.cos(t), 0.0], [0.0, 0.0, 1.0]]) + turned = (q - 2.0) @ rot.T + 2.0 + assert np.allclose(micro.level_set_at(q), micro.level_set_at(turned), atol=1e-10) + near = q[np.abs(micro.level_set_at(q)) < 0.01][:100] + slopes = [ + np.linalg.norm([(micro.level_set_at(p + e)[0] - micro.level_set_at(p - e)[0]) / 2e-5 + for e in 1e-5 * np.eye(3)]) + for p in near + ] # fmt: skip + assert np.median(slopes) == pytest.approx(1.0, abs=0.05) + img = micro.voxelize(shape=48) + assert np.array_equal(micro.level_set(shape=48).data <= 0, img.data == 1) + about_x = TPMS(surface="schwarz_p", volume_fraction=0.3, cells_around=8, cylinder_axis=0) + one = about_x.generate(domain) + t = 2.0 * np.pi / 8 + rot_x = np.array([[1.0, 0.0, 0.0], [0.0, np.cos(t), -np.sin(t)], [0.0, np.sin(t), np.cos(t)]]) + assert np.allclose(one.level_set_at(q), one.level_set_at((q - 2.0) @ rot_x.T + 2.0)) + tube = Part(infill=model, shape="tube", radius=1.8, inner_radius=1.2, shell=0.05) + assert 0.08 < tube.generate(domain).voxelize(shape=48).data.mean() < 0.25 + with pytest.raises(ValueError, match="non-periodic"): + model.generate(mg.Domain.cube(4.0)) + with pytest.raises(ValueError, match="cells_around"): + TPMS(volume_fraction=0.3, cells_around=0) + + +def test_errors_and_configuration(tmp_path): + """Errors, and a cylinder with end plates from a configuration to its STL surface.""" + with pytest.raises(ValueError, match="infill"): + Part() + with pytest.raises(ValueError, match="shape"): + Part(infill=GYROID, shape="cone") + with pytest.raises(ValueError, match="mesh"): + Part(infill=GYROID, shape="mesh") + with pytest.raises(ValueError, match="inner_radius"): + Part(infill=GYROID, shape="tube", radius=0.5, inner_radius=0.6) + with pytest.raises(ValueError, match="skins"): + Part(infill=GYROID, skins=(0.1,)) + with pytest.raises(ValueError, match="level set"): + Part(infill={"type": "voronoi", "n_cells": 5}) + with pytest.raises(ValueError, match="periodic"): + Part(infill=GYROID).generate(mg.Domain.cube(2.0)) + from morphogen import pipeline + from morphogen.config import load_config + + config = { + "model": {"type": "part", "shape": "cylinder", "shell": 0.1, "skins": [0.1, 0.1], + "infill": {"type": "strut_lattice", "cell": "octet", "volume_fraction": 0.15, + "cell_size": 0.5}}, + "domain": {"size": [2.0, 2.0, 3.0], "periodic": False}, + "voxels": {"shape": [32, 32, 48]}, + "outputs": {"directory": str(tmp_path), "name": "column", "surface": ["stl"]}, + } # fmt: skip + outdir = pipeline.run(load_config(config)) + assert list(outdir.rglob("column*.stl")) From a6aa83d0394681e4b07cdd09d752ef42c29721a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 23:41:52 +0000 Subject: [PATCH 05/13] Docstrings: the field of the spinodoids as a literal block The formula of the module of the spinodoids (|k_i|) was read by Sphinx as a substitution: it is a literal block, and the helper of the TPMS quotes its expressions. The site builds without warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MSrXEMpgnWPQNUwHwAgXHV --- src/morphogen/models/spinodoid.py | 2 +- src/morphogen/models/tpms.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/morphogen/models/spinodoid.py b/src/morphogen/models/spinodoid.py index bf1a731..bb3a446 100644 --- a/src/morphogen/models/spinodoid.py +++ b/src/morphogen/models/spinodoid.py @@ -1,7 +1,7 @@ """Spinodoids: the level sets of a sum of waves of one wavelength (Cahn 1965; Soyarslan et al. 2018; Kumar, Tan, Zheng & Kochmann 2020). -The field +The field:: phi(x) = sqrt(2 / N) sum_i cos(k_i . x + gamma_i), |k_i| = beta = 2 pi / lambda, diff --git a/src/morphogen/models/tpms.py b/src/morphogen/models/tpms.py index 1efbc37..8abe508 100644 --- a/src/morphogen/models/tpms.py +++ b/src/morphogen/models/tpms.py @@ -41,7 +41,7 @@ def _unit_cell_values(code: int, n: int = _CALIBRATION_SAMPLES) -> np.ndarray: def _side(values: np.ndarray, variant: str) -> np.ndarray: - """The values whose lowest quantiles are the solid: phi, |phi| or -phi.""" + """The values whose lowest quantiles are the solid: ``phi``, ``|phi|`` or ``-phi``.""" if variant == "sheet": return np.abs(values) if variant == "upper_network": From 20c14ab30f1900f9abfe25f14821c93cf2f95b88 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 23:46:39 +0000 Subject: [PATCH 06/13] Strut lattices: octahedral and rhombic dodecahedral cells, reinforcements, curves MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The strut lattices (theory notes §144, FR-G33, specification 1.258): the cells octahedral (the octahedra of the face centres, stretching-dominated) and rhombic_dodecahedron (the Voronoi cells of the fcc lattice, bending-dominated), their rigidity in the frames and the tool of the interface; struts added along an axis (the edges of the cube, or its axis: bcc-z, fcc-z, reinforced octet and octahedral cells); the struts inside the cell bent into circular arcs (circular octahedra); custom cells of struts given by their ends. A cell is a CellSpec (cached under its name when plain); the volume fraction is solved for all; the buckling of hierarchical lattices keeps to named cells. The public interface written again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MSrXEMpgnWPQNUwHwAgXHV --- CHANGELOG.md | 10 + docs/models.md | 2 +- docs/specification.md | 6 +- docs/theory.md | 53 ++++- src/morphogen/gui/tools/design.py | 5 +- .../homogenization/hierarchy_buckling.py | 5 +- src/morphogen/models/lattice.py | 192 ++++++++++++++++-- tests/public_api.txt | 7 +- tests/test_lattice_families.py | 129 ++++++++++++ 9 files changed, 386 insertions(+), 23 deletions(-) create mode 100644 tests/test_lattice_families.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 213e50f..bcf1745 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +* Strut lattices ([docs/theory.md](docs/theory.md) §144): the cells `octahedral` (the + octahedra of the face centres, stretching-dominated) and `rhombic_dodecahedron` (the + Voronoi cells of the fcc lattice, bending-dominated); `reinforcement: edges` or `axis` + along `reinforcement_axis` (bcc-z, fcc-z, reinforced octet and octahedral cells); + `curvature`, the struts inside the cell bent into circular arcs of a sagitta (circular + octahedra); `cell: custom` with its `struts`. The volume fraction is solved for all of + them; the rigidity of the frames takes the two new cells. Public interface: the + parameters `struts`, `reinforcement`, `reinforcement_axis`, `curvature` and + `arc_segments` of `StrutLattice`, `StrutLattice.spec`, and in `morphogen.models.lattice` + `CellSpec`, `as_spec` and `REINFORCEMENTS`. * Parts ready to print (`part`, [docs/theory.md](docs/theory.md) §143): any two-phase model filling a box, a cylinder, a tube, a sphere or a closed surface read from a file (STL, binary or ASCII, or OBJ, PLY... through meshio; `fit` scales it into the domain), with a diff --git a/docs/models.md b/docs/models.md index 3e23967..19cd11f 100644 --- a/docs/models.md +++ b/docs/models.md @@ -74,7 +74,7 @@ What a realization is made of, and how it becomes images and meshes, is the subj |---|---| | `tpms` | Ten surfaces: gyroid, Schwarz P and D, Neovius, Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P and I2-Y; the network on either side of the surface or the sheet, at a level, a volume fraction or a profile of the fraction along an axis (graded TPMS, [theory notes](theory.md) §140) | | `spinodoid` | Spinodoids (Kumar et al. 2020): the level of a sum of waves of one wavelength in random directions, isotropic or within cones about the axes (lamellar, columnar, cubic), network, sheet or the other network, at a fraction or graded; periodic in periodic boxes; their specific surface by Rice's formula ([theory notes](theory.md) §141) | -| `strut_lattice` | Cubic, BCC, FCC, octet, Kelvin, diamond and pyrochlore lattices, with solid or hollow struts; rotated and functionally graded lattices (non-periodic samples); their sections meshed in the plane by their exact contours | +| `strut_lattice` | Cubic, BCC, FCC, octet, Kelvin, diamond, pyrochlore, octahedral and rhombic dodecahedral lattices, or cells of one's own struts, with solid or hollow struts; reinforced along an axis (bcc-z, fcc-z), curved struts (circular octahedra, [theory notes](theory.md) §144); rotated and functionally graded lattices (non-periodic samples); their sections meshed in the plane by their exact contours | | `plate_lattice` | Plate lattices: closed cells walled by plates on the closest-packed planes of the cubic lattices, the {100} (`cubic`), {110} (`bcc`) and {111} (`fcc`, the octet plates) planes and their mixtures (Berger et al. 2017; Tancogne-Dejean et al. 2018), of a thickness or an exact relative density, in the ratio of an isotropic stiffness at low density (`isotropic`, which reaches the Hashin–Shtrikman bounds); turned, shifted and graded; the exact density and specific surface, the stiffness of the membranes at low density, exact meshes of their convex pieces ([below](#plate-lattices)) | | `random_lattice` | Strut lattices with missing struts and displaced nodes, with their rigidity (Maxwell–Calladine); their sections meshed in the plane by their exact contours | | `hierarchical_lattice` | Hierarchical lattices of (hollow) tubes: frames of generation G of regular octahedra (Rayneau-Kirkhope, Mao & Farr 2012); their sections meshed in the plane by their exact contours | diff --git a/docs/specification.md b/docs/specification.md index 8bf39a5..8cc9130 100644 --- a/docs/specification.md +++ b/docs/specification.md @@ -3,7 +3,7 @@ | | | |---|---| | Document | Software requirements specification | -| Version | 1.257 | +| Version | 1.258 | | Date | 2026-12-01 | | Author | @jdirr | | Status | Version 1.1 **validated** on 2026-10-21. The later versions, proposed, are listed in the change log (§13); changes go through pull requests that update this file and its change log. | @@ -366,6 +366,8 @@ centred on morphological modelling. | Delivered | FR-G31 (`hybrid`, [theory.md](theory.md) §142): `transition` linear, cylindrical or spherical, `position`, `radius`, `center` and `width` (the sigmoid of Yang et al. 2014), the functions bounded by `scale` before they are blended, each model where the weight is 0 or 1, the slope bounded by `max(L_1, L_2) + D / 2w` | | Additive manufacturing: parts (2026-12-01) | Specimens and components rather than boxes: Top6Meta's sandwiches, beams and cylinders, and the infill of any part. | | Delivered | FR-G32 (`part`, `mesh.distance`, `tpms` `cells_around`, [theory.md](theory.md) §143): `shape` box, cylinder, tube, sphere or mesh (`mesh`, `fit`, `resolution`), `shell`, `skins` and `supports` along their axes, the function of the part a maximum and minima of signed distances; the distance to a closed surface exact near it (Ericson's closest points), its inside by the parity of the columns; the cells of a TPMS wrapped around an axis | +| Additive manufacturing: strut lattices (2026-12-01) | The families of Top6Meta's strut module (octahedral, reinforced, circular) and of the literature on printed lattices (bcc-z, fcc-z, rhombic dodecahedron). | +| Delivered | FR-G33 (`strut_lattice` `cell: octahedral`, `rhombic_dodecahedron`, `custom` with `struts`, `reinforcement`, `curvature`, `CellSpec`, [theory.md](theory.md) §144): the two cells, their rigidity in the frames; reinforcements `edges` and `axis`; circular arcs of a sagitta, outward or inward, in straight pieces; custom cells; the fractions solved for every cell | ## 4. Scope @@ -445,6 +447,7 @@ version, 0.1). | FR-G30 | Spinodoids: the levels of sums of waves of one wavelength in random directions, on the sphere or within cones about the axes, the network, the sheet or the other network at a level, a fraction or a profile of fractions, periodic in periodic boxes; their specific surface by Rice's formula | S | 1d | | FR-G31 | Hybrid architectures: two models with implicit functions blended across a plane, a cylinder or a sphere by a sigmoid of the distance to it, their bounded functions mixed continuously; a bound of the slope of the blend | S | 1d | | FR-G32 | Parts ready to print: any two-phase model filling a box, a cylinder, a tube, a sphere or a closed surface read from a file, with a shell along its boundary, the skins of a sandwich and the supports of a beam; the signed distance to closed triangle surfaces; TPMS whose cells wrap around an axis (conformal TPMS) | S | 1d | +| FR-G33 | Strut lattices: the octahedral and rhombic dodecahedral cells, struts added along an axis (the edges of the cube or its axis), struts curved into circular arcs, custom cells of struts given by their ends | S | 1d | ### 5.2 Representations @@ -1435,6 +1438,7 @@ Packages: `models`, `kernels`, `analysis`, `rve`, `mesh`, `homogenization`, `io` | 1.255 | 2026-12-01 | Spinodoids: sums of waves of one wavelength, cones, grading, Rice's surface (FR-G30, §3.12) | | 1.256 | 2026-12-01 | Hybrid architectures: two models blended across a plane, a cylinder or a sphere (FR-G31, §3.12) | | 1.257 | 2026-12-01 | Parts ready to print: shapes, shells, skins, supports, closed surfaces from files, conformal TPMS (FR-G32, §3.12) | +| 1.258 | 2026-12-01 | Strut lattices: octahedral and rhombic dodecahedral cells, reinforcements, curved struts, custom cells (FR-G33, §3.12) | ## 14. References diff --git a/docs/theory.md b/docs/theory.md index efb0def..7bc995e 100644 --- a/docs/theory.md +++ b/docs/theory.md @@ -12,7 +12,7 @@ them by these numbers (§75); by theme: | Theme | Sections | |---|---| | Models of random media | [§1](#1-boolean-models) Boolean models, [§2](#2-poisson-fibres-jeulin-1991-dirrenberger-et-al-2014) Poisson fibres (Jeulin 1991; Dirrenberger et al. 2014), [§3](#3-random-sequential-addition) Random sequential addition, [§4](#4-tessellations) Tessellations, [§5](#5-excursions-of-gaussian-random-fields) Excursions of Gaussian random fields, [§22](#22-combinations-of-models-and-grain-boundary-phases) Combinations of models and grain-boundary phases, [§23](#23-further-models) Further models, [§29](#29-nested-models) Nested models, [§38](#38-torquatos-approaches-dense-packings-cherry-pit-spheres-reconstruction-and-descriptors) Torquato's approaches: dense packings, cherry-pit spheres, reconstruction and descriptors, [§42](#42-foams-as-level-sets-of-distance-fields-level_set_foam) Foams as level sets of distance fields, [§56](#56-affine-anisotropy-of-the-models-modelsaffine) Affine anisotropy of the models, [§93](#93-scale-rich-networks-scale_rich_network) Scale-rich networks, [§95](#95-long-fibres-unidirectional-composites-parallel-or-misaligned-long_fibers) Long fibres: unidirectional composites, parallel or misaligned, [§97](#97-grains-with-subgrains-or-filled-with-another-structure-modelsnested_grains) Grains with subgrains, or filled with another structure, [§98](#98-monodisperse-and-polydisperse-objects) Monodisperse and polydisperse objects, [§107](#107-images-as-microstructures-segmentation-and-the-model-image-morphologysegmentation-modelsimage) Images as microstructures: segmentation and the model `image`, [§114](#114-reconstruction-from-descriptors-by-gradient-descent-morphologyreconstruction) Reconstruction from descriptors by gradient descent, [§115](#115-grains-grown-from-seeds-modelsseeded-kernelsseeds) Grains grown from seeds, [§116](#116-seeds-of-several-phases-and-the-verification-of-their-grains-modelsseeded-meshpolyhedra-kernelsseeds) Seeds of several phases and the verification of their grains, [§117](#117-seeds-of-the-plane-and-the-figures-of-the-verification-modelsseeded-vizfigures) Seeds of the plane and the figures of the verification, [§118](#118-seeds-of-boxes-and-of-rectangles-modelsseeded) Seeds of boxes and of rectangles | -| Architected and bio-inspired structures | [§6](#6-tpms) TPMS, [§7](#7-strut-lattices) Strut lattices, [§30](#30-bio-inspired-models) Bio-inspired models, [§71](#71-diamond-and-pyrochlore-lattices-of-struts-homogenizationframes-modelslattice) Diamond and pyrochlore lattices of struts, [§96](#96-woven-textile-composites-woven_textile) Woven textile composites, [§110](#110-woven-textiles-the-variability-of-the-tows-3d-architectures-the-tows-as-unidirectional-composites-woven_textile-homogenizationunidirectional) Woven textiles: the variability of the tows, 3D architectures, the tows as unidirectional composites, [§125](#125-plate-lattices-plate_lattice) Plate lattices, [§140](#140-tpms-ten-surfaces-their-two-networks-and-their-gradients-modelstpms) TPMS: ten surfaces, their two networks and their gradients, [§141](#141-spinodoids-levels-of-sums-of-waves-of-one-wavelength-modelsspinodoid) Spinodoids: levels of sums of waves of one wavelength, [§142](#142-hybrid-architectures-two-models-blended-across-a-transition-modelshybrid) Hybrid architectures: two models blended across a transition, [§143](#143-parts-ready-to-print-infills-in-shapes-with-shells-skins-and-supports-modelspart) Parts ready to print: infills in shapes, with shells, skins and supports | +| Architected and bio-inspired structures | [§6](#6-tpms) TPMS, [§7](#7-strut-lattices) Strut lattices, [§30](#30-bio-inspired-models) Bio-inspired models, [§71](#71-diamond-and-pyrochlore-lattices-of-struts-homogenizationframes-modelslattice) Diamond and pyrochlore lattices of struts, [§96](#96-woven-textile-composites-woven_textile) Woven textile composites, [§110](#110-woven-textiles-the-variability-of-the-tows-3d-architectures-the-tows-as-unidirectional-composites-woven_textile-homogenizationunidirectional) Woven textiles: the variability of the tows, 3D architectures, the tows as unidirectional composites, [§125](#125-plate-lattices-plate_lattice) Plate lattices, [§140](#140-tpms-ten-surfaces-their-two-networks-and-their-gradients-modelstpms) TPMS: ten surfaces, their two networks and their gradients, [§141](#141-spinodoids-levels-of-sums-of-waves-of-one-wavelength-modelsspinodoid) Spinodoids: levels of sums of waves of one wavelength, [§142](#142-hybrid-architectures-two-models-blended-across-a-transition-modelshybrid) Hybrid architectures: two models blended across a transition, [§143](#143-parts-ready-to-print-infills-in-shapes-with-shells-skins-and-supports-modelspart) Parts ready to print: infills in shapes, with shells, skins and supports, [§144](#144-strut-lattices-octahedral-and-rhombic-dodecahedral-cells-reinforcements-curved-struts-custom-cells-modelslattice) Strut lattices: octahedral and rhombic dodecahedral cells, reinforcements, curved struts, custom cells | | Growth and design | [§14](#14-cellular-automata-automata) Cellular automata, [§15](#15-nucleation-and-growth-johnsonmehlavramikolmogorov) Nucleation and growth (Johnson–Mehl–Avrami–Kolmogorov), [§16](#16-aggregation) Aggregation, [§17](#17-combinatorial-design-design) Combinatorial design, [§18](#18-topology-optimization-of-periodic-cells-optimization) Topology optimization of periodic cells, [§78](#78-isogeometric-analysis-iga) Isogeometric analysis, [§79](#79-isogeometric-shape-optimization-igaoptimization) Isogeometric shape optimization, [§109](#109-inverse-design-of-active-structures-optimizationmorphing) Inverse design of active structures, [§113](#113-spinodal-decomposition-spinodal) Spinodal decomposition | | Geometry and meshes | [§19](#19-polycrystals-exact-cells-and-conforming-meshes-meshpolyhedra-meshpolycrystal) Polycrystals: exact cells and conforming meshes, [§24](#24-whole-periodic-grains-meshpolycrystal-cells-whole) Whole periodic grains, [§52](#52-views-and-measures-of-the-level-sets-vizsections) Views and measures of the level sets, [§75](#75-the-implicit-geometry-of-every-model-modelsimplicit-meshconforming) The implicit geometry of every model, [§76](#76-quadratic-tetrahedra-isoparametric-elements-and-curved-interfaces-meshcurved-homogenizationfe) Quadratic tetrahedra: isoparametric elements and curved interfaces, [§80](#80-sharp-edges-of-the-phases-meshes-that-follow-them-modelspieces-meshconforming-meshcurved) Sharp edges of the phases: meshes that follow them, [§94](#94-exact-meshes-without-a-background-grid-meshexact-meshoctree) Exact meshes without a background grid, [§119](#119-meshes-of-the-plane-and-their-finite-elements-meshtriangles-homogenizationplane) Meshes of the plane and their finite elements | | Measures | [§8](#8-specific-surface-by-cauchycrofton) Specific surface by Cauchy–Crofton, [§21](#21-morphological-measures-analysismorphology) Morphological measures, [§39](#39-random-sets-probed-by-structuring-elements-analysisrandom_sets-analysistopology) Random sets probed by structuring elements, [§55](#55-percolation-thresholds-analysispercolation) Percolation thresholds, [§70](#70-particles-of-a-phase-in-a-volume-analysisparticles) Particles of a phase in a volume, [§92](#92-crystallographic-textures-and-orientation-maps-texture-ioebsd-modelsebsd) Crystallographic textures and orientation maps, [§104](#104-measures-of-the-implicit-geometry-morphologymeasures) Measures of the implicit geometry, [§105](#105-unions-of-balls-and-of-discs-measured-exactly-morphologyballs) Unions of balls and of discs, measured exactly, [§106](#106-the-model-of-an-image-morphologyidentification) The model of an image | @@ -16814,6 +16814,57 @@ rotation of one cell, the slope of its level set of median 1 within 5 %, a Schwa around $x$, a tube filled with them; the errors; a column with end plates from a configuration to its STL surface. +## 144. Strut lattices: octahedral and rhombic dodecahedral cells, reinforcements, curved struts, custom cells (`models.lattice`) + +**Two more cells** (fractional coordinates of the cubic cell): + +* `octahedral`: the regular octahedron of the face centres (the inner octahedron of the + octet truss, §7), 12 struts of length $\sqrt2/2$; the octahedra of neighbouring cells + share their vertices, each node joins 8 struts, and Maxwell's count of the periodic + framework (§17) finds no floppy macroscopic strain: stretching-dominated. +* `rhombic_dodecahedron`: the edges of the Voronoi cells of the fcc lattice — each + tetrahedral site ($x_i \in \{1/4, 3/4\}$) joined to its four octahedral sites (the body + centre and the middles of the edges) at $\sqrt3/4$ — 32 struts per cell, nodes of 4 and 8 + struts (mean $16/3$), bending-dominated (five floppy strains); the cell of many bone + scaffolds. + +**Reinforcements.** `reinforcement: edges` adds the four edges of the cube along +`reinforcement_axis` (each shared by four cells: one strut of length $a$ per cell; the bcc-z +and fcc-z cells of the literature on additive manufacturing), `axis` the strut through the +centre of the cell from face to face (Top6Meta's reinforced octahedron; on a bcc lattice the +two are the same lattice, moved by $(a/2, a/2, a/2)$). They add a length $a$ per cell +and stiffen the lattice along the axis. + +**Curved struts.** `curvature` $\kappa$ bends each strut whose middle lies inside the cell +(not on its faces, where neighbouring cells would bend it both ways, and not through its +centre, where no direction is singled out) into the circular arc through its ends of +sagitta $h = |\kappa| L$, bulging away from the centre of the cell (toward it if +$\kappa < 0$): with $u$ the direction of the strut, $n$ the unit vector of the part of +$m - c$ normal to it ($m$ the middle, $c$ the centre of the cell), the radius is +$R = (L^2/4 + h^2)/2h$, the centre of the circle $m - n\,(R - h)\,\mathrm{sign}\,\kappa$ +and the half-angle $\arcsin(L/2R)$; the arc is cut into `arc_segments` straight pieces, +whose round caps join smoothly. Bent octahedra are Top6Meta's circular octahedra, which +spread the stress of the nodes. + +**Custom cells.** `cell: custom` takes `struts`, each the fractional coordinates of its two +ends; the struts shared with neighbouring cells may be given once or in each cell (the +duplicates of the lattice are removed). + +The volume fraction of every cell is solved as before (§7): voxel estimates of the union +of the struts, the closed form of the cubic cell; a reinforced, curved or custom cell is +cached under its specification (`CellSpec`), a named cell under its name. The rigidity of +the frames (§17) takes the two new cells; the buckling of hierarchical lattices (§137) +takes named cells only. + +Validated in `tests/test_lattice_families.py`: the struts of the two cells, their lengths +per cell ($12\sqrt2/2$, $32\sqrt3/4$), their coordinations and rigidity, the fraction of thin +struts $\pi r^2 L_V$ within 10 %, the fraction of a realization within 0.01; the length +added by the reinforcements, the axis strut through the centre, the radius of a reinforced +fcc lattice smaller than the plain one, its edges along $z$ solid; the arcs through the +ends, of the sagitta asked for, outward and inward, the struts on the faces left straight, +a circular octahedron at its fraction; a custom octet equal to the octet, a custom cube to +the cubic lattice voxel for voxel, a reinforced curved lattice read back; the errors. + ## References See [specification.md](specification.md#14-references). In addition: diff --git a/src/morphogen/gui/tools/design.py b/src/morphogen/gui/tools/design.py index 8233085..92c9204 100644 --- a/src/morphogen/gui/tools/design.py +++ b/src/morphogen/gui/tools/design.py @@ -145,7 +145,10 @@ def progress(g, best, cost): } -LATTICES = ("cubic", "bcc", "fcc", "octet", "kelvin", "diamond", "pyrochlore") +LATTICES = ( + "cubic", "bcc", "fcc", "octet", "kelvin", "diamond", "pyrochlore", "octahedral", + "rhombic_dodecahedron", +) # fmt: skip @tool( diff --git a/src/morphogen/homogenization/hierarchy_buckling.py b/src/morphogen/homogenization/hierarchy_buckling.py index 366b1c2..5b26d7c 100644 --- a/src/morphogen/homogenization/hierarchy_buckling.py +++ b/src/morphogen/homogenization/hierarchy_buckling.py @@ -340,8 +340,9 @@ def lattice_levels(hierarchy) -> list[tuple]: if getattr(sub, "wall_thickness", None) and k < len(subs) - 1: raise ValueError(f"level {k}: solid struts (no wall_thickness): tubes at the " "last level only") # fmt: skip - if sub.cell not in SPACE_LATTICES: - raise ValueError(f"level {k}: one of the frames {sorted(SPACE_LATTICES)}") + if sub.cell not in SPACE_LATTICES or not sub.spec.plain: + raise ValueError(f"level {k}: one of the frames {sorted(SPACE_LATTICES)} (neither " + "reinforced nor curved)") # fmt: skip if k > 0 and below[k - 1][1].frame != "members": raise ValueError(f"level {k}: its cell along the struts above (frame 'members')") size = float(getattr(sub, "cell_size", None) or 1.0) diff --git a/src/morphogen/models/lattice.py b/src/morphogen/models/lattice.py index 9c8099f..d4af923 100644 --- a/src/morphogen/models/lattice.py +++ b/src/morphogen/models/lattice.py @@ -48,8 +48,24 @@ def _pairs_at(nodes_a, nodes_b, distance, same: bool): return out -def unit_cell_struts(cell: str) -> np.ndarray: - """Struts of a unit cell in fractional coordinates, shape (n, 2, 3).""" +def unit_cell_struts(cell) -> np.ndarray: + """Struts of a unit cell (a name of :data:`CELLS` or a :class:`CellSpec`) in + fractional coordinates, shape (n, 2, 3).""" + if isinstance(cell, CellSpec): + if cell.cell == "custom": + base = np.asarray(cell.struts, dtype=float).reshape(-1, 2, 3) + else: + base = _named_struts(cell.cell) + if cell.reinforcement is not None: + base = np.concatenate([base, _reinforcement(cell.reinforcement, cell.axis)]) + if cell.curvature != 0.0: + base = _arcs(base, cell.curvature, cell.segments) + return base + return _named_struts(cell) + + +def _named_struts(cell: str) -> np.ndarray: + """Struts of a named unit cell in fractional coordinates, shape (n, 2, 3).""" h = math.sqrt(0.5) if cell == "cubic": pairs = _pairs_at(_CORNERS, _CORNERS, 1.0, True) @@ -88,12 +104,95 @@ def unit_cell_struts(cell: str) -> np.ndarray: for origin, corners in ((0.125, even), (0.375, -even)): vertices = centre + origin + corners pairs += _pairs_at(vertices, vertices, 0.25 * math.sqrt(2.0), True) + elif cell == "octahedral": + # the octahedron of the face centres (the inner octahedron of the octet), + # octahedra joined by their vertices (coordination 8) + pairs = _pairs_at(_FACE_CENTERS, _FACE_CENTERS, h, True) + elif cell == "rhombic_dodecahedron": + # the edges of the Voronoi cells of the fcc lattice: each tetrahedral site + # (coordinates 1/4 or 3/4) joined to its four octahedral sites (the body centre + # and the middles of the edges), coordination 4 and 8, bending-dominated + tetrahedral = np.array(list(itertools.product((0.25, 0.75), repeat=3))) + middles = [p for p in itertools.product((0.0, 0.5, 1.0), repeat=3) + if sorted(p).count(0.5) == 1 or p == (0.5, 0.5, 0.5)] # fmt: skip + pairs = _pairs_at(tetrahedral, np.array(middles), 0.25 * math.sqrt(3.0), False) else: raise ValueError(f"cell: expected one of {sorted(CELLS)}, got {cell!r}") return np.array([[p, q] for p, q in pairs], dtype=float) -CELLS = ("cubic", "bcc", "fcc", "octet", "kelvin", "diamond", "pyrochlore") +CELLS = ( + "cubic", "bcc", "fcc", "octet", "kelvin", "diamond", "pyrochlore", "octahedral", + "rhombic_dodecahedron", +) # fmt: skip +#: Struts added to a cell along an axis: the four edges of the cube along it, or the strut +#: through its centre from face to face. +REINFORCEMENTS = ("edges", "axis") + + +@dataclass(frozen=True) +class CellSpec: + """A unit cell of struts: a named cell (:data:`CELLS`) or ``custom`` struts (each six + fractional coordinates), with struts added along an axis (``reinforcement``: the + ``edges`` of the cube, or its ``axis`` from face to face) and the struts inside the + cell curved into circular arcs (``curvature``: the sagitta over the length, outward + from the centre of the cell when positive) of ``segments`` straight pieces.""" + + cell: str = "octet" + struts: tuple = () + reinforcement: str | None = None + axis: int = 2 + curvature: float = 0.0 + segments: int = 8 + + @property + def plain(self) -> bool: + """A named cell as it is.""" + return self.cell != "custom" and self.reinforcement is None and self.curvature == 0.0 + + +def as_spec(cell) -> CellSpec: + """The specification of a cell given by its name or by a :class:`CellSpec`.""" + return cell if isinstance(cell, CellSpec) else CellSpec(str(cell)) + + +def _reinforcement(kind: str, axis: int) -> np.ndarray: + b, c = (axis + 1) % 3, (axis + 2) % 3 + feet = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] if kind == "edges" else [(0.5, 0.5)] + out = [] + for u, v in feet: + p, q = np.zeros(3), np.zeros(3) + p[b], p[c], q[b], q[c], q[axis] = u, v, u, v, 1.0 + out.append([p, q]) + return np.array(out) + + +def _arcs(struts: np.ndarray, curvature: float, segments: int) -> np.ndarray: + """The struts whose middle lies inside the cell (not through its centre) as circular + arcs of sagitta ``curvature`` times their length, bulging away from the centre of the + cell (toward it for a negative curvature), in ``segments`` pieces; the others as they + are.""" + out = [] + centre = np.full(3, 0.5) + for p, q in struts: + m = 0.5 * (p + q) + length = float(np.linalg.norm(q - p)) + u = (q - p) / length + d = (m - centre) - ((m - centre) @ u) * u + inside = np.all((m > 1e-9) & (m < 1.0 - 1e-9)) + if not inside or np.linalg.norm(d) < 1e-9: + out.append([p, q]) + continue + n = np.sign(curvature) * d / np.linalg.norm(d) + h = abs(curvature) * length + radius = (0.25 * length * length + h * h) / (2.0 * h) + half = math.asin(min(1.0, 0.5 * length / radius)) + c = m - n * (radius - h) + t = np.linspace(-half, half, segments + 1) + points = c + radius * (np.cos(t)[:, None] * n + np.sin(t)[:, None] * u) + points[0], points[-1] = p, q + out.extend([points[k], points[k + 1]] for k in range(segments)) + return np.array(out, dtype=float) def _unique_segments(start: np.ndarray, end: np.ndarray, scale: float): @@ -164,13 +263,21 @@ def lattice_fraction(cell: str, radius: float, n: int | None = None) -> float: return float(counts.mean()) +def _key(cell): + """A named cell by its name (the closed forms and the caches of the names), any other + by its specification.""" + spec = as_spec(cell) + return spec.cell if spec.plain else spec + + @lru_cache(maxsize=512) -def strut_fraction(cell: str, r: float, t: float = 0.0, n: int | None = None) -> float: +def strut_fraction(cell, r: float, t: float = 0.0, n: int | None = None) -> float: """Solid fraction of a lattice of unit cell size 1, struts of radius ``r`` hollow with walls ``t`` (0: solid): the union of the struts minus that of their bores. Exact for the cubic cell, a voxel estimate on ``n^3`` voxels otherwise (default: 8 voxels across the walls of hollow struts, 10 across the radius of solid ones).""" hollow = 0 < t < r + cell = _key(cell) if cell == "cubic": # three orthogonal cylinders per node, minus their overlaps def union(x): @@ -212,7 +319,14 @@ class StrutLattice(Model): Cells: ``cubic`` (cube edges), ``bcc`` (body diagonals), ``fcc`` (face diagonals), ``octet`` (face diagonals and inner octahedron), ``kelvin`` (edges of the Kelvin - foam: truncated octahedra on a bcc lattice, 24 struts per cell). Give the strut + foam: truncated octahedra on a bcc lattice, 24 struts per cell), ``diamond``, + ``pyrochlore``, ``octahedral`` (the octahedron of the face centres) and + ``rhombic_dodecahedron`` (the edges of the Voronoi cells of the fcc lattice), or + ``custom`` struts (``struts``: six fractional coordinates each). ``reinforcement`` + adds the four ``edges`` of the cube along ``reinforcement_axis``, or its ``axis`` + from face to face (bcc-z, fcc-z, reinforced octet and octahedral cells), and + ``curvature`` bends the struts inside the cell into circular arcs (the sagitta over + the length; the circular octahedron). Give the strut radius or the target relative density (solid volume fraction). With ``wall_thickness``, the struts are hollow tubes: their union minus the union of their bores (which join at the nodes). @@ -237,7 +351,8 @@ class StrutLattice(Model): cell: str = param( "octet", - doc="Unit cell: cubic, bcc, fcc, octet, kelvin, diamond or pyrochlore", + doc="Unit cell: cubic, bcc, fcc, octet, kelvin, diamond, pyrochlore, octahedral, " + "rhombic_dodecahedron or custom", kind="str", ) cell_size: float = param(1.0, doc="Edge of the cubic unit cell", unit="length") @@ -268,11 +383,54 @@ class StrutLattice(Model): gradient_axis: int = param( 0, doc="Axis of the gradient of the strut radius: 0, 1 or 2", kind="int" ) + struts: tuple | None = param( + None, + doc="Custom cell: its struts, each the fractional coordinates of its two ends " + "[x1, y1, z1, x2, y2, z2]", + kind="json", + ) + reinforcement: str | None = param( + None, + doc="Struts added along reinforcement_axis: 'edges' (the four edges of the cube) or " + "'axis' (through its centre, from face to face)", + kind="str", + ) + reinforcement_axis: int = param(2, doc="Axis of the reinforcement: 0, 1 or 2", kind="int") + curvature: float = param( + 0.0, + doc="Struts inside the cell bent into circular arcs: the sagitta over the length " + "(outward from the centre of the cell; inward if negative)", + ) + arc_segments: int = param(8, doc="Straight pieces of each curved strut", kind="int") anisotropy: Anisotropy | None = param(None, doc=ANISOTROPY, kind="anisotropy", kw_only=True) + @property + def spec(self) -> CellSpec: + """The specification of the cell (named or custom, reinforced, curved).""" + struts = () if self.struts is None else tuple(tuple(float(v) for v in s) + for s in self.struts) # fmt: skip + return CellSpec(self.cell, struts, self.reinforcement, self.reinforcement_axis, + float(self.curvature), int(self.arc_segments)) # fmt: skip + def _validate(self) -> None: - if self.cell not in CELLS: - raise ValueError(f"cell: expected one of {list(CELLS)}, got {self.cell!r}") + if self.cell not in (*CELLS, "custom"): + raise ValueError(f"cell: expected one of {[*CELLS, 'custom']}, got {self.cell!r}") + if self.cell == "custom": + if not self.struts: + raise ValueError("struts: the struts of the custom cell") + for strut in self.struts: + if len(strut) != 6: + raise ValueError("struts: six fractional coordinates per strut") + elif self.struts is not None: + raise ValueError("struts: only for a custom cell (cell: custom)") + if self.reinforcement is not None and self.reinforcement not in REINFORCEMENTS: + raise ValueError(f"reinforcement: one of {list(REINFORCEMENTS)}") + if self.reinforcement_axis not in (0, 1, 2): + raise ValueError("reinforcement_axis: 0, 1 or 2") + if not -0.5 < self.curvature < 0.5: + raise ValueError("curvature: the sagitta over the length, within (-0.5, 0.5)") + if self.arc_segments < 2: + raise ValueError("arc_segments: at least 2") check_positive(self.cell_size, "cell_size") if self.rotation is not None and len(self.rotation) != 3: raise ValueError("rotation: three Bunge angles (degrees)") @@ -316,13 +474,13 @@ def radius(self) -> float: if self.strut_radius is not None and self.volume_fraction is None: return self.strut_radius.moment(1) t = 0.0 if self.wall_thickness is None else self.wall_thickness / self.cell_size - return strut_radius(self.cell, float(self.volume_fraction), t) * self.cell_size + return strut_radius(_key(self.spec), float(self.volume_fraction), t) * self.cell_size @property def length_density(self) -> float: """Length of the struts per unit volume, each strut of the periodic lattice once.""" unit = Domain.cube(1.0, periodic=True) - start, end = lattice_struts(self.cell, 1.0, unit.lower, unit.upper) + start, end = lattice_struts(_key(self.spec), 1.0, unit.lower, unit.upper) start, end = periodic_struts(start, end, unit) return float(np.linalg.norm(end - start, axis=1).sum()) / self.cell_size**2 @@ -331,7 +489,8 @@ def _struts(self, domain: Domain) -> tuple[np.ndarray, np.ndarray]: a = self.cell_size margin = 0.0 if domain.periodic else a if self.rotation is None: - return lattice_struts(self.cell, a, domain.lower - margin, domain.upper + margin) + return lattice_struts(_key(self.spec), a, domain.lower - margin, + domain.upper + margin) # fmt: skip from morphogen.orientations import euler_to_matrix g = euler_to_matrix(np.asarray(self.rotation, dtype=float))[0] # lattice = g sample @@ -339,7 +498,7 @@ def _struts(self, domain: Domain) -> tuple[np.ndarray, np.ndarray]: corners = np.array([[box.lower[i] if c[i] == 0 else box.upper[i] for i in range(3)] for c in itertools.product((0, 1), repeat=3)]) # fmt: skip local = (corners - domain.center) @ g.T - start, end = lattice_struts(self.cell, a, local.min(axis=0), local.max(axis=0)) + start, end = lattice_struts(_key(self.spec), a, local.min(axis=0), local.max(axis=0)) return domain.center + start @ g, domain.center + end @ g def _radii(self, domain: Domain, start, end) -> np.ndarray: @@ -421,11 +580,12 @@ def theory(self, domain: Domain | None = None) -> dict[str, float]: # the local density along the gradient, averaged (Gauss-Legendre) x, w = np.polynomial.legendre.leggauss(6) r0, r1 = (r / self.cell_size for r in self.radius_gradient) - local = [strut_fraction(self.cell, float(r0 + (r1 - r0) * (1 + xi) / 2)) for xi in x] + cell = _key(self.spec) + local = [strut_fraction(cell, float(r0 + (r1 - r0) * (1 + xi) / 2)) for xi in x] return { "volume_fraction": float(np.dot(w, local) / 2.0), - "volume_fraction_lower": strut_fraction(self.cell, float(r0)), - "volume_fraction_upper": strut_fraction(self.cell, float(r1)), + "volume_fraction_lower": strut_fraction(cell, float(r0)), + "volume_fraction_upper": strut_fraction(cell, float(r1)), } if sizes.polydisperse(self.strut_radius): # the mean radius; thin struts if self.volume_fraction is not None: @@ -439,5 +599,5 @@ def theory(self, domain: Domain | None = None) -> dict[str, float]: r = self.radius / self.cell_size t = 0.0 if self.wall_thickness is None else self.wall_thickness / self.cell_size # solid struts on fine voxels, hollow ones on the voxels of the radius solve - fraction = strut_fraction(self.cell, r, t, None if t else 256) + fraction = strut_fraction(_key(self.spec), r, t, None if t else 256) return {"strut_radius": self.radius, "volume_fraction": fraction} diff --git a/tests/public_api.txt b/tests/public_api.txt index ba3792f..d448154 100644 --- a/tests/public_api.txt +++ b/tests/public_api.txt @@ -4135,12 +4135,17 @@ morphogen.models.laminate.RandomLaminate.generate(self, domain, seed=None) morphogen.models.laminate.RandomLaminate.period morphogen.models.laminate.RandomLaminate.theory(self, domain=None) morphogen.models.lattice.CELLS -morphogen.models.lattice.StrutLattice(cell='octet', cell_size=1.0, strut_radius=None, volume_fraction=None, wall_thickness=None, rotation=None, radius_gradient=None, gradient_axis=0, *, anisotropy=None) +morphogen.models.lattice.CellSpec(cell='octet', struts=(), reinforcement=None, axis=2, curvature=0.0, segments=8) +morphogen.models.lattice.CellSpec.plain +morphogen.models.lattice.REINFORCEMENTS +morphogen.models.lattice.StrutLattice(cell='octet', cell_size=1.0, strut_radius=None, volume_fraction=None, wall_thickness=None, rotation=None, radius_gradient=None, gradient_axis=0, struts=None, reinforcement=None, reinforcement_axis=2, curvature=0.0, arc_segments=8, *, anisotropy=None) morphogen.models.lattice.StrutLattice.expected_count(self, domain) morphogen.models.lattice.StrutLattice.generate(self, domain, seed=None) morphogen.models.lattice.StrutLattice.length_density morphogen.models.lattice.StrutLattice.radius +morphogen.models.lattice.StrutLattice.spec morphogen.models.lattice.StrutLattice.theory(self, domain=None) +morphogen.models.lattice.as_spec(cell) morphogen.models.lattice.lattice_fraction(cell, radius, n=None) morphogen.models.lattice.lattice_struts(cell, cell_size, lower, upper) morphogen.models.lattice.periodic_struts(start, end, domain) diff --git a/tests/test_lattice_families.py b/tests/test_lattice_families.py new file mode 100644 index 0000000..a40c330 --- /dev/null +++ b/tests/test_lattice_families.py @@ -0,0 +1,129 @@ +"""Strut lattices: the octahedral and rhombic dodecahedral cells, reinforcements along an +axis, curved struts and custom cells (theory.md §144).""" + +import math + +import numpy as np +import pytest + +import morphogen as mg +from morphogen.design.frames import Framework +from morphogen.models.base import Microstructure +from morphogen.models.lattice import ( + CellSpec, + StrutLattice, + lattice_struts, + periodic_struts, + strut_fraction, + unit_cell_struts, +) + + +def _length_per_cell(cell) -> float: + unit = mg.Domain.cube(1.0) + start, end = periodic_struts(*lattice_struts(cell, 1.0, unit.lower, unit.upper), unit) + return float(np.linalg.norm(end - start, axis=1).sum()) + + +def test_new_cells(): + """The octahedral cell (12 struts of length sqrt(2)/2, coordination 8, stretching- + dominated) and the rhombic dodecahedron (32 struts of length sqrt(3)/4 per cell, + coordination 4 and 8, bending-dominated); their lengths per cell and the fraction of + thin struts, pi r^2 L_V to first order.""" + octa = unit_cell_struts("octahedral") + assert len(octa) == 12 + assert np.allclose(np.linalg.norm(octa[:, 1] - octa[:, 0], axis=1), math.sqrt(0.5)) + rd = unit_cell_struts("rhombic_dodecahedron") + assert np.allclose(np.linalg.norm(rd[:, 1] - rd[:, 0], axis=1), math.sqrt(3.0) / 4.0) + assert _length_per_cell("octahedral") == pytest.approx(12 * math.sqrt(0.5)) + assert _length_per_cell("rhombic_dodecahedron") == pytest.approx(32 * math.sqrt(3.0) / 4.0) + rigid = Framework.lattice("octahedral", 2).rigidity() + assert rigid["coordination"] == pytest.approx(8.0) and rigid["stretching_dominated"] + floppy = Framework.lattice("rhombic_dodecahedron", 2).rigidity() + assert floppy["coordination"] == pytest.approx(16 / 3) and not floppy["stretching_dominated"] + r = 0.01 + for cell in ("octahedral", "rhombic_dodecahedron"): + thin = math.pi * r * r * _length_per_cell(cell) + assert strut_fraction(cell, r, 0.0, 256) == pytest.approx(thin, rel=0.1) + model = StrutLattice(cell=cell, volume_fraction=0.2) + image = model.generate(mg.Domain.cube(2.0), seed=1).voxelize(shape=96) + assert image.data.mean() == pytest.approx(0.2, abs=0.01) + + +def test_reinforcements(): + """The four edges of the cube along an axis add one edge per cell (each shared by four + cells), the axis through the centre one strut; a bcc-z lattice is stiffer along z than + across (its struts along z), and the radius of a fraction is solved with them.""" + bcc = _length_per_cell("bcc") + edges = CellSpec("bcc", reinforcement="edges", axis=2) + axis = CellSpec("octahedral", reinforcement="axis", axis=0) + assert _length_per_cell(edges) == pytest.approx(bcc + 1.0) + assert _length_per_cell(axis) == pytest.approx(_length_per_cell("octahedral") + 1.0) + struts = unit_cell_struts(axis) + along_x = struts[np.isclose(np.abs(struts[:, 1, 0] - struts[:, 0, 0]), 1.0)] + assert len(along_x) == 1 and np.allclose(along_x[0, :, 1:], 0.5) + model = StrutLattice(cell="fcc", volume_fraction=0.15, reinforcement="edges") + plain = StrutLattice(cell="fcc", volume_fraction=0.15) + assert model.radius < plain.radius # more struts for the same fraction + image = model.generate(mg.Domain.cube(2.0), seed=1).voxelize(shape=96) + assert image.data.mean() == pytest.approx(0.15, abs=0.01) + column = image.data[:, :, :].reshape(2, 48, 2, 48, 96)[:, :2, :, :2].mean() + assert column > 0.9 # the edges along z at the corners of the cells + + +def test_curved_struts(): + """Struts inside the cell bent into circular arcs: the pieces on the circle through + the ends, of the sagitta asked for, bulging away from the centre; the struts on the + faces and through the centre straight; a circular octahedron at a fraction.""" + spec = CellSpec("octahedral", curvature=0.2, segments=8) + pieces = unit_cell_struts(spec) + assert len(pieces) == 12 * 8 + straight = unit_cell_struts("octahedral") + p, q = straight[0] + arc = pieces[:8] + assert np.allclose(arc[0, 0], p) and np.allclose(arc[-1, 1], q) + length = np.linalg.norm(q - p) + middle = arc[3, 1] # the middle of the arc + m = 0.5 * (p + q) + assert np.linalg.norm(middle - m) == pytest.approx(0.2 * length, rel=1e-9) + assert np.linalg.norm(middle - 0.5) > np.linalg.norm(m - 0.5) # away from the centre + inward = unit_cell_struts(CellSpec("octahedral", curvature=-0.2)) + assert np.linalg.norm(inward[3, 1] - 0.5) < np.linalg.norm(m - 0.5) + on_faces = unit_cell_struts(CellSpec("fcc", curvature=0.2)) + assert len(on_faces) == len(unit_cell_struts("fcc")) + assert _length_per_cell(spec) > _length_per_cell("octahedral") + model = StrutLattice(cell="octahedral", volume_fraction=0.15, curvature=0.15) + image = model.generate(mg.Domain.cube(2.0), seed=1).voxelize(shape=96) + assert image.data.mean() == pytest.approx(0.15, abs=0.01) + + +def test_custom_cells_and_round_trip(): + """A custom cell of the struts of the octet is the octet; a custom cell of the cube + edges the cubic lattice; a reinforced curved lattice read back.""" + octet = unit_cell_struts("octet") + custom = StrutLattice(cell="custom", struts=[[*a, *b] for a, b in octet], volume_fraction=0.2) + assert custom.radius == pytest.approx(StrutLattice(cell="octet", volume_fraction=0.2).radius) + edges = [[0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1]] + cubic = StrutLattice(cell="custom", struts=edges, strut_radius=0.1) + a = cubic.generate(mg.Domain.cube(2.0), seed=1).voxelize(shape=48).data + b = StrutLattice(cell="cubic", strut_radius=0.1).generate(mg.Domain.cube(2.0), 1) + assert np.array_equal(a, b.voxelize(shape=48).data) + model = StrutLattice(cell="bcc", volume_fraction=0.2, reinforcement="edges", curvature=0.1) + micro = model.generate(mg.Domain.cube(2.0), seed=2) + back = Microstructure.from_dict(micro.to_dict()) + assert np.array_equal(back.voxelize(shape=32).data, micro.voxelize(shape=32).data) + + +def test_errors(): + with pytest.raises(ValueError, match="cell"): + StrutLattice(cell="truncated_cube", volume_fraction=0.2) + with pytest.raises(ValueError, match="struts"): + StrutLattice(cell="custom", volume_fraction=0.2) + with pytest.raises(ValueError, match="six"): + StrutLattice(cell="custom", struts=[[0, 0, 0, 1, 1]], volume_fraction=0.2) + with pytest.raises(ValueError, match="custom"): + StrutLattice(cell="octet", struts=[[0, 0, 0, 1, 1, 1]], volume_fraction=0.2) + with pytest.raises(ValueError, match="reinforcement"): + StrutLattice(cell="octet", reinforcement="diagonals", volume_fraction=0.2) + with pytest.raises(ValueError, match="curvature"): + StrutLattice(cell="octet", curvature=0.6, volume_fraction=0.2) From 5e92ec6ec440d81fb0c1fef31fc6f0933f5fd7ef Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 00:06:34 +0000 Subject: [PATCH 07/13] Bodies for additive manufacturing: tiling surfaces, layers of TPMS, 3MF, STEP MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The closed bodies of phases that share their interfaces and tile their box (mesh.surface.phase_surfaces: the functions at the nodes, faces included, mirrored about their level beyond them, the caps moved back onto the faces, coincident vertices merged); layers of TPMS (tpms_layers: phases of several materials in the bands of the levels of a surface or a network); io.printing: 3MF packages of several bodies with a base material each, STEP files (AP214) of solids (manifold solid breps of planar advanced faces bounded by shared edges, one per connected piece), read by OpenCascade as valid solids at their volumes, or of faceted shells; outputs.surface {formats: stl, 3mf, step; phases; unit} (theory notes §145, FR-G34, FR-E20, specification 1.259). Templates graded_tpms, spinodoid, hybrid, part and tpms_layers, with their cards and images in a gallery family Additive manufacturing; 53 models in the documentation; the public interface written again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MSrXEMpgnWPQNUwHwAgXHV --- CHANGELOG.md | 15 ++ README.md | 2 +- docs/_static/gallery/graded_tpms.png | Bin 0 -> 13541 bytes docs/_static/gallery/hybrid.png | Bin 0 -> 14634 bytes docs/_static/gallery/part.png | Bin 0 -> 7145 bytes docs/_static/gallery/spinodoid.png | Bin 0 -> 12591 bytes docs/_static/gallery/tpms_layers.png | Bin 0 -> 18760 bytes docs/api.md | 2 +- docs/architecture.md | 2 +- docs/configuration.md | 5 +- docs/gallery.md | 142 +++++++++- docs/gallery/make_gallery.py | 25 +- docs/guide.md | 2 +- docs/index.md | 2 +- docs/interop.md | 7 +- docs/models.md | 3 +- docs/specification.md | 7 +- docs/theory.md | 71 ++++- docs/tutorial_geometry.md | 2 +- docs/tutorial_interface.md | 2 +- src/morphogen/config.py | 30 ++- src/morphogen/gui/api.py | 2 +- src/morphogen/io/__init__.py | 13 +- src/morphogen/io/printing.py | 324 +++++++++++++++++++++++ src/morphogen/kernels/implicit.py | 23 ++ src/morphogen/mesh/distance.py | 14 +- src/morphogen/mesh/surface.py | 81 +++++- src/morphogen/models/__init__.py | 6 +- src/morphogen/models/tpms.py | 187 +++++++++++++ src/morphogen/pipeline.py | 48 +++- src/morphogen/templates/graded_tpms.yaml | 24 ++ src/morphogen/templates/hybrid.yaml | 22 ++ src/morphogen/templates/part.yaml | 25 ++ src/morphogen/templates/spinodoid.yaml | 22 ++ src/morphogen/templates/tpms.yaml | 5 +- src/morphogen/templates/tpms_layers.yaml | 24 ++ src/morphogen/viz/sections.py | 3 +- tests/public_api.txt | 32 ++- tests/test_models_base.py | 1 + tests/test_printing.py | 203 ++++++++++++++ 40 files changed, 1324 insertions(+), 54 deletions(-) create mode 100644 docs/_static/gallery/graded_tpms.png create mode 100644 docs/_static/gallery/hybrid.png create mode 100644 docs/_static/gallery/part.png create mode 100644 docs/_static/gallery/spinodoid.png create mode 100644 docs/_static/gallery/tpms_layers.png create mode 100644 src/morphogen/io/printing.py create mode 100644 src/morphogen/templates/graded_tpms.yaml create mode 100644 src/morphogen/templates/hybrid.yaml create mode 100644 src/morphogen/templates/part.yaml create mode 100644 src/morphogen/templates/spinodoid.yaml create mode 100644 src/morphogen/templates/tpms_layers.yaml create mode 100644 tests/test_printing.py diff --git a/CHANGELOG.md b/CHANGELOG.md index bcf1745..8946c26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,21 @@ ## Unreleased +* Bodies for additive manufacturing and CAD ([docs/theory.md](docs/theory.md) §145): + `outputs.surface: {formats: [stl, 3mf, step], phases: all, unit: millimeter}` writes + the closed bodies of the phases asked for, which share their interfaces and tile the + box (`morphogen.mesh.surface.phase_surfaces`: the functions at the nodes, faces + included, mirrored beyond them); one 3MF package with a material per body, for + multi-material printing (`morphogen.io.printing.write_3mf`, `read_3mf`); STEP files + (AP214) of solids, each connected piece a manifold solid of planar faces bounded by + shared edges, which OpenCascade reads as valid solids at their volumes, or of faceted + shells (`write_step`). Layers of TPMS (`tpms_layers`): phases of several materials in + the bands of the levels of a surface or a network. The closed surfaces merge the + vertices of their caps (one vertex where they meet). Templates `graded_tpms`, + `spinodoid`, `hybrid`, `part` and `tpms_layers`, and a family *Additive manufacturing* + in the gallery. Public interface: `TPMSLayers`, `TPMSLayersStructure`, + `morphogen.io.printing`, `morphogen.mesh.surface.phase_surfaces`, `node_grid` and + `merge_vertices`, the keyword `caps` of `surface_mesh`. * Strut lattices ([docs/theory.md](docs/theory.md) §144): the cells `octahedral` (the octahedra of the face centres, stretching-dominated) and `rhombic_dodecahedron` (the Voronoi cells of the fcc lattice, bending-dominated); `reinforcement: edges` or `axis` diff --git a/README.md b/README.md index 4e68b7e..c74045f 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ A study follows one chain, and each step is a part of the package: | Step | What morphoGen does | |---|---| -| **Generate** | 52 models: Boolean models, packings, fibres, tessellations, Gaussian fields, dead leaves, automata and growths, spinodal decomposition, strut and plate lattices, foams, triply periodic surfaces, woven textiles, bio-inspired structures, images segmented into their phases; monodisperse or polydisperse; periodic or not, combined, nested; hierarchical structures of any models four or five levels deep, chains or trees (lattices of lattices or of tubes, tows of fibres in a porous resin, grains of lamellae); and the shapes of Microgen (3MAH) | +| **Generate** | 53 models: Boolean models, packings, fibres, tessellations, Gaussian fields, dead leaves, automata and growths, spinodal decomposition, strut and plate lattices, foams, triply periodic surfaces, woven textiles, bio-inspired structures, images segmented into their phases; monodisperse or polydisperse; periodic or not, combined, nested; hierarchical structures of any models four or five levels deep, chains or trees (lattices of lattices or of tubes, tows of fibres in a porous resin, grains of lamellae); and the shapes of Microgen (3MAH) | | **Describe** | an exact description of each realization (centres, axes, cells) and an implicit function for each phase, from which voxel images, surfaces and conforming meshes are cut at any resolution | | **Measure** | fractions, specific surface, covariance, chords, tortuosity, percolation thresholds, stereology..., each beside the closed form of its model when there is one; on the implicit geometry itself, exactly: the probes of mathematical morphology and the Minkowski functionals of unions of spheres; the model of an image or of a section identified among candidates | | **Compute** | elastic, thermal, electrical, dielectric, magnetic and diffusive properties, their couplings, harmonic regimes, the magnetization curves of saturating phases and the magnetostriction and stiffening in a field of magnetorheological elastomers, the magnetic domains of ferromagnets (micromagnetics: hysteresis loops and first-order reversal curves, their dynamics, their thermal fluctuations and their magnetostriction under stress), hierarchical structures homogenized level by level and the buckling of their levels (the walls of their tubes too), waves, flow and sound, thermo-chemo-elastic fields in time, periodic plates through their thickness (their stiffness of Kirchhoff and Love, their transverse shear by the bending gradient, their conductance and their bowing, the permeance and the inertance of perforated panels, the sound that panels let through, their guided waves and band gaps, prestressed too, the wrinkling and the dimpling of their faces, compressed or heated between fixed edges, their elastic limits and their collapse, and the panels of diff --git a/docs/_static/gallery/graded_tpms.png b/docs/_static/gallery/graded_tpms.png new file mode 100644 index 0000000000000000000000000000000000000000..89f0260e7fc0c3cfff3008834e12fdfde1839b3a GIT binary patch literal 13541 zcmd^mS2$c>6t5YK!RT$Y=z=Imi=ILdj9#K=5WV-#45CDfK1xWU*F=k+Otb_OT@WQo zNDxHt-1*<{zTAgadIt3XE836$Sg~sDY1_T6P zfPerr4<*Fc+&o0e;R`4|gpn$~I5^l>Sy{%W?y3^&EUxiQqZ?&|q z#|tJPkjT_{^w22i$M&nlfH~QQx|RwjD3}`hyyVXt`Fh&h+a(h@a=SM^>LmgRoMbYz zncD$2-+oB0_U_D%<+NWLA4T58QE}W0JN>uZ^M8H_%{}>fbIEi={V#ZR-y%Egdi(w< z33_Df>Nn2~zM;xFY3}FWHr5|D;;w6tE&Q}kEf@bR_bly=e1+Z1kug}@C2i*q)A20n zj5}QQbaMD7*E#kQ6Q#5>D!pvjIp*PsUF$*D>Atgv++hA4t=pdj*>cAPo1LU8-LsXA zes`dj`WHupLVW!Au_rE0DOU3Iy3y_le?%Db-oF1=tsG}ZjPs|Hd8eaowZ3*1ZeM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z0FKO-7bsP_?JlP~&)1ZVLXzRb_qc#4qX z7Bbu>XWc|bQ~E23-$Y3z*>Fdyl|*w6p7Iv^wAkl# z*_k2xJVr9D>}e@O8u3DiZQ+}l>It%6|Ale3v=@AuRV2$rJTBjo@&@w+{7GgcQ2U|w z_7xLpcc0`VMn~geQn8RaF^LMbB#)b3Br2;H@}fKjx9ku*@5)dSU@6r8YG zgr6Zi9^rptD0!$xPS8k#PWwO;QYZCcdMy#;Yxd1TtHQE}D5Usw_tU5FdEc(HuOcEU zcMH|&28IYS#t&E=RlIdI(vSZnuQ2B>l>1r6)*oS}9=BwGo?H^6ytmESGq3Pky(@V$ z8=(^`F4nwJ*q{8@z;CPk6i*i)=Re+XmnX(|xlV9(n!2n3R2(<3VDD$5v8DEH2HV;c z37yBMa9NrLIboEqL%sN#|cH z;^IY?uCaUy$8^$t#Rw%=uX~U4tI3~xq+9W6Q-Ug_ zaEm$6pg=~ieq7NgHLE?+PBz23HXgsrRcNe0Id?%PX|03S7`Dqh@nN%XIq%lb@JW~U zP$TiqXherQ+i3HVroc(M%rn+QwOzgf=kF$G4jaTcCu8=I;z&u!5B+ExvAhW5?6)!@ zam%pDu)|KFJEN>!jb8nuvi}rl<-b2`!VVh7Z5$^SshxC(DCVty6Rm=TQgjW`6-MRTvi z_1qT<3*ia#a2QUGW`rNAohnMYM}YC~KBBxFI#fMl#CoNVE*KB&BEo literal 0 HcmV?d00001 diff --git a/docs/_static/gallery/hybrid.png b/docs/_static/gallery/hybrid.png new file mode 100644 index 0000000000000000000000000000000000000000..156dabd27ffa5847a50668416fbab9c157d45e4e GIT binary patch literal 14634 zcmd^mRa_iT@aHZIEV^jWMFRv2E{i(^f`lM}U<(9y*T51qIKiDjAb|kET^4tD4est1 zIDY?oy~q39%hkhtrhBTor@N}Vzg0E!^_{8$E*1qA006*Md?WiF06^ga0Dy}apy!$= zDY(#c0r5^*Q|`Ig-`};rzgbvR09CLjfqmf8a<8bZV`gDV%r9qDvULhc3JDF?c8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}f=58`aXYKs@LgP!LW6VR@BLOG^$h;3A zfR;?s@g(R523*UB%dcK%3MUWaGu0BA%gJ(_w#l3T-w(%0>&qOeA}Nni{>*8dWYK~+ wO%^gc*sTy{<+hT5qx1IvGqy5nGVr?n9}+Ks4gdfE literal 0 HcmV?d00001 diff --git a/docs/_static/gallery/spinodoid.png b/docs/_static/gallery/spinodoid.png new file mode 100644 index 0000000000000000000000000000000000000000..b6a4f072ca6b24b5a2cbe42ddc579d78a2c0d3e0 GIT binary patch literal 12591 zcmd^lS3KO&)Az2`Euyd9g=ov_UBZeQUG&v^uTfX@-ec8ZbwPyaWR)nfqK61VB#7ul ziT3)x&&_l5zE{uPb1r^!&YbU=GxPh+ne+MlW)gLE)JTaLhyefqsrpkDeE)y4uKXZJMSJ~tok^qyCG6~F>UHEbjXH#P%-y%c6RI> z8WT2uDPtF3*E#5sR34I3Yhq&Di|JcgTm7-I5|L3{Tv}3ARy;7!i$GXKMMYS7hnKwV z5fv3tQc_ezgxxFlzoD7N{+YP96X~z7V*t4OzYY0cCeoKJS|*-glH(GWGC|7^5 z-d`ed9UEJd2@}!2%Dtwl{4F}SJ;>5@?fz+>14dT{m#r^p3iG(|x)-j?NvXGF`j1m| zHd35}vhv(}(L`2`zm2xqNzFbH4}p~gDr>njo$95oZmbT59Grxg z)TcIl`h{R4D9YonyiHDxzO9>vM2)*8uc~fsydB(`isBiV&r*>h!`aqxmVA~{@+-zkuRGer zS=3JZ=6bajPuIqgul80rQQ`P)U;o877}NN_;*cQg(@Je?hwK+xSN#DDcj_*?GpV@z z!x8V&RCHrzWp+*oeE|uJ5}Xg*y}tF~G$ogFT(T~MdjQ>I$K9Dr^{B0FL@hFnX zH9dcNQ7#TvZGh&19Vj47<-r{XK>|i@+LD%m>yG!%BP#9+ss7|r5?56g%d2fuuV>yq zIo^(v)UA4M`)NK&&9U!sYQ%Gr&Rj(y^7BI;v9;=2P^Vb@{Tb1zf*T5LCcZQ5=^8m} z`oTz0t&c7ie1;jfQ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G{O_4|1D54o+A8Bun zWNOkO-T<-gls-h#vl4P?J+Fch?l;JPLUnrEGZm3cre#s@0TP=UJX z${3j9Hx{)o^P%s}fxO)lFv=!E74uu6s@df~g?)A97|OA3c&uUXYW<%$)3&8vDJ92qp{opVA1@fh20s)653w%#oAGv+(+8n1Ept6u%+MHeltP~61`~Ww|xilW$=U!y^xuDspa=c;j5_T{goY4cTH=A zl$|1TR@z9pQL5)gWWOfZY5&bS)}C^n*Nk)4(~Sx8Y(!1GE7--B5K+#c>gLAejJ*8w zx&}V2l^;ljx~FG@^p5yEb$ViMRX0TUYCC)6pDAywf&Mdhx{m!Gk5Lg%atq-&B(a;&{`(6M4rRU|UvduS&Lnc-Lad_#||CG+F MtLmsUK1RI!KVu>N#Q*>R literal 0 HcmV?d00001 diff --git a/docs/_static/gallery/tpms_layers.png b/docs/_static/gallery/tpms_layers.png new file mode 100644 index 0000000000000000000000000000000000000000..f2c1ddbd5d59d7db84857788bfe0d4d12bb7b6b1 GIT binary patch literal 18760 zcmd42Ra9J0^zYeC<1WG7gE#IZxJz&gG!UF1!8MJ0aA+KYLxKkh)&z$JfSiQ~$$AdaRbD@>)q|g1T~9M$&kMkC3o%vyGvq_Q%2I+FxHnUs?^k*GNf8 z+?^eJN&87lR)qKs{%YT7suI$2U+}ik6y(jbGU~4?E-TFGEy^nSXju{)y0^X z=ilo6X<(oi6CG}6XXEYd(cIiHH#fPB=vn_>xR#qJBL5!pM!rnr?Yyhm2Z&jCaA2{T zl)H|u3^&Kyw{LiPd4t~w#5h{Vd%4nr-@M%5|DUh7T^PbI^MiV5Yv=%;|IY>eKdJwn zc>9v*`rn!Vr~m({^#AFWYcvVJ000Wt%5u`WK7Wn^eLw#hZ2CxtL@6&LLpQ|NxB(Cn zB0CgOF5|xlIBwhNIC&1vV-}dMt#ZhS12O1bdq0aTH>Kcm_?tQ&8Pp*7$0g4HUw_(Z z?^fDx`yS|Fk%3+9?p^sE{#H+P2-yyATaB_Qx1|+vA{&H`ZP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RWFEGh>Gh2I)jX}#WU`TY z=9y=ndFGjCo_Xe(XP$ZHnP;AP=9y=ndFGjCo_Xe(XP$ZH{owci0c@X!gpio&tpET3 M07*qoM6N<$f^y%J6#xJL literal 0 HcmV?d00001 diff --git a/docs/api.md b/docs/api.md index 6733c00..b96283c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -20,7 +20,7 @@ the steps of a study: | Step | Package | What it holds | |---|---|---| -| Generate | [`morphogen.models`](api/morphogen.models.rst) | the 52 models of microstructures and the shapes of Microgen (3MAH), their realizations and their theory | +| Generate | [`morphogen.models`](api/morphogen.models.rst) | the 53 models of microstructures and the shapes of Microgen (3MAH), their realizations and their theory | | | [`morphogen.automata`](api/morphogen.automata.rst) | cellular automata and lattice growth processes, on grids and tilings | | | [`morphogen.design`](api/morphogen.design.rst) | tile assemblies, strut frameworks and their rigidity, searches of design spaces | | | [`morphogen.optimization`](api/morphogen.optimization.rst) | topology optimization of periodic cells by inverse homogenization, and the inverse design of active structures | diff --git a/docs/architecture.md b/docs/architecture.md index cc1770a..d02ab62 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1362,7 +1362,7 @@ style. | `test_conforming.py` | MMG meshes: tiling, mirrored meshes of symmetric cells (exact symmetries, matching faces, the group of a 2 x 2 array of holes), volume fractions, exact faces, matching periodic faces and exact PBC, porous lattices, exports (VTU, INP, MSH, Medit) and readers | | `test_iga.py` | B-spline functions against the recurrence of Cox and de Boor, their derivatives and the embeddings of their refinements; exact arcs, refined patches and assemblies; the patch test (plane strain, plane stress, a solid); Lamé's thick-walled cylinder (orders 3 and 2, 4 and 3) and Kirsch's plate with a hole; the effective tensors of a homogeneous cell, of a laminate (elasticity, conduction) and of a cell with a hole, against the curved finite elements of the solid (slow); cells of any lattice (other cuts of the same cell, strips with gaps, a cell and its neighbour), the square and hexagonal arrays of holes against the series of Perrins et al. and the isotropy of the hexagonal one, the sheet with alternating holes (exact fraction, symmetries of the square, the square array with circles, Poisson's ratio against the ligaments; against the FFT solver, slow) | | `test_iga_optimization.py` | the design and its geometries (linear maps, symmetric radial variables); the analytical shape derivatives of the tensor and of the fraction of a cell (elasticity, conduction) and of the compliance and the area of a structure against central differences; the hole of largest bulk modulus against the bound of Hashin and Shtrikman (Vigdergauz; SLSQP and MMA); the hole of a plate under biaxial tension against the ellipse (slow); folded designs and the history of the kept iterates; variables linked by the symmetries of a pattern (images and directions, periods, derivatives, errors); the holes of an auxetic sheet found again from their effective constants; its lowest Poisson's ratio at a given stiffness, with linear constraints | -| `test_implicit.py` | the implicit geometry of every model: for the 52 models, the shapes of Microgen and 19 other configurations of several phases, an implicit function of each phase whose sign is that of the voxel image on two grids and which partition the points; the Menger sponge on the grid of its cubes, two cells and their boundary layer against their planes, leaves and a transparent leaf against their spheres; the interpolation on the background mesh; the conforming mesh of a coated sphere (three phases cut one after the other: volumes, matching faces, the phases kept, finite elements against the FFT solver), cells of three phases meshed by their grains, coated hard spheres (slow) | +| `test_implicit.py` | the implicit geometry of every model: for the 53 models, the shapes of Microgen and 19 other configurations of several phases, an implicit function of each phase whose sign is that of the voxel image on two grids and which partition the points; the Menger sponge on the grid of its cubes, two cells and their boundary layer against their planes, leaves and a transparent leaf against their spheres; the interpolation on the background mesh; the conforming mesh of a coated sphere (three phases cut one after the other: volumes, matching faces, the phases kept, finite elements against the FFT solver), cells of three phases meshed by their grains, coated hard spheres (slow) | | `test_radioss.py` | the inputs of OpenRadioss read back card by card against the columns of the Radioss Reference Guide (units, nodes, bricks and tetrahedra oriented for Radioss, their mid-side nodes on their edges, parts, the solid property, LAW1, LAW36 with its yield curves at the rates of Norton's viscosity, LAW2, node groups, held and driven faces, the anchor of free faces, a shear, an impact on a rigid wall, the self contact, the time histories and their sampling, the Engine input, the length scale); the model (units, materials, loadings, time steps); the listings, time histories and legacy VTK grids (ASCII and binary, classic and VTK 5.1) | | `test_dynamics.py` | the installation of OpenRadioss found (the paths, the environment, the permissions restored), runs with a stand-in of OpenRadioss (`fake_openradioss.py`): the curves of a bar against its modulus, the forces from the time history or the animations, the frames for the 3D view, a shear, an impact, the failures of the Starter, the stops, the conversions; a release installed from a GitHub API served locally (the archive of each system, no member leaving its folder); the command line | | `test_gui_tools_dynamics.py` | the tab Explicit dynamics: the inputs written without OpenRadioss (engineering units, the materials of the fields and of the JSON), the errors, a dynamic test with the stand-in (its summary in MPa and MJ/m³, the curves in morphoGen's components compared with another run, the 3D view of its last frame), the results read back, the installation found, an impact | diff --git a/docs/configuration.md b/docs/configuration.md index 58fb4bc..8f7c76c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -87,7 +87,10 @@ outputs: # dual: the flow through the mesh on its polyhedral dual, # velocity: the flow periodic along the axis at this filtration # velocity, convection: linear | linearUpwind} - surface: [stl] + surface: [stl] # or {formats: [stl, 3mf, step], phases: all | [0, 1], unit: + # millimeter}: the closed bodies of the phases asked for, which + # share their interfaces and tile the box; 3MF (one file, a + # material per body) and STEP (a solid per connected piece) database: null # SQLite file recording the run and its results (results.py) tables: [txt, xlsx] # the tables of the run in these formats too (besides .csv) shell_section: true # the homogenized plate of each realization as a section of Abaqus' diff --git a/docs/gallery.md b/docs/gallery.md index e331ee0..1889fc5 100644 --- a/docs/gallery.md +++ b/docs/gallery.md @@ -1308,9 +1308,9 @@ morphogen run level_set_foam.yaml :::: -## TPMS +## TPMS and spinodoids -Triply periodic minimal surfaces, as sheets or networks (the stiffness of the gyroid is under Linear homogenization). +Triply periodic minimal surfaces, as sheets or networks (the stiffness of the gyroid is under Linear homogenization), and the stochastic spinodoids. ::::{container} gallery @@ -1340,6 +1340,32 @@ morphogen run tpms.yaml ::: +:::{container} gallery-card +:name: gallery-spinodoid + +```{image} _static/gallery/spinodoid.png +:alt: spinodoid +:loading: lazy +``` + +**`spinodoid`** — A cubic spinodoid: the level of a sum of 1000 waves of one wavelength within cones of 30° about the axes (Kumar et al. 2020), at 40 %, its specific surface against Rice's formula. + +*Needs scikit-image (extra `surface`).* + +```bash +morphogen template spinodoid -o spinodoid.yaml +morphogen run spinodoid.yaml +``` + +

Configuration + +```{literalinclude} ../src/morphogen/templates/spinodoid.yaml +:language: yaml +``` + +
+::: + :::{container} gallery-card :name: gallery-microgen @@ -1366,6 +1392,118 @@ morphogen run microgen.yaml :::: +## Additive manufacturing + +Architectures made into parts: graded and blended, filling shapes with walls and skins, in layers of several materials, written as STL, 3MF and STEP. + +::::{container} gallery + +:::{container} gallery-card +:name: gallery-graded-tpms + +```{image} _static/gallery/graded_tpms.png +:alt: graded_tpms +:loading: lazy +``` + +**`graded_tpms`** — A sheet of Schoen's I-WP graded from 10 % to 40 % relative density along z, each height at the level of its fraction, written as STL and as a STEP solid. + +*Needs scikit-image (extra `surface`).* + +```bash +morphogen template graded_tpms -o graded_tpms.yaml +morphogen run graded_tpms.yaml +``` + +
Configuration + +```{literalinclude} ../src/morphogen/templates/graded_tpms.yaml +:language: yaml +``` + +
+::: + +:::{container} gallery-card +:name: gallery-hybrid + +```{image} _static/gallery/hybrid.png +:alt: hybrid +:loading: lazy +``` + +**`hybrid`** — A gyroid sheet that turns into a Schwarz P sheet along a beam, the two blended across its middle by a sigmoid (Yang et al. 2014). + +*Needs scikit-image (extra `surface`).* + +```bash +morphogen template hybrid -o hybrid.yaml +morphogen run hybrid.yaml +``` + +
Configuration + +```{literalinclude} ../src/morphogen/templates/hybrid.yaml +:language: yaml +``` + +
+::: + +:::{container} gallery-card +:name: gallery-part + +```{image} _static/gallery/part.png +:alt: part +:loading: lazy +``` + +**`part`** — A sandwich beam ready to print: a gyroid core between skins, with solid supports at its ends, written as STL and as a STEP solid (cylinders, tubes, spheres and closed surfaces of one's own are filled alike). + +*Needs scikit-image (extra `surface`).* + +```bash +morphogen template part -o part.yaml +morphogen run part.yaml +``` + +
Configuration + +```{literalinclude} ../src/morphogen/templates/part.yaml +:language: yaml +``` + +
+::: + +:::{container} gallery-card +:name: gallery-tpms-layers + +```{image} _static/gallery/tpms_layers.png +:alt: tpms_layers +:loading: lazy +``` + +**`tpms_layers`** — A composite of three materials in the layers of a gyroid: the closed bodies of the three phases share their surfaces and tile the box, in one 3MF file for multi-material printing and as STEP solids. + +*Needs scikit-image (extra `surface`).* + +```bash +morphogen template tpms_layers -o tpms_layers.yaml +morphogen run tpms_layers.yaml +``` + +
Configuration + +```{literalinclude} ../src/morphogen/templates/tpms_layers.yaml +:language: yaml +``` + +
+::: + +:::: + ## Automata and tilings Structures grown on lattices by local rules, and assemblies of building blocks. diff --git a/docs/gallery/make_gallery.py b/docs/gallery/make_gallery.py index 92279b0..2964d19 100644 --- a/docs/gallery/make_gallery.py +++ b/docs/gallery/make_gallery.py @@ -328,18 +328,39 @@ ], ), ( - "TPMS", + "TPMS and spinodoids", "Triply periodic minimal surfaces, as sheets or networks (the stiffness of the " - "gyroid is under Linear homogenization).", + "gyroid is under Linear homogenization), and the stochastic spinodoids.", [ ("tpms", "A sheet gyroid at 20 % relative density, with its watertight STL " "surface."), + ("spinodoid", "A cubic spinodoid: the level of a sum of 1000 waves of one " + "wavelength within cones of 30° about the axes (Kumar et al. 2020), at 40 %, " + "its specific surface against Rice's formula."), ("microgen", "A sheet of Schoen's I-WP surface built by " "[Microgen](https://github.com/3MAH/microgen) (3MAH), which morphoGen calls: " "any shape of Microgen with a field (TPMS, spinodoids, primitives) is taken as " "a model (needs the package microgen; cite Microgen when you use it)."), ], ), + ( + "Additive manufacturing", + "Architectures made into parts: graded and blended, filling shapes with walls and " + "skins, in layers of several materials, written as STL, 3MF and STEP.", + [ + ("graded_tpms", "A sheet of Schoen's I-WP graded from 10 % to 40 % relative " + "density along z, each height at the level of its fraction, written as STL and " + "as a STEP solid."), + ("hybrid", "A gyroid sheet that turns into a Schwarz P sheet along a beam, the " + "two blended across its middle by a sigmoid (Yang et al. 2014)."), + ("part", "A sandwich beam ready to print: a gyroid core between skins, with " + "solid supports at its ends, written as STL and as a STEP solid (cylinders, " + "tubes, spheres and closed surfaces of one's own are filled alike)."), + ("tpms_layers", "A composite of three materials in the layers of a gyroid: the " + "closed bodies of the three phases share their surfaces and tile the box, in one " + "3MF file for multi-material printing and as STEP solids."), + ], + ), ( "Automata and tilings", "Structures grown on lattices by local rules, and assemblies of building blocks.", diff --git a/docs/guide.md b/docs/guide.md index 0377503..6c92d74 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -10,7 +10,7 @@ questions. | Step | Page | What it covers | |---|---|---| -| Generate | [Models of microstructures](models.md) | the 52 models by family and the shapes of Microgen, their anisotropy, their sizes (monodisperse or polydisperse), automata and growth, nested and bio-inspired models | +| Generate | [Models of microstructures](models.md) | the 53 models by family and the shapes of Microgen, their anisotropy, their sizes (monodisperse or polydisperse), automata and growth, nested and bio-inspired models | | Describe | [Geometry, voxels and meshes](geometry.md) | exact descriptions, implicit functions, voxel images, conforming meshes, symmetric cells | | Measure | [Measures and theory](measures.md) | the closed forms of the models, the measures of images, percolation, crystallographic textures | | Compute | [The library of materials](library.md) | the materials of the phases by their names — metals, crystals, ceramics, glasses, polymers, elastomers, fibres, fluids —, their values, sources and units; materials of one's own | diff --git a/docs/index.md b/docs/index.md index 70a0bb5..ba2fb34 100644 --- a/docs/index.md +++ b/docs/index.md @@ -39,7 +39,7 @@ package, a command line and a graphical interface in the web browser; free softw ::::{container} card **[Generate](models.md)** -52 models of random and architected media: Boolean models, packings, fibres, +53 models of random and architected media: Boolean models, packings, fibres, tessellations, Gaussian fields, dead leaves, automata and growths, spinodal decomposition, strut and plate lattices, foams, triply periodic surfaces, woven textiles, bio-inspired structures, images segmented into their phases; periodic or not, combined, nested; diff --git a/docs/interop.md b/docs/interop.md index 6c53f07..ce6b243 100644 --- a/docs/interop.md +++ b/docs/interop.md @@ -49,7 +49,12 @@ writer from the object and the suffix of the file. Code_Aster (`morphogen mfront`), checked against morphoGen's own kernels; the user's own MFront laws go to AMITEX and Abaqus inputs too, in small or finite strains (every phase an MFront law then, Hencky's elasticity for the elastic ones). -* Watertight STL surfaces for additive manufacturing. +* Watertight surfaces for additive manufacturing and CAD (`outputs.surface`, + `morphogen.io.printing`, [theory notes](theory.md) §145): STL; the bodies of several + phases, which share their interfaces and tile the box (`phases: all`), as one 3MF + package with a material per body for multi-material printing; and STEP files (AP214) of + solids, each connected piece a manifold solid of planar faces bounded by shared edges, + read as solids by OpenCascade (FreeCAD) at the volumes of their surfaces. * Particles for the discrete element method (`morphogen.io.dem`, `export(..., particles=k)`, `morphogen export --particles k`): one phase without its matrix, a closed surface per particle (STL solids or files, OBJ objects, VTU), whole across diff --git a/docs/models.md b/docs/models.md index 19cd11f..96a3d42 100644 --- a/docs/models.md +++ b/docs/models.md @@ -4,7 +4,7 @@ A model holds the parameters of a random set or of a deterministic architecture, closed-form characteristics of the set when they exist (`model.theory()`: volume fraction, specific surface, covariance, integral range...). `model.generate(domain, seed)` draws one realization of it in a box, periodic or not; the same seed gives the -same realization. morphoGen has 52 models, listed below by family, and takes the shapes of +same realization. morphoGen has 53 models, listed below by family, and takes the shapes of [Microgen](https://github.com/3MAH/microgen) (3MAH) through the model `microgen` ([below](#shapes-of-microgen)): `morphogen models` lists them, `morphogen models ` gives the parameters of one, and the @@ -73,6 +73,7 @@ What a realization is made of, and how it becomes images and meshes, is the subj | Model | Description | |---|---| | `tpms` | Ten surfaces: gyroid, Schwarz P and D, Neovius, Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P and I2-Y; the network on either side of the surface or the sheet, at a level, a volume fraction or a profile of the fraction along an axis (graded TPMS, [theory notes](theory.md) §140) | +| `tpms_layers` | Layers of a TPMS for composites of several materials: the bands of the levels of a surface (the sheet, then the layers on both of its sides) or of a network, at given volume fractions, whose closed bodies tile the box ([theory notes](theory.md) §145) | | `spinodoid` | Spinodoids (Kumar et al. 2020): the level of a sum of waves of one wavelength in random directions, isotropic or within cones about the axes (lamellar, columnar, cubic), network, sheet or the other network, at a fraction or graded; periodic in periodic boxes; their specific surface by Rice's formula ([theory notes](theory.md) §141) | | `strut_lattice` | Cubic, BCC, FCC, octet, Kelvin, diamond, pyrochlore, octahedral and rhombic dodecahedral lattices, or cells of one's own struts, with solid or hollow struts; reinforced along an axis (bcc-z, fcc-z), curved struts (circular octahedra, [theory notes](theory.md) §144); rotated and functionally graded lattices (non-periodic samples); their sections meshed in the plane by their exact contours | | `plate_lattice` | Plate lattices: closed cells walled by plates on the closest-packed planes of the cubic lattices, the {100} (`cubic`), {110} (`bcc`) and {111} (`fcc`, the octet plates) planes and their mixtures (Berger et al. 2017; Tancogne-Dejean et al. 2018), of a thickness or an exact relative density, in the ratio of an isotropic stiffness at low density (`isotropic`, which reaches the Hashin–Shtrikman bounds); turned, shifted and graded; the exact density and specific surface, the stiffness of the membranes at low density, exact meshes of their convex pieces ([below](#plate-lattices)) | diff --git a/docs/specification.md b/docs/specification.md index 8cc9130..758dcc6 100644 --- a/docs/specification.md +++ b/docs/specification.md @@ -3,7 +3,7 @@ | | | |---|---| | Document | Software requirements specification | -| Version | 1.258 | +| Version | 1.259 | | Date | 2026-12-01 | | Author | @jdirr | | Status | Version 1.1 **validated** on 2026-10-21. The later versions, proposed, are listed in the change log (§13); changes go through pull requests that update this file and its change log. | @@ -368,6 +368,8 @@ centred on morphological modelling. | Delivered | FR-G32 (`part`, `mesh.distance`, `tpms` `cells_around`, [theory.md](theory.md) §143): `shape` box, cylinder, tube, sphere or mesh (`mesh`, `fit`, `resolution`), `shell`, `skins` and `supports` along their axes, the function of the part a maximum and minima of signed distances; the distance to a closed surface exact near it (Ericson's closest points), its inside by the parity of the columns; the cells of a TPMS wrapped around an axis | | Additive manufacturing: strut lattices (2026-12-01) | The families of Top6Meta's strut module (octahedral, reinforced, circular) and of the literature on printed lattices (bcc-z, fcc-z, rhombic dodecahedron). | | Delivered | FR-G33 (`strut_lattice` `cell: octahedral`, `rhombic_dodecahedron`, `custom` with `struts`, `reinforcement`, `curvature`, `CellSpec`, [theory.md](theory.md) §144): the two cells, their rigidity in the frames; reinforcements `edges` and `axis`; circular arcs of a sagitta, outward or inward, in straight pieces; custom cells; the fractions solved for every cell | +| Additive manufacturing: bodies, 3MF and STEP (2026-12-01) | Multi-material parts and the files of slicers and CAD programs, beyond Top6Meta's STL and faceted STEP. | +| Delivered | FR-G34, FR-E20 (`tpms_layers`, `mesh.surface.phase_surfaces`, `io.printing`, `outputs.surface: {formats, phases, unit}`, [theory.md](theory.md) §145): the bodies of the phases tiling the box (nodes with the faces, mirrored padding, merged vertices); layers of TPMS; 3MF with base materials; STEP solids (AP214, `MANIFOLD_SOLID_BREP` of planar `ADVANCED_FACE`s) read by OpenCascade as valid solids at their volumes, or faceted shells | ## 4. Scope @@ -448,6 +450,7 @@ version, 0.1). | FR-G31 | Hybrid architectures: two models with implicit functions blended across a plane, a cylinder or a sphere by a sigmoid of the distance to it, their bounded functions mixed continuously; a bound of the slope of the blend | S | 1d | | FR-G32 | Parts ready to print: any two-phase model filling a box, a cylinder, a tube, a sphere or a closed surface read from a file, with a shell along its boundary, the skins of a sandwich and the supports of a beam; the signed distance to closed triangle surfaces; TPMS whose cells wrap around an axis (conformal TPMS) | S | 1d | | FR-G33 | Strut lattices: the octahedral and rhombic dodecahedral cells, struts added along an axis (the edges of the cube or its axis), struts curved into circular arcs, custom cells of struts given by their ends | S | 1d | +| FR-G34 | Layers of a TPMS: phases of several materials in the bands of the levels of a surface or a network, at given volume fractions, their implicit functions | S | 1d | ### 5.2 Representations @@ -506,6 +509,7 @@ version, 0.1). | FR-E17 | VIMSEO: the computations of morphoGen as its models (configurations, exact morphological densities with their closed forms as references), for the verification of the code and of the solutions, the validation, the uncertainties and the calibration (optional dependency, Python 3.10 to 3.12) | C | 3d | | FR-E18 | Meshes of the plane: triangular meshes (three or six nodes) of the structures invariant across a plane, the exact polygons of the tessellations of coplanar germs (columnar grains) graded from their small features, the sections of any structure in a plane, matching periodic sides; the plane elements of Abaqus and CalculiX, Gmsh, VTK and Medit files read back | S | 3d | | FR-E19 | Forchheimer's law through OpenFOAM: the flows through the pores periodic along their axis and driven to a filtration velocity at finite Reynolds numbers, run by OpenFOAM, and the laws of the weak inertia and of Forchheimer fitted to them (`morphogen openfoam forchheimer`); verified with OpenFOAM itself where it is installed | S | 1d | +| FR-E20 | Bodies for additive manufacturing and CAD: the closed surfaces of the phases asked for, which share their interfaces and tile their box; 3MF packages of several bodies, a material per body; STEP files of solids (manifold solid boundary representations) or faceted shells | S | 1d | ### 5.6 Interfaces @@ -1439,6 +1443,7 @@ Packages: `models`, `kernels`, `analysis`, `rve`, `mesh`, `homogenization`, `io` | 1.256 | 2026-12-01 | Hybrid architectures: two models blended across a plane, a cylinder or a sphere (FR-G31, §3.12) | | 1.257 | 2026-12-01 | Parts ready to print: shapes, shells, skins, supports, closed surfaces from files, conformal TPMS (FR-G32, §3.12) | | 1.258 | 2026-12-01 | Strut lattices: octahedral and rhombic dodecahedral cells, reinforcements, curved struts, custom cells (FR-G33, §3.12) | +| 1.259 | 2026-12-01 | Bodies that tile their box, layers of TPMS, 3MF and STEP (FR-G34, FR-E20, §3.12) | ## 14. References diff --git a/docs/theory.md b/docs/theory.md index 7bc995e..5d47fc3 100644 --- a/docs/theory.md +++ b/docs/theory.md @@ -22,7 +22,7 @@ them by these numbers (§75); by theme: | Behaviours along loading paths | [§31](#31-nonlinear-behaviours-along-loading-paths-the-periodic-element) Nonlinear behaviours along loading paths: the periodic element, [§32](#32-crystal-plasticity-homogenizationcrystal) Crystal plasticity, [§33](#33-finite-strains-homogenizationfinite) Finite strains, [§34](#34-loading-paths-on-voxel-images-the-nonlinear-fft-solver-homogenizationfft_nonlinear) Loading paths on voxel images: the nonlinear FFT solver, [§36](#36-mfront-behaviours-homogenizationmfront) MFront behaviours, [§37](#37-mfront-sources-of-morphogens-behaviours-iomfront) MFront sources of morphoGen's behaviours, [§43](#43-the-nonuniform-transformation-field-analysis-homogenizationntfa) The nonuniform transformation field analysis, [§49](#49-porous-plasticity-gurson-tvergaard-needleman-rousselier-compaction-homogenizationporous) Porous plasticity: Gurson-Tvergaard-Needleman, Rousselier, compaction, [§50](#50-micromorphic-continua-the-microfoam-model-and-micromorphic-damage-micromorphic) Micromorphic continua: the microfoam model and micromorphic damage, [§53](#53-identification-of-a-behaviour-homogenizationidentification) Identification of a behaviour, [§54](#54-hills-anisotropic-plasticity-homogenizationbehaviours) Hill's anisotropic plasticity, [§57](#57-behaviours-learned-from-data-learning) Behaviours learned from data, [§61](#61-viscoelasticity-hyperelasticity-and-damage-homogenizationlaws) Viscoelasticity, hyperelasticity and damage, [§83](#83-damage-coupled-to-plasticity-of-concrete-and-the-unilateral-effect-homogenizationlaws) Damage: coupled to plasticity, of concrete, and the unilateral effect, [§86](#86-twinning-of-crystals-and-hexagonal-lattices-homogenizationcrystal) Twinning of crystals, and hexagonal lattices, [§89](#89-cracks-that-close-twins-that-shear-back-and-turn-the-lattice-homogenizationcrystal) Cracks that close, twins that shear back and turn the lattice | | Fracture, contact and fatigue | [§46](#46-cohesive-zone-elements-fracturecohesive) Cohesive zone elements, [§47](#47-cracks-conforming-meshes-and-xfem-fracturelefm) Cracks: conforming meshes and XFEM, [§48](#48-mixed-mode-cracks-in-3d-in-small-and-finite-strains-fracturemixed) Mixed-mode cracks in 3D, in small and finite strains, [§51](#51-cracks-in-inelastic-solids-in-small-and-finite-strains-fracturebulk) Cracks in inelastic solids, in small and finite strains, [§64](#64-phase-field-of-brittle-fracture-fracturephasefield) Phase field of brittle fracture, [§73](#73-cracks-of-any-surface-and-front-fracturesurface) Cracks of any surface and front, [§81](#81-friction-of-interfaces-and-of-the-lips-of-cracks-fracturecohesive-fracturemixed) Friction of interfaces and of the lips of cracks, [§82](#82-contact-of-surfaces-self-contact-and-friction-contact) Contact of surfaces, self-contact and friction, [§84](#84-interfaces-that-debond-in-periodic-cells-fractureperiodic) Interfaces that debond in periodic cells, [§85](#85-multiaxial-high-cycle-fatigue-of-the-points-of-a-cell-homogenizationfatigue) Multiaxial high-cycle fatigue of the points of a cell, [§87](#87-cleavage-of-crystals-cracks-through-the-grains-and-between-them-homogenizationcrystal-fractureperiodic) Cleavage of crystals; cracks through the grains and between them, [§88](#88-cleavage-by-the-local-approach-the-weibull-stress-of-beremin-homogenizationberemin) Cleavage by the local approach: the Weibull stress of Beremin, [§90](#90-cleavage-that-the-slip-nucleates-homogenizationcrystal) Cleavage that the slip nucleates, [§91](#91-cleavage-planes-regularized-by-their-microdamage-homogenizationcrystal) Cleavage planes regularized by their microdamage | | Stability of periodic architectures | [§45](#45-post-bifurcated-patterns-by-group-theory-symmetry-homogenizationframes) Post-bifurcated patterns by group theory, [§128](#128-periodic-plates-their-local-buckling-homogenizationplate_buckling) Periodic plates: their local buckling, [§130](#130-periodic-plates-their-thermal-and-hygral-buckling-homogenizationplate_buckling) Periodic plates: their thermal and hygral buckling, [§132](#132-panels-of-homogenized-plates-homogenizationpanels) Panels of homogenized plates | -| Other codes and libraries | [§99](#99-arrays-of-other-libraries-and-phase-fields-for-spectral-solvers-interoparrays) Arrays of other libraries and phase fields for spectral solvers, [§100](#100-the-particles-of-a-phase-for-the-discrete-element-method-iodem-modelsmesh_particles) The particles of a phase for the discrete element method, [§101](#101-microgen-modelsmicrogen-interopmicrogen) Microgen, [§102](#102-rigid-bodies-of-blender-interopblender) Rigid bodies of Blender, [§103](#103-alloys-from-their-phases-to-their-microstructures-interopalloys) Alloys: from their phases to their microstructures, [§111](#111-code_aster-and-openfoam-the-meshes-the-conditions-and-the-cases-written-iocode_aster-ioopenfoam) Code_Aster and OpenFOAM: the meshes, the conditions and the cases written, [§112](#112-the-credibility-of-the-simulations-with-vimseo-interopvimseo) The credibility of the simulations with VIMSEO, [§126](#126-the-library-of-materials-its-units-and-the-checks-of-its-values-library) The library of materials: its units and the checks of its values, [§139](#139-forchheimers-law-the-inertia-of-the-flow-through-the-pores-by-openfoam-ioopenfoamforchheimer) Forchheimer's law: the inertia of the flow through the pores, by OpenFOAM | +| Other codes and libraries | [§99](#99-arrays-of-other-libraries-and-phase-fields-for-spectral-solvers-interoparrays) Arrays of other libraries and phase fields for spectral solvers, [§100](#100-the-particles-of-a-phase-for-the-discrete-element-method-iodem-modelsmesh_particles) The particles of a phase for the discrete element method, [§101](#101-microgen-modelsmicrogen-interopmicrogen) Microgen, [§102](#102-rigid-bodies-of-blender-interopblender) Rigid bodies of Blender, [§103](#103-alloys-from-their-phases-to-their-microstructures-interopalloys) Alloys: from their phases to their microstructures, [§111](#111-code_aster-and-openfoam-the-meshes-the-conditions-and-the-cases-written-iocode_aster-ioopenfoam) Code_Aster and OpenFOAM: the meshes, the conditions and the cases written, [§112](#112-the-credibility-of-the-simulations-with-vimseo-interopvimseo) The credibility of the simulations with VIMSEO, [§126](#126-the-library-of-materials-its-units-and-the-checks-of-its-values-library) The library of materials: its units and the checks of its values, [§139](#139-forchheimers-law-the-inertia-of-the-flow-through-the-pores-by-openfoam-ioopenfoamforchheimer) Forchheimer's law: the inertia of the flow through the pores, by OpenFOAM, [§145](#145-bodies-for-additive-manufacturing-surfaces-that-tile-their-box-layers-of-tpms-3mf-and-step-meshsurface-ioprinting) Bodies for additive manufacturing: surfaces that tile their box, layers of TPMS, 3MF and STEP | | Laser-architectured sheets | [§58](#58-architectured-sheets-by-localized-laser-treatment-laser) Architectured sheets by localized laser treatment, [§74](#74-a-treated-sheet-in-its-volume-lasersolid) A treated sheet in its volume | ## 1. Boolean models @@ -16865,6 +16865,68 @@ ends, of the sagitta asked for, outward and inward, the struts on the faces left a circular octahedron at its fraction; a custom octet equal to the octet, a custom cube to the cubic lattice voxel for voxel, a reinforced curved lattice read back; the errors. +## 145. Bodies for additive manufacturing: surfaces that tile their box, layers of TPMS, 3MF and STEP (`mesh.surface`, `io.printing`) + +**Bodies that tile the box.** A part printed in several materials is a set of closed +bodies that share their interfaces exactly. Marching cubes (Lorensen & Cline 1987) on the +implicit function of each phase gives the same interface points to complementary +functions ($\varphi$ and $-\varphi$ cross zero at the same point of each edge), but the +caps that close each body at the faces of the box do not match: on the voxel centres, the +crossing of an edge from the last centre to a padding far outside lies near the centre, +and each body joins its interface to the face by its own oblique wall (the solid and the +void of a sheet gyroid on $32^3$ voxels add up to 0.993 of the box). +`phase_surfaces` samples the functions at the nodes of the grid, the faces of the box +included (`node_grid`: $n + 1$ centres from face to face), pads them by the mirror +$\ell + |\varphi - \ell|$ about the level $\ell$ — the crossing of the padded edges half a +cell out of the faces, on the side of the body only — moves those crossings back onto the +faces, drops the walls it flattens and merges the vertices that meet. The caps of +complementary bodies are then the two sides of the same zero curves on each face, and +the bodies tile the box: closed (each edge of two triangles), their volumes adding up to +the box within $10^{-12}$, their interior vertices the same (sheet and network TPMS, an +octet lattice). Layers with more than two phases tile it within the resolution of their +thinnest layers. + +**Layers of a TPMS** (`tpms_layers`). With the variable $v$ of the variant ($\varphi$, +$|\varphi|$ or $-\varphi$, §140) and the fractions $f_k$ of the layers, the bounds +$t_k = F_v^{-1}(f_1 + \dots + f_k)$ (the quantiles of $v$ over the cell) make the phase +$k$ the band $t_{k-1} < v \le t_k$ ($t_0 = -\infty$) and the phase 0 the rest $v > t_n$ +(none when the fractions add up to 1): from a sheet, the sheet and then the layers on both +of its sides (Top6Meta's layered composites of 2 to 9 layers); from a network, the network +and the layers around it. The function of the band $k$ is the first-order distance +$\max(t_{k-1} - v,\ v - t_k)/|\nabla\varphi|$, and adjacent bands share their zero sets. + +**3MF** (3MF Consortium, core specification 1.3). A ZIP package of three parts (the +content types, the relationships, the model `3D/3dmodel.model`), the model a resource of +base materials (one per body: its name and display colour) and an object of type `model` +per body, its vertices and triangles (counter-clockwise seen from outside) and its +material (`pid`, `pindex`), each placed in the build; the unit of the coordinates is the +model's (`millimeter` by default). A slicer prints each body in its own material. + +**STEP** (ISO 10303-21 and the schema of AP214, `AUTOMOTIVE_DESIGN`). Each body a +product (product, formation, definition, shape) and a shape representation in a context of +length units (`SI_UNIT(.MILLI.,.METRE.)`). `kind="solid"` (the default) writes each +connected piece of a body (its faces joined by their vertices) as a +`MANIFOLD_SOLID_BREP`: a `CLOSED_SHELL` of `ADVANCED_FACE`s, each a `PLANE` (through its +first vertex, along its outward normal) bounded by an `EDGE_LOOP` of three +`ORIENTED_EDGE`s, each `EDGE_CURVE` (a `LINE` between two `VERTEX_POINT`s) shared by the +two faces of the edge; `kind="faceted"`, lighter, writes `FACETED_BREP`s of +`FACE_SURFACE`s bounded by `POLY_LOOP`s of shared points, which readers take as shells. +OpenCascade 7.8 (the kernel of FreeCAD and of Top6Meta's STEP export) reads the solids +as valid solids at the volumes of their surfaces within $10^{-9}$: the three pieces of a +gyroid sheet cut by its box, its void, an octet lattice of 63 168 faces — where Top6Meta +writes the shell of its STL and no STEP of its strut lattices. + +Validated in `tests/test_printing.py`: the solid and the complement of a sheet gyroid, of +the network of an I-WP and of an octet lattice, closed, their volumes adding up to the box +within $10^{-12}$, the same interior vertices; the nodes of a grid; the layers of a gyroid +(fractions within 0.01, the bands, the functions of the three phases negative exactly on +their voxels and at points, the three bodies tiling the box within $10^{-3}$, read back); +a 3MF package of two bodies, its parts, names, colours, unit and meshes read back; the +STEP files of the two kinds, their entities (an `EDGE_CURVE` per edge), the faceted bodies +read back at their volumes; OpenCascade's solid of an octet lattice (where `cadquery-ocp` +is installed); the surfaces of a run: the STL of the solid by default, the bodies of every +phase as STL, 3MF and STEP, the errors of the configuration. + ## References See [specification.md](specification.md#14-references). In addition: @@ -18041,3 +18103,10 @@ See [specification.md](specification.md#14-references). In addition: hybridization CAD design of minimal surface porous structures for use in tissue engineering. *Comput.-Aided Des.* 56, 11–21. * Ericson, C. (2005). *Real-Time Collision Detection*. Morgan Kaufmann, San Francisco. +* Lorensen, W. E., Cline, H. E. (1987). Marching cubes: a high resolution 3D surface + construction algorithm. *Comput. Graph.* 21, 163–169. +* 3MF Consortium (2022). *3D Manufacturing Format, core specification and reference + guide*, version 1.3. +* ISO 10303-21 (2016). *Industrial automation systems and integration — Product data + representation and exchange — Part 21: Implementation methods: clear text encoding of + the exchange structure*. diff --git a/docs/tutorial_geometry.md b/docs/tutorial_geometry.md index cd61ef6..79ed260 100644 --- a/docs/tutorial_geometry.md +++ b/docs/tutorial_geometry.md @@ -63,7 +63,7 @@ print(level.data.dtype, bool(((level.data < 0) == (image.data == 2)).all())) mg.io.save_image(level, "interphase.vti") # for ParaView: its zero level is the interface ``` -Every model has such functions — the 52 models, the shapes of Microgen, their combinations, coatings, nested and +Every model has such functions — the 53 models, the shapes of Microgen, their combinations, coatings, nested and transformed structures: distances to unions of spheres and segments, differences of power distances to the germs of cells, the rings of osteons, the leaves of a dead-leaves model outside those that cover them ([theory notes](theory.md), §75). A structure of two diff --git a/docs/tutorial_interface.md b/docs/tutorial_interface.md index 155d234..bbbc91d 100644 --- a/docs/tutorial_interface.md +++ b/docs/tutorial_interface.md @@ -23,7 +23,7 @@ opens its menu (where to send it, its 3D view, a new title), its cross **×** (o middle click) closes it — **Undo** beside the strip brings it back for a few seconds; its files stay in the folder of the session either way. -In *Create › Generate*, the menu lists the 52 models and the shapes of Microgen by family (the filter above it +In *Create › Generate*, the menu lists the 53 models and the shapes of Microgen by family (the filter above it finds one by a word of its name or of its summary). Choose `boolean_spheres`: its form opens filled with its template; set the radius to 1, the volume fraction to 0.2, the size of the domain to 10 and the seed to 1, then **Generate** (or `Ctrl + Enter`, which diff --git a/src/morphogen/config.py b/src/morphogen/config.py index a9fb050..f3305bc 100644 --- a/src/morphogen/config.py +++ b/src/morphogen/config.py @@ -37,7 +37,7 @@ from morphogen.models.base import Model, get_model, model_from_config from morphogen.rve.study import TENSOR_PROPERTIES -SURFACE_FORMATS = ("stl",) +SURFACE_FORMATS = ("stl", "3mf", "step") MESH_FORMATS = ("inp", "msh", "vtu", "xdmf", "med", "mesh", "mail") HOMOGENIZATION_METHODS = ("auto", "fe", "fft", "xfem", "levels") #: Formats of the tables of a run besides .csv (outputs.tables), of the figures and the @@ -217,6 +217,11 @@ class OutputSpec: periodic_pairs: bool = False periodic_equations: bool = False surface: list[str] = field(default_factory=list) + #: the phases whose bodies the surfaces are ("all", or a list), or None (the phase 1 + #: of two phases, each phase but the last of more) + surface_phases: list[int] | str | None = None + #: the unit of the coordinates of 3MF and STEP files + surface_unit: str = "millimeter" damask: bool = False neper: bool = False database: Path | None = None @@ -917,6 +922,25 @@ def _outputs(data, base: Path) -> OutputSpec: "shell_section", } _check_keys("outputs", data, allowed) + surface = data.get("surface") + surface_phases, surface_unit = None, "millimeter" + if isinstance(surface, dict): + _check_keys("outputs.surface", surface, {"formats", "phases", "unit"}) + surface_phases = surface.get("phases") + surface_unit = str(surface.get("unit", "millimeter")) + surface = surface.get("formats", ["stl"]) + if surface_phases is not None and surface_phases != "all": + if isinstance(surface_phases, (str, int)) or not all( + isinstance(k, int) and 0 <= k <= 255 for k in surface_phases + ): + raise ConfigError("outputs.surface.phases: 'all' or a list of phases") + surface_phases = [int(k) for k in surface_phases] + from morphogen.io.printing import UNITS_3MF, UNITS_STEP + + if surface_unit not in UNITS_3MF: + raise ConfigError(f"outputs.surface.unit: one of {list(UNITS_3MF)}") + if "step" in surface and surface_unit not in UNITS_STEP: + raise ConfigError(f"outputs.surface.unit: for STEP, one of {list(UNITS_STEP)}") mesh = data.get("mesh") phases = None if isinstance(mesh, dict): @@ -949,7 +973,9 @@ def _outputs(data, base: Path) -> OutputSpec: periodic_equations=bool(data.get("periodic_equations", False)), damask=bool(data.get("damask", False)), neper=bool(data.get("neper", False)), - surface=_list_of("outputs.surface", data.get("surface"), SURFACE_FORMATS), + surface=_list_of("outputs.surface", surface, SURFACE_FORMATS), + surface_phases=surface_phases, + surface_unit=surface_unit, database=database, tables=[ t for t in _list_of("outputs.tables", data.get("tables"), TABLE_FORMATS) if t != "csv" diff --git a/src/morphogen/gui/api.py b/src/morphogen/gui/api.py index 1a615d4..d24f0bb 100644 --- a/src/morphogen/gui/api.py +++ b/src/morphogen/gui/api.py @@ -196,7 +196,7 @@ def examples() -> dict[str, dict]: ), "Lattices and TPMS": ( "strut_lattice", "plate_lattice", "random_lattice", "hierarchical_lattice", - "scale_rich_network", "tpms", "spinodoid", "fractal_sponge", "microgen", + "scale_rich_network", "tpms", "tpms_layers", "spinodoid", "fractal_sponge", "microgen", ), "Bio-inspired": ("nacre", "bouligand", "osteons"), "Growth and patterns": ( diff --git a/src/morphogen/io/__init__.py b/src/morphogen/io/__init__.py index d11071b..e8939d9 100644 --- a/src/morphogen/io/__init__.py +++ b/src/morphogen/io/__init__.py @@ -175,14 +175,19 @@ def load_image(path, name: str | None = None) -> VoxelImage: def save_mesh(mesh, path, **options) -> Path: - """A mesh written to a file whose extension gives the format: a surface mesh as .stl, a - tetrahedral mesh as .inp, .msh, .vtu, .mesh, .xdmf (FEniCSx) or .mail (Code_Aster), a - triangular mesh of the plane as .inp, .msh, .vtu or .mesh, a voxel mesh as .inp, .msh or - .vtu, and any of them in the other formats of meshio.""" + """A mesh written to a file whose extension gives the format: a surface mesh as .stl, + .3mf or .step (:mod:`morphogen.io.printing`), a tetrahedral mesh as .inp, .msh, .vtu, + .mesh, .xdmf (FEniCSx) or .mail (Code_Aster), a triangular mesh of the plane as .inp, + .msh, .vtu or .mesh, a voxel mesh as .inp, .msh or .vtu, and any of them in the other + formats of meshio.""" ext = _ext(path) if isinstance(mesh, SurfaceMesh): if ext == "stl": return write_stl(path, mesh, **options) + if ext in ("3mf", "step", "stp"): + from morphogen.io.printing import write_3mf, write_step + + return (write_3mf if ext == "3mf" else write_step)(path, mesh, **options) return write_meshio(path, mesh) if isinstance(mesh, TriMesh): writers = {"inp": write_inp_tri, "msh": write_msh_tri, "vtu": write_vtu_tri, diff --git a/src/morphogen/io/printing.py b/src/morphogen/io/printing.py new file mode 100644 index 0000000..ea0dc2c --- /dev/null +++ b/src/morphogen/io/printing.py @@ -0,0 +1,324 @@ +"""Files for additive manufacturing and CAD: 3MF (bodies of several materials in one file) +and STEP (faceted boundary representations). + +3MF (3MF Consortium, core specification 1.3): a ZIP package whose model +(``3D/3dmodel.model``) lists the vertices and triangles of each body (an ``object`` of type +``model``, its triangles counter-clockwise seen from outside) and a base material per body +(name and display colour), so that a slicer prints each body with its own material; the +unit of the coordinates is the model's (millimetres by default). + +STEP (ISO 10303-21, the schema AUTOMOTIVE_DESIGN of AP214): each body a faceted boundary +representation (``FACETED_BREP``: a closed shell of planar faces bounded by poly-loops), +within the product structure that CAD programs read (product, definition, shape +representation in a context of length units). +""" + +from __future__ import annotations + +import io as _io +import re +import zipfile +from datetime import UTC, datetime +from pathlib import Path +from xml.etree import ElementTree + +import numpy as np + +from morphogen.mesh.surface import SurfaceMesh + +_CORE = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02" +_CONTENT_TYPES = """ + + + + +""" +_RELS = """ + + + +""" +#: Display colours of the bodies, in turn (navy, red, green, gold, violet, grey). +COLORS = ("#1F4E79", "#D6604D", "#199E70", "#E0A526", "#7B5EA7", "#8C8C8C") +#: The units of 3MF files. +UNITS_3MF = ("micron", "millimeter", "centimeter", "inch", "foot", "meter") +#: The units of length of STEP files and their prefixes (SI_UNIT). +UNITS_STEP = {"millimeter": ".MILLI.", "meter": "$", "centimeter": ".CENTI.", + "micron": ".MICRO."} # fmt: skip + + +def _bodies(bodies) -> list[tuple[str, SurfaceMesh]]: + """The bodies as (name, surface) pairs: a surface, a list of surfaces or of pairs, or + a mapping of names to surfaces.""" + if isinstance(bodies, SurfaceMesh): + return [("body", bodies)] + if isinstance(bodies, dict): + return [(str(k), v) for k, v in bodies.items()] + out = [] + for k, item in enumerate(bodies): + if isinstance(item, SurfaceMesh): + out.append((f"body {k + 1}", item)) + else: + name, surface = item + out.append((str(name), surface)) + return out + + +def write_3mf(path, bodies, *, unit: str = "millimeter", colors=None) -> Path: + """Bodies (closed surfaces) written as one 3MF package, each body an object of its own + base material (named as the body, of the display colours ``colors`` or + :data:`COLORS`).""" + if unit not in UNITS_3MF: + raise ValueError(f"unit: one of {', '.join(UNITS_3MF)}") + items = _bodies(bodies) + colors = list(colors) if colors is not None else [COLORS[k % len(COLORS)] + for k in range(len(items))] # fmt: skip + out = _io.StringIO() + out.write('\n') + out.write(f'\n') + out.write(' morphoGen\n \n') + out.write(' \n') + for (name, _), color in zip(items, colors, strict=True): + hexa = color.upper() + ("FF" if len(color) == 7 else "") + out.write(f' \n') + out.write(" \n") + for k, (name, surface) in enumerate(items): + v = np.asarray(surface.vertices, dtype=float) + f = np.asarray(surface.faces, dtype=np.int64) + out.write(f' \n \n \n') # fmt: skip + out.write("".join(f' \n' + for x, y, z in v)) # fmt: skip + out.write(" \n \n") + out.write("".join(f' \n' for a, b, c in f)) + out.write(" \n \n \n") + out.write(" \n \n") + out.write("".join(f' \n' for k in range(len(items)))) + out.write(" \n\n") + path = Path(path) + with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as package: + package.writestr("[Content_Types].xml", _CONTENT_TYPES) + package.writestr("_rels/.rels", _RELS) + package.writestr("3D/3dmodel.model", out.getvalue()) + return path + + +def read_3mf(path) -> list[tuple[str, SurfaceMesh, str]]: + """The bodies of a 3MF package: (name, surface, display colour) for each object of + type ``model`` with a mesh.""" + with zipfile.ZipFile(path) as package: + root = ElementTree.fromstring(package.read("3D/3dmodel.model")) + ns = {"m": _CORE} + colors = [b.get("displaycolor", "") for b in root.iterfind(".//m:basematerials/m:base", ns)] + out = [] + for obj in root.iterfind(".//m:resources/m:object", ns): + mesh = obj.find("m:mesh", ns) + if mesh is None: + continue + v = np.array([[float(e.get(a)) for a in "xyz"] + for e in mesh.iterfind("m:vertices/m:vertex", ns)]) # fmt: skip + triangles = mesh.iterfind("m:triangles/m:triangle", ns) + f = np.array([[int(e.get(a)) for a in ("v1", "v2", "v3")] for e in triangles], + dtype=np.int64) # fmt: skip + index = int(obj.get("pindex", 0)) + out.append((obj.get("name", ""), SurfaceMesh(v, f), colors[index] if colors else "")) + return out + + +def _escape(text: str) -> str: + return (text.replace("&", "&").replace('"', """).replace("<", "<") + .replace(">", ">")) # fmt: skip + + +def _step_string(text: str) -> str: + """A string of a STEP file (ISO 10303-21: apostrophes doubled, ASCII).""" + ascii_text = text.encode("ascii", "replace").decode("ascii") + return "'" + ascii_text.replace("'", "''") + "'" + + +def _components(faces: np.ndarray, n_vertices: int) -> list[np.ndarray]: + """The faces of each connected piece of a surface (faces joined by their vertices).""" + from scipy.sparse import coo_matrix + from scipy.sparse.csgraph import connected_components + + m = len(faces) + rows = np.repeat(np.arange(m), 3) + graph = coo_matrix((np.ones(3 * m), (rows, faces.ravel())), shape=(m, n_vertices)) + adjacency = (graph @ graph.T).tocsr() + _, labels = connected_components(adjacency, directed=False) + return [np.flatnonzero(labels == k) for k in np.unique(labels)] + + +class _Step: + """The entities of a STEP file, numbered as they are added.""" + + def __init__(self): + self.lines: list[str] = [] + + def add(self, entity: str) -> int: + self.lines.append(entity) + return len(self.lines) + + def direction(self, d) -> int: + return self.add(f"DIRECTION('',({d[0]:.12g},{d[1]:.12g},{d[2]:.12g}))") + + def points(self, v: np.ndarray) -> int: + """The Cartesian points of the vertices; the number of the first.""" + first = len(self.lines) + 1 + self.lines.extend(f"CARTESIAN_POINT('',({x:.12g},{y:.12g},{z:.12g}))" for x, y, z in v) + return first + + def planes(self, v: np.ndarray, tri: np.ndarray, first: int) -> list[int]: + """The plane of each triangle: through its first vertex, normal to it (outward).""" + normal = np.cross(v[tri[:, 1]] - v[tri[:, 0]], v[tri[:, 2]] - v[tri[:, 0]]) + normal /= np.maximum(np.linalg.norm(normal, axis=1, keepdims=True), 1e-300) + ref = v[tri[:, 1]] - v[tri[:, 0]] + ref /= np.maximum(np.linalg.norm(ref, axis=1, keepdims=True), 1e-300) + out = [] + for f in range(len(tri)): + axis, x = self.direction(normal[f]), self.direction(ref[f]) + placement = self.add(f"AXIS2_PLACEMENT_3D('',#{first + tri[f, 0]},#{axis},#{x})") + out.append(self.add(f"PLANE('',#{placement})")) + return out + + def faceted(self, label: str, v, tri, geometry: int) -> int: + """A faceted boundary representation; its shape representation.""" + first = self.points(v) + planes = self.planes(v, tri, first) + faces = [] + for f, (a, b, c) in enumerate(tri): + loop = self.add(f"POLY_LOOP('',(#{first + a},#{first + b},#{first + c}))") + bound = self.add(f"FACE_OUTER_BOUND('',#{loop},.T.)") + faces.append(self.add(f"FACE_SURFACE('',(#{bound}),#{planes[f]},.T.)")) + shell = self.add("CLOSED_SHELL('',(" + ",".join(f"#{f}" for f in faces) + "))") + brep = self.add(f"FACETED_BREP({label},#{shell})") + return self.add(f"FACETED_BREP_SHAPE_REPRESENTATION({label},(#{brep}),#{geometry})") + + def solid(self, label: str, v, tri, geometry: int) -> int: + """A solid of planar faces bounded by loops of shared edges, per connected piece; + their shape representation.""" + first = self.points(v) + planes = self.planes(v, tri, first) + vertex = {} + for k in np.unique(tri): + vertex[int(k)] = self.add(f"VERTEX_POINT('',#{first + k})") + edges = np.sort(np.stack([tri[:, [0, 1]], tri[:, [1, 2]], tri[:, [2, 0]]], axis=1), + axis=2).reshape(-1, 2) # fmt: skip + unique, inverse = np.unique(edges, axis=0, return_inverse=True) + inverse = inverse.reshape(-1, 3) + curves = [] + for a, b in unique: + d = v[b] - v[a] + size = float(np.linalg.norm(d)) + vector = self.add(f"VECTOR('',#{self.direction(d / max(size, 1e-300))},{size:.12g})") + line = self.add(f"LINE('',#{first + a},#{vector})") + curves.append(self.add(f"EDGE_CURVE('',#{vertex[int(a)]},#{vertex[int(b)]}," + f"#{line},.T.)")) # fmt: skip + solids = [] + for piece in _components(tri, len(v)): + faces = [] + for f in piece: + oriented = [] + for side in range(3): + e = inverse[f, side] + sense = ".T." if unique[e][0] == tri[f, side] else ".F." + oriented.append(self.add(f"ORIENTED_EDGE('',*,*,#{curves[e]},{sense})")) + loop = self.add("EDGE_LOOP('',(" + ",".join(f"#{o}" for o in oriented) + "))") + bound = self.add(f"FACE_OUTER_BOUND('',#{loop},.T.)") + faces.append(self.add(f"ADVANCED_FACE('',(#{bound}),#{planes[f]},.T.)")) + shell = self.add("CLOSED_SHELL('',(" + ",".join(f"#{f}" for f in faces) + "))") + solids.append(self.add(f"MANIFOLD_SOLID_BREP({label},#{shell})")) + items = ",".join(f"#{s}" for s in solids) + return self.add(f"ADVANCED_BREP_SHAPE_REPRESENTATION({label},({items}),#{geometry})") + + +def write_step( + path, bodies, *, unit: str = "millimeter", name: str = "morphoGen", kind: str = "solid" +) -> Path: + """Bodies (closed surfaces) written as one STEP file (AP214). ``kind="solid"``: each + connected piece of a body a solid (``MANIFOLD_SOLID_BREP`` of planar ``ADVANCED_FACE`` + bounded by loops of shared edges and vertices: a closed shell that CAD programs read + as a solid); ``"faceted"``: a lighter shell of planar faces bounded by poly-loops of + shared points (``FACETED_BREP``), read as a shell.""" + if unit not in UNITS_STEP: + raise ValueError(f"unit: one of {', '.join(UNITS_STEP)}") + if kind not in ("solid", "faceted"): + raise ValueError("kind: 'solid' or 'faceted'") + step = _Step() + add = step.add + context = add("APPLICATION_CONTEXT('automotive design')") + add("APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000," + f"#{context})") # fmt: skip + product_context = add(f"PRODUCT_CONTEXT('',#{context},'mechanical')") + definition_context = add(f"PRODUCT_DEFINITION_CONTEXT('part definition',#{context},'design')") + length = add(f"(LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT({UNITS_STEP[unit]},.METRE.))") + angle = add("(NAMED_UNIT(*) PLANE_ANGLE_UNIT() SI_UNIT($,.RADIAN.))") + solid_angle = add("(NAMED_UNIT(*) SI_UNIT($,.STERADIAN.) SOLID_ANGLE_UNIT())") + uncertainty = add(f"UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-07),#{length}," + "'distance_accuracy_value','confusion accuracy')") # fmt: skip + geometry = add( + "(GEOMETRIC_REPRESENTATION_CONTEXT(3) GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT(" + f"(#{uncertainty})) GLOBAL_UNIT_ASSIGNED_CONTEXT((#{length},#{angle},#{solid_angle})) " + "REPRESENTATION_CONTEXT('Context #1','3D Context with UNIT and UNCERTAINTY'))" + ) + for body, surface in _bodies(bodies): + label = _step_string(body) + product = add(f"PRODUCT({label},{label},'',(#{product_context}))") + formation = add(f"PRODUCT_DEFINITION_FORMATION('','',#{product})") + definition = add(f"PRODUCT_DEFINITION('design','',#{formation},#{definition_context})") + shape = add(f"PRODUCT_DEFINITION_SHAPE('','',#{definition})") + v = np.asarray(surface.vertices, dtype=float) + tri = np.asarray(surface.faces, dtype=np.int64) + writer = step.solid if kind == "solid" else step.faceted + representation = writer(label, v, tri, geometry) + add(f"SHAPE_DEFINITION_REPRESENTATION(#{shape},#{representation})") + stamp = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S") + header = ( + "ISO-10303-21;\nHEADER;\n" + "FILE_DESCRIPTION(('morphoGen bodies'),'2;1');\n" + f"FILE_NAME({_step_string(Path(path).name)},'{stamp}',(''),('')," + f"{_step_string(name)},{_step_string(name)},'');\n" + "FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));\nENDSEC;\nDATA;\n" + ) + body_text = "".join(f"#{k + 1}={e};\n" for k, e in enumerate(step.lines)) + path = Path(path) + path.write_text(header + body_text + "ENDSEC;\nEND-ISO-10303-21;\n", encoding="ascii") + return path + + +_ENTITY = re.compile(r"#(\d+)=([A-Z_]+)\((.*)\);") + + +def read_step_bodies(path) -> list[tuple[str, SurfaceMesh]]: + """The faceted bodies of a STEP file written by :func:`write_step` (its own entities: + a check of the files, not a general reader).""" + entities = {} + for line in Path(path).read_text(encoding="ascii").splitlines(): + m = _ENTITY.match(line) + if m: + entities[int(m.group(1))] = (m.group(2), m.group(3)) + + def refs(text): + return [int(r) for r in re.findall(r"#(\d+)", text)] + + out = [] + for kind, args in entities.values(): + if kind != "FACETED_BREP": + continue + name = re.match(r"'((?:[^']|'')*)'", args).group(1).replace("''", "'") + shell = refs(args)[-1] + points: dict[int, int] = {} + coords, faces = [], [] + for face in refs(entities[shell][1]): + bound = refs(entities[face][1])[0] + loop = refs(entities[bound][1])[0] + tri = [] + for p in refs(entities[loop][1]): + if p not in points: + xyz = re.search(r"\(([^()]*)\)$", entities[p][1]).group(1) + points[p] = len(coords) + coords.append([float(c) for c in xyz.split(",")]) + tri.append(points[p]) + faces.append(tri) + out.append((name, SurfaceMesh(np.array(coords), np.array(faces, dtype=np.int64)))) + return out diff --git a/src/morphogen/kernels/implicit.py b/src/morphogen/kernels/implicit.py index 6b39fee..e7ea50a 100644 --- a/src/morphogen/kernels/implicit.py +++ b/src/morphogen/kernels/implicit.py @@ -294,6 +294,29 @@ def tpms_points(code, mode, levels, axis, lo, length, k, offset, frame, pts, out ) +@njit(parallel=True, cache=True) +def tpms_fields(code, k, offset, frame, grid_lo, spacing, shape, phi, grad): + """``phi`` and ``|grad phi|`` at voxel centres.""" + for i in prange(shape[0]): + x = grid_lo[0] + (i + 0.5) * spacing[0] + for j in range(shape[1]): + y = grid_lo[1] + (j + 0.5) * spacing[1] + for kk in range(shape[2]): + z = grid_lo[2] + (kk + 0.5) * spacing[2] + v, gx, gy, gz = _value_gradient(code, k, offset, frame, x, y, z) + phi[i, j, kk] = v + grad[i, j, kk] = math.sqrt(gx * gx + gy * gy + gz * gz) + + +@njit(parallel=True, cache=True) +def tpms_fields_points(code, k, offset, frame, pts, phi, grad): + """``phi`` and ``|grad phi|`` at points.""" + for p in prange(pts.shape[0]): + v, gx, gy, gz = _value_gradient(code, k, offset, frame, pts[p, 0], pts[p, 1], pts[p, 2]) + phi[p] = v + grad[p] = math.sqrt(gx * gx + gy * gy + gz * gz) + + @njit(parallel=True, cache=True) def tpms_cell_values(code, n, out): """``phi`` at the centres of an ``n^3`` grid of one period ``[0, 2 pi)^3``.""" diff --git a/src/morphogen/mesh/distance.py b/src/morphogen/mesh/distance.py index 9e71a41..2417816 100644 --- a/src/morphogen/mesh/distance.py +++ b/src/morphogen/mesh/distance.py @@ -20,7 +20,7 @@ from morphogen.domain import Grid from morphogen.kernels.meshes import surface_parity -from morphogen.mesh.surface import SurfaceMesh +from morphogen.mesh.surface import SurfaceMesh, merge_vertices #: Nodes about each triangle whose distance is exact. BAND = 3 @@ -102,15 +102,9 @@ def _band_distances(vertices, faces, origin, spacing, band, out): def merged(surface: SurfaceMesh, tolerance: float = 1e-9) -> SurfaceMesh: """The surface with its coincident vertices merged (within ``tolerance`` of the size - of its box) and its degenerate faces removed.""" - v = np.asarray(surface.vertices, dtype=float) - size = float(np.ptp(v, axis=0).max()) if len(v) else 1.0 - keys = np.round(v / (tolerance * max(size, 1e-300))).astype(np.int64) - _, first, inverse = np.unique(keys, axis=0, return_index=True, return_inverse=True) - faces = inverse.reshape(-1)[np.asarray(surface.faces, dtype=np.int64)] - a, b, c = faces[:, 0], faces[:, 1], faces[:, 2] - good = (a != b) & (b != c) & (a != c) - return SurfaceMesh(v[first], faces[good]) + of its box) and its degenerate faces removed (:func:`morphogen.mesh.surface. + merge_vertices`).""" + return merge_vertices(surface, tolerance) def is_closed(surface: SurfaceMesh) -> bool: diff --git a/src/morphogen/mesh/surface.py b/src/morphogen/mesh/surface.py index 0d43faa..f791c1e 100644 --- a/src/morphogen/mesh/surface.py +++ b/src/morphogen/mesh/surface.py @@ -6,6 +6,7 @@ import numpy as np +from morphogen.domain import Grid from morphogen.image import VoxelImage @@ -44,14 +45,27 @@ def _marching_cubes(): def surface_mesh( - image: VoxelImage, *, level: float = 0.0, phase: int = 1, closed: bool = True + image: VoxelImage, + *, + level: float = 0.0, + phase: int = 1, + closed: bool = True, + caps: str = "box", ) -> SurfaceMesh: """Surface of phase 1 from a level-set image (negative inside) or a phase image. Phase images (integers) and partial-volume images (floats named ``fraction``) are converted to ``0.5 - indicator``. With ``closed=True`` the solid is closed by caps on - the faces of the box (watertight surface, e.g. for additive manufacturing). + the faces of the box (watertight surface, e.g. for additive manufacturing). With + ``caps="centres"`` the image samples its box at the nodes of a grid that includes + the faces (the voxel centres of :func:`node_grid`): the caps lie on the planes of the + outer centres, the field mirrored about its level beyond them (the cap a half cell + out, moved back onto the planes), so that the closed surfaces of complementary + functions share their interfaces and their caps tile the faces: bodies that tile the + box. """ + if caps not in ("box", "centres"): + raise ValueError("caps: 'box' or 'centres'") marching_cubes = _marching_cubes() data = image.data if data.dtype.kind in "iub": @@ -69,7 +83,14 @@ def surface_mesh( field = np.where(field == level, np.float32(level + 1e-3 * max(scale, 1e-30)), field) spacing = np.asarray(image.spacing, dtype=float) origin = np.asarray(image.origin, dtype=float) + 0.5 * spacing - if closed: + if closed and caps == "centres": # mirrored: the crossing half a cell out of the planes + edge = np.pad(field, 1, mode="edge") + field = np.where(np.pad(np.zeros(field.shape, bool), 1, constant_values=True), + np.float32(level) + np.abs(edge - np.float32(level)), + edge).astype(np.float32) # fmt: skip + field = np.where(field == level, np.float32(level + 1e-3 * max(scale, 1e-30)), field) + origin = origin - spacing + elif closed: outside = np.float32(max(float(np.abs(field).max()), 1.0) + abs(level) + 1.0) field = np.pad(field, 1, mode="constant", constant_values=outside) origin = origin - spacing @@ -83,15 +104,63 @@ def surface_mesh( verts = verts + origin if closed: # cap vertices lie on edges joining the outer voxel centres to the padding: - # move them onto the faces of the box + # move them onto the faces of the box (or onto the planes of the outer centres) lower = np.asarray(image.origin, dtype=float) upper = lower + spacing * np.array(image.shape) first = lower + 0.5 * spacing last = upper - 0.5 * spacing eps = 1e-9 * spacing - verts = np.where(verts < first - eps, lower, verts) - verts = np.where(verts > last + eps, upper, verts) + low, high = (first, last) if caps == "centres" else (lower, upper) + verts = np.where(verts < first - eps, low, verts) + verts = np.where(verts > last + eps, high, verts) + if caps == "centres": # the walls between the planes and the caps flattened + v = verts[faces] + area = np.linalg.norm(np.cross(v[:, 1] - v[:, 0], v[:, 2] - v[:, 0]), axis=1) + faces = faces[area > 1e-12 * float(np.max(spacing)) ** 2] + used, faces = np.unique(faces, return_inverse=True) + verts, faces = verts[used], faces.reshape(-1, 3) mesh = SurfaceMesh(verts, faces.astype(np.int64)) + if closed: # the cap vertices moved onto the faces meet others: one vertex each + mesh = merge_vertices(mesh) + verts, faces = mesh.vertices, mesh.faces if mesh.volume() < 0: mesh = SurfaceMesh(verts, faces[:, ::-1].astype(np.int64)) return mesh + + +def merge_vertices(surface: SurfaceMesh, tolerance: float = 1e-9) -> SurfaceMesh: + """The surface with its coincident vertices merged (within ``tolerance`` of the size of + its box) and the faces that the merge makes degenerate removed.""" + v = np.asarray(surface.vertices, dtype=float) + if len(v) == 0: + return surface + size = float(np.ptp(v, axis=0).max()) + keys = np.round(v / (tolerance * max(size, 1e-300))).astype(np.int64) + _, first, inverse = np.unique(keys, axis=0, return_index=True, return_inverse=True) + faces = inverse.reshape(-1)[np.asarray(surface.faces, dtype=np.int64)] + a, b, c = faces[:, 0], faces[:, 1], faces[:, 2] + return SurfaceMesh(v[first], faces[(a != b) & (b != c) & (a != c)]) + + +def node_grid(grid: Grid) -> Grid: + """The grid whose voxel centres are the nodes of ``grid``, its faces included: ``n + 1`` + centres along each axis, from the lower to the upper face of its box.""" + from morphogen.domain import Domain + + lower = np.asarray(grid.origin, dtype=float) - 0.5 * np.asarray(grid.spacing) + size = np.asarray(grid.spacing) * (np.array(grid.shape) + 1) + domain = Domain(size=tuple(size), origin=tuple(lower), periodic=False) + return Grid(domain, tuple(int(n) + 1 for n in grid.shape)) + + +def phase_surfaces(micro, phases, grid: Grid) -> dict[int, SurfaceMesh]: + """The closed surfaces of phases of a realization that tile the box of ``grid``: the + implicit function of each phase at the nodes of the grid (:func:`node_grid`), meshed + with ``caps="centres"``. Adjacent phases share their interfaces, their caps tile the + faces of the box, and their volumes add up to its volume.""" + nodes = node_grid(grid) + out = {} + for k in phases: + field = micro.phase_level_set(int(k), grid=nodes) + out[int(k)] = surface_mesh(field, closed=True, caps="centres") + return out diff --git a/src/morphogen/models/__init__.py b/src/morphogen/models/__init__.py index ee926ab..f9e4fb0 100644 --- a/src/morphogen/models/__init__.py +++ b/src/morphogen/models/__init__.py @@ -24,6 +24,8 @@ ``gaussian_excursion`` Excursion set of a Gaussian random field ``tpms`` TPMS of ten surfaces (gyroid, Schwarz P/D, Neovius, I-WP, F-RD, Fischer-Koch S, lidinoid, split P, I2-Y): sheets, networks, graded +``tpms_layers`` Layers of a TPMS: bands of its levels, phases of several materials + (interpenetrating phase composites) ``spinodoid`` Spinodoids: levels of sums of waves of one wavelength in random directions or cones (Kumar et al. 2020), graded ``hybrid`` Two models blended across a plane, a cylinder or a sphere @@ -159,7 +161,7 @@ from morphogen.models.tessellation import Laguerre, Tessellation, Voronoi from morphogen.models.textile import TextileStructure, WovenTextile from morphogen.models.tiling_field import TilingField -from morphogen.models.tpms import TPMS, TPMSStructure +from morphogen.models.tpms import TPMS, TPMSLayers, TPMSLayersStructure, TPMSStructure from morphogen.models.transparent import TransparentDeadLeaves, TransparentDeadLeavesModel from morphogen.models.union import PrimitiveUnion @@ -246,6 +248,8 @@ "Spinodoid", "SpinodoidStructure", "StrutLattice", + "TPMSLayers", + "TPMSLayersStructure", "TPMSStructure", "Tessellation", "TextileStructure", diff --git a/src/morphogen/models/tpms.py b/src/morphogen/models/tpms.py index 8abe508..28de320 100644 --- a/src/morphogen/models/tpms.py +++ b/src/morphogen/models/tpms.py @@ -367,3 +367,190 @@ def theory(self, domain: Domain | None = None) -> dict[str, float]: if self.fraction_gradient is not None: return {"volume_fraction": self.mean_fraction()} return {"level": self.iso_level, "volume_fraction": self.solid_fraction()} + + +@register_kind +class TPMSLayersStructure(Microstructure): + """Layers of a TPMS: the phase ``k`` (1 to ``n``) the band ``t_{k-1} < v <= t_k`` of + the variable ``v`` of the variant (``phi``, ``|phi|`` or ``-phi``), the phase 0 beyond + ``t_n`` (see :class:`TPMSLayers`).""" + + kind = "tpms_layers" + + def __init__(self, domain, surface, variant, bounds, cell_size, **kwargs): + super().__init__(domain, **kwargs) + self.surface = surface + self.variant = variant + self.bounds = np.asarray(bounds, dtype=float) + self.cell_size = np.asarray(as_triplet(cell_size, "cell_size", positive=True)) + self._code = implicit.SURFACES[surface] + self._k = 2.0 * np.pi / self.cell_size + + def _variable(self, phi, grad): + v = np.abs(phi) if self.variant == "sheet" else (-phi if self.variant == + "upper_network" else phi) # fmt: skip + return v, np.maximum(grad, 1e-12) + + def _on_grid(self, grid: Grid): + phi = np.empty(grid.shape) + grad = np.empty(grid.shape) + shape = np.array(grid.shape, dtype=np.int64) + implicit.tpms_fields(self._code, self._k, self.domain.lower, np.zeros(6), grid.origin, + grid.spacing, shape, phi, grad) # fmt: skip + return self._variable(phi, grad) + + def _at(self, points): + pts = np.ascontiguousarray(points, dtype=float).reshape(-1, 3) + phi = np.empty(len(pts)) + grad = np.empty(len(pts)) + implicit.tpms_fields_points(self._code, self._k, self.domain.lower, np.zeros(6), pts, + phi, grad) # fmt: skip + return self._variable(phi, grad) + + def _phases(self, v) -> np.ndarray: + k = np.searchsorted(self.bounds, v, side="left") + 1 + return np.where(k > len(self.bounds), 0, k).astype(np.uint8) + + def _function(self, phase: int, v, g): + if phase == 0: + return (self.bounds[-1] - v) / g + upper = v - self.bounds[phase - 1] + if phase == 1: + return upper / g + return np.maximum(self.bounds[phase - 2] - v, upper) / g + + def implicit_phases(self) -> list[int]: + return list(range(len(self.bounds) + 1)) + + def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1): + grid = self.grid(shape, voxel_size=voxel_size, grid=grid) + if int(supersampling) != 1: + raise ValueError("tpms_layers: one sample per voxel (several phases)") + v, _ = self._on_grid(grid) + return VoxelImage.from_grid(self._phases(v), grid, name="phase", + metadata=self.image_metadata()) # fmt: skip + + def phase_level_set(self, phase, shape=None, *, voxel_size=None, grid: Grid | None = None): + """The first-order distance of the band of a phase.""" + phase = int(phase) + if phase not in self.implicit_phases(): + raise ValueError(f"phase {phase}: the phases are {self.implicit_phases()}") + grid = self.grid(shape, voxel_size=voxel_size, grid=grid) + v, g = self._on_grid(grid) + data = self._function(phase, v, g).astype(np.float32) + return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata()) + + def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage: + return self.phase_level_set(1, shape, voxel_size=voxel_size, grid=grid) + + def phase_level_sets_at(self, points, reach: float = np.inf) -> dict[int, np.ndarray]: + v, g = self._at(points) + return {k: self._function(k, v, g) for k in self.implicit_phases()} + + def level_set_at(self, points, reach: float = np.inf) -> np.ndarray: + v, g = self._at(points) + return self._function(1, v, g) + + def contains(self, points) -> np.ndarray: + return self.level_set_at(points) <= 0.0 + + def phases_at(self, points) -> np.ndarray: + """The phase of each point.""" + v, _ = self._at(points) + return self._phases(v) + + #: First-order distances: a margin for the curvature of the bands + lipschitz = 1.5 + + def summary(self) -> dict: + return {"surface": self.surface, "layers": len(self.bounds)} + + def _geometry(self) -> dict: + return {"surface": self.surface, "variant": self.variant, + "bounds": self.bounds.tolist(), "cell_size": self.cell_size.tolist()} # fmt: skip + + @classmethod + def _from_geometry(cls, domain, geometry, **kwargs): + return cls(domain, geometry["surface"], geometry["variant"], geometry["bounds"], + geometry["cell_size"], **kwargs) # fmt: skip + + +@register +@dataclass(frozen=True) +class TPMSLayers(Model): + """Layers of a TPMS for composites of several materials (interpenetrating phases): + the phase ``k`` of ``fractions`` (1 to ``n``) the band of the levels of the variable of + the variant whose volume fraction is ``fractions[k-1]``, nested from the surface + (``sheet``: the sheet, then the layers on both of its sides) or from one side + (``network``: the network, then the layers around it); the phase 0 the rest. + Adjacent layers share their surfaces: their closed surfaces tile the box + (:func:`morphogen.mesh.surface.phase_surfaces`).""" + + name = "tpms_layers" + phases: ClassVar[dict[int, str]] = {0: "matrix", 1: "layer 1"} + has_level_set: ClassVar[bool] = False + count_label = "unit cells" + + surface: str = param("gyroid", doc="The surface (as in tpms)", kind="str") + cell_size: float | tuple = param( + 1.0, doc="Edge of the unit cell (one value or three)", kind="vector", unit="length" + ) + variant: str = param( + "sheet", + doc="'sheet' (layers about the surface), 'network' or 'upper_network' (layers about a " + "network)", + kind="str", + ) + fractions: tuple[float, ...] = param( + (0.2, 0.2), doc="Volume fraction of each layer (phases 1, 2...); sum at most 1", + kind="floats", + ) # fmt: skip + + def _validate(self) -> None: + if self.surface not in implicit.SURFACES: + raise ValueError(f"surface: expected one of {list(SURFACES)}, got {self.surface!r}") + if self.variant not in implicit.MODES: + raise ValueError(f"variant: expected one of {list(VARIANTS)}, got {self.variant!r}") + as_triplet(self.cell_size, "cell_size", positive=True) + f = np.asarray(self.fractions, dtype=float) + if len(f) < 1 or len(f) > 254: + raise ValueError("fractions: between 1 and 254 layers") + if np.any(f <= 0.0) or f.sum() > 1.0 + 1e-12: + raise ValueError("fractions: positive, summing to at most 1") + + def active_phases(self) -> dict[int, str]: + out = {k + 1: f"layer {k + 1}" for k in range(len(self.fractions))} + if sum(self.fractions) < 1.0 - 1e-12: + out[0] = "matrix" + return out + + def bounds(self) -> np.ndarray: + """The upper level of each layer: the quantiles of the variable at the cumulated + fractions.""" + cumulated = np.minimum(np.cumsum(np.asarray(self.fractions, dtype=float)), 1.0) + values = _side(_unit_cell_values(implicit.SURFACES[self.surface]), self.variant) + out = np.quantile(values, cumulated) + if cumulated[-1] >= 1.0 - 1e-12: + out[-1] = np.inf + return out + + def generate(self, domain: Domain, seed: SeedLike = None) -> TPMSLayersStructure: + _, seed_info = make_rng(seed) + cell = np.array(as_triplet(self.cell_size, "cell_size", positive=True)) + if domain.periodic: + ratio = domain.lengths / cell + if np.any(np.abs(ratio - np.rint(ratio)) > 1e-6 * np.maximum(ratio, 1.0)): + raise ValueError( + "tpms_layers: a periodic domain must contain a whole number of unit cells" + ) + return TPMSLayersStructure(domain, self.surface, self.variant, self.bounds(), + tuple(cell), model=self, seed=seed_info) # fmt: skip + + def expected_count(self, domain: Domain) -> float: + return domain.volume / float(np.prod(np.broadcast_to(self.cell_size, 3))) + + def theory(self, domain: Domain | None = None) -> dict[str, float]: + out = {f"volume_fraction_{k + 1}": float(f) for k, f in enumerate(self.fractions)} + out["volume_fraction_0"] = float(max(0.0, 1.0 - sum(self.fractions))) + out["volume_fraction"] = out["volume_fraction_1"] + return out diff --git a/src/morphogen/pipeline.py b/src/morphogen/pipeline.py index 4c25e63..db5c865 100644 --- a/src/morphogen/pipeline.py +++ b/src/morphogen/pipeline.py @@ -105,7 +105,7 @@ from morphogen.image import VoxelImage from morphogen.io.tables import write_table from morphogen.mesh.conforming import conforming_mesh -from morphogen.mesh.surface import surface_mesh +from morphogen.mesh.surface import phase_surfaces, surface_mesh from morphogen.mesh.tetra import TetMesh from morphogen.mesh.triangles import TriMesh, plane_mesh from morphogen.mesh.voxel import voxel_mesh @@ -882,18 +882,48 @@ def _voxel_outputs( io.write_periodic_pairs(outdir / f"{stem}_periodic.csv", mesh) if out.periodic_equations and image.periodic and out.mesh_phases is None: io.write_periodic_equations(outdir / f"{stem}_equations.inp", mesh) - for fmt in out.surface: - if several: # the surface of each phase but the last (that of the others together) - for k in micro.implicit_phases()[:-1]: - field = micro.phase_level_set(k, grid=grid) - io.save_mesh(surface_mesh(field), outdir / f"{stem}_phase{k}.{fmt}") - continue + if out.surface: + _surface_outputs(micro, out, grid, stem, outdir, several, vox) + return image, labels + + +def _surface_outputs(micro, out, grid, stem: str, outdir: Path, several: bool, vox) -> None: + """The closed surfaces of a realization: by default, that of the phase 1 of two phases, + or of each phase but the last; with ``outputs.surface.phases``, the bodies of the + phases asked for (``all``: every phase), which tile the box + (:func:`morphogen.mesh.surface.phase_surfaces`). STL: a file per surface; 3MF and + STEP: one file of all the bodies, each phase a body of its own material.""" + from morphogen.io.printing import write_3mf, write_step + + phases = out.surface_phases + if phases is not None: + chosen = micro.implicit_phases() if phases == "all" else [int(k) for k in phases] + bodies = phase_surfaces(micro, chosen, grid) + names = {k: micro.model.active_phases().get(k, f"phase {k}") if micro.model else + f"phase {k}" for k in chosen} # fmt: skip + elif several: # the surface of each phase but the last (that of the others together) + chosen = micro.implicit_phases()[:-1] + bodies = {k: surface_mesh(micro.phase_level_set(k, grid=grid)) for k in chosen} + names = {k: f"phase {k}" for k in chosen} + else: try: field = micro.level_set(grid=grid) except NotImplementedError: field = micro.voxelize(grid=grid, supersampling=max(2, vox.supersampling)) - io.save_mesh(surface_mesh(field), outdir / f"{stem}.{fmt}") - return image, labels + bodies, names = {1: surface_mesh(field)}, {1: "solid"} + single = phases is None and not several + for fmt in out.surface: + if fmt == "3mf": + write_3mf(outdir / f"{stem}.3mf", [(names[k], b) for k, b in bodies.items()], + unit=out.surface_unit) # fmt: skip + elif fmt == "step": + write_step(outdir / f"{stem}.step", [(names[k], b) for k, b in bodies.items()], + unit=out.surface_unit) # fmt: skip + elif single: + io.save_mesh(bodies[1], outdir / f"{stem}.{fmt}") + else: + for k, body in bodies.items(): + io.save_mesh(body, outdir / f"{stem}_phase{k}.{fmt}") def _measure_names(): diff --git a/src/morphogen/templates/graded_tpms.yaml b/src/morphogen/templates/graded_tpms.yaml new file mode 100644 index 0000000..3d35f91 --- /dev/null +++ b/src/morphogen/templates/graded_tpms.yaml @@ -0,0 +1,24 @@ +# A graded TPMS for additive manufacturing: a sheet of Schoen's I-WP whose relative density +# grows from 10 % at the bottom to 40 % at the top along z (each height at the level of its +# fraction), its watertight surface written as STL and as a STEP solid for CAD. +model: + type: tpms + surface: schoen_iwp + variant: sheet + cell_size: 5.0 + fraction_gradient: [0.1, 0.4] # the fractions at the lower and upper faces (or more) + gradient_axis: 2 +domain: + size: [10.0, 10.0, 20.0] + periodic: false # graded TPMS are not periodic + unit: mm +voxels: + voxel_size: 0.1 +outputs: + directory: out/graded_tpms + name: iwp + surface: + formats: [stl, step] + phases: [1] + unit: millimeter +analysis: [volume_fraction, specific_surface] diff --git a/src/morphogen/templates/hybrid.yaml b/src/morphogen/templates/hybrid.yaml new file mode 100644 index 0000000..5dcd4b7 --- /dev/null +++ b/src/morphogen/templates/hybrid.yaml @@ -0,0 +1,22 @@ +# A hybrid architecture: a gyroid sheet that turns into a Schwarz P sheet along x, both at +# 20 % relative density, blended by a sigmoid of width 1.5 mm across the middle of the +# beam (Yang et al. 2014), its watertight surface written as STL. +model: + type: hybrid + transition: linear # linear | cylindrical | spherical + axis: 0 + width: 1.5 + models: + - {type: tpms, surface: gyroid, variant: sheet, cell_size: 5.0, volume_fraction: 0.2} + - {type: tpms, surface: schwarz_p, variant: sheet, cell_size: 5.0, volume_fraction: 0.2} +domain: + size: [30.0, 10.0, 10.0] + periodic: false + unit: mm +voxels: + voxel_size: 0.15 +outputs: + directory: out/hybrid + name: hybrid + surface: [stl] +analysis: [volume_fraction] diff --git a/src/morphogen/templates/part.yaml b/src/morphogen/templates/part.yaml new file mode 100644 index 0000000..97ed5c8 --- /dev/null +++ b/src/morphogen/templates/part.yaml @@ -0,0 +1,25 @@ +# A part ready to print: a sandwich beam, its core a gyroid sheet at 15 % relative density +# between skins of 1 mm, with solid supports of 4 mm at its ends; its surface as STL and as +# a STEP solid. Cylinders, tubes, spheres and closed surfaces of one's own are filled alike +# (shape: cylinder, with a shell; shape: mesh, mesh: part.stl, fit: true). +model: + type: part + shape: box # box | cylinder | tube | sphere | mesh + skins: [1.0, 1.0] # plates at the lower and upper faces along skin_axis + skin_axis: 2 + supports: [4.0, 4.0] # blocks at the ends along support_axis + support_axis: 0 + infill: {type: tpms, surface: gyroid, variant: sheet, cell_size: 4.0, volume_fraction: 0.15} +domain: + size: [40.0, 10.0, 8.0] + periodic: false + unit: mm +voxels: + voxel_size: 0.1 +outputs: + directory: out/part + name: beam + surface: + formats: [stl, step] + unit: millimeter +analysis: [volume_fraction] diff --git a/src/morphogen/templates/spinodoid.yaml b/src/morphogen/templates/spinodoid.yaml new file mode 100644 index 0000000..3659d31 --- /dev/null +++ b/src/morphogen/templates/spinodoid.yaml @@ -0,0 +1,22 @@ +# A spinodoid (Kumar et al. 2020): the level of a sum of 1000 waves of one wavelength whose +# directions lie within cones of 30 degrees about the three axes (a cubic spinodoid), a +# network at 40 % relative density; its specific surface against Rice's formula. +model: + type: spinodoid + wavelength: 2.0 + n_waves: 1000 + cone_angles: [30, 30, 30] # 90, 90, 90: isotropic; 15, 0, 0: lamellar; 0, 15, 15: columnar + variant: network # network | sheet | upper_network + volume_fraction: 0.4 +domain: + size: 10.0 + periodic: false + unit: mm +seed: 3 +voxels: + voxel_size: 0.1 +outputs: + directory: out/spinodoid + name: spinodoid + surface: [stl] +analysis: [volume_fraction, specific_surface] diff --git a/src/morphogen/templates/tpms.yaml b/src/morphogen/templates/tpms.yaml index 18e6819..cba3c18 100644 --- a/src/morphogen/templates/tpms.yaml +++ b/src/morphogen/templates/tpms.yaml @@ -1,8 +1,9 @@ # Sheet gyroid at 20 % relative density (architected material for additive manufacturing). model: type: tpms - surface: gyroid # gyroid | schwarz_p | schwarz_d | neovius - variant: sheet # sheet | network + surface: gyroid # gyroid | schwarz_p | schwarz_d | neovius | schoen_iwp | + # schoen_frd | fischer_koch_s | lidinoid | split_p | i2_y + variant: sheet # sheet | network | upper_network cell_size: 5.0 volume_fraction: 0.2 domain: diff --git a/src/morphogen/templates/tpms_layers.yaml b/src/morphogen/templates/tpms_layers.yaml new file mode 100644 index 0000000..635752a --- /dev/null +++ b/src/morphogen/templates/tpms_layers.yaml @@ -0,0 +1,24 @@ +# An interpenetrating composite of three materials: the layers of a gyroid, its sheet (20 %) +# and the layer of 30 % about it, the rest a third material; the closed bodies of the three +# phases, which share their surfaces and tile the box, in one 3MF file (a material per +# body, for multi-material printing) and as STEP solids. +model: + type: tpms_layers + surface: gyroid + variant: sheet # sheet: layers about the surface; network: about a network + cell_size: 5.0 + fractions: [0.2, 0.3] # the fractions of the layers (phases 1, 2); phase 0 the rest +domain: + size: 10.0 + periodic: true + unit: mm +voxels: + voxel_size: 0.125 +outputs: + directory: out/tpms_layers + name: layers + surface: + formats: [3mf, step] + phases: all # the bodies of every phase + unit: millimeter +analysis: [volume_fraction] diff --git a/src/morphogen/viz/sections.py b/src/morphogen/viz/sections.py index 4a78a74..bb23f46 100644 --- a/src/morphogen/viz/sections.py +++ b/src/morphogen/viz/sections.py @@ -97,7 +97,7 @@ from morphogen.models.spinodoid import SpinodoidStructure from morphogen.models.tessellation import Tessellation from morphogen.models.textile import TextileStructure -from morphogen.models.tpms import TPMSStructure +from morphogen.models.tpms import TPMSLayersStructure, TPMSStructure from morphogen.models.transparent import TransparentDeadLeaves from morphogen.models.union import PrimitiveUnion from morphogen.viz.png import PALETTE, label_colors @@ -135,6 +135,7 @@ _POINTWISE = ( PrimitiveUnion, TPMSStructure, + TPMSLayersStructure, SpinodoidStructure, HybridStructure, PartStructure, diff --git a/tests/public_api.txt b/tests/public_api.txt index d448154..dce3d5d 100644 --- a/tests/public_api.txt +++ b/tests/public_api.txt @@ -350,7 +350,7 @@ morphogen.config.MeshSpec.plane_kwargs(self, porous=False) morphogen.config.MeshSpec.plate_layers(self, z0=0.0) morphogen.config.NONLINEAR_OPTIONS morphogen.config.OPENFOAM_OPTIONS -morphogen.config.OutputSpec(directory=Path('morphogen_output'), name='sample', geometry=, image=, labels=, level_set=, mesh=, mesh_phases=None, conforming_mesh=, periodic_pairs=False, periodic_equations=False, surface=, damask=False, neper=False, database=None, amitex=None, code_aster=None, openfoam=None, tables=, shell_section=False) +morphogen.config.OutputSpec(directory=Path('morphogen_output'), name='sample', geometry=, image=, labels=, level_set=, mesh=, mesh_phases=None, conforming_mesh=, periodic_pairs=False, periodic_equations=False, surface=, surface_phases=None, surface_unit='millimeter', damask=False, neper=False, database=None, amitex=None, code_aster=None, openfoam=None, tables=, shell_section=False) morphogen.config.OutputSpec.needs_voxels morphogen.config.RVESpec(method='ensemble', sizes=, realizations=, size=None, window_sizes=, properties=, relative_errors=, n_realizations=, gamma=None, min_volume=None, max_volume=None, bootstrap=1000, weights='none', shifts=1) morphogen.config.RunConfig(model, domain, seed=None, realizations=1, voxels=None, mesh=None, outputs=, analysis=, rve=None, homogenization=None, diffusion=None, visualization=None, threads=None, source=) @@ -2670,6 +2670,13 @@ morphogen.io.openfoam.read_polymesh(directory) morphogen.io.openfoam.run_openfoam(directory, *, environment=None, timeout=None) morphogen.io.openfoam.write_openfoam(directory, sample, *, kind='flow', phases=(0,), axis=0, lateral=None, viscosity=1.0, pressure_drop=1.0, diffusivity=1.0, difference=1.0, iterations=2000, tolerance=1e-07, connected=True, dual=None, velocity=None, convection='linear') morphogen.io.openfoam.write_polymesh(directory, mesh) +morphogen.io.printing.COLORS +morphogen.io.printing.UNITS_3MF +morphogen.io.printing.UNITS_STEP +morphogen.io.printing.read_3mf(path) +morphogen.io.printing.read_step_bodies(path) +morphogen.io.printing.write_3mf(path, bodies, *, unit='millimeter', colors=None) +morphogen.io.printing.write_step(path, bodies, *, unit='millimeter', name='morphoGen', kind='solid') morphogen.io.radioss.ANIM_ELEMENTS morphogen.io.radioss.ANIM_VECTORS morphogen.io.radioss.ELEMENTS @@ -3447,7 +3454,10 @@ morphogen.mesh.surface.SurfaceMesh(vertices, faces) morphogen.mesh.surface.SurfaceMesh.area(self) morphogen.mesh.surface.SurfaceMesh.face_normals(self) morphogen.mesh.surface.SurfaceMesh.volume(self) -morphogen.mesh.surface.surface_mesh(image, *, level=0.0, phase=1, closed=True) +morphogen.mesh.surface.merge_vertices(surface, tolerance=1e-09) +morphogen.mesh.surface.node_grid(grid) +morphogen.mesh.surface.phase_surfaces(micro, phases, grid) +morphogen.mesh.surface.surface_mesh(image, *, level=0.0, phase=1, closed=True, caps='box') morphogen.mesh.tetra.TetMesh(nodes, elements, phase, lower, upper, periodic=False, metadata=, cell=None, orientations=None, whole=False, outer=None, side=None, sharp=None, sharp_pieces=None) morphogen.mesh.tetra.TetMesh.boundary_faces(self, axis, side) morphogen.mesh.tetra.TetMesh.boundary_nodes(self) @@ -3690,6 +3700,8 @@ morphogen.models: SpinodalStructure morphogen.models: Spinodoid morphogen.models: SpinodoidStructure morphogen.models: StrutLattice +morphogen.models: TPMSLayers +morphogen.models: TPMSLayersStructure morphogen.models: TPMSStructure morphogen.models: Tessellation morphogen.models: TextileStructure @@ -4699,6 +4711,22 @@ morphogen.models.tpms.TPMS.iso_level morphogen.models.tpms.TPMS.mean_fraction(self) morphogen.models.tpms.TPMS.solid_fraction(self) morphogen.models.tpms.TPMS.theory(self, domain=None) +morphogen.models.tpms.TPMSLayers(surface='gyroid', cell_size=1.0, variant='sheet', fractions=(0.2, 0.2)) +morphogen.models.tpms.TPMSLayers.active_phases(self) +morphogen.models.tpms.TPMSLayers.bounds(self) +morphogen.models.tpms.TPMSLayers.expected_count(self, domain) +morphogen.models.tpms.TPMSLayers.generate(self, domain, seed=None) +morphogen.models.tpms.TPMSLayers.theory(self, domain=None) +morphogen.models.tpms.TPMSLayersStructure(domain, surface, variant, bounds, cell_size, **kwargs) +morphogen.models.tpms.TPMSLayersStructure.contains(self, points) +morphogen.models.tpms.TPMSLayersStructure.implicit_phases(self) +morphogen.models.tpms.TPMSLayersStructure.level_set(self, shape=None, *, voxel_size=None, grid=None) +morphogen.models.tpms.TPMSLayersStructure.level_set_at(self, points, reach=inf) +morphogen.models.tpms.TPMSLayersStructure.phase_level_set(self, phase, shape=None, *, voxel_size=None, grid=None) +morphogen.models.tpms.TPMSLayersStructure.phase_level_sets_at(self, points, reach=inf) +morphogen.models.tpms.TPMSLayersStructure.phases_at(self, points) +morphogen.models.tpms.TPMSLayersStructure.summary(self) +morphogen.models.tpms.TPMSLayersStructure.voxelize(self, shape=None, *, voxel_size=None, grid=None, supersampling=1) morphogen.models.tpms.TPMSStructure(domain, surface, variant, level, cell_size, *, levels=None, gradient_axis=0, cells_around=None, cylinder_axis=2, cylinder_center=None, **kwargs) morphogen.models.tpms.TPMSStructure.contains(self, points) morphogen.models.tpms.TPMSStructure.level_set(self, shape=None, *, voxel_size=None, grid=None) diff --git a/tests/test_models_base.py b/tests/test_models_base.py index d5d1cb3..52ce087 100644 --- a/tests/test_models_base.py +++ b/tests/test_models_base.py @@ -66,6 +66,7 @@ True, ), "spinodoid": ({"wavelength": 2.0, "volume_fraction": 0.4, "n_waves": 200}, True), + "tpms_layers": ({"cell_size": 4.0, "fractions": [0.2, 0.3]}, True), "part": ( { "infill": {"type": "tpms", "cell_size": 4.0, "volume_fraction": 0.3}, diff --git a/tests/test_printing.py b/tests/test_printing.py new file mode 100644 index 0000000..1e31ec2 --- /dev/null +++ b/tests/test_printing.py @@ -0,0 +1,203 @@ +"""Bodies for additive manufacturing: the closed surfaces of phases that tile their box, +layers of TPMS, 3MF and STEP files (theory.md §145).""" + +import zipfile + +import numpy as np +import pytest + +import morphogen as mg +from morphogen import io, pipeline +from morphogen.config import ConfigError, load_config +from morphogen.io.printing import read_3mf, read_step_bodies, write_3mf, write_step +from morphogen.mesh.distance import is_closed +from morphogen.mesh.surface import SurfaceMesh, node_grid, phase_surfaces +from morphogen.models.base import Microstructure +from morphogen.models.lattice import StrutLattice +from morphogen.models.tpms import TPMS, TPMSLayers + + +def _edge_uses(surface: SurfaceMesh) -> set[int]: + f = surface.faces + edges = np.sort(np.concatenate([f[:, [0, 1]], f[:, [1, 2]], f[:, [2, 0]]]), axis=1) + return set(np.unique(np.unique(edges, axis=0, return_counts=True)[1]).tolist()) + + +def _tetrahedron() -> SurfaceMesh: + v = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=float) + return SurfaceMesh(v, np.array([[0, 2, 1], [0, 1, 3], [0, 3, 2], [1, 2, 3]])) + + +@pytest.mark.parametrize( + "model, domain", + [ + (TPMS(surface="gyroid", variant="sheet", volume_fraction=0.3), mg.Domain.cube(1.0)), + (TPMS(surface="schoen_iwp", volume_fraction=0.4), + mg.Domain(size=(2.0, 1.0, 1.0), periodic=False)), + (StrutLattice(cell="octet", volume_fraction=0.2), mg.Domain.cube(2.0)), + ], +) # fmt: skip +def test_complementary_bodies_tile_the_box(model, domain): + """The solid and its complement: closed (each edge of two triangles), their volumes + adding up to the box, their interfaces made of the same vertices.""" + micro = model.generate(domain, seed=1) + bodies = phase_surfaces(micro, [0, 1], domain.grid(32)) + assert _edge_uses(bodies[0]) == {2} and _edge_uses(bodies[1]) == {2} + assert bodies[0].volume() + bodies[1].volume() == pytest.approx(domain.volume, rel=1e-12) + lo, hi = domain.lower, domain.upper + + def inner(v): + keep = np.all((v > lo + 1e-9) & (v < hi - 1e-9), axis=1) + return {tuple(np.round(p, 9)) for p in v[keep]} + + assert inner(bodies[0].vertices) == inner(bodies[1].vertices) + + +def test_node_grid(): + """The nodes of a grid, its faces included, as the centres of another grid.""" + grid = mg.Domain(size=(2.0, 1.0, 1.0), periodic=False).grid(shape=(8, 4, 4)) + nodes = node_grid(grid) + assert nodes.shape == (9, 5, 5) + centres = nodes.center_points() + assert np.allclose(centres.min(axis=0), [0.0, 0.0, 0.0]) + assert np.allclose(centres.max(axis=0), [2.0, 1.0, 1.0]) + + +def test_tpms_layers(): + """Layers of a gyroid: the fractions of the phases, the bands of the levels, the + functions of the phases negative exactly on their voxels, at points too, the three + bodies tiling the box; a realization read back; errors.""" + model = TPMSLayers(surface="gyroid", variant="sheet", fractions=(0.2, 0.3)) + micro = model.generate(mg.Domain.cube(1.0)) + img = micro.voxelize(shape=64) + for k, f in ((1, 0.2), (2, 0.3), (0, 0.5)): + assert np.mean(img.data == k) == pytest.approx(f, abs=0.01) + assert model.theory()[f"volume_fraction_{k}"] == pytest.approx(f) + grid = micro.domain.grid(24) + phases = micro.voxelize(grid=grid).data + values = micro.phase_level_sets_at(grid.center_points()) + for k in range(3): + assert np.array_equal(micro.phase_level_set(k, grid=grid).data <= 0, phases == k) + assert np.array_equal(values[k].reshape(grid.shape) <= 0, phases == k) + bodies = phase_surfaces(micro, [0, 1, 2], micro.domain.grid(32)) + assert sum(b.volume() for b in bodies.values()) == pytest.approx(1.0, rel=1e-3) + back = Microstructure.from_dict(micro.to_dict()) + assert np.array_equal(back.voxelize(shape=16).data, micro.voxelize(shape=16).data) + full = TPMSLayers(surface="schwarz_p", variant="network", fractions=(0.4, 0.6)) + assert np.isinf(full.bounds()[-1]) + assert set(np.unique(full.generate(mg.Domain.cube(1.0)).voxelize(shape=16).data)) == {1, 2} + with pytest.raises(ValueError, match="fractions"): + TPMSLayers(fractions=(0.6, 0.6)) + with pytest.raises(ValueError, match="surface"): + TPMSLayers(surface="schwarz_h") + + +def test_3mf(tmp_path): + """A 3MF package: its parts, the bodies of their materials and colours, read back.""" + tetra = _tetrahedron() + moved = SurfaceMesh(tetra.vertices + 2.0, tetra.faces) + path = write_3mf(tmp_path / "two.3mf", {"steel": tetra, "resin & co": moved}, + unit="micron", colors=["#112233", "#445566"]) # fmt: skip + with zipfile.ZipFile(path) as package: + names = set(package.namelist()) + model = package.read("3D/3dmodel.model").decode() + assert names == {"[Content_Types].xml", "_rels/.rels", "3D/3dmodel.model"} + assert 'unit="micron"' in model and "resin & co" in model + bodies = read_3mf(path) + assert [(n, c) for n, _, c in bodies] == [("steel", "#112233FF"), ("resin & co", "#445566FF")] + assert np.allclose(bodies[1][1].vertices, moved.vertices) + assert np.array_equal(bodies[0][1].faces, tetra.faces) + assert bodies[0][1].volume() == pytest.approx(1.0 / 6.0) + io.save_mesh(tetra, tmp_path / "one.3mf") + assert len(read_3mf(tmp_path / "one.3mf")) == 1 + with pytest.raises(ValueError, match="unit"): + write_3mf(tmp_path / "bad.3mf", tetra, unit="furlong") + + +@pytest.mark.parametrize("kind", ["solid", "faceted"]) +def test_step(tmp_path, kind): + """A STEP file of two bodies: its entities, a solid per connected piece, the bodies + read back with their volumes.""" + micro = TPMS(surface="gyroid", variant="sheet", volume_fraction=0.3).generate( + mg.Domain(size=(2.0, 2.0, 2.0), periodic=False) + ) + bodies = phase_surfaces(micro, [0, 1], micro.domain.grid(16)) + path = write_step(tmp_path / "gyroid.step", {"solid": bodies[1], "void": bodies[0]}, + kind=kind) # fmt: skip + text = path.read_text(encoding="ascii") + assert text.startswith("ISO-10303-21;") and text.rstrip().endswith("END-ISO-10303-21;") + assert "AUTOMOTIVE_DESIGN" in text and "SI_UNIT(.MILLI.,.METRE.)" in text + if kind == "solid": + assert text.count("=MANIFOLD_SOLID_BREP(") >= 2 and "=ADVANCED_FACE(" in text + assert text.count("=EDGE_CURVE(") == sum( + len({tuple(sorted(e)) for f in b.faces for e in ((f[0], f[1]), (f[1], f[2]), + (f[2], f[0]))}) + for b in bodies.values() + ) # fmt: skip + else: + assert text.count("=FACETED_BREP(") == 2 and "=POLY_LOOP(" in text + if kind == "faceted": + back = dict(read_step_bodies(path)) + assert back["solid"].volume() == pytest.approx(bodies[1].volume(), rel=1e-9) + assert back["void"].volume() == pytest.approx(bodies[0].volume(), rel=1e-9) + io.save_mesh(_tetrahedron(), tmp_path / "tetra.step") + assert "=MANIFOLD_SOLID_BREP(" in (tmp_path / "tetra.step").read_text() + with pytest.raises(ValueError, match="unit"): + write_step(tmp_path / "bad.step", _tetrahedron(), unit="inch") + + +def test_step_with_opencascade(tmp_path): + """The solids of a STEP file read by OpenCascade (where it is installed: the package + cadquery-ocp): a solid per connected piece, valid, of the volume of its surface.""" + pytest.importorskip("OCP") + from OCP.BRepCheck import BRepCheck_Analyzer + from OCP.BRepGProp import BRepGProp + from OCP.GProp import GProp_GProps + from OCP.STEPControl import STEPControl_Reader + from OCP.TopAbs import TopAbs_SOLID + from OCP.TopExp import TopExp_Explorer + + lattice = StrutLattice(cell="octet", volume_fraction=0.15, cell_size=5.0) + micro = lattice.generate(mg.Domain(size=(10.0, 10.0, 10.0), periodic=False), seed=1) + body = phase_surfaces(micro, [1], micro.domain.grid(32))[1] + path = write_step(tmp_path / "octet.step", {"octet": body}) + reader = STEPControl_Reader() + reader.ReadFile(str(path)) + reader.TransferRoots() + shape = reader.Shape(1) + props = GProp_GProps() + BRepGProp.VolumeProperties_s(shape, props) + solids = TopExp_Explorer(shape, TopAbs_SOLID) + assert solids.More() and BRepCheck_Analyzer(shape).IsValid() + assert props.Mass() == pytest.approx(body.volume(), rel=1e-9) + + +def test_surface_outputs_of_a_run(tmp_path): + """The surfaces of a run: by default the STL of the solid; with phases, a file per + body and one 3MF and one STEP of all of them; errors of the configuration.""" + base = { + "model": {"type": "tpms", "surface": "gyroid", "variant": "sheet", + "volume_fraction": 0.3}, + "domain": {"size": 1.0, "periodic": True}, + "voxels": {"shape": 16}, + } # fmt: skip + default = pipeline.run(load_config({**base, "outputs": { + "directory": str(tmp_path / "a"), "name": "g", "surface": ["stl"]}})) # fmt: skip + assert [p.name for p in default.rglob("*.stl")] == ["g_0000.stl"] + bodies = pipeline.run(load_config({**base, "outputs": { + "directory": str(tmp_path / "b"), "name": "g", + "surface": {"formats": ["stl", "3mf", "step"], "phases": "all"}}})) # fmt: skip + assert sorted(p.name for p in bodies.rglob("g*.*") if p.suffix != ".json") == [ + "g_0000.3mf", "g_0000.step", "g_0000_phase0.stl", "g_0000_phase1.stl"] # fmt: skip + package = read_3mf(next(bodies.rglob("g_0000.3mf"))) + assert [n for n, _, _ in package] == ["void", "solid"] + assert sum(s.volume() for _, s, _ in package) == pytest.approx(1.0, rel=1e-9) + assert all(is_closed(s) for _, s, _ in package) + for bad, message in ( + ({"formats": ["stl"], "phases": "solid"}, "phases"), + ({"formats": ["stl"], "unit": "furlong"}, "unit"), + ({"formats": ["step"], "unit": "inch"}, "STEP"), + ({"formats": ["obj"]}, "surface"), + ): + with pytest.raises(ConfigError, match=message): + load_config({**base, "outputs": {"directory": str(tmp_path), "surface": bad}}) From aa407cf5f5fcfa8532c0bef047f99660a663fc86 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 00:07:40 +0000 Subject: [PATCH 08/13] Documentation: the link of the home page to the family TPMS and spinodoids Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MSrXEMpgnWPQNUwHwAgXHV --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index ba2fb34..b97a6ba 100644 --- a/docs/index.md +++ b/docs/index.md @@ -27,7 +27,7 @@ package, a command line and a graphical interface in the web browser; free softw [![the excursion of a Gaussian field](_static/gallery/gaussian_excursion.png)](gallery.md#dead-leaves-gaussian-fields-and-reconstructions) [![fibres packed without overlap](_static/gallery/random_walk_fibers.png)](gallery.md#fibres-and-layers) [![a lattice of struts](_static/gallery/strut_lattice.png)](gallery.md#foams-and-lattices) -[![a gyroid](_static/gallery/tpms.png)](gallery.md#tpms) +[![a gyroid](_static/gallery/tpms.png)](gallery.md#tpms-and-spinodoids) [![trabecular bone](_static/gallery/trabecular_bone.png)](gallery.md#bio-inspired) [![a pattern of reaction and diffusion](_static/gallery/reaction_diffusion.png)](gallery.md#automata-and-tilings) ::: From ced0f5b6011eb0523d9497b998fee5ebc85d754c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 00:10:23 +0000 Subject: [PATCH 09/13] Meshes for LS-DYNA and ANSYS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit io.structural (theory notes §146, FR-E21, specification 1.260): the voxel and tetrahedral meshes as LS-DYNA keyword files (nodes and solid elements in fixed fields, a part per phase with its section and elastic material, the node sets of the faces; linear elements) and ANSYS Mechanical APDL inputs (SOLID185, SOLID285 or SOLID187, the materials, a command per node and element, the components of the faces), from io.save_mesh and the mesh outputs of a run (k, ans) with the elastic materials of its homogenization. The public interface written again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MSrXEMpgnWPQNUwHwAgXHV --- CHANGELOG.md | 8 ++ docs/configuration.md | 3 +- docs/interop.md | 6 ++ docs/specification.md | 6 +- docs/theory.md | 44 ++++++++- src/morphogen/config.py | 2 +- src/morphogen/io/__init__.py | 9 +- src/morphogen/io/structural.py | 166 +++++++++++++++++++++++++++++++++ src/morphogen/pipeline.py | 7 +- tests/public_api.txt | 4 + tests/test_structural.py | 105 +++++++++++++++++++++ 11 files changed, 353 insertions(+), 7 deletions(-) create mode 100644 src/morphogen/io/structural.py create mode 100644 tests/test_structural.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8946c26..3c152cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +* Meshes for LS-DYNA and ANSYS ([docs/theory.md](docs/theory.md) §146, + `morphogen.io.structural`): the voxel and tetrahedral meshes as LS-DYNA keyword files + (`.k`: nodes and solid elements in fixed fields, a part per phase with its section and + its `*MAT_ELASTIC`, the node sets of the faces) and as ANSYS Mechanical APDL inputs + (`.ans`: SOLID185, SOLID285 or SOLID187, the materials, the components of the faces), + from `io.save_mesh` and the outputs `mesh` and `conforming_mesh` of a run (with the + elastic materials of its homogenization). Public interface: + `morphogen.io.structural` (`write_lsdyna`, `write_ansys`, `read_lsdyna`). * Bodies for additive manufacturing and CAD ([docs/theory.md](docs/theory.md) §145): `outputs.surface: {formats: [stl, 3mf, step], phases: all, unit: millimeter}` writes the closed bodies of the phases asked for, which share their interfaces and tile the diff --git a/docs/configuration.md b/docs/configuration.md index 8f7c76c..3239a26 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -64,7 +64,8 @@ outputs: image: [vti, vtk, mhd, npz, npy, tif] labels: [vti] # tessellations: cell labels level_set: [vti] - mesh: {formats: [inp, msh, vtu], phases: [1]} # voxel hexahedra + mesh: {formats: [inp, msh, vtu], phases: [1]} # voxel hexahedra; also k (LS-DYNA) and + # ans (ANSYS APDL), with the elastic materials of the run conforming_mesh: [vtu, inp, msh, mesh, xdmf, mail] # tetrahedra (needs the mesh section); # the triangles of the plane: vtu, inp (plane strain elements), msh, # mesh and the formats of meshio diff --git a/docs/interop.md b/docs/interop.md index ce6b243..52b6d7e 100644 --- a/docs/interop.md +++ b/docs/interop.md @@ -12,6 +12,12 @@ writer from the object and the suffix of the file. ## File formats * Volumes: VTK (`.vti`, legacy `.vtk` for FFT codes), XDMF, MetaImage, NumPy, TIFF. +* Voxel and tetrahedral meshes for LS-DYNA (`.k`: nodes and solid elements in the fixed + fields of the keyword format, a part per phase with its section and its elastic + material, the node sets of the faces) and for ANSYS Mechanical APDL (`.ans`, read by + `/INPUT`: SOLID185, SOLID285 or SOLID187 elements, the materials, the components of the + faces), `morphogen.io.structural`, [theory notes](theory.md) §146; ANSYS Workbench reads + the Abaqus inputs below as external models too. * Conforming tetrahedral meshes and hexahedral voxel meshes, with phase, grain and face sets: Abaqus/CalculiX `.inp` (with orientations, sections and the materials of the phases: elastic, the nonlinear ones as MFront laws), Gmsh `.msh`, diff --git a/docs/specification.md b/docs/specification.md index 758dcc6..5eea6ac 100644 --- a/docs/specification.md +++ b/docs/specification.md @@ -3,7 +3,7 @@ | | | |---|---| | Document | Software requirements specification | -| Version | 1.259 | +| Version | 1.260 | | Date | 2026-12-01 | | Author | @jdirr | | Status | Version 1.1 **validated** on 2026-10-21. The later versions, proposed, are listed in the change log (§13); changes go through pull requests that update this file and its change log. | @@ -370,6 +370,8 @@ centred on morphological modelling. | Delivered | FR-G33 (`strut_lattice` `cell: octahedral`, `rhombic_dodecahedron`, `custom` with `struts`, `reinforcement`, `curvature`, `CellSpec`, [theory.md](theory.md) §144): the two cells, their rigidity in the frames; reinforcements `edges` and `axis`; circular arcs of a sagitta, outward or inward, in straight pieces; custom cells; the fractions solved for every cell | | Additive manufacturing: bodies, 3MF and STEP (2026-12-01) | Multi-material parts and the files of slicers and CAD programs, beyond Top6Meta's STL and faceted STEP. | | Delivered | FR-G34, FR-E20 (`tpms_layers`, `mesh.surface.phase_surfaces`, `io.printing`, `outputs.surface: {formats, phases, unit}`, [theory.md](theory.md) §145): the bodies of the phases tiling the box (nodes with the faces, mirrored padding, merged vertices); layers of TPMS; 3MF with base materials; STEP solids (AP214, `MANIFOLD_SOLID_BREP` of planar `ADVANCED_FACE`s) read by OpenCascade as valid solids at their volumes, or faceted shells | +| Additive manufacturing: LS-DYNA and ANSYS (2026-12-01) | The voxel meshes of the AM+ edition of Top6Meta, for two more codes of structures. | +| Delivered | FR-E21 (`io.structural.write_lsdyna`, `write_ansys`, the mesh formats `k` and `ans` of `outputs.mesh` and `outputs.conforming_mesh`, [theory.md](theory.md) §146) | ## 4. Scope @@ -510,6 +512,7 @@ version, 0.1). | FR-E18 | Meshes of the plane: triangular meshes (three or six nodes) of the structures invariant across a plane, the exact polygons of the tessellations of coplanar germs (columnar grains) graded from their small features, the sections of any structure in a plane, matching periodic sides; the plane elements of Abaqus and CalculiX, Gmsh, VTK and Medit files read back | S | 3d | | FR-E19 | Forchheimer's law through OpenFOAM: the flows through the pores periodic along their axis and driven to a filtration velocity at finite Reynolds numbers, run by OpenFOAM, and the laws of the weak inertia and of Forchheimer fitted to them (`morphogen openfoam forchheimer`); verified with OpenFOAM itself where it is installed | S | 1d | | FR-E20 | Bodies for additive manufacturing and CAD: the closed surfaces of the phases asked for, which share their interfaces and tile their box; 3MF packages of several bodies, a material per body; STEP files of solids (manifold solid boundary representations) or faceted shells | S | 1d | +| FR-E21 | Voxel and tetrahedral meshes for LS-DYNA (keyword files: parts, sections, elastic materials, the node sets of the faces) and ANSYS Mechanical APDL (inputs: element types, materials, nodes, elements, the components of the faces) | S | 1d | ### 5.6 Interfaces @@ -1444,6 +1447,7 @@ Packages: `models`, `kernels`, `analysis`, `rve`, `mesh`, `homogenization`, `io` | 1.257 | 2026-12-01 | Parts ready to print: shapes, shells, skins, supports, closed surfaces from files, conformal TPMS (FR-G32, §3.12) | | 1.258 | 2026-12-01 | Strut lattices: octahedral and rhombic dodecahedral cells, reinforcements, curved struts, custom cells (FR-G33, §3.12) | | 1.259 | 2026-12-01 | Bodies that tile their box, layers of TPMS, 3MF and STEP (FR-G34, FR-E20, §3.12) | +| 1.260 | 2026-12-01 | Meshes for LS-DYNA and ANSYS (FR-E21, §3.12) | ## 14. References diff --git a/docs/theory.md b/docs/theory.md index 5d47fc3..b62ff8d 100644 --- a/docs/theory.md +++ b/docs/theory.md @@ -22,7 +22,7 @@ them by these numbers (§75); by theme: | Behaviours along loading paths | [§31](#31-nonlinear-behaviours-along-loading-paths-the-periodic-element) Nonlinear behaviours along loading paths: the periodic element, [§32](#32-crystal-plasticity-homogenizationcrystal) Crystal plasticity, [§33](#33-finite-strains-homogenizationfinite) Finite strains, [§34](#34-loading-paths-on-voxel-images-the-nonlinear-fft-solver-homogenizationfft_nonlinear) Loading paths on voxel images: the nonlinear FFT solver, [§36](#36-mfront-behaviours-homogenizationmfront) MFront behaviours, [§37](#37-mfront-sources-of-morphogens-behaviours-iomfront) MFront sources of morphoGen's behaviours, [§43](#43-the-nonuniform-transformation-field-analysis-homogenizationntfa) The nonuniform transformation field analysis, [§49](#49-porous-plasticity-gurson-tvergaard-needleman-rousselier-compaction-homogenizationporous) Porous plasticity: Gurson-Tvergaard-Needleman, Rousselier, compaction, [§50](#50-micromorphic-continua-the-microfoam-model-and-micromorphic-damage-micromorphic) Micromorphic continua: the microfoam model and micromorphic damage, [§53](#53-identification-of-a-behaviour-homogenizationidentification) Identification of a behaviour, [§54](#54-hills-anisotropic-plasticity-homogenizationbehaviours) Hill's anisotropic plasticity, [§57](#57-behaviours-learned-from-data-learning) Behaviours learned from data, [§61](#61-viscoelasticity-hyperelasticity-and-damage-homogenizationlaws) Viscoelasticity, hyperelasticity and damage, [§83](#83-damage-coupled-to-plasticity-of-concrete-and-the-unilateral-effect-homogenizationlaws) Damage: coupled to plasticity, of concrete, and the unilateral effect, [§86](#86-twinning-of-crystals-and-hexagonal-lattices-homogenizationcrystal) Twinning of crystals, and hexagonal lattices, [§89](#89-cracks-that-close-twins-that-shear-back-and-turn-the-lattice-homogenizationcrystal) Cracks that close, twins that shear back and turn the lattice | | Fracture, contact and fatigue | [§46](#46-cohesive-zone-elements-fracturecohesive) Cohesive zone elements, [§47](#47-cracks-conforming-meshes-and-xfem-fracturelefm) Cracks: conforming meshes and XFEM, [§48](#48-mixed-mode-cracks-in-3d-in-small-and-finite-strains-fracturemixed) Mixed-mode cracks in 3D, in small and finite strains, [§51](#51-cracks-in-inelastic-solids-in-small-and-finite-strains-fracturebulk) Cracks in inelastic solids, in small and finite strains, [§64](#64-phase-field-of-brittle-fracture-fracturephasefield) Phase field of brittle fracture, [§73](#73-cracks-of-any-surface-and-front-fracturesurface) Cracks of any surface and front, [§81](#81-friction-of-interfaces-and-of-the-lips-of-cracks-fracturecohesive-fracturemixed) Friction of interfaces and of the lips of cracks, [§82](#82-contact-of-surfaces-self-contact-and-friction-contact) Contact of surfaces, self-contact and friction, [§84](#84-interfaces-that-debond-in-periodic-cells-fractureperiodic) Interfaces that debond in periodic cells, [§85](#85-multiaxial-high-cycle-fatigue-of-the-points-of-a-cell-homogenizationfatigue) Multiaxial high-cycle fatigue of the points of a cell, [§87](#87-cleavage-of-crystals-cracks-through-the-grains-and-between-them-homogenizationcrystal-fractureperiodic) Cleavage of crystals; cracks through the grains and between them, [§88](#88-cleavage-by-the-local-approach-the-weibull-stress-of-beremin-homogenizationberemin) Cleavage by the local approach: the Weibull stress of Beremin, [§90](#90-cleavage-that-the-slip-nucleates-homogenizationcrystal) Cleavage that the slip nucleates, [§91](#91-cleavage-planes-regularized-by-their-microdamage-homogenizationcrystal) Cleavage planes regularized by their microdamage | | Stability of periodic architectures | [§45](#45-post-bifurcated-patterns-by-group-theory-symmetry-homogenizationframes) Post-bifurcated patterns by group theory, [§128](#128-periodic-plates-their-local-buckling-homogenizationplate_buckling) Periodic plates: their local buckling, [§130](#130-periodic-plates-their-thermal-and-hygral-buckling-homogenizationplate_buckling) Periodic plates: their thermal and hygral buckling, [§132](#132-panels-of-homogenized-plates-homogenizationpanels) Panels of homogenized plates | -| Other codes and libraries | [§99](#99-arrays-of-other-libraries-and-phase-fields-for-spectral-solvers-interoparrays) Arrays of other libraries and phase fields for spectral solvers, [§100](#100-the-particles-of-a-phase-for-the-discrete-element-method-iodem-modelsmesh_particles) The particles of a phase for the discrete element method, [§101](#101-microgen-modelsmicrogen-interopmicrogen) Microgen, [§102](#102-rigid-bodies-of-blender-interopblender) Rigid bodies of Blender, [§103](#103-alloys-from-their-phases-to-their-microstructures-interopalloys) Alloys: from their phases to their microstructures, [§111](#111-code_aster-and-openfoam-the-meshes-the-conditions-and-the-cases-written-iocode_aster-ioopenfoam) Code_Aster and OpenFOAM: the meshes, the conditions and the cases written, [§112](#112-the-credibility-of-the-simulations-with-vimseo-interopvimseo) The credibility of the simulations with VIMSEO, [§126](#126-the-library-of-materials-its-units-and-the-checks-of-its-values-library) The library of materials: its units and the checks of its values, [§139](#139-forchheimers-law-the-inertia-of-the-flow-through-the-pores-by-openfoam-ioopenfoamforchheimer) Forchheimer's law: the inertia of the flow through the pores, by OpenFOAM, [§145](#145-bodies-for-additive-manufacturing-surfaces-that-tile-their-box-layers-of-tpms-3mf-and-step-meshsurface-ioprinting) Bodies for additive manufacturing: surfaces that tile their box, layers of TPMS, 3MF and STEP | +| Other codes and libraries | [§99](#99-arrays-of-other-libraries-and-phase-fields-for-spectral-solvers-interoparrays) Arrays of other libraries and phase fields for spectral solvers, [§100](#100-the-particles-of-a-phase-for-the-discrete-element-method-iodem-modelsmesh_particles) The particles of a phase for the discrete element method, [§101](#101-microgen-modelsmicrogen-interopmicrogen) Microgen, [§102](#102-rigid-bodies-of-blender-interopblender) Rigid bodies of Blender, [§103](#103-alloys-from-their-phases-to-their-microstructures-interopalloys) Alloys: from their phases to their microstructures, [§111](#111-code_aster-and-openfoam-the-meshes-the-conditions-and-the-cases-written-iocode_aster-ioopenfoam) Code_Aster and OpenFOAM: the meshes, the conditions and the cases written, [§112](#112-the-credibility-of-the-simulations-with-vimseo-interopvimseo) The credibility of the simulations with VIMSEO, [§126](#126-the-library-of-materials-its-units-and-the-checks-of-its-values-library) The library of materials: its units and the checks of its values, [§139](#139-forchheimers-law-the-inertia-of-the-flow-through-the-pores-by-openfoam-ioopenfoamforchheimer) Forchheimer's law: the inertia of the flow through the pores, by OpenFOAM, [§145](#145-bodies-for-additive-manufacturing-surfaces-that-tile-their-box-layers-of-tpms-3mf-and-step-meshsurface-ioprinting) Bodies for additive manufacturing: surfaces that tile their box, layers of TPMS, 3MF and STEP, [§146](#146-meshes-for-ls-dyna-and-ansys-iostructural) Meshes for LS-DYNA and ANSYS | | Laser-architectured sheets | [§58](#58-architectured-sheets-by-localized-laser-treatment-laser) Architectured sheets by localized laser treatment, [§74](#74-a-treated-sheet-in-its-volume-lasersolid) A treated sheet in its volume | ## 1. Boolean models @@ -16927,6 +16927,44 @@ read back at their volumes; OpenCascade's solid of an octet lattice (where `cadq is installed); the surfaces of a run: the STL of the solid by default, the bodies of every phase as STL, 3MF and STEP, the errors of the configuration. +## 146. Meshes for LS-DYNA and ANSYS (`io.structural`) + +The voxel meshes (8-node bricks) and the tetrahedral meshes of morphoGen go to the codes of +structures with their phases and their elastic materials (Top6Meta's AM+ edition exports +voxel meshes for Abaqus and ANSYS; morphoGen writes Abaqus inputs with periodic constraint +equations already). + +**LS-DYNA** (`.k`, the keyword format of its manual): `*NODE` (numbers in 8 columns, +coordinates in 16) and `*ELEMENT_SOLID` (the number, the part and eight nodes in 8 columns +each: 80 columns), a 4-node tetrahedron as a degenerate brick repeating its fourth node +($n_1\,n_2\,n_3\,n_4\,n_4\,n_4\,n_4\,n_4$); a `*PART` per phase (`pid = phase + 1`) with +its `*SECTION_SOLID` (ELFORM 1, the one-point brick; 10, the one-point tetrahedron) and, +for an isotropic elastic material, its `*MAT_ELASTIC` (density — 1 when none is given —, +Young's modulus, Poisson's ratio), these cards in the free format of commas that LS-DYNA +reads; the nodes of the six faces of the box as `*SET_NODE_LIST_TITLE` (`X0` to `Z1`), for +the boundary conditions. Linear elements only (the 10-node tetrahedra are refused). + +**ANSYS Mechanical APDL** (`.ans`, commands of `/PREP7` read by `/INPUT`): the element type +(`SOLID185`, the 8-node brick; `SOLID285`, the 4-node tetrahedron; `SOLID187`, the 10-node +tetrahedron), the isotropic elastic materials (`MP,EX`, `MP,PRXY`, `MP,DENS`; `MAT = phase ++ 1`), a command `N` per node and `EN` per element (`EMORE` for its nodes beyond eight), +`TYPE` and `MAT` before the elements of each phase, and the components of the nodes of the +faces selected by their location (`NSEL,S,LOC`, `CM,X0,NODE`...). + +The node orders are those of morphoGen's meshes, which are Abaqus's and those of the three +element types: the lower face of a brick counter-clockwise seen from inside then its upper +face; the middles of the edges of a 10-node tetrahedron in the order 1-2, 2-3, 3-1, 1-4, +2-4, 3-4. The units are those of the mesh and of the materials, as given. The files are +written to the formats of the manuals of the two codes, checked by their own reader +(LS-DYNA's) and their structure; neither code runs here. + +Validated in `tests/test_structural.py`: a voxel mesh of two phases written for LS-DYNA and +read back node for node and element for element, its parts, materials, sections, node sets +and columns; 4-node tetrahedra repeating their fourth node, the comment of a phase without +material, quadratic tetrahedra refused; the APDL input of the bricks (element type, +materials, a command per node and per element, the components of the faces), of linear and +quadratic tetrahedra (SOLID285, SOLID187 with `EMORE`); a run that writes both. + ## References See [specification.md](specification.md#14-references). In addition: @@ -18110,3 +18148,7 @@ See [specification.md](specification.md#14-references). In addition: * ISO 10303-21 (2016). *Industrial automation systems and integration — Product data representation and exchange — Part 21: Implementation methods: clear text encoding of the exchange structure*. +* Livermore Software Technology (2023). *LS-DYNA keyword user's manual*, volumes I and II, + R14. +* ANSYS, Inc. (2023). *Mechanical APDL command reference* and *element reference*, release + 2023 R2. diff --git a/src/morphogen/config.py b/src/morphogen/config.py index f3305bc..82cb5ac 100644 --- a/src/morphogen/config.py +++ b/src/morphogen/config.py @@ -38,7 +38,7 @@ from morphogen.rve.study import TENSOR_PROPERTIES SURFACE_FORMATS = ("stl", "3mf", "step") -MESH_FORMATS = ("inp", "msh", "vtu", "xdmf", "med", "mesh", "mail") +MESH_FORMATS = ("inp", "msh", "vtu", "xdmf", "med", "mesh", "mail", "k", "ans") HOMOGENIZATION_METHODS = ("auto", "fe", "fft", "xfem", "levels") #: Formats of the tables of a run besides .csv (outputs.tables), of the figures and the #: videos of the visualization section (the 3D views of VTK are bitmaps) diff --git a/src/morphogen/io/__init__.py b/src/morphogen/io/__init__.py index e8939d9..8f47b06 100644 --- a/src/morphogen/io/__init__.py +++ b/src/morphogen/io/__init__.py @@ -178,8 +178,9 @@ def save_mesh(mesh, path, **options) -> Path: """A mesh written to a file whose extension gives the format: a surface mesh as .stl, .3mf or .step (:mod:`morphogen.io.printing`), a tetrahedral mesh as .inp, .msh, .vtu, .mesh, .xdmf (FEniCSx) or .mail (Code_Aster), a triangular mesh of the plane as .inp, - .msh, .vtu or .mesh, a voxel mesh as .inp, .msh or .vtu, and any of them in the other - formats of meshio.""" + .msh, .vtu or .mesh, a voxel mesh as .inp, .msh or .vtu, voxel and tetrahedral meshes + as .k (LS-DYNA) and .ans (ANSYS APDL, :mod:`morphogen.io.structural`), and any of them + in the other formats of meshio.""" ext = _ext(path) if isinstance(mesh, SurfaceMesh): if ext == "stl": @@ -195,6 +196,10 @@ def save_mesh(mesh, path, **options) -> Path: if ext in writers: return writers[ext](path, mesh, **options) return write_meshio(path, mesh) + if ext in ("k", "ans") and isinstance(mesh, (TetMesh, VoxelMesh)): + from morphogen.io.structural import write_ansys, write_lsdyna + + return (write_lsdyna if ext == "k" else write_ansys)(path, mesh, **options) if isinstance(mesh, TetMesh): writers = { "inp": write_inp_tet, diff --git a/src/morphogen/io/structural.py b/src/morphogen/io/structural.py new file mode 100644 index 0000000..4703ede --- /dev/null +++ b/src/morphogen/io/structural.py @@ -0,0 +1,166 @@ +"""Meshes for the explicit and implicit codes of structures: LS-DYNA keyword files and +ANSYS Mechanical APDL inputs, of voxel meshes (8-node bricks) and tetrahedral meshes (4- +or 10-node tetrahedra), a part per phase with its material. + +LS-DYNA (``.k``): ``*NODE`` and ``*ELEMENT_SOLID`` in the fixed fields of the keyword +format (I8 numbers, E16 coordinates); a ``*PART`` per phase with its ``*SECTION_SOLID`` +(ELFORM 1, one-point bricks; 10, one-point tetrahedra) and, for an isotropic elastic +material, its ``*MAT_ELASTIC`` (density, Young's modulus, Poisson's ratio), these cards in +the free format of commas; the nodes of the faces of the box as ``*SET_NODE_LIST_TITLE``. +Tetrahedra of four nodes repeat their fourth node as LS-DYNA asks (``n1 n2 n3 n4 n4 n4 n4 +n4``); linear elements only (bricks and 4-node tetrahedra). + +ANSYS (``.ans``, read by ``/INPUT``): commands of /PREP7, ``ET`` (SOLID185 bricks, +SOLID285 or SOLID187 tetrahedra), ``MP`` (EX, PRXY, DENS) per phase, ``N`` and ``E`` +(``EMORE`` for the nodes beyond eight), ``TYPE`` and ``MAT`` before the elements of each +phase, and the components of the faces of the box (``CM``). ANSYS Workbench reads the +Abaqus inputs of morphoGen as external models too (:func:`morphogen.io.write_inp`). + +The node orders of the three codes are those of morphoGen's meshes (Abaqus's: the four +nodes of the lower face of a brick counter-clockwise, then those of the upper face; the +middles of the edges of a 10-node tetrahedron in the order 1-2, 2-3, 3-1, 1-4, 2-4, 3-4). +Units: those of the mesh and of the materials, as given (no conversion). +""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np + +from morphogen import __version__ +from morphogen.mesh.tetra import TetMesh +from morphogen.mesh.voxel import VoxelMesh + +FACE_NAMES = ("x0", "x1", "y0", "y1", "z0", "z1") + + +def _elastic(material) -> tuple[float, float, float] | None: + """(density, Young's modulus, Poisson's ratio) of an isotropic elastic material, or + None (a material of another kind, or none).""" + if material is None or getattr(material, "void", False): + return None + young, poisson = getattr(material, "young", None), getattr(material, "poisson", None) + if young is None or poisson is None or not getattr(material, "isotropic", True): + return None + density = getattr(material, "density", None) + return (1.0 if density is None else float(density)), float(young), float(poisson) + + +def _kind(mesh) -> tuple[str, np.ndarray]: + if isinstance(mesh, VoxelMesh): + return "brick", np.asarray(mesh.elements, dtype=np.int64) + if isinstance(mesh, TetMesh): + return ("tet4" if mesh.order == 1 else "tet10"), np.asarray(mesh.elements, np.int64) + raise TypeError("a VoxelMesh or a TetMesh") + + +def _face_sets(mesh) -> dict[str, np.ndarray]: + sets = getattr(mesh, "node_sets", None) + if sets: + return {k: np.asarray(v, dtype=np.int64) for k, v in sets.items() if len(v)} + lower, upper = mesh.nodes.min(axis=0), mesh.nodes.max(axis=0) + tol = 1e-9 * float(np.max(upper - lower)) + out = {} + for a in range(3): + out[FACE_NAMES[2 * a]] = np.flatnonzero(np.abs(mesh.nodes[:, a] - lower[a]) <= tol) + out[FACE_NAMES[2 * a + 1]] = np.flatnonzero(np.abs(mesh.nodes[:, a] - upper[a]) <= tol) + return out + + +def write_lsdyna(path, mesh, *, materials: dict | None = None, title: str = "morphoGen") -> Path: + """An LS-DYNA keyword file (``.k``) of a voxel mesh or a mesh of 4-node tetrahedra: + its nodes, its solid elements by part (a part per phase, ``pid = phase + 1``), their + sections and the isotropic elastic materials of ``materials`` (phase -> material), the + node sets of the faces of the box (see the module).""" + kind, elements = _kind(mesh) + if kind == "tet10": + raise ValueError("LS-DYNA: linear elements (bricks, 4-node tetrahedra), not 10-node") + phases = np.unique(mesh.phase) + lines = ["*KEYWORD", "*TITLE", f"{title} {__version__}: {kind} mesh, {len(elements)} elements"] + lines.append("*NODE") + lines.extend(f"{i:8d}{x:16.9e}{y:16.9e}{z:16.9e}" + for i, (x, y, z) in enumerate(mesh.nodes, start=1)) # fmt: skip + lines.append("*ELEMENT_SOLID") + for e, (p, nodes) in enumerate(zip(mesh.phase, elements + 1, strict=True), start=1): + n = list(nodes) if kind == "brick" else [*nodes, nodes[3], nodes[3], nodes[3], nodes[3]] + lines.append(f"{e:8d}{int(p) + 1:8d}" + "".join(f"{k:8d}" for k in n)) + elform = 1 if kind == "brick" else 10 + for p in phases: + pid = int(p) + 1 + elastic = _elastic((materials or {}).get(int(p))) + lines += ["*PART", f"phase {int(p)}", f"{pid},{pid},{pid}"] + lines += ["*SECTION_SOLID", f"{pid},{elform}"] + if elastic is not None: + rho, young, nu = elastic + lines += ["*MAT_ELASTIC", f"{pid},{rho:.9g},{young:.9g},{nu:.9g}"] + else: + lines.append(f"$ the material {pid} of the phase {int(p)}: to be defined") + for k, (name, nodes) in enumerate(_face_sets(mesh).items(), start=1): + lines += ["*SET_NODE_LIST_TITLE", name.upper(), f"{k}"] + ids = nodes + 1 + for start in range(0, len(ids), 8): + lines.append(",".join(str(n) for n in ids[start : start + 8])) + lines.append("*END") + path = Path(path) + path.write_text("\n".join(lines) + "\n", encoding="ascii", newline="\n") + return path + + +def write_ansys(path, mesh, *, materials: dict | None = None) -> Path: + """An ANSYS Mechanical APDL input (``.ans``, read by ``/INPUT``) of a voxel or + tetrahedral mesh: element types, the isotropic elastic materials of ``materials`` + (phase -> material; ``MAT = phase + 1``), nodes, elements by phase and the components + of the faces of the box (see the module).""" + kind, elements = _kind(mesh) + etype = {"brick": "SOLID185", "tet4": "SOLID285", "tet10": "SOLID187"}[kind] + phases = np.unique(mesh.phase) + lines = [f"! morphoGen {__version__}: {kind} mesh, {len(elements)} elements", + "/PREP7", f"ET,1,{etype}"] # fmt: skip + for p in phases: + elastic = _elastic((materials or {}).get(int(p))) + if elastic is not None: + rho, young, nu = elastic + m = int(p) + 1 + lines += [f"MP,EX,{m},{young:.9g}", f"MP,PRXY,{m},{nu:.9g}", f"MP,DENS,{m},{rho:.9g}"] + lines.append("! nodes") + lines.extend(f"N,{i},{x:.12g},{y:.12g},{z:.12g}" + for i, (x, y, z) in enumerate(mesh.nodes, start=1)) # fmt: skip + lines.append("TYPE,1") + eid = 1 + for p in phases: + lines += [f"! phase {int(p)}", f"MAT,{int(p) + 1}"] + for nodes in elements[mesh.phase == p] + 1: + lines.append(f"EN,{eid}," + ",".join(str(n) for n in nodes[:8])) + if len(nodes) > 8: + lines.append("EMORE," + ",".join(str(n) for n in nodes[8:])) + eid += 1 + lower, upper = mesh.nodes.min(axis=0), mesh.nodes.max(axis=0) + for a, axis in enumerate("XYZ"): + for name, value in ((f"{axis}0", lower[a]), (f"{axis}1", upper[a])): + lines += [f"NSEL,S,LOC,{axis},{value:.12g}", f"CM,{name},NODE"] + lines.append("ALLSEL,ALL") + lines.append("FINISH") + path = Path(path) + path.write_text("\n".join(lines) + "\n", encoding="ascii", newline="\n") + return path + + +def read_lsdyna(path) -> dict: + """The nodes, the solid elements and their parts of an LS-DYNA keyword file written + by :func:`write_lsdyna` (a check of the files, not a general reader).""" + nodes, elements, parts = [], [], [] + block = None + for line in Path(path).read_text(encoding="ascii").splitlines(): + if line.startswith("*"): + block = line.strip() + continue + if line.startswith("$") or not line.strip(): + continue + if block == "*NODE": + nodes.append([float(line[8:24]), float(line[24:40]), float(line[40:56])]) + elif block == "*ELEMENT_SOLID": + fields = [int(line[k : k + 8]) for k in range(0, len(line.rstrip()), 8)] + elements.append(fields[2:]) + parts.append(fields[1]) + return {"nodes": np.array(nodes), "elements": np.array(elements), "parts": np.array(parts)} diff --git a/src/morphogen/pipeline.py b/src/morphogen/pipeline.py index db5c865..d076d1f 100644 --- a/src/morphogen/pipeline.py +++ b/src/morphogen/pipeline.py @@ -565,6 +565,8 @@ def _process( extra = {"materials": homog.materials} if not plane: extra["kinematics"] = _kinematics(homog) + elif fmt in ("k", "ans") and homog is not None: + extra = {"materials": homog.materials} target = outdir / f"{stem}_{kind}.{fmt}" try: io.save_mesh(mesh, target, **extra) @@ -877,7 +879,10 @@ def _voxel_outputs( if labels is not None and _oriented(micro, homog): extra["orientations"] = micro.orientations for fmt in out.mesh: - io.save_mesh(mesh, outdir / f"{stem}.{fmt}", **(extra if fmt == "inp" else {})) + options = extra if fmt == "inp" else {} + if fmt in ("k", "ans") and "materials" in extra: + options = {"materials": extra["materials"]} + io.save_mesh(mesh, outdir / f"{stem}.{fmt}", **options) if out.periodic_pairs: io.write_periodic_pairs(outdir / f"{stem}_periodic.csv", mesh) if out.periodic_equations and image.periodic and out.mesh_phases is None: diff --git a/tests/public_api.txt b/tests/public_api.txt index dce3d5d..79f730a 100644 --- a/tests/public_api.txt +++ b/tests/public_api.txt @@ -2709,6 +2709,10 @@ morphogen.io.solvers.write_damask(stem, grains, orientations, grain_phases=None, morphogen.io.solvers.write_fenicsx(path, mesh) morphogen.io.solvers.write_neper(stem, tessellation) morphogen.io.solvers.write_periodic_equations(path, mesh, *, physics='elastic') +morphogen.io.structural.FACE_NAMES +morphogen.io.structural.read_lsdyna(path) +morphogen.io.structural.write_ansys(path, mesh, *, materials=None) +morphogen.io.structural.write_lsdyna(path, mesh, *, materials=None, title='morphoGen') morphogen.io.tables.FORMATS morphogen.io.tables.as_columns(table, header=None) morphogen.io.tables.read_table(path, sheet=0) diff --git a/tests/test_structural.py b/tests/test_structural.py new file mode 100644 index 0000000..3486aa4 --- /dev/null +++ b/tests/test_structural.py @@ -0,0 +1,105 @@ +"""Meshes for LS-DYNA and ANSYS (theory.md §146).""" + +import numpy as np +import pytest + +import morphogen as mg +from morphogen import io, pipeline +from morphogen.config import load_config +from morphogen.homogenization import Material +from morphogen.io.structural import read_lsdyna, write_ansys, write_lsdyna +from morphogen.mesh.voxel import voxel_mesh +from morphogen.models.boolean import BooleanSpheres + +STEEL = Material(young=210e3, poisson=0.3, density=7.85e-9) +RESIN = Material(young=3e3, poisson=0.35) + + +def _voxels(): + micro = BooleanSpheres(radius=0.25, volume_fraction=0.3).generate(mg.Domain.cube(1.0), 1) + return voxel_mesh(micro.voxelize(shape=6)) + + +def _tetrahedra(): + from morphogen.mesh.tetra import TetMesh + + nodes = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 1]], dtype=float) + elements = np.array([[0, 1, 2, 3], [1, 2, 3, 4]]) + return TetMesh(nodes, elements, np.array([0, 1]), np.zeros(3), np.ones(3)) + + +def test_lsdyna_voxels(tmp_path): + """A voxel mesh: its nodes and bricks read back as written, a part per phase, the + elastic materials, the sets of the faces; fixed fields of eight columns.""" + mesh = _voxels() + path = write_lsdyna(tmp_path / "v.k", mesh, materials={0: RESIN, 1: STEEL}) + back = read_lsdyna(path) + assert np.allclose(back["nodes"], mesh.nodes, atol=1e-8) + assert np.array_equal(back["elements"], mesh.elements + 1) + assert np.array_equal(back["parts"], mesh.phase + 1) + text = path.read_text() + assert text.startswith("*KEYWORD") and text.rstrip().endswith("*END") + assert "*MAT_ELASTIC\n2,7.85e-09,210000,0.3" in text + assert "*MAT_ELASTIC\n1,1,3000,0.35" in text # a density of 1 when none is given + assert text.count("*PART") == 2 and "*SECTION_SOLID\n1,1" in text + assert text.count("*SET_NODE_LIST_TITLE") == 6 + lines = text.splitlines() + first = lines.index("*ELEMENT_SOLID") + 1 + assert len(lines[first]) == 80 # EID, PID and eight nodes of eight columns + + +def test_lsdyna_tetrahedra(tmp_path): + """Tetrahedra of four nodes repeat their fourth node; ELFORM 10; no material: a + comment; quadratic tetrahedra refused.""" + mesh = _tetrahedra() + path = write_lsdyna(tmp_path / "t.k", mesh) + back = read_lsdyna(path) + assert back["elements"].tolist() == [[1, 2, 3, 4, 4, 4, 4, 4], [2, 3, 4, 5, 5, 5, 5, 5]] + text = path.read_text() + assert "*SECTION_SOLID\n1,10" in text and "to be defined" in text + from morphogen.mesh.tetra import TetMesh + + quadratic = TetMesh(mesh.nodes, np.hstack([mesh.elements] * 3)[:, :10], mesh.phase, + mesh.lower, mesh.upper) # fmt: skip + with pytest.raises(ValueError, match="10-node"): + write_lsdyna(tmp_path / "q.k", quadratic) + + +def test_ansys(tmp_path): + """An APDL input: the element type of each mesh, the materials, a node and an element + command each, the components of the faces; EMORE for the nodes beyond eight.""" + mesh = _voxels() + path = io.save_mesh(mesh, tmp_path / "v.ans", materials={1: STEEL}) + text = path.read_text() + assert "/PREP7" in text and "ET,1,SOLID185" in text and text.rstrip().endswith("FINISH") + assert "MP,EX,2,210000" in text and "MP,PRXY,2,0.3" in text and "MP,DENS,2,7.85e-09" in text + nodes = [ln for ln in text.splitlines() if ln.startswith("N,")] + elements = [ln for ln in text.splitlines() if ln.startswith("EN,")] + assert len(nodes) == mesh.n_nodes and len(elements) == mesh.n_elements + first = elements[0].split(",") + assert len(first) == 10 + for face in ("X0", "X1", "Y0", "Y1", "Z0", "Z1"): + assert f"CM,{face},NODE" in text + from morphogen.mesh.tetra import TetMesh + + tets = _tetrahedra() + assert "ET,1,SOLID285" in write_ansys(tmp_path / "t.ans", tets).read_text() + mids = np.arange(5, 11).reshape(1, 6) % 5 + quadratic = TetMesh(tets.nodes, np.hstack([tets.elements[:1], mids]), tets.phase[:1], + tets.lower, tets.upper) # fmt: skip + text = write_ansys(tmp_path / "q.ans", quadratic).read_text() + assert "ET,1,SOLID187" in text and "EMORE," in text + + +def test_in_a_run(tmp_path): + """A run writes its voxel mesh for LS-DYNA and ANSYS with the materials of its + homogenization.""" + config = { + "model": {"type": "boolean_spheres", "radius": 0.25, "volume_fraction": 0.3}, + "domain": {"size": 1.0, "periodic": True}, + "voxels": {"shape": 8}, + "seed": 1, + "outputs": {"directory": str(tmp_path), "name": "spheres", "mesh": ["k", "ans"]}, + } + outdir = pipeline.run(load_config(config)) + assert list(outdir.rglob("spheres*.k")) and list(outdir.rglob("spheres*.ans")) From d2cd82559c3e5e781954568682dd34cc03afe499 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 00:16:56 +0000 Subject: [PATCH 10/13] Printability by additive manufacturing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit analysis.printability (theory notes §147, FR-M9, specification 1.261): the thinnest walls and holes of a realization or an image against the process and the resolution of its voxels (local thickness, first percentiles and medians), its overhangs below the self-supporting angle along the six directions of the axes (the implicit surface, or the smoothed signed distance of the voxels, whose terraces halve the overhangs), the islands of the solid that do not reach the build plate and the closed cavities that trap powder; a verdict, the need of supports and the reasons. The section printability of a run writes a JSON report per realization and the columns printability.*. Checked against a horizontal cylinder. The public interface written again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MSrXEMpgnWPQNUwHwAgXHV --- CHANGELOG.md | 9 + docs/configuration.md | 6 + docs/measures.md | 11 ++ docs/specification.md | 6 +- docs/theory.md | 50 ++++- src/morphogen/analysis/printability.py | 258 +++++++++++++++++++++++++ src/morphogen/config.py | 35 ++++ src/morphogen/pipeline.py | 21 ++ tests/public_api.txt | 8 +- tests/test_printability.py | 124 ++++++++++++ 10 files changed, 525 insertions(+), 3 deletions(-) create mode 100644 src/morphogen/analysis/printability.py create mode 100644 tests/test_printability.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c152cf..15eb71e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +* Printability by additive manufacturing ([docs/theory.md](docs/theory.md) §147, + `morphogen.analysis.printability`, the section `printability:` of a run): the thinnest + walls against the process (`min_wall`) and the resolution of the voxels, the narrowest + holes against drainage (`min_hole`), the overhangs below the self-supporting angle along + the six directions of the axes (the best proposed), the islands that do not reach the + build plate and the closed cavities that trap powder; `printable`, `needs_supports` and + the reasons; a JSON report per realization and the columns `printability.*`. Public + interface: `morphogen.analysis.printability` (`printability`, `Printability`, + `DIRECTIONS`). * Meshes for LS-DYNA and ANSYS ([docs/theory.md](docs/theory.md) §146, `morphogen.io.structural`): the voxel and tetrahedral meshes as LS-DYNA keyword files (`.k`: nodes and solid elements in fixed fields, a part per phase with its section and diff --git a/docs/configuration.md b/docs/configuration.md index 3239a26..ab8de97 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -105,6 +105,12 @@ analysis: [volume_fraction, specific_surface, connectivity, phase_fractions, cel # union of spheres exactly: exact_V_V, exact_S_V, exact_M_V, exact_chi_V), # exact_grains (the grains of a tessellation on its exact cells; the # grains of seeds against their seeds) +printability: # the checks of additive manufacturing of every realization, on its + build: +z # voxels (needs the voxels section): the direction of the build + min_wall: 0.3 # the thinnest wall the process builds; min_hole: the narrowest + min_hole: 0.5 # channel that drains; overhang_angle: 45 (from the horizontal); + # __printability.json and the columns printability.* + # (printable, overhang_fraction, islands, trapped_voids...) homogenization: # apparent properties of every realization method: auto # fe (mesh section) | fft (voxels, periodic) | xfem (the level set # of the model cut by the grid of the voxels section, periodic) | diff --git a/docs/measures.md b/docs/measures.md index f04c0f8..04f3f3d 100644 --- a/docs/measures.md +++ b/docs/measures.md @@ -160,6 +160,17 @@ model = mg.models.Reconstruction(reference=spheres, cell_size=1.0, method="gradi seeds, fractions of the phases; `morphogen.viz.figures.seed_figure` draws them; the tool *Grains and their seeds* of the interface; [theory notes](theory.md) §116, §117). +## Printability for additive manufacturing + +`morphogen.analysis.printability.printability(micro or image, build="+z", min_wall=..., +min_hole=..., overhang_angle=45)` checks a part before printing it +([theory notes](theory.md) §147): the thinnest walls against the process and the +resolution of the voxels, the narrowest holes against the drainage of powder or resin, the +overhangs (and the direction of the six that has the fewest), the islands of the solid +that do not reach the build plate and the closed cavities that trap powder; `printable`, +`needs_supports` and the warnings that say why. A run does it for each realization with a +section `printability:` (the report as JSON, its values in the results). + ## Crystallographic textures and orientation maps `morphogen.texture` and `morphogen.io.ebsd` handle the orientations of polycrystals: the diff --git a/docs/specification.md b/docs/specification.md index 5eea6ac..ce10997 100644 --- a/docs/specification.md +++ b/docs/specification.md @@ -3,7 +3,7 @@ | | | |---|---| | Document | Software requirements specification | -| Version | 1.260 | +| Version | 1.261 | | Date | 2026-12-01 | | Author | @jdirr | | Status | Version 1.1 **validated** on 2026-10-21. The later versions, proposed, are listed in the change log (§13); changes go through pull requests that update this file and its change log. | @@ -372,6 +372,8 @@ centred on morphological modelling. | Delivered | FR-G34, FR-E20 (`tpms_layers`, `mesh.surface.phase_surfaces`, `io.printing`, `outputs.surface: {formats, phases, unit}`, [theory.md](theory.md) §145): the bodies of the phases tiling the box (nodes with the faces, mirrored padding, merged vertices); layers of TPMS; 3MF with base materials; STEP solids (AP214, `MANIFOLD_SOLID_BREP` of planar `ADVANCED_FACE`s) read by OpenCascade as valid solids at their volumes, or faceted shells | | Additive manufacturing: LS-DYNA and ANSYS (2026-12-01) | The voxel meshes of the AM+ edition of Top6Meta, for two more codes of structures. | | Delivered | FR-E21 (`io.structural.write_lsdyna`, `write_ansys`, the mesh formats `k` and `ans` of `outputs.mesh` and `outputs.conforming_mesh`, [theory.md](theory.md) §146) | +| Additive manufacturing: printability (2026-12-01) | The checks of Top6Meta's AM+ edition, before printing. | +| Delivered | FR-M9 (`analysis.printability`, the section `printability` of a run, [theory.md](theory.md) §147): local thickness of the solid and of the void (first percentiles and medians), overhangs of the implicit surface or of the smoothed distance of the voxels, islands and trapped voids, the best of the six directions; checked against a horizontal cylinder | ## 4. Scope @@ -475,6 +477,7 @@ version, 0.1). | FR-M6 | Identification of a morphological model from an image or a volume: candidates fitted by their closed forms to the fraction and the specific surface, simulated on voxels of the size of the image, calibrated and ranked by the shapes of the covariance and of the contact distributions; from a volume or from one section (stereology) | S | 3d | | FR-M7 | Segmentation of grey-level images and stacks: Otsu's thresholds (one or several), smoothing and equalization, the particles and the ellipsoids of their moments, the laws of their sizes, the scores of a segmentation against a reference | S | 3d | | FR-M8 | Reconstruction from descriptors by gradient descent: the cells relaxed, the two-point probability at every lag and the lineal paths with their exact gradients, towards the closed forms of a model of random sets or the measures of an image; a volume from a planar section | S | 3d | +| FR-M9 | Printability by additive manufacturing: the thinnest walls and holes against the process and the resolution, the overhangs along the six directions of the axes, the islands of the solid off the build plate, the closed cavities trapping powder; a verdict and its reasons, in the runs | S | 1d | ### 5.4 RVE statistics @@ -1448,6 +1451,7 @@ Packages: `models`, `kernels`, `analysis`, `rve`, `mesh`, `homogenization`, `io` | 1.258 | 2026-12-01 | Strut lattices: octahedral and rhombic dodecahedral cells, reinforcements, curved struts, custom cells (FR-G33, §3.12) | | 1.259 | 2026-12-01 | Bodies that tile their box, layers of TPMS, 3MF and STEP (FR-G34, FR-E20, §3.12) | | 1.260 | 2026-12-01 | Meshes for LS-DYNA and ANSYS (FR-E21, §3.12) | +| 1.261 | 2026-12-01 | Printability by additive manufacturing (FR-M9, §3.12) | ## 14. References diff --git a/docs/theory.md b/docs/theory.md index b62ff8d..38f9669 100644 --- a/docs/theory.md +++ b/docs/theory.md @@ -15,7 +15,7 @@ them by these numbers (§75); by theme: | Architected and bio-inspired structures | [§6](#6-tpms) TPMS, [§7](#7-strut-lattices) Strut lattices, [§30](#30-bio-inspired-models) Bio-inspired models, [§71](#71-diamond-and-pyrochlore-lattices-of-struts-homogenizationframes-modelslattice) Diamond and pyrochlore lattices of struts, [§96](#96-woven-textile-composites-woven_textile) Woven textile composites, [§110](#110-woven-textiles-the-variability-of-the-tows-3d-architectures-the-tows-as-unidirectional-composites-woven_textile-homogenizationunidirectional) Woven textiles: the variability of the tows, 3D architectures, the tows as unidirectional composites, [§125](#125-plate-lattices-plate_lattice) Plate lattices, [§140](#140-tpms-ten-surfaces-their-two-networks-and-their-gradients-modelstpms) TPMS: ten surfaces, their two networks and their gradients, [§141](#141-spinodoids-levels-of-sums-of-waves-of-one-wavelength-modelsspinodoid) Spinodoids: levels of sums of waves of one wavelength, [§142](#142-hybrid-architectures-two-models-blended-across-a-transition-modelshybrid) Hybrid architectures: two models blended across a transition, [§143](#143-parts-ready-to-print-infills-in-shapes-with-shells-skins-and-supports-modelspart) Parts ready to print: infills in shapes, with shells, skins and supports, [§144](#144-strut-lattices-octahedral-and-rhombic-dodecahedral-cells-reinforcements-curved-struts-custom-cells-modelslattice) Strut lattices: octahedral and rhombic dodecahedral cells, reinforcements, curved struts, custom cells | | Growth and design | [§14](#14-cellular-automata-automata) Cellular automata, [§15](#15-nucleation-and-growth-johnsonmehlavramikolmogorov) Nucleation and growth (Johnson–Mehl–Avrami–Kolmogorov), [§16](#16-aggregation) Aggregation, [§17](#17-combinatorial-design-design) Combinatorial design, [§18](#18-topology-optimization-of-periodic-cells-optimization) Topology optimization of periodic cells, [§78](#78-isogeometric-analysis-iga) Isogeometric analysis, [§79](#79-isogeometric-shape-optimization-igaoptimization) Isogeometric shape optimization, [§109](#109-inverse-design-of-active-structures-optimizationmorphing) Inverse design of active structures, [§113](#113-spinodal-decomposition-spinodal) Spinodal decomposition | | Geometry and meshes | [§19](#19-polycrystals-exact-cells-and-conforming-meshes-meshpolyhedra-meshpolycrystal) Polycrystals: exact cells and conforming meshes, [§24](#24-whole-periodic-grains-meshpolycrystal-cells-whole) Whole periodic grains, [§52](#52-views-and-measures-of-the-level-sets-vizsections) Views and measures of the level sets, [§75](#75-the-implicit-geometry-of-every-model-modelsimplicit-meshconforming) The implicit geometry of every model, [§76](#76-quadratic-tetrahedra-isoparametric-elements-and-curved-interfaces-meshcurved-homogenizationfe) Quadratic tetrahedra: isoparametric elements and curved interfaces, [§80](#80-sharp-edges-of-the-phases-meshes-that-follow-them-modelspieces-meshconforming-meshcurved) Sharp edges of the phases: meshes that follow them, [§94](#94-exact-meshes-without-a-background-grid-meshexact-meshoctree) Exact meshes without a background grid, [§119](#119-meshes-of-the-plane-and-their-finite-elements-meshtriangles-homogenizationplane) Meshes of the plane and their finite elements | -| Measures | [§8](#8-specific-surface-by-cauchycrofton) Specific surface by Cauchy–Crofton, [§21](#21-morphological-measures-analysismorphology) Morphological measures, [§39](#39-random-sets-probed-by-structuring-elements-analysisrandom_sets-analysistopology) Random sets probed by structuring elements, [§55](#55-percolation-thresholds-analysispercolation) Percolation thresholds, [§70](#70-particles-of-a-phase-in-a-volume-analysisparticles) Particles of a phase in a volume, [§92](#92-crystallographic-textures-and-orientation-maps-texture-ioebsd-modelsebsd) Crystallographic textures and orientation maps, [§104](#104-measures-of-the-implicit-geometry-morphologymeasures) Measures of the implicit geometry, [§105](#105-unions-of-balls-and-of-discs-measured-exactly-morphologyballs) Unions of balls and of discs, measured exactly, [§106](#106-the-model-of-an-image-morphologyidentification) The model of an image | +| Measures | [§8](#8-specific-surface-by-cauchycrofton) Specific surface by Cauchy–Crofton, [§21](#21-morphological-measures-analysismorphology) Morphological measures, [§39](#39-random-sets-probed-by-structuring-elements-analysisrandom_sets-analysistopology) Random sets probed by structuring elements, [§55](#55-percolation-thresholds-analysispercolation) Percolation thresholds, [§70](#70-particles-of-a-phase-in-a-volume-analysisparticles) Particles of a phase in a volume, [§92](#92-crystallographic-textures-and-orientation-maps-texture-ioebsd-modelsebsd) Crystallographic textures and orientation maps, [§104](#104-measures-of-the-implicit-geometry-morphologymeasures) Measures of the implicit geometry, [§105](#105-unions-of-balls-and-of-discs-measured-exactly-morphologyballs) Unions of balls and of discs, measured exactly, [§106](#106-the-model-of-an-image-morphologyidentification) The model of an image, [§147](#147-printability-by-additive-manufacturing-analysisprintability) Printability by additive manufacturing | | Representative volume element | [§9](#9-representative-volume-element) Representative volume element, [§13](#13-statistical-analysis-of-apparent-properties-dirrenberger-et-al-2014) Statistical analysis of apparent properties (Dirrenberger et al. 2014) | | Apparent properties and solvers | [§10](#10-apparent-properties-of-a-volume-element) Apparent properties of a volume element, [§11](#11-finite-elements-on-conforming-meshes) Finite elements on conforming meshes, [§12](#12-fft-solver-on-voxel-images) FFT solver on voxel images, [§20](#20-anisotropic-crystals-homogenizationmaterials) Anisotropic crystals, [§25](#25-the-periodic-element-macroscopic-strains-and-stresses-as-unknowns) The periodic element: macroscopic strains and stresses as unknowns, [§26](#26-thermo-elasticity) Thermo-elasticity, [§27](#27-post-processing-compliance-engineering-constants-anisotropy-normalized-values) Post-processing: compliance, engineering constants, anisotropy, normalized values, [§28](#28-results-database-and-ashby-charts-results) Results database and Ashby charts, [§35](#35-the-fft-solvers-on-the-gpu-morphogengpu-homogenizationgpu) The FFT solvers on the GPU, [§41](#41-the-fenicsx-solver-homogenizationfenicsx) The FEniCSx solver, [§63](#63-extended-finite-elements-of-level-sets-homogenizationxfem) Extended finite elements of level sets, [§77](#77-nearly-incompressible-phases-the-mean-dilatation-of-the-10-node-tetrahedra-homogenizationdilatation) Nearly incompressible phases: the mean dilatation of the 10-node tetrahedra, [§122](#122-periodic-plates-their-stiffness-of-kirchhoff-and-love-homogenizationplates) Periodic plates: their stiffness of Kirchhoff and Love, [§123](#123-periodic-plates-their-transverse-shear-by-the-bending-gradient-homogenizationplates) Periodic plates: their transverse shear by the bending gradient, [§129](#129-periodic-plates-their-elastic-limits-homogenizationplate_strength) Periodic plates: their elastic limits, [§133](#133-periodic-plates-their-collapse-homogenizationplate_collapse) Periodic plates: their collapse, [§134](#134-panels-of-periodic-plates-their-collapse-by-yield-lines-homogenizationpanels-homogenizationplate_collapse) Panels of periodic plates: their collapse by yield lines, [§135](#135-nonlinear-magnetostatics-saturating-magnetization-homogenizationmagnetics) Nonlinear magnetostatics: saturating magnetization, [§136](#136-magnetoelastic-coupling-at-finite-strains-magnetorheological-elastomers-homogenizationmagnetoelastic) Magnetoelastic coupling at finite strains: magnetorheological elastomers, [§137](#137-hierarchical-structures-and-their-homogenization-level-by-level-modelshierarchy-homogenizationhierarchy) Hierarchical structures and their homogenization level by level, [§138](#138-micromagnetics-of-microstructures-magnetic-domains-and-their-evolution-in-a-field-homogenizationmicromagnetics) Micromagnetics of microstructures: magnetic domains and their evolution in a field | | Other physics and waves | [§40](#40-couplings-diffusion-thermal-oxidation-ageing-hygromorphs-coupling) Couplings: diffusion, thermal oxidation, ageing, hygromorphs, [§44](#44-bloch-waves-in-periodic-cells-homogenizationbloch) Bloch waves in periodic cells, [§59](#59-transport-phenomena-of-a-scalar-potential-homogenizationmaterials-apparent) Transport phenomena of a scalar potential, [§60](#60-strong-couplings-homogenizationcoupled) Strong couplings, [§62](#62-harmonic-regimes-homogenizationharmonic) Harmonic regimes, [§65](#65-weak-couplings-swelling-and-poroelasticity-homogenizationporoelastic) Weak couplings: swelling and poroelasticity, [§66](#66-scalar-bloch-waves-homogenizationbloch) Scalar Bloch waves, [§67](#67-flow-through-the-pores-darcys-permeability-homogenizationflow) Flow through the pores: Darcy's permeability, [§68](#68-acoustics-of-porous-media-homogenizationacoustics) Acoustics of porous media, [§69](#69-electromagnetic-bloch-waves-of-three-dimensional-crystals-homogenizationphotonic) Electromagnetic Bloch waves of three-dimensional crystals, [§72](#72-thermal-oxidation-in-a-microstructure-couplingoxidation_field) Thermal oxidation in a microstructure, [§108](#108-thermo-chemo-elastic-couplings-in-time-couplingthermochemoelastic) Thermo-chemo-elastic couplings in time, [§120](#120-creeping-flow-through-the-pores-of-the-plane-homogenizationplane_flow) Creeping flow through the pores of the plane, [§121](#121-creeping-flow-through-the-pores-of-a-conforming-mesh-homogenizationmesh_flow) Creeping flow through the pores of a conforming mesh, [§124](#124-panels-their-sound-transmission-homogenizationacoustics) Panels: their sound transmission, [§127](#127-periodic-plates-their-waves-homogenizationbloch-homogenizationplates) Periodic plates: their waves, [§131](#131-periodic-plates-their-prestressed-waves-homogenizationbloch-homogenizationplates) Periodic plates: their prestressed waves | @@ -16965,6 +16965,54 @@ material, quadratic tetrahedra refused; the APDL input of the bricks (element ty materials, a command per node and per element, the components of the faces), of linear and quadratic tetrahedra (SOLID285, SOLID187 with `EMORE`); a run that writes both. +## 147. Printability by additive manufacturing (`analysis.printability`) + +Before a part is printed, a slicer or a process engineer checks that each of its layers +stands on the one below and that its features are within reach of the process; Top6Meta +sells these checks as its AM+ edition. `printability` makes them on the voxels and the +surface of a realization (its implicit surface) or of an image (the surface of the signed +distance of its voxels, smoothed over one voxel), built along a direction $b$ of the six +of the axes. + +**Walls and holes.** The local thickness of the solid at a point is the diameter of the +largest ball within the solid that contains it (Hildebrand & Rüegsegger 1997; §21); the +walls thinner than the thinnest the process builds (`min_wall`: about 0.3 mm in laser +powder-bed fusion, 0.5 mm in stereolithography) are a share of the solid, and the local +thickness of the void against the narrowest channel that drains (`min_hole`) a share of +the void. The thinnest walls and holes are the first percentiles of their thickness over +their volumes (the slivers that the faces of the box cut from a TPMS do not set them). A +voxel image resolves a thickness of three voxels at least: thinner walls are flagged. + +**Overhangs.** A face of outward normal $n$ facing down ($n\cdot b < 0$) makes the angle +$\arccos(-n\cdot b)$ with the horizontal; below the self-supporting angle $\theta_c$ +(`overhang_angle`, 45° by default) it needs supports: $-n\cdot b > \cos\theta_c$. The faces +lying on the build plate (the face of the box where the build starts) are supported. The +share of the overhangs in the area of the surface off the plate is computed for the six +directions; the one with the fewest is proposed. On a horizontal cylinder of radius $R$ and +length $L$ the faces within 45° of straight down are a quarter of its side, a share +$\tfrac14\,2\pi RL/(2\pi RL + 2\pi R^2)$ of its surface (0.208 for $R = 2$, $L = 10$); the +surface of its level set gives 0.194 on $64^3$ voxels and 0.202 on $128^3$. The terraces +of the surface of the voxels themselves give half of it (their facets are horizontal, +vertical or at 45°, on the threshold): the smoothed signed distance of a voxel image gives +0.198. + +**Islands and trapped powder.** The components of the solid connected by their faces +(6-connectivity) that do not reach the layer of the build plate grow on nothing; the +components of the void that reach no face of the box are closed cavities whose powder or +resin cannot drain. The part is printable with no island, no trapped void and thin walls +below `tolerance` of its solid (1 %); it needs supports when its overhangs exceed +`tolerance` of its surface. + +Validated in `tests/test_printability.py`: the overhangs of the smooth surface of a +horizontal cylinder converging to the share of the quarter of its side, those of its +voxels within 0.015 of it, none along its axis, which is proposed, the cylinder an island, +its median wall its diameter within 0.5; a plate with a cube hollowed by a closed cavity +and a floating cube (one island, one trapped void, the share of the cavity; built from +the top, two islands); the walls of a sheet gyroid under-resolved on coarse voxels, +resolved on fine ones, thin walls and narrow holes against the process; a sandwich of a +gyroid between skins printable without islands nor trapped voids; a run writing the report +and its columns, the errors of the configuration. + ## References See [specification.md](specification.md#14-references). In addition: diff --git a/src/morphogen/analysis/printability.py b/src/morphogen/analysis/printability.py new file mode 100644 index 0000000..616d0fa --- /dev/null +++ b/src/morphogen/analysis/printability.py @@ -0,0 +1,258 @@ +"""Printability of a part by additive manufacturing (powder-bed and vat processes): the +checks that a slicer or a process engineer makes before printing, on the voxels and the +surface of a realization or of an image. + +* **Walls and holes.** The local thickness of the solid (the diameter of the largest ball + inside it that covers each point; Hildebrand & Rüegsegger 1997) against the thinnest + wall the process builds (``min_wall``), and that of the void against the narrowest + channel through which powder or resin drains (``min_hole``): the fractions of the solid + and of the void below them, the thinnest walls and holes (the first percentile of the + thickness over their volume, which the slivers left by the faces of the box do not + set) and the median ones. A voxel image resolves a thickness of three voxels at least: + thinner walls are flagged as under-resolved. +* **Overhangs.** A face of the surface whose outward normal points down, at an angle from + the horizontal smaller than the self-supporting angle (``overhang_angle``, 45 degrees by + default: ``-n . b > cos(angle)``, ``b`` the build direction), needs supports; the faces + that lie on the build plate (the lower face of the box) do not. The area of the + overhangs, and its share of the area of the surface off the plate, for the six + directions of the axes: the best of them to build along. +* **Islands.** The components of the solid (connected by their faces) that do not reach + the build plate grow on nothing. +* **Trapped powder.** The components of the void (connected by their faces) that do not + reach a face of the box are closed cavities from which powder or resin cannot drain. + +The part is printable when it has no island, no trapped void and its thin walls are less +than ``tolerance`` of its solid (0.01); it needs supports when its overhangs exceed +``tolerance`` of its surface. +""" + +from __future__ import annotations + +import math +from dataclasses import asdict, dataclass, field + +import numpy as np +from scipy import ndimage + +from morphogen.analysis.morphology import local_thickness +from morphogen.image import VoxelImage +from morphogen.mesh.surface import SurfaceMesh, surface_mesh + +#: The six build directions: the axis and its sense. +DIRECTIONS = {"+x": (0, 1), "-x": (0, -1), "+y": (1, 1), "-y": (1, -1), "+z": (2, 1), + "-z": (2, -1)} # fmt: skip +#: Voxels across the thinnest wall that a voxel image resolves. +RESOLVED = 3 + + +@dataclass +class Printability: + """The checks of a part (see the module); lengths in the units of the image.""" + + build: str + voxel_size: float + min_wall: float | None + min_hole: float | None + overhang_angle: float + solid_fraction: float + wall_min: float + wall_median: float + thin_fraction: float | None + hole_min: float | None + hole_median: float | None + narrow_fraction: float | None + surface_area: float + overhang_area: float + overhang_fraction: float + orientations: dict[str, float] + best_build: str + components: int + islands: int + island_fraction: float + trapped_voids: int + trapped_fraction: float + under_resolved: bool + printable: bool + needs_supports: bool + warnings: list[str] = field(default_factory=list) + + def to_dict(self) -> dict: + return asdict(self) + + def summary(self) -> str: + """The verdict and its reasons, in a few lines.""" + verdict = "printable" if self.printable else "not printable as it is" + lines = [f"{verdict}, built along {self.build}" + + (" (with supports)" if self.needs_supports else "")] # fmt: skip + lines += [f" {w}" for w in self.warnings] + lines.append(f" best direction: {self.best_build} " + f"(overhangs {100 * self.orientations[self.best_build]:.1f} %)") # fmt: skip + return "\n".join(lines) + + +def _overhangs(surface: SurfaceMesh, axis: int, sense: int, plate: float, angle: float, tol): + """The area of the overhanging faces and the area off the plate, for a direction.""" + v = surface.vertices[surface.faces] + cross = np.cross(v[:, 1] - v[:, 0], v[:, 2] - v[:, 0]) + area = 0.5 * np.linalg.norm(cross, axis=1) + normal = cross / np.maximum(2.0 * area, 1e-300)[:, None] + on_plate = np.all(np.abs(v[:, :, axis] - plate) <= tol, axis=1) + down = -sense * normal[:, axis] + overhang = (down > math.cos(math.radians(angle))) & ~on_plate + off = float(area[~on_plate].sum()) + return float(area[overhang].sum()), off + + +def _smooth_distance(solid: np.ndarray, image: VoxelImage) -> VoxelImage: + """The signed distance to the boundary of the solid voxels (negative inside, the + boundary half a voxel from the centres), smoothed over a voxel: a surface without the + terraces of a voxel image, whose normals are those of the shape (the overhangs of a + terraced surface are half of the true ones).""" + h = np.asarray(image.spacing, dtype=float) + half = 0.5 * float(h.min()) + inner = ndimage.distance_transform_edt(solid, sampling=h) - half + outer = ndimage.distance_transform_edt(~solid, sampling=h) - half + d = ndimage.gaussian_filter(np.where(solid, -inner, outer), 1.0, mode="nearest") + return VoxelImage.from_grid(d.astype(np.float32), image.grid(), name="level_set") + + +def _touching(labels: np.ndarray, n: int, faces) -> np.ndarray: + """Whether each label (1 to n) reaches one of the faces of the array given as + ``(axis, index)``.""" + hit = np.zeros(n + 1, dtype=bool) + for axis, index in faces: + hit[np.unique(np.take(labels, index, axis=axis))] = True + hit[0] = False + return hit + + +def printability( + source, + *, + shape=None, + voxel_size=None, + build: str = "+z", + min_wall: float | None = None, + min_hole: float | None = None, + overhang_angle: float = 45.0, + tolerance: float = 0.01, +) -> Printability: + """The checks of the printability of a realization (phase 1 the solid; voxelized at + ``shape`` or ``voxel_size``, its surface from its implicit function) or of a voxel + image (phase 1 the solid), built along ``build`` (``+z``: from the lower face of the + box up; ``-x`` ...) — see the module.""" + if build not in DIRECTIONS: + raise ValueError(f"build: one of {', '.join(DIRECTIONS)}") + if not 0.0 < overhang_angle < 90.0: + raise ValueError("overhang_angle: between 0 and 90 degrees") + if isinstance(source, VoxelImage): + image = source + solid = image.data == 1 if image.data.dtype.kind in "iub" else image.data >= 0.5 + surface = surface_mesh(_smooth_distance(solid, image), closed=True) + else: + if shape is None and voxel_size is None: + shape = 128 + image = source.voxelize(shape=shape, voxel_size=voxel_size) + solid = image.data == 1 + try: + field_ = source.level_set(grid=image.grid()) + except NotImplementedError: + field_ = _smooth_distance(solid, image) + surface = surface_mesh(field_, closed=True) + h = np.asarray(image.spacing, dtype=float) + hmin = float(h.min()) + warnings = [] + fraction = float(solid.mean()) + + # walls and holes + walls = local_thickness(VoxelImage.from_grid(solid.astype(np.uint8), image.grid()), 1, + periodic=False)[solid] # fmt: skip + wall_min = float(np.percentile(walls, 1.0)) if walls.size else 0.0 + wall_median = float(np.median(walls)) if walls.size else 0.0 + thin = None if min_wall is None else float(np.mean(walls < min_wall)) if walls.size else 0.0 + under = wall_min < RESOLVED * hmin + if under: + warnings.append(f"walls of {wall_min:.4g} resolved by fewer than {RESOLVED} voxels of " + f"{hmin:.4g}: refine the voxels") # fmt: skip + if thin: + warnings.append(f"{100 * thin:.1f} % of the solid thinner than the walls of " + f"{min_wall:g} the process builds") # fmt: skip + hole_min = hole_median = narrow = None + if (~solid).any(): + voids = local_thickness(VoxelImage.from_grid((~solid).astype(np.uint8), image.grid()), + 1, periodic=False)[~solid] # fmt: skip + hole_min, hole_median = float(np.percentile(voids, 1.0)), float(np.median(voids)) + if min_hole is not None: + narrow = float(np.mean(voids < min_hole)) + if narrow: + warnings.append(f"{100 * narrow:.1f} % of the void narrower than the holes of " + f"{min_hole:g} that drain") # fmt: skip + + # overhangs, for the six directions + lower = np.asarray(image.origin, dtype=float) + upper = lower + h * np.array(image.shape) + tol = 1e-6 * float(np.max(upper - lower)) + orientations, area_off = {}, {} + for name, (axis, sense) in DIRECTIONS.items(): + plate = lower[axis] if sense > 0 else upper[axis] + over, off = _overhangs(surface, axis, sense, plate, overhang_angle, tol) + orientations[name] = over / off if off > 0 else 0.0 + area_off[name] = (over, off) + overhang_area, off = area_off[build] + overhang_fraction = orientations[build] + best = min(orientations, key=orientations.get) + if overhang_fraction > tolerance: + tilt = 90 - overhang_angle + warnings.append(f"{100 * overhang_fraction:.1f} % of the surface overhangs by more " + f"than {tilt:g} degrees from the vertical: supports") # fmt: skip + + # islands and trapped voids + axis, sense = DIRECTIONS[build] + structure = ndimage.generate_binary_structure(3, 1) + labels, n = ndimage.label(solid, structure=structure) + plate_index = 0 if sense > 0 else solid.shape[axis] - 1 + grounded = _touching(labels, n, [(axis, plate_index)]) + sizes = np.bincount(labels.ravel(), minlength=n + 1) + islands = int(n - grounded[1:].sum()) + island_fraction = float(sizes[1:][~grounded[1:]].sum() / max(sizes[1:].sum(), 1)) + if islands: + warnings.append(f"{islands} island(s) of the solid not reaching the build plate " + f"({100 * island_fraction:.2g} % of the solid)") # fmt: skip + voids, m = ndimage.label(~solid, structure=structure) + faces = [(a, i) for a in range(3) for i in (0, solid.shape[a] - 1)] + open_ = _touching(voids, m, faces) + void_sizes = np.bincount(voids.ravel(), minlength=m + 1) + trapped = int(m - open_[1:].sum()) + trapped_fraction = float(void_sizes[1:][~open_[1:]].sum() / max(void_sizes[1:].sum(), 1)) + if trapped: + warnings.append(f"{trapped} closed cavit{'y' if trapped == 1 else 'ies'} trapping powder " + f"or resin ({100 * trapped_fraction:.2g} % of the void)") # fmt: skip + printable = islands == 0 and trapped == 0 and (thin or 0.0) <= tolerance + return Printability( + build=build, + voxel_size=hmin, + min_wall=min_wall, + min_hole=min_hole, + overhang_angle=float(overhang_angle), + solid_fraction=fraction, + wall_min=wall_min, + wall_median=wall_median, + thin_fraction=thin, + hole_min=hole_min, + hole_median=hole_median, + narrow_fraction=narrow, + surface_area=float(surface.area()), + overhang_area=overhang_area, + overhang_fraction=overhang_fraction, + orientations=orientations, + best_build=best, + components=int(n), + islands=islands, + island_fraction=island_fraction, + trapped_voids=trapped, + trapped_fraction=trapped_fraction, + under_resolved=bool(under), + printable=bool(printable), + needs_supports=bool(overhang_fraction > tolerance), + warnings=warnings, + ) diff --git a/src/morphogen/config.py b/src/morphogen/config.py index 82cb5ac..f28c481 100644 --- a/src/morphogen/config.py +++ b/src/morphogen/config.py @@ -690,6 +690,9 @@ class RunConfig: visualization: VisualizationSpec | None = None threads: int | None = None source: dict = field(default_factory=dict) + #: the checks of printability of each realization (the options of + #: morphogen.analysis.printability.printability), or None + printability: dict | None = None def read_config_file(path) -> dict: @@ -3110,6 +3113,33 @@ def _model_paths(model, base: Path): return out +def _printability(data) -> dict | None: + """The options of the checks of printability (``true``: the defaults).""" + if data is None or data is False: + return None + if data is True: + return {} + if not isinstance(data, dict): + raise ConfigError("printability: true, or a mapping of its options") + from morphogen.analysis.printability import DIRECTIONS + + _check_keys("printability", data, {"build", "min_wall", "min_hole", "overhang_angle", + "tolerance"}) # fmt: skip + out = dict(data) + if str(out.get("build", "+z")) not in DIRECTIONS: + raise ConfigError(f"printability.build: one of {list(DIRECTIONS)}") + for key in ("min_wall", "min_hole"): + if out.get(key) is not None: + out[key] = _positive_float(f"printability.{key}", out[key]) + angle = float(out.get("overhang_angle", 45.0)) + if not 0.0 < angle < 90.0: + raise ConfigError("printability.overhang_angle: between 0 and 90 degrees") + tolerance = float(out.get("tolerance", 0.01)) + if not 0.0 <= tolerance < 1.0: + raise ConfigError("printability.tolerance: between 0 and 1") + return out + + def load_config(source, *, base_dir=None) -> RunConfig: """Validate a configuration given as a file path or a mapping.""" if isinstance(source, (str, Path)): @@ -3134,6 +3164,7 @@ def load_config(source, *, base_dir=None) -> RunConfig: "visualization", "threads", "version", + "printability", } if "optimization" in data and "model" not in data: raise ConfigError("this is a topology optimization: run it with 'morphogen optimize'") @@ -3182,6 +3213,9 @@ def load_config(source, *, base_dir=None) -> RunConfig: if missing: raise ConfigError(f"diffusion.phases: no properties for phase(s) {missing}") mesh = _mesh(data["mesh"]) if data.get("mesh") is not None else None + printability = _printability(data.get("printability")) + if printability is not None and voxels is None: + raise ConfigError("printability: give the voxel grid (voxels section)") outputs = _outputs(data.get("outputs") or {}, base) from morphogen.morphology.measures import EXACT_MEASURES @@ -3351,4 +3385,5 @@ def load_config(source, *, base_dir=None) -> RunConfig: visualization=viz, threads=threads, source=data, + printability=printability, ) diff --git a/src/morphogen/pipeline.py b/src/morphogen/pipeline.py index d076d1f..54d3f5c 100644 --- a/src/morphogen/pipeline.py +++ b/src/morphogen/pipeline.py @@ -614,6 +614,8 @@ def _process( ).get(1, 0.0) if cfg.diffusion is not None: values.update(_diffuse(image, cfg.diffusion, stem, outdir)) + if cfg.printability is not None: + values.update(_printability(micro, cfg, stem, outdir)) fe_rows: list[dict] = [] results = None if homog is not None and homogenize: @@ -892,6 +894,25 @@ def _voxel_outputs( return image, labels +def _printability(micro, cfg: RunConfig, stem: str, outdir: Path) -> dict: + """The checks of printability of a realization on the voxels of the run: the report + ``_printability.json`` and the values of its row.""" + from morphogen.analysis.printability import printability + + report = printability(micro, **cfg.voxels.kwargs(), **cfg.printability) + (outdir / f"{stem}_printability.json").write_text( + json.dumps(report.to_dict(), indent=2), encoding="utf-8" + ) + keys = ("overhang_fraction", "wall_min", "wall_median", "thin_fraction", "hole_min", + "narrow_fraction", "islands", "island_fraction", "trapped_voids", + "trapped_fraction") # fmt: skip + out = {f"printability.{k}": getattr(report, k) for k in keys if getattr(report, k) is not None} + out["printability.printable"] = float(report.printable) + out["printability.needs_supports"] = float(report.needs_supports) + out["printability.best_overhang_fraction"] = report.orientations[report.best_build] + return out + + def _surface_outputs(micro, out, grid, stem: str, outdir: Path, several: bool, vox) -> None: """The closed surfaces of a realization: by default, that of the phase 1 of two phases, or of each phase but the last; with ``outputs.surface.phases``, the bodies of the diff --git a/tests/public_api.txt b/tests/public_api.txt index 79f730a..146ad50 100644 --- a/tests/public_api.txt +++ b/tests/public_api.txt @@ -179,6 +179,12 @@ morphogen.analysis.power_laws.CANDIDATES morphogen.analysis.power_laws.PowerLawTail(exponent, x_min, n_tail, error, ks, discrete) morphogen.analysis.power_laws.PowerLawTail.to_dict(self) morphogen.analysis.power_laws.power_law_tail(values, *, x_min=None, discrete=False, min_tail=10) +morphogen.analysis.printability.DIRECTIONS +morphogen.analysis.printability.Printability(build, voxel_size, min_wall, min_hole, overhang_angle, solid_fraction, wall_min, wall_median, thin_fraction, hole_min, hole_median, narrow_fraction, surface_area, overhang_area, overhang_fraction, orientations, best_build, components, islands, island_fraction, trapped_voids, trapped_fraction, under_resolved, printable, needs_supports, warnings=) +morphogen.analysis.printability.Printability.summary(self) +morphogen.analysis.printability.Printability.to_dict(self) +morphogen.analysis.printability.RESOLVED +morphogen.analysis.printability.printability(source, *, shape=None, voxel_size=None, build='+z', min_wall=None, min_hole=None, overhang_angle=45.0, tolerance=0.01) morphogen.analysis.random_sets.Capacity(element, sizes, values, volume_fraction) morphogen.analysis.random_sets.Capacity.complement morphogen.analysis.random_sets.Capacity.contact_distribution(self) @@ -353,7 +359,7 @@ morphogen.config.OPENFOAM_OPTIONS morphogen.config.OutputSpec(directory=Path('morphogen_output'), name='sample', geometry=, image=, labels=, level_set=, mesh=, mesh_phases=None, conforming_mesh=, periodic_pairs=False, periodic_equations=False, surface=, surface_phases=None, surface_unit='millimeter', damask=False, neper=False, database=None, amitex=None, code_aster=None, openfoam=None, tables=, shell_section=False) morphogen.config.OutputSpec.needs_voxels morphogen.config.RVESpec(method='ensemble', sizes=, realizations=, size=None, window_sizes=, properties=, relative_errors=, n_realizations=, gamma=None, min_volume=None, max_volume=None, bootstrap=1000, weights='none', shifts=1) -morphogen.config.RunConfig(model, domain, seed=None, realizations=1, voxels=None, mesh=None, outputs=, analysis=, rve=None, homogenization=None, diffusion=None, visualization=None, threads=None, source=) +morphogen.config.RunConfig(model, domain, seed=None, realizations=1, voxels=None, mesh=None, outputs=, analysis=, rve=None, homogenization=None, diffusion=None, visualization=None, threads=None, source=, printability=None) morphogen.config.STRESS_UNITS morphogen.config.SURFACE_FORMATS morphogen.config.TABLE_FORMATS diff --git a/tests/test_printability.py b/tests/test_printability.py new file mode 100644 index 0000000..ef53fb0 --- /dev/null +++ b/tests/test_printability.py @@ -0,0 +1,124 @@ +"""The printability of parts by additive manufacturing (theory.md §147).""" + +import json +import math + +import numpy as np +import pytest + +import morphogen as mg +from morphogen import pipeline +from morphogen.analysis.printability import DIRECTIONS, _overhangs, printability +from morphogen.config import ConfigError, load_config +from morphogen.image import VoxelImage +from morphogen.mesh.surface import surface_mesh +from morphogen.models.part import Part +from morphogen.models.tpms import TPMS + +DOMAIN = mg.Domain(size=(10.0, 10.0, 10.0), periodic=False) + + +def _cylinder(n=64, axis=0): + grid = DOMAIN.grid(n) + c = grid.center_points() + across = [a for a in range(3) if a != axis] + phi = np.hypot(c[:, across[0]] - 5.0, c[:, across[1]] - 5.0) - 2.0 + return grid, phi.reshape(grid.shape) + + +def test_overhangs_of_a_horizontal_cylinder(): + """The faces of a horizontal cylinder within 45 degrees of straight down are a quarter + of its side: the overhangs of its smooth surface tend to that share of its area off + the plate; its terraced voxels show half of it, which the smoothed distance of a voxel + image restores; built along its axis it has none.""" + lateral, caps = 2 * math.pi * 2 * 10, 2 * math.pi * 4 + expected = 0.25 * lateral / (lateral + caps) + shares = [] + for n in (64, 128): + grid, phi = _cylinder(n) + surface = surface_mesh(VoxelImage.from_grid(phi.astype(np.float32), grid, + name="level_set"), closed=True) # fmt: skip + over, off = _overhangs(surface, 2, 1, 0.0, 45.0, 1e-6) + shares.append(over / off) + assert abs(shares[1] - expected) < abs(shares[0] - expected) < 0.02 + grid, phi = _cylinder(64) + image = VoxelImage.from_grid((phi <= 0).astype(np.uint8), grid, name="phase") + report = printability(image) + assert report.overhang_fraction == pytest.approx(expected, abs=0.015) + assert report.orientations["+x"] < 0.01 and report.best_build in ("+x", "-x") + assert report.islands == 1 and not report.printable # floating above the plate + assert report.wall_median == pytest.approx(4.0, abs=0.5) + + +def test_islands_and_trapped_powder(): + """A plate with a cube standing on it hollowed by a closed cavity, and a floating + cube: one island, one trapped void, not printable; built from the top, the plate is + the island.""" + grid = DOMAIN.grid(40) + c = grid.center_points().reshape(40, 40, 40, 3) + data = np.zeros((40, 40, 40), np.uint8) + data[:, :, :8] = 1 # the plate, 2 high + data[(np.abs(c - [5, 5, 4]) < 2.0).all(axis=-1)] = 1 # a cube on the plate + data[(np.abs(c - [5, 5, 4.5]) < 1.0).all(axis=-1)] = 0 # its closed cavity + data[(np.abs(c - [2, 2, 8.5]) < 0.6).all(axis=-1)] = 1 # a floating cube + report = printability(VoxelImage.from_grid(data, grid, name="phase")) + assert report.components == 2 and report.islands == 1 and report.trapped_voids == 1 + assert 0 < report.island_fraction < 0.05 + assert report.trapped_fraction == pytest.approx(8.0 / (1000.0 - data.sum() / 64.0 - 8.0 + + 8.0), rel=0.2) # fmt: skip + assert not report.printable and any("cavit" in w for w in report.warnings) + top = printability(VoxelImage.from_grid(data, grid, name="phase"), build="-z") + assert top.islands == 2 # nothing reaches the upper face: the plate and the cube float + + +def test_walls_holes_and_resolution(): + """A gyroid sheet: walls thinner than three voxels are flagged under-resolved, thin + walls and narrow holes against the process; finer voxels resolve them.""" + model = TPMS(surface="gyroid", variant="sheet", volume_fraction=0.2, cell_size=5.0) + micro = model.generate(DOMAIN) + coarse = printability(micro, shape=40, min_wall=1.0, min_hole=10.0) + assert coarse.under_resolved and coarse.thin_fraction > 0.5 + assert coarse.narrow_fraction == pytest.approx(1.0) + assert any("refine" in w for w in coarse.warnings) + fine = printability(micro, shape=128, min_wall=0.1) + assert not fine.under_resolved and fine.thin_fraction == 0.0 + assert fine.wall_median == pytest.approx(coarse.wall_median, rel=0.5) + assert set(fine.orientations) == set(DIRECTIONS) + + +def test_a_sandwich_part_is_printable(): + """A sandwich panel of a gyroid core between skins: built on its lower skin, no island + and no trapped void; overhangs inside its core.""" + part = Part(infill={"type": "tpms", "surface": "gyroid", "variant": "sheet", + "volume_fraction": 0.25, "cell_size": 5.0}, skins=(1.0, 1.0)) # fmt: skip + domain = mg.Domain(size=(10.0, 10.0, 6.0), periodic=False) + report = printability(part.generate(domain), shape=(80, 80, 48)) + assert report.islands == 0 and report.trapped_voids == 0 and report.printable + assert report.needs_supports + assert "printable" in report.summary() + + +def test_in_a_run(tmp_path): + """A run with the checks: the report of each realization and its columns; errors.""" + config = { + "model": {"type": "tpms", "surface": "schwarz_p", "volume_fraction": 0.3, + "cell_size": 5.0}, + "domain": {"size": 10.0, "periodic": False}, + "voxels": {"shape": 32}, + "printability": {"min_wall": 0.5, "build": "+z"}, + } # fmt: skip + outdir = pipeline.run(load_config({**config, "outputs": {"directory": str(tmp_path)}})) + reports = list(outdir.rglob("*_printability.json")) + assert reports and json.loads(reports[0].read_text())["build"] == "+z" + row = pipeline.read_rows(outdir / "results.csv")[0] + assert "printability.printable" in row and "printability.overhang_fraction" in row + for bad, message in ( + ({"build": "+w"}, "build"), + ({"overhang_angle": 95}, "overhang_angle"), + ({"min_wall": -1}, "min_wall"), + ({"colour": "red"}, "colour"), + ): + with pytest.raises(ConfigError, match=message): + load_config({**config, "printability": bad}) + with pytest.raises(ConfigError, match="voxel"): + load_config({k: v for k, v in config.items() if k != "voxels"}) From fe1bb6cb22d9be5bb83429eb3c973e4ba0437bf9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 00:24:10 +0000 Subject: [PATCH 11/13] The tab Additive manufacturing of the interface The tools Part for printing (a TPMS, strut lattice or spinodoid at a fraction or graded, in a box, cylinder, tube or sphere with a shell, skins and supports: its morphology in the workspace, its printability, its bodies as STL, 3MF and STEP, the void as a second body) and Printability (the checks of any morphology), in the section Create (FR-I10, specification 1.262). The bodies of complementary phases give the nodes where their functions vanish to one phase, the most inside: a part cut by the faces of its box tiles it too. The search of the page: "stl" finds the new tool first, "surface stl" the surfaces of Export. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MSrXEMpgnWPQNUwHwAgXHV --- CHANGELOG.md | 8 + docs/interface.md | 13 +- docs/specification.md | 6 +- src/morphogen/gui/tools/printing.py | 290 ++++++++++++++++++++++++++++ src/morphogen/mesh/surface.py | 16 +- tests/test_gui_tools_printing.py | 80 ++++++++ tests/test_viz_gui.py | 3 +- 7 files changed, 410 insertions(+), 6 deletions(-) create mode 100644 src/morphogen/gui/tools/printing.py create mode 100644 tests/test_gui_tools_printing.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 15eb71e..bb6f8d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +* The tab **Additive manufacturing** of the interface (section Create): *Part for + printing* designs a part in one form — a TPMS of the ten surfaces, a strut lattice or a + spinodoid at a volume fraction or graded, in a box, a cylinder, a tube or a sphere, with + a shell, skins and supports — adds its morphology to the workspace, checks its + printability and writes its bodies as STL, 3MF and STEP (the void as a second body for + two materials); *Printability* checks any morphology of the workspace. The bodies of + complementary phases give the nodes of their interfaces to one phase (a part cut by the + faces of its box tiles it too). * Printability by additive manufacturing ([docs/theory.md](docs/theory.md) §147, `morphogen.analysis.printability`, the section `printability:` of a run): the thinnest walls against the process (`min_wall`) and the resolution of the voxels, the narrowest diff --git a/docs/interface.md b/docs/interface.md index 42b2a14..8bb7512 100644 --- a/docs/interface.md +++ b/docs/interface.md @@ -23,7 +23,8 @@ the workspace holds items not saved. The forms of every model open filled with its example configuration (its template: parameters and domain), so that any model runs as it opens. Its menus follow the work in four sections, each with its -tabs: **Create** (Generate, Topology optimization, Inverse design, Tile assemblies), +tabs: **Create** (Generate, Topology optimization, Inverse design, Tile assemblies, +Additive manufacturing), **Characterize** (Statistics), **Simulate** (Linear homogenization, Materials, Mechanics, Learning, Fracture, Contact, Nonlocal damage, Stability, Physics, Couplings, Explicit dynamics) and **Export & compare** @@ -89,6 +90,16 @@ The workspace is saved to a folder and opened again in another session (**Save aggregation), the animation of their formation with the share of the cells changed at each step; for the network models with `frame_stiffness`, the stiffness of their frame of beams in a table of its own and in the card of the morphology; +* **Additive manufacturing**: *Part for printing*, a part designed in one form: an + architecture (a TPMS of the ten surfaces, a strut lattice of the nine cells, a spinodoid + in its cones) at a volume fraction or graded along an axis, filling a box, a cylinder, a + tube or a sphere with a shell, the skins of a sandwich and the supports of a beam; its + morphology joins the workspace, its printability is checked (the verdict, the thinnest + walls, the overhangs of the six build directions, the islands and the trapped voids, + with the reasons) and its bodies are written as STL, 3MF (a material per body) and STEP + solids, the void as a second body for two materials; *Printability*, the same checks + of any morphology of the workspace along a build direction + ([theory notes](theory.md) §147); * **Statistics**: the size of the representative volume element of the model of a morphology, by the ensemble or the window method (its windows also shifted around a periodic realization), for its volume fraction or apparent moduli (the variance fitted diff --git a/docs/specification.md b/docs/specification.md index ce10997..41ccec1 100644 --- a/docs/specification.md +++ b/docs/specification.md @@ -3,7 +3,7 @@ | | | |---|---| | Document | Software requirements specification | -| Version | 1.261 | +| Version | 1.262 | | Date | 2026-12-01 | | Author | @jdirr | | Status | Version 1.1 **validated** on 2026-10-21. The later versions, proposed, are listed in the change log (§13); changes go through pull requests that update this file and its change log. | @@ -374,6 +374,8 @@ centred on morphological modelling. | Delivered | FR-E21 (`io.structural.write_lsdyna`, `write_ansys`, the mesh formats `k` and `ans` of `outputs.mesh` and `outputs.conforming_mesh`, [theory.md](theory.md) §146) | | Additive manufacturing: printability (2026-12-01) | The checks of Top6Meta's AM+ edition, before printing. | | Delivered | FR-M9 (`analysis.printability`, the section `printability` of a run, [theory.md](theory.md) §147): local thickness of the solid and of the void (first percentiles and medians), overhangs of the implicit surface or of the smoothed distance of the voxels, islands and trapped voids, the best of the six directions; checked against a horizontal cylinder | +| Additive manufacturing: the interface (2026-12-01) | Top6Meta's design and export in one screen, with the checks and the files beyond it. | +| Delivered | FR-I10 (the tab Additive manufacturing of the section Create: the tools *Part for printing* and *Printability*); the bodies of complementary phases keep the nodes of their interfaces once | ## 4. Scope @@ -529,6 +531,7 @@ version, 0.1). | FR-I7 | Videos (3b): .mp4 (ffmpeg), .gif or PNG frames, played once, in a loop or back and forth; sections sweeping through a voxel image and the three orthogonal sections (Avizo-like), turntables of phases and meshes, cross-sections sweeping through a mesh and fields animated with a magnified displacement, coloured by matplotlib colormaps on a fixed range (3D views rendered off screen by VTK) | S | 3b | | FR-I8 | The whole chain in one configuration (3b): from the morphological model to its voxel image, conforming mesh and the fields of the homogenization; the `visualization` section draws figures (bitmaps, vector graphics, TikZ) and videos of the first realizations: sections and orthoslices of the image and its labels, views, turntables and sweeps of the mesh coloured by phase, the fields of properties, loadings and loading paths (at every step) on the deformed mesh (magnified, total or fluctuation, cut by a plane) or the voxels, the curves of the paths, colour bars on fixed ranges; `outputs.tables` writes the tables as .txt and .xlsx; missing dependencies (VTK, ffmpeg) are reported before the run; the template `workflow`; `morphogen export` converts images, meshes with their fields, geometries and tables to other formats, figures and videos | S | 3b | | FR-I9 | The workspace and the results in the page (0.7): a cross and an Undo on each item; the fields of the loading paths in 3D step by step without an external viewer, videos on demand only; an editor of the laws of the sizes in the forms | S | 3c | +| FR-I10 | A tab of additive manufacturing in the interface: a part designed in one form (architecture, fraction or gradient, shape, shell, skins, supports), its printability and its files (STL, 3MF, STEP); the printability of any morphology | S | 1d | | FR-I5 | Parameter metadata (description, kind, unit, default) available programmatically, for the command line, the documentation and the future GUI | S | 1 | ### 5.7 Batch and HPC @@ -1452,6 +1455,7 @@ Packages: `models`, `kernels`, `analysis`, `rve`, `mesh`, `homogenization`, `io` | 1.259 | 2026-12-01 | Bodies that tile their box, layers of TPMS, 3MF and STEP (FR-G34, FR-E20, §3.12) | | 1.260 | 2026-12-01 | Meshes for LS-DYNA and ANSYS (FR-E21, §3.12) | | 1.261 | 2026-12-01 | Printability by additive manufacturing (FR-M9, §3.12) | +| 1.262 | 2026-12-01 | The tab Additive manufacturing of the interface (FR-I10, §3.12) | ## 14. References diff --git a/src/morphogen/gui/tools/printing.py b/src/morphogen/gui/tools/printing.py new file mode 100644 index 0000000..809ad2d --- /dev/null +++ b/src/morphogen/gui/tools/printing.py @@ -0,0 +1,290 @@ +"""The tools of the tab Additive manufacturing: a part designed in one form and its files, +and the printability of a morphology of the workspace. + +* Part for printing (:func:`printable_part`): an architecture (a TPMS of the ten surfaces, + a strut lattice of the cells of morphoGen, a spinodoid) at a volume fraction or graded + along an axis, filling a box, a cylinder, a tube or a sphere, with a shell, the skins of + a sandwich and the supports of a beam (:class:`~morphogen.models.part.Part`); its + morphology joins the workspace, its printability is checked + (:mod:`morphogen.analysis.printability`), and its bodies are written as STL, 3MF and + STEP (:mod:`morphogen.io.printing`), with the void as a second body for two materials. +* Printability (:func:`printability_check`): the checks of a morphology of the workspace, + built along any of the six directions of the axes. +""" + +from __future__ import annotations + +import zipfile + +from morphogen.gui.tools import Field, tab, tool + +tab( + "printing", + "Additive manufacturing", + "Parts for additive manufacturing: an architecture (TPMS, strut lattice, spinodoid) " + "at a volume fraction or graded, filling a box, a cylinder, a tube or a sphere with a " + "shell, skins and supports, its printability checked (walls, holes, overhangs, islands, " + "trapped powder) and its bodies written as STL, 3MF (a material per body) and STEP " + "solids; the printability of any morphology of the workspace.", + order=76, + section="create", +) + +FAMILIES = ( + ("tpms", "TPMS (triply periodic minimal surfaces)"), + ("strut_lattice", "strut lattice"), + ("spinodoid", "spinodoid"), +) +SURFACES = ("gyroid", "schwarz_p", "schwarz_d", "neovius", "schoen_iwp", "schoen_frd", + "fischer_koch_s", "lidinoid", "split_p", "i2_y") # fmt: skip +CELLS = ("octet", "bcc", "fcc", "cubic", "kelvin", "diamond", "pyrochlore", "octahedral", + "rhombic_dodecahedron") # fmt: skip +SHAPES = ("box", "cylinder", "tube", "sphere") +BUILDS = ("+z", "-z", "+x", "-x", "+y", "-y") +FORMATS = ("stl", "3mf", "step") +AXES = (("0", "x"), ("1", "y"), ("2", "z")) + + +def _infill(p: dict) -> dict: + """The configuration of the architecture of the form.""" + family = p["family"] + graded = bool(p.get("graded")) + fractions = {"fraction_gradient": [float(p["fraction"]), float(p["fraction_top"])], + "gradient_axis": int(p.get("gradient_axis") or 2)} if graded else { + "volume_fraction": float(p["fraction"])} # fmt: skip + if family == "tpms": + return {"type": "tpms", "surface": p["surface"], "variant": p["variant"], + "cell_size": float(p["cell_size"]), **fractions} # fmt: skip + if family == "spinodoid": + return {"type": "spinodoid", "wavelength": float(p["cell_size"]), + "variant": p["variant"], "cone_angles": list(p.get("cones") or (90, 90, 90)), + **fractions} # fmt: skip + if graded: + raise ValueError("graded strut lattices: give a radius gradient in a configuration") + return {"type": "strut_lattice", "cell": p["cell"], "cell_size": float(p["cell_size"]), + "volume_fraction": float(p["fraction"])} # fmt: skip + + +def _model(p: dict) -> dict: + """The configuration of the part (the infill alone when nothing surrounds it).""" + infill = _infill(p) + shell = float(p.get("shell") or 0.0) + skins = [float(t) for t in (p.get("skins") or ())] + supports = [float(t) for t in (p.get("supports") or ())] + if p["shape"] == "box" and not shell and not any(skins) and not any(supports): + return infill + spec = {"type": "part", "shape": p["shape"], "infill": infill, "shell": shell} + if any(skins): + spec["skins"] = skins + if any(supports): + spec["supports"] = supports + if p["shape"] == "tube" and p.get("inner_radius"): + spec["inner_radius"] = float(p["inner_radius"]) + return spec + + +@tool( + "printable_part", + "printing", + "Part for printing", + "An architecture filling a part: its morphology in the workspace, its printability and " + "its bodies as STL, 3MF and STEP solids.", + fields=( + Field("family", "choice", "tpms", "architecture", choices=FAMILIES), + Field( + "surface", "choice", "gyroid", "surface", choices=SURFACES, when={"family": ["tpms"]} + ), + Field("cell", "choice", "octet", "cell", choices=CELLS, when={"family": ["strut_lattice"]}), + Field( + "variant", + "choice", + "sheet", + "solid", + choices=( + ("sheet", "sheet"), + ("network", "network"), + ("upper_network", "the other network"), + ), + when={"family": ["tpms", "spinodoid"]}, + ), + Field("cell_size", "float", 5.0, "cell size (wavelength)", unit="mm"), + Field("fraction", "float", 0.2, "volume fraction (at the lower face if graded)"), + Field( + "graded", "bool", False, "graded along an axis", when={"family": ["tpms", "spinodoid"]} + ), + Field( + "fraction_top", + "float", + 0.4, + "volume fraction at the upper face", + when={"graded": [True]}, + ), + Field( + "gradient_axis", + "choice", + "2", + "axis of the gradient", + choices=AXES, + when={"graded": [True]}, + ), + Field( + "cones", + "floats", + (90.0, 90.0, 90.0), + "cones of the waves (degrees)", + doc="Half-angles about x, y and z: 90, 90, 90 isotropic; 15, 0, 0 lamellar", + when={"family": ["spinodoid"]}, + ), + Field("shape", "choice", "box", "shape", choices=SHAPES), + Field("size", "floats", (20.0, 20.0, 20.0), "size of the box", unit="mm"), + Field( + "inner_radius", + "float", + None, + "inner radius of the tube", + unit="mm", + when={"shape": ["tube"]}, + ), + Field("shell", "float", 0.0, "shell along the boundary", unit="mm"), + Field("skins", "floats", (0.0, 0.0), "skins at the lower and upper faces (z)", unit="mm"), + Field("supports", "floats", (0.0, 0.0), "supports at the ends (x)", unit="mm"), + Field("voxels", "int", 96, "voxels along the longest edge"), + Field("build", "choice", "+z", "build direction", choices=BUILDS), + Field("min_wall", "float", 0.3, "thinnest wall of the process", unit="mm"), + Field("min_hole", "float", 0.5, "narrowest channel that drains", unit="mm"), + Field("formats", "choices", ("stl", "3mf"), "files", choices=FORMATS), + Field("void_body", "bool", False, "the void as a second body (two materials)"), + ), + groups=( + ("Architecture", "family"), + ("Part", "shape"), + ("Printing", "voxels"), + ("Files", "formats"), + ), +) +def printable_part(p: dict, ctx) -> dict: + from morphogen.analysis.printability import printability + from morphogen.domain import Domain + from morphogen.gui import api + from morphogen.io.printing import write_3mf, write_step + from morphogen.mesh.surface import phase_surfaces + from morphogen.models.base import model_from_config + + size = [float(v) for v in p["size"]] + if len(size) != 3 or min(size) <= 0: + raise ValueError("size: three positive lengths") + spec = _model(p) + model = model_from_config(spec) + domain = Domain(size=tuple(size), periodic=False) + ctx.progress(0.1, "the part") + micro = model.generate(domain, 1) + n = int(p["voxels"]) + if not 16 <= n <= 256: + raise ValueError("voxels: from 16 to 256 along the longest edge") + ctx.progress(0.3, "the printability") + report = printability(micro, shape=n, build=p["build"], min_wall=p.get("min_wall"), + min_hole=p.get("min_hole")) # fmt: skip + ctx.table([{"direction": k, "overhangs": round(v, 4)} for k, v in + report.orientations.items()], "overhangs", + "share of the surface overhanging, by build direction") # fmt: skip + ctx.progress(0.6, "the bodies") + grid = domain.grid(n) + phases = [1, 0] if p.get("void_body") else [1] + bodies = phase_surfaces(micro, phases, grid) + names = {1: "solid", 0: "void"} + pairs = [(names[k], bodies[k]) for k in phases] + formats = list(p.get("formats") or ()) + for fmt in formats: + if fmt == "stl": + from morphogen.io import save_mesh + + for name, body in pairs: + save_mesh(body, ctx.path(f"part_{name}.stl")) + elif fmt == "3mf": + write_3mf(ctx.path("part.3mf"), pairs) + else: + write_step(ctx.path("part.step"), pairs) + ctx.progress(0.85, "the views") + views = api.morphology_views(micro, 256) + for s in views["sections"]: + ctx.figures.append({"title": s["title"], "url": s["png"]}) + ctx.add( + "morphology", + f"{spec['type']} for printing", + micro=micro, + origin="printing", + model=model.to_config(), + domain={"size": size, "periodic": False}, + seed=1, + phases={"0": "void", "1": "solid"}, + thumbnail=views["thumbnail"], + fraction=views["fraction"], + info={"model": spec["type"]}, + ) + files = sorted(q for q in ctx.folder.iterdir() if q.suffix in (".stl", ".3mf", ".step")) + out = { + "values": { + "verdict": "printable" if report.printable else "not printable as it is", + "supports": "needed" if report.needs_supports else "none", + "volume fraction": round(report.solid_fraction, 4), + "thinnest walls": round(report.wall_min, 4), + "overhangs": round(report.overhang_fraction, 4), + "best direction": report.best_build, + "islands": report.islands, + "trapped voids": report.trapped_voids, + "warnings": "; ".join(report.warnings) or "none", + }, + "files": [{"name": q.name, "kind": "data", "url": ctx.url(q.name)} for q in files], + } + if files: + target = ctx.path("part_files.zip") + with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as archive: + for q in files: + archive.write(q, q.name) + out["archive"] = ctx.url(target.name) + ctx.progress(1.0, "done") + return out + + +@tool( + "printability_check", + "printing", + "Printability", + "The checks of a morphology of the workspace before printing it: walls and holes " + "against the process, overhangs by build direction, islands and trapped powder.", + fields=( + Field("source", "item", None, "morphology", required=True), + Field("voxels", "int", 96, "voxels along the longest edge"), + Field("build", "choice", "+z", "build direction", choices=BUILDS), + Field("min_wall", "float", 0.3, "thinnest wall of the process"), + Field("min_hole", "float", 0.5, "narrowest channel that drains"), + Field("overhang_angle", "float", 45.0, "self-supporting angle", unit="degrees"), + ), +) +def printability_check(p: dict, ctx) -> dict: + from morphogen.analysis.printability import printability + + item = p["source"] + n = int(p["voxels"]) + if not 16 <= n <= 256: + raise ValueError("voxels: from 16 to 256 along the longest edge") + report = printability(item["micro"], shape=n, build=p["build"], min_wall=p.get("min_wall"), + min_hole=p.get("min_hole"), + overhang_angle=float(p["overhang_angle"])) # fmt: skip + ctx.table([{"direction": k, "overhangs": round(v, 4)} for k, v in + report.orientations.items()], "overhangs", + "share of the surface overhanging, by build direction") # fmt: skip + return { + "values": { + "verdict": "printable" if report.printable else "not printable as it is", + "supports": "needed" if report.needs_supports else "none", + "thinnest walls": round(report.wall_min, 4), + "median walls": round(report.wall_median, 4), + "narrowest holes": None if report.hole_min is None else round(report.hole_min, 4), + "overhangs": round(report.overhang_fraction, 4), + "best direction": report.best_build, + "islands": report.islands, + "trapped voids": report.trapped_voids, + "warnings": "; ".join(report.warnings) or "none", + } + } diff --git a/src/morphogen/mesh/surface.py b/src/morphogen/mesh/surface.py index f791c1e..b79898a 100644 --- a/src/morphogen/mesh/surface.py +++ b/src/morphogen/mesh/surface.py @@ -159,8 +159,18 @@ def phase_surfaces(micro, phases, grid: Grid) -> dict[int, SurfaceMesh]: with ``caps="centres"``. Adjacent phases share their interfaces, their caps tile the faces of the box, and their volumes add up to its volume.""" nodes = node_grid(grid) + phases = [int(k) for k in phases] + fields = {k: micro.phase_level_set(k, grid=nodes) for k in phases} + # the nodes on an interface (a function exactly zero: the faces of a part, the planes + # of a cut) go to one phase, the one most inside: complementary bodies keep them once + stack = np.stack([np.asarray(fields[k].data, dtype=np.float32) for k in phases]) + owner = np.argmin(stack, axis=0) + tiny = np.float32(1e-6 * float(np.min(grid.spacing))) out = {} - for k in phases: - field = micro.phase_level_set(int(k), grid=nodes) - out[int(k)] = surface_mesh(field, closed=True, caps="centres") + for i, k in enumerate(phases): + data = stack[i].copy() + zero = data == 0.0 + data[zero & (owner == i)] = -tiny + data[zero & (owner != i)] = tiny + out[k] = surface_mesh(fields[k].with_data(data), closed=True, caps="centres") return out diff --git a/tests/test_gui_tools_printing.py b/tests/test_gui_tools_printing.py new file mode 100644 index 0000000..fdd5387 --- /dev/null +++ b/tests/test_gui_tools_printing.py @@ -0,0 +1,80 @@ +"""The tools of the tab Additive manufacturing: a part designed in one form, and the +printability of a morphology of the workspace.""" + +import pytest + +from morphogen.domain import Domain +from morphogen.gui import api +from morphogen.gui.tools import TABS, TOOLS, ToolJob, catalog +from morphogen.io.printing import read_3mf +from morphogen.models.base import model_from_config + + +def _run(session, name, params): + job = ToolJob({"tool": name, "params": params}, session) + job._run() + status = job.status() + assert status["state"] == "done", status.get("error") + return status["result"] + + +def test_the_tab(): + catalog() # the tools are loaded with the catalog + assert TABS["printing"]["section"] == "create" + assert {"printable_part", "printability_check"} <= set(TOOLS) + + +def test_a_sandwich_panel(tmp_path): + """A gyroid sandwich panel: its morphology in the workspace (a part of the model), its + verdict, its overhangs by direction, its solid and void as STL, 3MF and STEP.""" + session = api.Session(tmp_path) + out = _run(session, "printable_part", { + "family": "tpms", "surface": "gyroid", "variant": "sheet", "cell_size": 5.0, + "fraction": 0.25, "shape": "box", "size": [10.0, 10.0, 6.0], "skins": [1.0, 1.0], + "voxels": 64, "min_wall": 0.2, "formats": ["stl", "3mf", "step"], + "void_body": True}) # fmt: skip + values = out["values"] + assert values["islands"] == 0 and values["trapped voids"] == 0 + assert values["verdict"] == "printable" + names = {f["name"] for f in out["files"]} + assert {"part_solid.stl", "part_void.stl", "part.3mf", "part.step"} <= names + (item,) = out["items"] + stored = session.item(item["key"]) + assert stored["model"]["type"] == "part" and stored["model"]["skins"] == [1.0, 1.0] + bodies = read_3mf(tmp_path / next(f["url"] for f in out["files"] + if f["name"] == "part.3mf").split("/files/")[-1]) # fmt: skip + assert [b[0] for b in bodies] == ["solid", "void"] + assert sum(b[1].volume() for b in bodies) == pytest.approx(600.0, rel=1e-9) + (table,) = out["tables"] + assert len(table["rows"]) == 6 + + +def test_graded_spinodoid_and_lattice(tmp_path): + """A graded spinodoid alone (no part around it) and an octet lattice in a cylinder.""" + session = api.Session(tmp_path) + out = _run(session, "printable_part", { + "family": "spinodoid", "variant": "network", "cell_size": 3.0, "fraction": 0.3, + "graded": True, "fraction_top": 0.5, "gradient_axis": "2", "cones": [90, 90, 90], + "shape": "box", "size": [10.0, 10.0, 10.0], "voxels": 48, "formats": ["stl"]}) # fmt: skip + model = session.item(out["items"][0]["key"])["model"] + assert model["type"] == "spinodoid" and model["fraction_gradient"] == [0.3, 0.5] + out = _run(session, "printable_part", { + "family": "strut_lattice", "cell": "octet", "cell_size": 5.0, "fraction": 0.15, + "shape": "cylinder", "size": [12.0, 12.0, 10.0], "shell": 0.6, "voxels": 48, + "formats": []}) # fmt: skip + model = session.item(out["items"][0]["key"])["model"] + assert model["type"] == "part" and model["infill"]["cell"] == "octet" + assert out["files"] == [] + + +def test_printability_of_a_morphology(tmp_path): + """The checks of a morphology of the workspace, built along another direction.""" + session = api.Session(tmp_path) + model = model_from_config({"type": "tpms", "surface": "schwarz_p", "cell_size": 5.0, + "volume_fraction": 0.3}) # fmt: skip + micro = model.generate(Domain(size=10.0, periodic=False)) + key, _ = session.folder() + session.add(key, "morphology", "P", micro=micro, model=model.to_config()) + out = _run(session, "printability_check", {"source": key, "voxels": 48, "build": "-x"}) + assert out["values"]["verdict"] in ("printable", "not printable as it is") + assert out["values"]["best direction"] in ("+x", "-x", "+y", "-y", "+z", "-z") diff --git a/tests/test_viz_gui.py b/tests/test_viz_gui.py index 4e60361..fe26c6a 100644 --- a/tests/test_viz_gui.py +++ b/tests/test_viz_gui.py @@ -359,7 +359,8 @@ def test_search_of_the_page(): "PHASE field": ["fracture/phase_field", None, None], "abaqus": ["interop/abaqus_input", None, None], "paris": ["fracture/crack_growth", "paris_C", None], - "stl": ["export", "surface (.stl)", None], + "stl": ["printing/printable_part", "formats", "stl"], + "surface stl": ["export", "surface (.stl)", None], "export": ["export", None, None], } nothing = ["xyzzy", "", " ", "omparisons"] From af8301f2a457334ec2032b68a96da47080138c93 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 00:29:08 +0000 Subject: [PATCH 12/13] Part for printing: the axis of the gradient given as an integer The axis 0 (x) given as an integer fell back to z. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MSrXEMpgnWPQNUwHwAgXHV --- src/morphogen/gui/tools/printing.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/morphogen/gui/tools/printing.py b/src/morphogen/gui/tools/printing.py index 809ad2d..059b0cb 100644 --- a/src/morphogen/gui/tools/printing.py +++ b/src/morphogen/gui/tools/printing.py @@ -49,8 +49,10 @@ def _infill(p: dict) -> dict: """The configuration of the architecture of the form.""" family = p["family"] graded = bool(p.get("graded")) + axis = p.get("gradient_axis") + axis = 2 if axis in (None, "") else int(axis) fractions = {"fraction_gradient": [float(p["fraction"]), float(p["fraction_top"])], - "gradient_axis": int(p.get("gradient_axis") or 2)} if graded else { + "gradient_axis": axis} if graded else { "volume_fraction": float(p["fraction"])} # fmt: skip if family == "tpms": return {"type": "tpms", "surface": p["surface"], "variant": p["variant"], From 0960571afa76e18bdd2496f06a0c03b7bb0a5b90 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 06:23:46 +0000 Subject: [PATCH 13/13] Documentation: the additive manufacturing features described from the literature MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The theory notes §140 to §147, the rows of the specification after 1.2.0, the docstring of the hybrid model and the curved octahedra of the strut lattices reworded after the literature alone; the variant of an error test renamed. No change of behaviour. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MSrXEMpgnWPQNUwHwAgXHV --- CHANGELOG.md | 2 +- docs/models.md | 2 +- docs/specification.md | 16 +++++++------- docs/theory.md | 38 +++++++++++++++------------------ src/morphogen/models/hybrid.py | 7 +++--- src/morphogen/models/lattice.py | 2 +- tests/test_lattice_families.py | 2 +- tests/test_tpms_surfaces.py | 2 +- 8 files changed, 33 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bb6f8d1..055e408 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,7 +46,7 @@ octahedra of the face centres, stretching-dominated) and `rhombic_dodecahedron` (the Voronoi cells of the fcc lattice, bending-dominated); `reinforcement: edges` or `axis` along `reinforcement_axis` (bcc-z, fcc-z, reinforced octet and octahedral cells); - `curvature`, the struts inside the cell bent into circular arcs of a sagitta (circular + `curvature`, the struts inside the cell bent into circular arcs of a sagitta (curved octahedra); `cell: custom` with its `struts`. The volume fraction is solved for all of them; the rigidity of the frames takes the two new cells. Public interface: the parameters `struts`, `reinforcement`, `reinforcement_axis`, `curvature` and diff --git a/docs/models.md b/docs/models.md index 96a3d42..de1409b 100644 --- a/docs/models.md +++ b/docs/models.md @@ -75,7 +75,7 @@ What a realization is made of, and how it becomes images and meshes, is the subj | `tpms` | Ten surfaces: gyroid, Schwarz P and D, Neovius, Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P and I2-Y; the network on either side of the surface or the sheet, at a level, a volume fraction or a profile of the fraction along an axis (graded TPMS, [theory notes](theory.md) §140) | | `tpms_layers` | Layers of a TPMS for composites of several materials: the bands of the levels of a surface (the sheet, then the layers on both of its sides) or of a network, at given volume fractions, whose closed bodies tile the box ([theory notes](theory.md) §145) | | `spinodoid` | Spinodoids (Kumar et al. 2020): the level of a sum of waves of one wavelength in random directions, isotropic or within cones about the axes (lamellar, columnar, cubic), network, sheet or the other network, at a fraction or graded; periodic in periodic boxes; their specific surface by Rice's formula ([theory notes](theory.md) §141) | -| `strut_lattice` | Cubic, BCC, FCC, octet, Kelvin, diamond, pyrochlore, octahedral and rhombic dodecahedral lattices, or cells of one's own struts, with solid or hollow struts; reinforced along an axis (bcc-z, fcc-z), curved struts (circular octahedra, [theory notes](theory.md) §144); rotated and functionally graded lattices (non-periodic samples); their sections meshed in the plane by their exact contours | +| `strut_lattice` | Cubic, BCC, FCC, octet, Kelvin, diamond, pyrochlore, octahedral and rhombic dodecahedral lattices, or cells of one's own struts, with solid or hollow struts; reinforced along an axis (bcc-z, fcc-z), curved struts ([theory notes](theory.md) §144); rotated and functionally graded lattices (non-periodic samples); their sections meshed in the plane by their exact contours | | `plate_lattice` | Plate lattices: closed cells walled by plates on the closest-packed planes of the cubic lattices, the {100} (`cubic`), {110} (`bcc`) and {111} (`fcc`, the octet plates) planes and their mixtures (Berger et al. 2017; Tancogne-Dejean et al. 2018), of a thickness or an exact relative density, in the ratio of an isotropic stiffness at low density (`isotropic`, which reaches the Hashin–Shtrikman bounds); turned, shifted and graded; the exact density and specific surface, the stiffness of the membranes at low density, exact meshes of their convex pieces ([below](#plate-lattices)) | | `random_lattice` | Strut lattices with missing struts and displaced nodes, with their rigidity (Maxwell–Calladine); their sections meshed in the plane by their exact contours | | `hierarchical_lattice` | Hierarchical lattices of (hollow) tubes: frames of generation G of regular octahedra (Rayneau-Kirkhope, Mao & Farr 2012); their sections meshed in the plane by their exact contours | diff --git a/docs/specification.md b/docs/specification.md index 41ccec1..8268ce0 100644 --- a/docs/specification.md +++ b/docs/specification.md @@ -360,21 +360,21 @@ centred on morphological modelling. | Delivered | FR-E19 (`io.openfoam`, `morphogen openfoam forchheimer`, `outputs.openfoam.velocity`, [theory.md](theory.md) §139): the flow periodic along its axis too (a cyclic pair, the pressure fixed at one cell), driven to a filtration velocity by `meanVelocityForce` for both lines of OpenFOAM (OpenCFD's `fvOptions`, the Foundation's `fvConstraints`, put in place by `Allrun`), its pressure gradient read from the log of the solver, its apparent permeability and its convergence (the residuals, or a flow that no longer changes); the sweep `forchheimer`: a creeping flow (Darcy's permeability), periodic flows at the Reynolds numbers asked for, the failed and unsteady flows reported and left out, Forchheimer's law (`k_F`, `β`, `c_F = β √k`) and the weak inertia (`k / k_app − 1 = A Re²`) fitted, the exponents from flow to flow, `forchheimer.json` and `forchheimer.csv`; the scheme of the convection; the periodic flow in the tool *OpenFOAM case*; verified by laws standing in for OpenFOAM (10⁻⁹) and by OpenFOAM v2412 itself: the permeability of a slit at every Reynolds number (10⁻⁶), the weak inertia (exponent 2) and the stronger inertia of staggered rods | | Additive manufacturing: TPMS (2026-12-01) | The surfaces of Schoen, Fischer–Koch and Lidin, the other network of a surface, graded TPMS. | | Delivered | FR-G29 (`tpms`, [theory.md](theory.md) §140): six more nodal surfaces (Schoen's I-WP and F-RD, Fischer–Koch S, the lidinoid, split P, I2-Y; Lord & Mackay 2003), their derivatives for the first-order distance; the network `upper_network` on the other side of the level; `fraction_gradient` along `gradient_axis`, the level of each position that of its fraction (any piecewise-linear profile, in non-periodic domains) | -| Additive manufacturing: spinodoids (2026-12-01) | The stochastic architectures of Kumar et al. (2020) and of Top6Meta's spinodal module. | +| Additive manufacturing: spinodoids (2026-12-01) | The stochastic architectures of Kumar et al. (2020): isotropic or anisotropic, uniform or graded. | | Delivered | FR-G30 (`spinodoid`, [theory.md](theory.md) §141): `n_waves` waves of a `wavelength`, directions uniform or within `cone_angles` (lamellar, columnar, cubic), random phases; the three solids at a level of the normal law, graded by `fraction_gradient`; the modes of a shell of `bandwidth` in periodic boxes; the specific surface by Rice's formula; grids by products of complex matrices | -| Additive manufacturing: hybrids (2026-12-01) | Multi-morphology architectures, as Top6Meta's hybrids, for any two models. | +| Additive manufacturing: hybrids (2026-12-01) | Multi-morphology architectures: any two models blended into each other. | | Delivered | FR-G31 (`hybrid`, [theory.md](theory.md) §142): `transition` linear, cylindrical or spherical, `position`, `radius`, `center` and `width` (the sigmoid of Yang et al. 2014), the functions bounded by `scale` before they are blended, each model where the weight is 0 or 1, the slope bounded by `max(L_1, L_2) + D / 2w` | -| Additive manufacturing: parts (2026-12-01) | Specimens and components rather than boxes: Top6Meta's sandwiches, beams and cylinders, and the infill of any part. | +| Additive manufacturing: parts (2026-12-01) | Specimens and components rather than boxes: sandwich panels, beams, cylinders and tubes, and the infill of any part. | | Delivered | FR-G32 (`part`, `mesh.distance`, `tpms` `cells_around`, [theory.md](theory.md) §143): `shape` box, cylinder, tube, sphere or mesh (`mesh`, `fit`, `resolution`), `shell`, `skins` and `supports` along their axes, the function of the part a maximum and minima of signed distances; the distance to a closed surface exact near it (Ericson's closest points), its inside by the parity of the columns; the cells of a TPMS wrapped around an axis | -| Additive manufacturing: strut lattices (2026-12-01) | The families of Top6Meta's strut module (octahedral, reinforced, circular) and of the literature on printed lattices (bcc-z, fcc-z, rhombic dodecahedron). | +| Additive manufacturing: strut lattices (2026-12-01) | The families of the literature on printed lattices: octahedral, reinforced along an axis (bcc-z, fcc-z), curved, rhombic dodecahedron, cells of one's own struts. | | Delivered | FR-G33 (`strut_lattice` `cell: octahedral`, `rhombic_dodecahedron`, `custom` with `struts`, `reinforcement`, `curvature`, `CellSpec`, [theory.md](theory.md) §144): the two cells, their rigidity in the frames; reinforcements `edges` and `axis`; circular arcs of a sagitta, outward or inward, in straight pieces; custom cells; the fractions solved for every cell | -| Additive manufacturing: bodies, 3MF and STEP (2026-12-01) | Multi-material parts and the files of slicers and CAD programs, beyond Top6Meta's STL and faceted STEP. | +| Additive manufacturing: bodies, 3MF and STEP (2026-12-01) | Multi-material parts and the files of slicers and CAD programs: 3MF and STEP solids beside STL. | | Delivered | FR-G34, FR-E20 (`tpms_layers`, `mesh.surface.phase_surfaces`, `io.printing`, `outputs.surface: {formats, phases, unit}`, [theory.md](theory.md) §145): the bodies of the phases tiling the box (nodes with the faces, mirrored padding, merged vertices); layers of TPMS; 3MF with base materials; STEP solids (AP214, `MANIFOLD_SOLID_BREP` of planar `ADVANCED_FACE`s) read by OpenCascade as valid solids at their volumes, or faceted shells | -| Additive manufacturing: LS-DYNA and ANSYS (2026-12-01) | The voxel meshes of the AM+ edition of Top6Meta, for two more codes of structures. | +| Additive manufacturing: LS-DYNA and ANSYS (2026-12-01) | The voxel and tetrahedral meshes of morphoGen for two more codes of structures. | | Delivered | FR-E21 (`io.structural.write_lsdyna`, `write_ansys`, the mesh formats `k` and `ans` of `outputs.mesh` and `outputs.conforming_mesh`, [theory.md](theory.md) §146) | -| Additive manufacturing: printability (2026-12-01) | The checks of Top6Meta's AM+ edition, before printing. | +| Additive manufacturing: printability (2026-12-01) | The checks of a part before it is printed: walls, holes, overhangs, islands, trapped powder. | | Delivered | FR-M9 (`analysis.printability`, the section `printability` of a run, [theory.md](theory.md) §147): local thickness of the solid and of the void (first percentiles and medians), overhangs of the implicit surface or of the smoothed distance of the voxels, islands and trapped voids, the best of the six directions; checked against a horizontal cylinder | -| Additive manufacturing: the interface (2026-12-01) | Top6Meta's design and export in one screen, with the checks and the files beyond it. | +| Additive manufacturing: the interface (2026-12-01) | The design of a part, its checks and its files in one screen. | | Delivered | FR-I10 (the tab Additive manufacturing of the section Create: the tools *Part for printing* and *Printability*); the bodies of complementary phases keep the nodes of their interfaces once | ## 4. Scope diff --git a/docs/theory.md b/docs/theory.md index 38f9669..258e07a 100644 --- a/docs/theory.md +++ b/docs/theory.md @@ -16602,7 +16602,7 @@ its level instead. **The two networks.** A level $t$ cuts space into the network $\{\varphi \le t\}$ (`network`), the sheet $\{|\varphi| \le t\}$ (`sheet`) and the other network -$\{\varphi \ge t\}$ (`upper_network`: Top6Meta's exoskeletal, Microgen's upper skeletal). +$\{\varphi \ge t\}$ (`upper_network`: Microgen's upper skeletal). With $F$ the distribution of $\varphi$ over the cell (sampled at $96^3$ points), a fraction $f$ is the level $F^{-1}(f)$ of the network, $F^{-1}(1 - f)$ of the other one, and the quantile $f$ of $|\varphi|$ for the sheet; the first-order distance is @@ -16618,7 +16618,7 @@ fills 0.469, 0.432, 0.385, 0.509 and 0.445 of their cells. **Graded TPMS.** `fraction_gradient` $(f_0, \dots, f_{m-1})$ gives the volume fraction at $m$ equally spaced positions from the lower to the upper face of a non-periodic domain along `gradient_axis`, interpolated linearly: $f(s)$, $s \in [0, 1]$ (two values: the -linear gradient of Top6Meta's FG type 1; more: any piecewise-linear profile). Each +linear gradient; more: any piecewise-linear profile). Each position takes the level of its fraction, $t(s) = F^{-1}(f(s))$ (tabulated at 64 points per interval of the profile and interpolated), so that a slab across the gradient, thin before the length of the gradient but a cell or more thick, has the fraction $f(s)$ of its @@ -16721,7 +16721,7 @@ $G$ the signed distance to the surface of the transition (`transition`): a plane an axis ($G = x_a - x_0$, `position`, by default the middle of the domain), a cylinder about an axis ($G = r - R$) or a sphere ($G = |x - c| - R$; `radius` by default a quarter of the smallest edge across the axis, `center` the centre of the domain); $w$ the `width` of the -transition ($\alpha$ goes from 0.9 to 0.1 over $4.4w$; Top6Meta's sharpness $k$ is $1/w$). +transition ($\alpha$ goes from 0.9 to 0.1 over $4.4w$, a sharpness $1/w$). The first model lies below the plane, inside the cylinder or the sphere ($G < 0$, $\alpha \to 1$), the second beyond. @@ -16756,7 +16756,7 @@ the errors; a run from a configuration to its STL surface. ## 143. Parts ready to print: infills in shapes, with shells, skins and supports (`models.part`) The other models fill boxes; a part fills a shape, with the solid walls that make it a -specimen or a component (Top6Meta's sandwiches, beams and cylinders): with $s$ the signed +specimen or a component (sandwich panels, beams, cylinders): with $s$ the signed distance to the shape (negative inside) and $\varphi$ the function of the infill (any model with a level set of its phase 1, generated in the domain), the function of the part is @@ -16831,7 +16831,7 @@ configuration to its STL surface. **Reinforcements.** `reinforcement: edges` adds the four edges of the cube along `reinforcement_axis` (each shared by four cells: one strut of length $a$ per cell; the bcc-z and fcc-z cells of the literature on additive manufacturing), `axis` the strut through the -centre of the cell from face to face (Top6Meta's reinforced octahedron; on a bcc lattice the +centre of the cell from face to face (on a bcc lattice the two are the same lattice, moved by $(a/2, a/2, a/2)$). They add a length $a$ per cell and stiffen the lattice along the axis. @@ -16843,8 +16843,7 @@ $\kappa < 0$): with $u$ the direction of the strut, $n$ the unit vector of the p $m - c$ normal to it ($m$ the middle, $c$ the centre of the cell), the radius is $R = (L^2/4 + h^2)/2h$, the centre of the circle $m - n\,(R - h)\,\mathrm{sign}\,\kappa$ and the half-angle $\arcsin(L/2R)$; the arc is cut into `arc_segments` straight pieces, -whose round caps join smoothly. Bent octahedra are Top6Meta's circular octahedra, which -spread the stress of the nodes. +whose round caps join smoothly. Bent struts spread the stress of the nodes. **Custom cells.** `cell: custom` takes `struts`, each the fractional coordinates of its two ends; the struts shared with neighbouring cells may be given once or in each cell (the @@ -16862,7 +16861,7 @@ struts $\pi r^2 L_V$ within 10 %, the fraction of a realization within 0.01; the added by the reinforcements, the axis strut through the centre, the radius of a reinforced fcc lattice smaller than the plain one, its edges along $z$ solid; the arcs through the ends, of the sagitta asked for, outward and inward, the struts on the faces left straight, -a circular octahedron at its fraction; a custom octet equal to the octet, a custom cube to +a curved octahedron at its fraction; a custom octet equal to the octet, a custom cube to the cubic lattice voxel for voxel, a reinforced curved lattice read back; the errors. ## 145. Bodies for additive manufacturing: surfaces that tile their box, layers of TPMS, 3MF and STEP (`mesh.surface`, `io.printing`) @@ -16891,7 +16890,7 @@ $|\varphi|$ or $-\varphi$, §140) and the fractions $f_k$ of the layers, the bou $t_k = F_v^{-1}(f_1 + \dots + f_k)$ (the quantiles of $v$ over the cell) make the phase $k$ the band $t_{k-1} < v \le t_k$ ($t_0 = -\infty$) and the phase 0 the rest $v > t_n$ (none when the fractions add up to 1): from a sheet, the sheet and then the layers on both -of its sides (Top6Meta's layered composites of 2 to 9 layers); from a network, the network +of its sides; from a network, the network and the layers around it. The function of the band $k$ is the first-order distance $\max(t_{k-1} - v,\ v - t_k)/|\nabla\varphi|$, and adjacent bands share their zero sets. @@ -16911,10 +16910,9 @@ first vertex, along its outward normal) bounded by an `EDGE_LOOP` of three `ORIENTED_EDGE`s, each `EDGE_CURVE` (a `LINE` between two `VERTEX_POINT`s) shared by the two faces of the edge; `kind="faceted"`, lighter, writes `FACETED_BREP`s of `FACE_SURFACE`s bounded by `POLY_LOOP`s of shared points, which readers take as shells. -OpenCascade 7.8 (the kernel of FreeCAD and of Top6Meta's STEP export) reads the solids -as valid solids at the volumes of their surfaces within $10^{-9}$: the three pieces of a -gyroid sheet cut by its box, its void, an octet lattice of 63 168 faces — where Top6Meta -writes the shell of its STL and no STEP of its strut lattices. +OpenCascade 7.8 (the kernel of FreeCAD) reads the solids as valid solids at the volumes +of their surfaces within $10^{-9}$: the three pieces of a gyroid sheet cut by its box, its +void, an octet lattice of 63 168 faces. Validated in `tests/test_printing.py`: the solid and the complement of a sheet gyroid, of the network of an I-WP and of an octet lattice, closed, their volumes adding up to the box @@ -16930,9 +16928,8 @@ phase as STL, 3MF and STEP, the errors of the configuration. ## 146. Meshes for LS-DYNA and ANSYS (`io.structural`) The voxel meshes (8-node bricks) and the tetrahedral meshes of morphoGen go to the codes of -structures with their phases and their elastic materials (Top6Meta's AM+ edition exports -voxel meshes for Abaqus and ANSYS; morphoGen writes Abaqus inputs with periodic constraint -equations already). +structures with their phases and their elastic materials (morphoGen writes Abaqus inputs +with periodic constraint equations already). **LS-DYNA** (`.k`, the keyword format of its manual): `*NODE` (numbers in 8 columns, coordinates in 16) and `*ELEMENT_SOLID` (the number, the part and eight nodes in 8 columns @@ -16968,11 +16965,10 @@ quadratic tetrahedra (SOLID285, SOLID187 with `EMORE`); a run that writes both. ## 147. Printability by additive manufacturing (`analysis.printability`) Before a part is printed, a slicer or a process engineer checks that each of its layers -stands on the one below and that its features are within reach of the process; Top6Meta -sells these checks as its AM+ edition. `printability` makes them on the voxels and the -surface of a realization (its implicit surface) or of an image (the surface of the signed -distance of its voxels, smoothed over one voxel), built along a direction $b$ of the six -of the axes. +stands on the one below and that its features are within reach of the process. +`printability` makes these checks on the voxels and the surface of a realization (its +implicit surface) or of an image (the surface of the signed distance of its voxels, +smoothed over one voxel), built along a direction $b$ of the six of the axes. **Walls and holes.** The local thickness of the solid at a point is the diameter of the largest ball within the solid that contains it (Hildebrand & Rüegsegger 1997; §21); the diff --git a/src/morphogen/models/hybrid.py b/src/morphogen/models/hybrid.py index 0254e42..eff3a9c 100644 --- a/src/morphogen/models/hybrid.py +++ b/src/morphogen/models/hybrid.py @@ -11,10 +11,9 @@ axis (``cylindrical``, ``G = r - radius``) or a sphere (``spherical``, ``G = |x - c| - radius``). The first model lies below the plane, inside the cylinder or the sphere, the second beyond; within a few widths of the surface the two functions mix and the two -architectures merge into each other continuously (Top6Meta's hybrids, after the blending -of level sets of Yang et al. 2014). Blending distances rather than raw functions makes any -two models with implicit functions mix alike, a gyroid with a strut lattice as well as two -TPMS. +architectures merge into each other continuously (the blending of level sets of Yang et +al. 2014). Blending distances rather than raw functions makes any two models with implicit +functions mix alike, a gyroid with a strut lattice as well as two TPMS. Before they are blended, the functions are bounded, ``D tanh(phi_i / D)``: their zero sets and their slopes at the surfaces are kept, while their values far from the surfaces, diff --git a/src/morphogen/models/lattice.py b/src/morphogen/models/lattice.py index d4af923..38b19e3 100644 --- a/src/morphogen/models/lattice.py +++ b/src/morphogen/models/lattice.py @@ -326,7 +326,7 @@ class StrutLattice(Model): adds the four ``edges`` of the cube along ``reinforcement_axis``, or its ``axis`` from face to face (bcc-z, fcc-z, reinforced octet and octahedral cells), and ``curvature`` bends the struts inside the cell into circular arcs (the sagitta over - the length; the circular octahedron). Give the strut + the length; a curved octahedron). Give the strut radius or the target relative density (solid volume fraction). With ``wall_thickness``, the struts are hollow tubes: their union minus the union of their bores (which join at the nodes). diff --git a/tests/test_lattice_families.py b/tests/test_lattice_families.py index a40c330..679fdbf 100644 --- a/tests/test_lattice_families.py +++ b/tests/test_lattice_families.py @@ -74,7 +74,7 @@ def test_reinforcements(): def test_curved_struts(): """Struts inside the cell bent into circular arcs: the pieces on the circle through the ends, of the sagitta asked for, bulging away from the centre; the struts on the - faces and through the centre straight; a circular octahedron at a fraction.""" + faces and through the centre straight; a curved octahedron at a fraction.""" spec = CellSpec("octahedral", curvature=0.2, segments=8) pieces = unit_cell_struts(spec) assert len(pieces) == 12 * 8 diff --git a/tests/test_tpms_surfaces.py b/tests/test_tpms_surfaces.py index 9fff845..60a215a 100644 --- a/tests/test_tpms_surfaces.py +++ b/tests/test_tpms_surfaces.py @@ -163,7 +163,7 @@ def test_graded_levels_and_errors(): with pytest.raises(ValueError, match="gradient_axis"): TPMS(fraction_gradient=(0.2, 0.4), gradient_axis=3) with pytest.raises(ValueError, match="variant"): - TPMS(variant="exoskeletal", volume_fraction=0.3) + TPMS(variant="skeleton", volume_fraction=0.3) def test_graded_in_a_configuration(tmp_path):