morphogen 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- morphogen/__init__.py +60 -0
- morphogen/__main__.py +7 -0
- morphogen/_platform.py +55 -0
- morphogen/_public.py +153 -0
- morphogen/_utils.py +80 -0
- morphogen/_version.py +1 -0
- morphogen/analysis/__init__.py +174 -0
- morphogen/analysis/anisotropy.py +135 -0
- morphogen/analysis/basic.py +38 -0
- morphogen/analysis/cells.py +54 -0
- morphogen/analysis/connectivity.py +156 -0
- morphogen/analysis/correlation.py +195 -0
- morphogen/analysis/covariance.py +80 -0
- morphogen/analysis/fractal.py +54 -0
- morphogen/analysis/measures.py +188 -0
- morphogen/analysis/morphology.py +265 -0
- morphogen/analysis/particles.py +160 -0
- morphogen/analysis/percolation.py +2034 -0
- morphogen/analysis/power_laws.py +143 -0
- morphogen/analysis/random_sets.py +351 -0
- morphogen/analysis/stereology.py +289 -0
- morphogen/analysis/surface.py +107 -0
- morphogen/analysis/topology.py +92 -0
- morphogen/automata/__init__.py +74 -0
- morphogen/automata/engine.py +211 -0
- morphogen/automata/growth.py +686 -0
- morphogen/automata/lattice.py +143 -0
- morphogen/automata/reaction.py +255 -0
- morphogen/automata/rules.py +353 -0
- morphogen/automata/tilings.py +1715 -0
- morphogen/cli.py +3526 -0
- morphogen/config.py +2167 -0
- morphogen/contact/__init__.py +113 -0
- morphogen/contact/experiments.py +368 -0
- morphogen/contact/hertz.py +104 -0
- morphogen/contact/kernels.py +827 -0
- morphogen/contact/periodic.py +278 -0
- morphogen/contact/problem.py +578 -0
- morphogen/contact/surfaces.py +310 -0
- morphogen/coupling/__init__.py +43 -0
- morphogen/coupling/ageing.py +143 -0
- morphogen/coupling/diffusion.py +226 -0
- morphogen/coupling/fenicsx.py +484 -0
- morphogen/coupling/oxidation.py +447 -0
- morphogen/coupling/plates.py +247 -0
- morphogen/design/__init__.py +51 -0
- morphogen/design/csp.py +616 -0
- morphogen/design/frames.py +277 -0
- morphogen/design/search.py +287 -0
- morphogen/design/tiles.py +336 -0
- morphogen/distributions.py +312 -0
- morphogen/domain.py +203 -0
- morphogen/dynamics/__init__.py +179 -0
- morphogen/dynamics/model.py +638 -0
- morphogen/dynamics/openradioss.py +643 -0
- morphogen/dynamics/results.py +515 -0
- morphogen/fracture/__init__.py +170 -0
- morphogen/fracture/bulk.py +349 -0
- morphogen/fracture/cohesive.py +1614 -0
- morphogen/fracture/ductile.py +557 -0
- morphogen/fracture/lefm.py +1168 -0
- morphogen/fracture/mixed.py +1178 -0
- morphogen/fracture/periodic.py +733 -0
- morphogen/fracture/phasefield.py +714 -0
- morphogen/fracture/phasefield_finite.py +368 -0
- morphogen/fracture/surface.py +572 -0
- morphogen/fracture/toughness.py +566 -0
- morphogen/gpu.py +108 -0
- morphogen/gui/__init__.py +8 -0
- morphogen/gui/api.py +1927 -0
- morphogen/gui/desktop.py +387 -0
- morphogen/gui/icon.png +0 -0
- morphogen/gui/index.html +1909 -0
- morphogen/gui/server.py +229 -0
- morphogen/gui/tools/__init__.py +629 -0
- morphogen/gui/tools/compare.py +149 -0
- morphogen/gui/tools/contact.py +391 -0
- morphogen/gui/tools/couplings.py +1085 -0
- morphogen/gui/tools/crackfront.py +245 -0
- morphogen/gui/tools/design.py +224 -0
- morphogen/gui/tools/dynamics.py +824 -0
- morphogen/gui/tools/fracture.py +2586 -0
- morphogen/gui/tools/interop.py +1654 -0
- morphogen/gui/tools/learning.py +595 -0
- morphogen/gui/tools/mechanics.py +3881 -0
- morphogen/gui/tools/nonlocal_damage.py +1321 -0
- morphogen/gui/tools/phasefield.py +215 -0
- morphogen/gui/tools/physics.py +597 -0
- morphogen/gui/tools/stability.py +1756 -0
- morphogen/gui/tools/statistics.py +1408 -0
- morphogen/gui/viewer.js +1100 -0
- morphogen/homogenization/__init__.py +210 -0
- morphogen/homogenization/acoustics.py +566 -0
- morphogen/homogenization/amg.py +1005 -0
- morphogen/homogenization/apparent.py +1046 -0
- morphogen/homogenization/behaviours.cu +2285 -0
- morphogen/homogenization/behaviours.py +944 -0
- morphogen/homogenization/beremin.py +263 -0
- morphogen/homogenization/bifurcation.py +1085 -0
- morphogen/homogenization/bloch.py +507 -0
- morphogen/homogenization/bounds.py +226 -0
- morphogen/homogenization/core.py +458 -0
- morphogen/homogenization/coupled.py +1135 -0
- morphogen/homogenization/crystal.py +2967 -0
- morphogen/homogenization/dilatation.py +454 -0
- morphogen/homogenization/elements.py +157 -0
- morphogen/homogenization/fatigue.py +768 -0
- morphogen/homogenization/fe.py +1739 -0
- morphogen/homogenization/fenicsx.py +307 -0
- morphogen/homogenization/fft.py +499 -0
- morphogen/homogenization/fft_nonlinear.py +391 -0
- morphogen/homogenization/finite.py +613 -0
- morphogen/homogenization/flow.py +361 -0
- morphogen/homogenization/frames.py +1125 -0
- morphogen/homogenization/gpu.py +1241 -0
- morphogen/homogenization/harmonic.py +427 -0
- morphogen/homogenization/identification.py +579 -0
- morphogen/homogenization/kernels.py +760 -0
- morphogen/homogenization/laws.py +2061 -0
- morphogen/homogenization/materials.py +1080 -0
- morphogen/homogenization/mfront.py +589 -0
- morphogen/homogenization/networks.py +880 -0
- morphogen/homogenization/nonlinear.py +2612 -0
- morphogen/homogenization/ntfa.py +577 -0
- morphogen/homogenization/paths.py +476 -0
- morphogen/homogenization/photonic.py +467 -0
- morphogen/homogenization/poroelastic.py +212 -0
- morphogen/homogenization/porous.py +1120 -0
- morphogen/homogenization/postprocess.py +290 -0
- morphogen/homogenization/solvers.py +1140 -0
- morphogen/homogenization/tensors.py +240 -0
- morphogen/homogenization/voxel_fe.py +457 -0
- morphogen/homogenization/xfem.py +1016 -0
- morphogen/homogenization/zmat.py +1258 -0
- morphogen/iga/__init__.py +48 -0
- morphogen/iga/analysis.py +508 -0
- morphogen/iga/basis.py +214 -0
- morphogen/iga/geometry.py +501 -0
- morphogen/iga/homogenization.py +219 -0
- morphogen/iga/optimization.py +700 -0
- morphogen/iga/shapes.py +331 -0
- morphogen/image.py +128 -0
- morphogen/io/__init__.py +246 -0
- morphogen/io/amitex.py +741 -0
- morphogen/io/ebsd.py +881 -0
- morphogen/io/export.py +196 -0
- morphogen/io/geometry.py +158 -0
- morphogen/io/medit.py +147 -0
- morphogen/io/meshes.py +844 -0
- morphogen/io/metaimage.py +97 -0
- morphogen/io/mfront.py +1104 -0
- morphogen/io/native.py +57 -0
- morphogen/io/radioss.py +764 -0
- morphogen/io/solvers.py +371 -0
- morphogen/io/tables.py +278 -0
- morphogen/io/tiff.py +66 -0
- morphogen/io/vtk.py +701 -0
- morphogen/io/xdmf.py +200 -0
- morphogen/kernels/__init__.py +5 -0
- morphogen/kernels/annealing.py +192 -0
- morphogen/kernels/cells.py +69 -0
- morphogen/kernels/collective.py +87 -0
- morphogen/kernels/force_biased.py +595 -0
- morphogen/kernels/implicit.py +145 -0
- morphogen/kernels/leaves.py +132 -0
- morphogen/kernels/packing.py +304 -0
- morphogen/kernels/raster.py +279 -0
- morphogen/kernels/rsa.py +371 -0
- morphogen/kernels/union.py +135 -0
- morphogen/kernels/watershed.py +190 -0
- morphogen/laser/__init__.py +234 -0
- morphogen/laser/architectures.py +375 -0
- morphogen/laser/bending.py +216 -0
- morphogen/laser/cells.py +1694 -0
- morphogen/laser/design.py +940 -0
- morphogen/laser/figures.py +227 -0
- morphogen/laser/heat.py +804 -0
- morphogen/laser/materials.py +691 -0
- morphogen/laser/mechanics.py +1670 -0
- morphogen/laser/metallurgy.py +615 -0
- morphogen/laser/patterns.py +828 -0
- morphogen/laser/periodic.py +392 -0
- morphogen/laser/process.py +362 -0
- morphogen/laser/run.py +534 -0
- morphogen/laser/solid.py +216 -0
- morphogen/laser/specimen.py +200 -0
- morphogen/laser/structures.py +708 -0
- morphogen/learning/__init__.py +81 -0
- morphogen/learning/behaviour.py +398 -0
- morphogen/learning/data.py +328 -0
- morphogen/learning/learned.cpp +668 -0
- morphogen/learning/logarithmic.py +202 -0
- morphogen/learning/mfront.py +409 -0
- morphogen/learning/networks.py +767 -0
- morphogen/learning/run.py +212 -0
- morphogen/learning/standard.py +814 -0
- morphogen/learning/training.py +235 -0
- morphogen/mesh/__init__.py +29 -0
- morphogen/mesh/conforming.py +1423 -0
- morphogen/mesh/curved.py +600 -0
- morphogen/mesh/exact.py +1717 -0
- morphogen/mesh/octree.py +350 -0
- morphogen/mesh/polycrystal.py +1041 -0
- morphogen/mesh/polyhedra.py +677 -0
- morphogen/mesh/regularize.py +570 -0
- morphogen/mesh/surface.py +97 -0
- morphogen/mesh/tetra.py +512 -0
- morphogen/mesh/voxel.py +124 -0
- morphogen/micromorphic/__init__.py +31 -0
- morphogen/micromorphic/damage.py +359 -0
- morphogen/micromorphic/ductile.py +534 -0
- morphogen/micromorphic/finite.py +220 -0
- morphogen/micromorphic/microfoam.py +787 -0
- morphogen/micromorphic/space.py +341 -0
- morphogen/models/__init__.py +195 -0
- morphogen/models/affine.py +384 -0
- morphogen/models/automata.py +592 -0
- morphogen/models/base.py +500 -0
- morphogen/models/boolean.py +310 -0
- morphogen/models/bouligand.py +331 -0
- morphogen/models/branching.py +241 -0
- morphogen/models/combination.py +430 -0
- morphogen/models/deadleaves.py +766 -0
- morphogen/models/design.py +289 -0
- morphogen/models/ebsd.py +206 -0
- morphogen/models/fibers.py +1476 -0
- morphogen/models/foam.py +594 -0
- morphogen/models/gaussian.py +314 -0
- morphogen/models/growth.py +459 -0
- morphogen/models/hardcore.py +317 -0
- morphogen/models/hierarchical.py +269 -0
- morphogen/models/honeycomb.py +749 -0
- morphogen/models/implicit.py +177 -0
- morphogen/models/laminate.py +470 -0
- morphogen/models/lattice.py +351 -0
- morphogen/models/lattice_field.py +345 -0
- morphogen/models/levelset_foam.py +563 -0
- morphogen/models/nacre.py +411 -0
- morphogen/models/nested.py +924 -0
- morphogen/models/osteons.py +374 -0
- morphogen/models/pieces.py +167 -0
- morphogen/models/planar.py +126 -0
- morphogen/models/reconstruction.py +203 -0
- morphogen/models/scale_rich.py +1409 -0
- morphogen/models/scale_rich_3d.py +1616 -0
- morphogen/models/tessellation.py +735 -0
- morphogen/models/tiling_field.py +302 -0
- morphogen/models/tpms.py +197 -0
- morphogen/models/transparent.py +406 -0
- morphogen/models/union.py +141 -0
- morphogen/optimization/__init__.py +43 -0
- morphogen/optimization/cell.py +295 -0
- morphogen/optimization/filters.py +115 -0
- morphogen/optimization/mma.py +226 -0
- morphogen/optimization/run.py +219 -0
- morphogen/optimization/topology.py +632 -0
- morphogen/orientations.py +568 -0
- morphogen/parallel.py +599 -0
- morphogen/pipeline.py +978 -0
- morphogen/primitives.py +188 -0
- morphogen/results.py +564 -0
- morphogen/rve/__init__.py +73 -0
- morphogen/rve/report.py +627 -0
- morphogen/rve/scaling.py +363 -0
- morphogen/rve/study.py +1054 -0
- morphogen/rve/windows.py +345 -0
- morphogen/seeding.py +51 -0
- morphogen/settings.py +118 -0
- morphogen/stopping.py +48 -0
- morphogen/symmetry.py +384 -0
- morphogen/templates/activator_inhibitor.yaml +22 -0
- morphogen/templates/aggregation.yaml +23 -0
- morphogen/templates/boolean_cylinders.yaml +20 -0
- morphogen/templates/boolean_spheres.yaml +22 -0
- morphogen/templates/bouligand.yaml +28 -0
- morphogen/templates/cellular_automaton.yaml +25 -0
- morphogen/templates/coated_spheres.yaml +26 -0
- morphogen/templates/contact_fibers.yaml +27 -0
- morphogen/templates/cox_nanocomposite.yaml +22 -0
- morphogen/templates/cross_linked_fibers.yaml +26 -0
- morphogen/templates/curved_arcs.yaml +28 -0
- morphogen/templates/curved_fibers.yaml +24 -0
- morphogen/templates/dead_leaves.yaml +22 -0
- morphogen/templates/delaunay_network.yaml +22 -0
- morphogen/templates/dense_packing.yaml +22 -0
- morphogen/templates/diffusion.yaml +33 -0
- morphogen/templates/ebsd.yaml +34 -0
- morphogen/templates/ebsd_map.ctf +3087 -0
- morphogen/templates/fracture_composite.yaml +42 -0
- morphogen/templates/fracture_rubber.yaml +47 -0
- morphogen/templates/gaussian_excursion.yaml +17 -0
- morphogen/templates/graded_lattice.yaml +24 -0
- morphogen/templates/hardcore_fibers.yaml +22 -0
- morphogen/templates/hardcore_spheres.yaml +22 -0
- morphogen/templates/hierarchical_lattice.yaml +22 -0
- morphogen/templates/homogenization_acoustic_foam.yaml +36 -0
- morphogen/templates/homogenization_beremin.yaml +50 -0
- morphogen/templates/homogenization_cleavage.yaml +51 -0
- morphogen/templates/homogenization_cleavage_band.yaml +55 -0
- morphogen/templates/homogenization_contact.yaml +43 -0
- morphogen/templates/homogenization_crack_closure.yaml +49 -0
- morphogen/templates/homogenization_crystal_plasticity.yaml +50 -0
- morphogen/templates/homogenization_crystal_plasticity_fft.yaml +52 -0
- morphogen/templates/homogenization_crystallization.yaml +30 -0
- morphogen/templates/homogenization_debonding.yaml +43 -0
- morphogen/templates/homogenization_detwinning.yaml +58 -0
- morphogen/templates/homogenization_ductile_damage.yaml +47 -0
- morphogen/templates/homogenization_fatigue.yaml +40 -0
- morphogen/templates/homogenization_grain_fracture.yaml +56 -0
- morphogen/templates/homogenization_gyroid.yaml +30 -0
- morphogen/templates/homogenization_intergranular.yaml +43 -0
- morphogen/templates/homogenization_interphase.yaml +42 -0
- morphogen/templates/homogenization_mixed_loading.yaml +33 -0
- morphogen/templates/homogenization_ntfa.yaml +56 -0
- morphogen/templates/homogenization_piezoelectric.yaml +27 -0
- morphogen/templates/homogenization_polycrystal.yaml +30 -0
- morphogen/templates/homogenization_polycrystal_inclusions.yaml +30 -0
- morphogen/templates/homogenization_poroelastic.yaml +26 -0
- morphogen/templates/homogenization_rubber.yaml +40 -0
- morphogen/templates/homogenization_slip_cleavage.yaml +50 -0
- morphogen/templates/homogenization_spheres.yaml +31 -0
- morphogen/templates/homogenization_transport.yaml +29 -0
- morphogen/templates/homogenization_twinning.yaml +54 -0
- morphogen/templates/homogenization_viscoelastic.yaml +34 -0
- morphogen/templates/homogenization_viscoplastic.yaml +42 -0
- morphogen/templates/homogenization_voronoi.yaml +26 -0
- morphogen/templates/homogenization_xfem.yaml +23 -0
- morphogen/templates/hyperuniform_cells.yaml +24 -0
- morphogen/templates/laguerre.yaml +18 -0
- morphogen/templates/laser_bending.yaml +35 -0
- morphogen/templates/laser_cells.yaml +38 -0
- morphogen/templates/laser_corrugated.yaml +36 -0
- morphogen/templates/level_set_foam.yaml +29 -0
- morphogen/templates/menger_sponge.yaml +17 -0
- morphogen/templates/nacre.yaml +25 -0
- morphogen/templates/nucleation_growth.yaml +25 -0
- morphogen/templates/optimize_auxetic.yaml +29 -0
- morphogen/templates/optimize_auxetic_3d.yaml +27 -0
- morphogen/templates/optimize_bulk.yaml +23 -0
- morphogen/templates/optimize_conductivity.yaml +20 -0
- morphogen/templates/osteons.yaml +28 -0
- morphogen/templates/penetrable_spheres.yaml +21 -0
- morphogen/templates/poisson_fibers.yaml +21 -0
- morphogen/templates/random_laminate.yaml +26 -0
- morphogen/templates/random_lattice.yaml +27 -0
- morphogen/templates/random_walk_fibers.yaml +26 -0
- morphogen/templates/reaction_diffusion.yaml +22 -0
- morphogen/templates/reconstruction.yaml +22 -0
- morphogen/templates/rve_cellular_automaton.yaml +23 -0
- morphogen/templates/rve_crystal_plasticity_fft.yaml +51 -0
- morphogen/templates/rve_multiphysics.yaml +43 -0
- morphogen/templates/rve_poisson_fibers.yaml +22 -0
- morphogen/templates/rve_poisson_fibers_fe.yaml +33 -0
- morphogen/templates/rve_voronoi_windows.yaml +20 -0
- morphogen/templates/scale_rich_network.yaml +29 -0
- morphogen/templates/scale_rich_plates.yaml +30 -0
- morphogen/templates/sequential_dead_leaves.yaml +25 -0
- morphogen/templates/strut_lattice.yaml +21 -0
- morphogen/templates/tile_assembly.yaml +28 -0
- morphogen/templates/tpms.yaml +19 -0
- morphogen/templates/trabecular_bone.yaml +29 -0
- morphogen/templates/transparent_dead_leaves.yaml +23 -0
- morphogen/templates/vascular_tree.yaml +23 -0
- morphogen/templates/voronoi.yaml +20 -0
- morphogen/templates/wood.yaml +34 -0
- morphogen/templates/workflow.yaml +56 -0
- morphogen/texture.py +665 -0
- morphogen/theory.py +162 -0
- morphogen/viz/__init__.py +12 -0
- morphogen/viz/export.py +244 -0
- morphogen/viz/figures.py +707 -0
- morphogen/viz/png.py +148 -0
- morphogen/viz/sections.py +696 -0
- morphogen/viz/surfaces.py +1352 -0
- morphogen/viz/video.py +904 -0
- morphogen/viz/workflow.py +488 -0
- morphogen-1.0.0.dist-info/METADATA +2316 -0
- morphogen-1.0.0.dist-info/RECORD +381 -0
- morphogen-1.0.0.dist-info/WHEEL +4 -0
- morphogen-1.0.0.dist-info/entry_points.txt +5 -0
- morphogen-1.0.0.dist-info/licenses/LICENSE +674 -0
|
@@ -0,0 +1,1756 @@
|
|
|
1
|
+
"""The tools of the tab Stability: the patterns that periodic architectured materials may
|
|
2
|
+
adopt after buckling, predicted from the symmetry of their cell by group theory (Azulay &
|
|
3
|
+
Combescure 2024; :mod:`morphogen.homogenization.bifurcation`), for lattice frames of beams
|
|
4
|
+
(:mod:`morphogen.homogenization.frames`) and for the morphologies of the workspace, with
|
|
5
|
+
the Bloch waves of the buckling that tell the cell a pattern needs; the bifurcations of a
|
|
6
|
+
cell along a nonlinear loading path in finite strains (the pattern transformation of a
|
|
7
|
+
square array of holes); and the band structures of the elastic Bloch waves of a cell and
|
|
8
|
+
their band gaps (:mod:`morphogen.homogenization.bloch`).
|
|
9
|
+
|
|
10
|
+
A morphology is analysed on its primitive cell (one unit cell of its model, or its box)
|
|
11
|
+
repeated 1 or 2 times along each axis: on a conforming mesh of its level set, meshed in
|
|
12
|
+
the irreducible part of the cell and mirrored when the cell is symmetric about its
|
|
13
|
+
mid-planes (:func:`morphogen.mesh.mirrored_mesh`, whose symmetries are exact), or on six
|
|
14
|
+
tetrahedra per voxel of its voxel image (the Kuhn triangulation, which has the symmetries
|
|
15
|
+
of the image); a plane morphology (one voxel thick) as a slab of two elements, its level
|
|
16
|
+
set the same through the slab."""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
import warnings
|
|
23
|
+
from fractions import Fraction
|
|
24
|
+
from itertools import pairwise, product
|
|
25
|
+
from math import lcm
|
|
26
|
+
|
|
27
|
+
import numpy as np
|
|
28
|
+
|
|
29
|
+
from morphogen.gui.tools import Field, tab, tool
|
|
30
|
+
|
|
31
|
+
tab(
|
|
32
|
+
"stability",
|
|
33
|
+
"Stability",
|
|
34
|
+
"Stability of periodic cells by group theory (Azulay & Combescure 2024): the "
|
|
35
|
+
"irreducible representations of the symmetry of a cell and of its loading, their "
|
|
36
|
+
"critical loads and multiplicities, the first bifurcation, its post-bifurcated patterns "
|
|
37
|
+
"and the cell they need (Bloch waves), for lattice frames and for the morphologies of "
|
|
38
|
+
"the workspace; bifurcations along nonlinear loading paths in finite strains (the "
|
|
39
|
+
"pattern transformation of a square array of holes); and the band structures of the "
|
|
40
|
+
"elastic Bloch waves of a cell, with their band gaps.",
|
|
41
|
+
order=60,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
PLANE_LATTICES = ("honeycomb", "triangular", "square", "kagome")
|
|
45
|
+
SPACE_LATTICES = ("cubic", "bcc", "octet", "kelvin", "diamond", "pyrochlore")
|
|
46
|
+
LATTICES = (
|
|
47
|
+
("honeycomb", "honeycomb (plane)"),
|
|
48
|
+
("triangular", "triangular (plane)"),
|
|
49
|
+
("square", "square (plane)"),
|
|
50
|
+
("kagome", "kagome (plane)"),
|
|
51
|
+
("cubic", "cubic lattice of struts (space)"),
|
|
52
|
+
("bcc", "body-centred cubic lattice of struts (space)"),
|
|
53
|
+
("octet", "octet truss (space)"),
|
|
54
|
+
("kelvin", "Kelvin cell (space)"),
|
|
55
|
+
("diamond", "diamond lattice of struts (space: the honeycomb of space)"),
|
|
56
|
+
("pyrochlore", "pyrochlore lattice of tetrahedra (space: the kagome of space)"),
|
|
57
|
+
)
|
|
58
|
+
LOADINGS = (
|
|
59
|
+
("hydrostatic", "hydrostatic compression (equibiaxial in the plane)"),
|
|
60
|
+
("uniaxial", "uniaxial compression along an axis"),
|
|
61
|
+
("biaxial", "biaxial compression in the x-y plane, E22 = ratio E11"),
|
|
62
|
+
("shear", "shear in the x-y plane (ε12 = γ12 / 2)"),
|
|
63
|
+
("custom", "the components of a strain"),
|
|
64
|
+
)
|
|
65
|
+
AXES = (("x", "x"), ("y", "y"), ("z", "z"))
|
|
66
|
+
PATTERNS = (
|
|
67
|
+
("critical", "of the irreps of the first bifurcation"),
|
|
68
|
+
("all", "of every irrep"),
|
|
69
|
+
)
|
|
70
|
+
MESHES = (
|
|
71
|
+
("auto", "auto: a mirrored conforming mesh if the cell is symmetric, else voxels"),
|
|
72
|
+
("mirrored", "a conforming mesh of its level set, mirrored (exact symmetries; MMG)"),
|
|
73
|
+
("voxels", "six tetrahedra per voxel of its voxel image"),
|
|
74
|
+
)
|
|
75
|
+
CELLS = (
|
|
76
|
+
("unit", "one unit cell of its model (TPMS, strut lattices), else its box"),
|
|
77
|
+
("box", "the box of the morphology"),
|
|
78
|
+
)
|
|
79
|
+
ORDERS = (
|
|
80
|
+
("1", "4-node tetrahedra (stiff in the bending of slender struts and walls)"),
|
|
81
|
+
("2", "10-node tetrahedra (accurate in bending; slower)"),
|
|
82
|
+
)
|
|
83
|
+
#: The models whose realizations repeat a unit cell of edges ``cell_size``
|
|
84
|
+
UNIT_CELL_MODELS = ("tpms", "strut_lattice")
|
|
85
|
+
#: The relative asymmetry of a sampled level set below which a mid-plane is a mirror
|
|
86
|
+
SYMMETRY_TOLERANCE = 1e-5
|
|
87
|
+
#: Patterns shown as views and videos, at most
|
|
88
|
+
SHOWN = 3
|
|
89
|
+
#: Patterns drawn in the figure of every irrep, at most (those of the lowest loads)
|
|
90
|
+
ALL_DRAWN = 30
|
|
91
|
+
#: Frames of the videos of the patterns oscillating
|
|
92
|
+
FRAMES = 36
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class _Busy:
|
|
96
|
+
"""Reports the progress of a long call from a thread: the fraction creeping from
|
|
97
|
+
``start`` towards ``end`` (half way after ``expected`` seconds) with the time spent."""
|
|
98
|
+
|
|
99
|
+
def __init__(self, ctx, start: float, end: float, message: str, expected: float = 20.0):
|
|
100
|
+
self.ctx, self.start, self.end = ctx, start, end
|
|
101
|
+
self.message, self.expected = message, max(float(expected), 1.0)
|
|
102
|
+
self._stop = threading.Event()
|
|
103
|
+
|
|
104
|
+
def __enter__(self) -> _Busy:
|
|
105
|
+
self.ctx.progress(self.start, self.message)
|
|
106
|
+
self._thread = threading.Thread(target=self._run, daemon=True)
|
|
107
|
+
self._thread.start()
|
|
108
|
+
return self
|
|
109
|
+
|
|
110
|
+
def __exit__(self, *exc) -> None:
|
|
111
|
+
self._stop.set()
|
|
112
|
+
self._thread.join(timeout=2)
|
|
113
|
+
self.ctx.progress(self.end, self.message)
|
|
114
|
+
|
|
115
|
+
def _run(self):
|
|
116
|
+
t0 = time.perf_counter()
|
|
117
|
+
while not self._stop.wait(0.5):
|
|
118
|
+
t = time.perf_counter() - t0
|
|
119
|
+
fraction = self.start + (self.end - self.start) * t / (t + self.expected)
|
|
120
|
+
self.ctx.progress(fraction, f"{self.message} ({t:.0f} s)")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# -- loadings ---------------------------------------------------------------------------
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _loading_fields(default: str = "hydrostatic") -> list[Field]:
|
|
127
|
+
return [
|
|
128
|
+
Field(
|
|
129
|
+
"loading",
|
|
130
|
+
"choice",
|
|
131
|
+
default,
|
|
132
|
+
choices=LOADINGS,
|
|
133
|
+
doc="the direction of the macroscopic strain; the critical loads λ are the "
|
|
134
|
+
"magnitudes of its largest component at the bifurcations",
|
|
135
|
+
),
|
|
136
|
+
Field("axis", "choice", "x", choices=AXES, when={"loading": "uniaxial"}),
|
|
137
|
+
Field("ratio", "float", 1.0, when={"loading": "biaxial"}, doc="E22 / E11"),
|
|
138
|
+
Field(
|
|
139
|
+
"strain",
|
|
140
|
+
"floats",
|
|
141
|
+
label="strain components",
|
|
142
|
+
when={"loading": "custom"},
|
|
143
|
+
doc="ε11, ε22, ε33, ε23, ε31, ε12 (a plane frame: ε11, ε22, ε12); negative in "
|
|
144
|
+
"compression",
|
|
145
|
+
),
|
|
146
|
+
]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _strain(p: dict, dim: int) -> tuple[np.ndarray, str]:
|
|
150
|
+
"""The macroscopic strain of a loading of the form (dim x dim, its largest component
|
|
151
|
+
of magnitude 1, compressions negative) and its description."""
|
|
152
|
+
kind = p["loading"]
|
|
153
|
+
e = np.zeros((dim, dim))
|
|
154
|
+
if kind == "hydrostatic":
|
|
155
|
+
e[:] = -np.eye(dim)
|
|
156
|
+
text = "equibiaxial compression" if dim == 2 else "hydrostatic compression"
|
|
157
|
+
elif kind == "uniaxial":
|
|
158
|
+
axis = "xyz".index(p.get("axis") or "x")
|
|
159
|
+
if axis >= dim:
|
|
160
|
+
raise ValueError("axis: x or y for a plane frame")
|
|
161
|
+
e[axis, axis] = -1.0
|
|
162
|
+
text = f"uniaxial compression along {'xyz'[axis]}"
|
|
163
|
+
elif kind == "biaxial":
|
|
164
|
+
ratio = float(p.get("ratio") if p.get("ratio") is not None else 1.0)
|
|
165
|
+
e[0, 0], e[1, 1] = -1.0, -ratio
|
|
166
|
+
text = f"biaxial compression, E22 = {ratio:g} E11"
|
|
167
|
+
elif kind == "shear":
|
|
168
|
+
e[0, 1] = e[1, 0] = 1.0
|
|
169
|
+
text = "shear ε12"
|
|
170
|
+
else:
|
|
171
|
+
values = [float(v) for v in p.get("strain") or []]
|
|
172
|
+
order = (
|
|
173
|
+
((0, 0), (1, 1), (0, 1))
|
|
174
|
+
if dim == 2
|
|
175
|
+
else ((0, 0), (1, 1), (2, 2), (1, 2), (2, 0), (0, 1))
|
|
176
|
+
)
|
|
177
|
+
if len(values) != len(order):
|
|
178
|
+
names = "ε11, ε22, ε12" if dim == 2 else "ε11, ε22, ε33, ε23, ε31, ε12"
|
|
179
|
+
raise ValueError(f"strain components: {len(order)} values, {names}")
|
|
180
|
+
for (a, b), v in zip(order, values, strict=True):
|
|
181
|
+
e[a, b] = e[b, a] = v
|
|
182
|
+
text = "the strain " + ", ".join(f"{v:g}" for v in values)
|
|
183
|
+
scale = float(np.abs(e).max())
|
|
184
|
+
if not scale > 0:
|
|
185
|
+
raise ValueError("strain components: not all zero")
|
|
186
|
+
return e / scale, text
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# -- the results of the analyses ----------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _critical(b) -> list[int]:
|
|
193
|
+
"""The irreps of the first bifurcation (several when their loads coincide)."""
|
|
194
|
+
if b.first is None:
|
|
195
|
+
return []
|
|
196
|
+
load = b.first[0]
|
|
197
|
+
return np.flatnonzero(np.abs(b.loads - load) <= 1e-6 * abs(load)).tolist()
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _wave_vectors(b, cells) -> list:
|
|
201
|
+
"""The wave vectors of each irrep (:meth:`~morphogen.homogenization.bifurcation.
|
|
202
|
+
Bifurcation.wave_vectors`) when the pure translations of the group are primitive ones,
|
|
203
|
+
by an edge of a primitive cell along the axes of two of them; else (centring
|
|
204
|
+
translations, those of the body- or face-centred lattices, or cells of more primitive
|
|
205
|
+
cells) None for every irrep."""
|
|
206
|
+
g = b.group
|
|
207
|
+
dim = g.rotations.shape[1]
|
|
208
|
+
pure = np.abs(g.rotations - np.eye(dim)).max(axis=(1, 2)) < 1e-9
|
|
209
|
+
halves = 2.0 * g.translations[pure] @ np.linalg.inv(g.lattice).T
|
|
210
|
+
m = np.round(halves)
|
|
211
|
+
single = np.asarray(cells[:dim]) == 1
|
|
212
|
+
if np.abs(halves - m).max() > 1e-6 or np.any(m[:, single] % 2):
|
|
213
|
+
return [None] * len(b.irreps)
|
|
214
|
+
return [b.wave_vectors(i) for i in range(len(b.irreps))]
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _waves(waves) -> str:
|
|
218
|
+
"""Wave vectors in units of π over the primitive edges (Γ for zero)."""
|
|
219
|
+
if waves is None:
|
|
220
|
+
return ""
|
|
221
|
+
return ", ".join("Γ" if not any(k) else "(" + ", ".join(map(str, k)) + ")" for k in waves)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _doubled(waves) -> str:
|
|
225
|
+
"""The axes along which the patterns of these wave vectors double the period."""
|
|
226
|
+
if not waves:
|
|
227
|
+
return ""
|
|
228
|
+
axes = sorted({i for k in waves for i, v in enumerate(k) if v})
|
|
229
|
+
return ", ".join("xyz"[i] for i in axes) if axes else "none"
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _irrep_rows(b, critical, waves, *, load="critical load λ", scale=1.0) -> list[dict]:
|
|
233
|
+
"""The rows of the table of the irreps: their loads (times ``scale``, in the column
|
|
234
|
+
``load``), rank, wave vectors (``waves``: of each irrep) and patterns."""
|
|
235
|
+
loads = np.where(np.isfinite(b.loads), b.loads, np.inf)
|
|
236
|
+
rank = np.empty(len(loads), dtype=int)
|
|
237
|
+
rank[np.argsort(loads, kind="stable")] = np.arange(1, len(loads) + 1)
|
|
238
|
+
rows = []
|
|
239
|
+
for i, irrep in enumerate(b.irreps):
|
|
240
|
+
finite = bool(np.isfinite(b.loads[i]))
|
|
241
|
+
rows.append(
|
|
242
|
+
{
|
|
243
|
+
"irrep": i + 1,
|
|
244
|
+
"dimension": irrep.dim,
|
|
245
|
+
"multiplicity": int(b.multiplicities[i]),
|
|
246
|
+
load: float(b.loads[i]) * scale if finite else None,
|
|
247
|
+
"rank": int(rank[i]) if finite else None,
|
|
248
|
+
"wave vectors (π/a)": _waves(waves[i]),
|
|
249
|
+
"period doubled along": _doubled(waves[i]),
|
|
250
|
+
"patterns": sum(p.irrep == i for p in b.patterns),
|
|
251
|
+
"first bifurcation": "yes" if i in critical else "",
|
|
252
|
+
}
|
|
253
|
+
)
|
|
254
|
+
return rows
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _pattern_rows(b, *, load="critical load λ", scale=1.0) -> list[dict]:
|
|
258
|
+
rows = []
|
|
259
|
+
for p in b.patterns:
|
|
260
|
+
d = p.description
|
|
261
|
+
rows.append(
|
|
262
|
+
{
|
|
263
|
+
"irrep": p.irrep + 1,
|
|
264
|
+
"point group": d["point_group"],
|
|
265
|
+
"order |H|": d["order"],
|
|
266
|
+
"translations": d["translations"],
|
|
267
|
+
"conjugates": len(p.subgroups),
|
|
268
|
+
"dim Fix(H)": p.dimension,
|
|
269
|
+
"energy": p.energy,
|
|
270
|
+
load: p.load * scale if np.isfinite(p.load) else None,
|
|
271
|
+
}
|
|
272
|
+
)
|
|
273
|
+
return rows
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _first(b, waves) -> tuple[dict, str]:
|
|
277
|
+
"""The values of the first bifurcation and a sentence on it (``waves``: the wave
|
|
278
|
+
vectors of each irrep)."""
|
|
279
|
+
if b.first is None:
|
|
280
|
+
return {"bifurcation": "none"}, "No bifurcation under this loading."
|
|
281
|
+
load, i, count = b.first
|
|
282
|
+
waves = waves[i]
|
|
283
|
+
doubled = _doubled(waves)
|
|
284
|
+
values = {
|
|
285
|
+
"first critical load λ": load,
|
|
286
|
+
"irrep of the first bifurcation": i + 1,
|
|
287
|
+
"its dimension": b.irreps[i].dim,
|
|
288
|
+
"multiplicity": count,
|
|
289
|
+
}
|
|
290
|
+
if doubled:
|
|
291
|
+
values["period doubled along"] = doubled
|
|
292
|
+
kinds = {1: "simple", 2: "double", 3: "triple", 4: "quadruple", 6: "sextuple"}
|
|
293
|
+
classes = [p.description for p in b.patterns if p.irrep in _critical(b)]
|
|
294
|
+
text = (
|
|
295
|
+
f"First bifurcation at λ = {load:.5g}, in irrep {i + 1} of dimension "
|
|
296
|
+
f"{b.irreps[i].dim}: a {kinds.get(count, f'{count}-fold')} point"
|
|
297
|
+
)
|
|
298
|
+
if classes:
|
|
299
|
+
text += "; its patterns: " + ", ".join(
|
|
300
|
+
f"{d['point_group']} (|H| = {d['order']}, {d['translations']} "
|
|
301
|
+
f"translation{'s' if d['translations'] > 1 else ''})"
|
|
302
|
+
for d in classes
|
|
303
|
+
)
|
|
304
|
+
if doubled and doubled != "none":
|
|
305
|
+
text += f". Its wave vectors {_waves(waves)} double the period along {doubled}"
|
|
306
|
+
elif doubled == "none":
|
|
307
|
+
text += ". Its patterns repeat in every primitive cell"
|
|
308
|
+
return values, text + "."
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _patterns_of(b, irreps) -> list:
|
|
312
|
+
"""The patterns of these irreps, the softest first."""
|
|
313
|
+
return sorted((p for p in b.patterns if p.irrep in irreps), key=lambda p: p.energy)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _first_irreps(b, most: int) -> list[int]:
|
|
317
|
+
"""The irreps with patterns, by increasing critical load (in their order without
|
|
318
|
+
loads), while their patterns number at most ``most`` (one irrep at least)."""
|
|
319
|
+
present = sorted(
|
|
320
|
+
{p.irrep for p in b.patterns}, key=lambda i: (np.nan_to_num(b.loads[i], nan=np.inf), i)
|
|
321
|
+
)
|
|
322
|
+
out, count = [], 0
|
|
323
|
+
for i in present:
|
|
324
|
+
count += sum(p.irrep == i for p in b.patterns)
|
|
325
|
+
if out and count > most:
|
|
326
|
+
break
|
|
327
|
+
out.append(i)
|
|
328
|
+
return out
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _title(p) -> str:
|
|
332
|
+
d = p.description
|
|
333
|
+
return f"irrep {p.irrep + 1}: {d['point_group']}, |H| = {d['order']}"
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
# -- lattice frames -------------------------------------------------------------------------
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
@tool(
|
|
340
|
+
"frame_bifurcation",
|
|
341
|
+
"stability",
|
|
342
|
+
"Post-bifurcation of a lattice frame",
|
|
343
|
+
"The post-bifurcated patterns of a periodic frame of Euler–Bernoulli beams by group "
|
|
344
|
+
"theory (Azulay & Combescure 2024): a plane lattice (honeycomb, triangular, square, "
|
|
345
|
+
"kagome) or a lattice of struts in space, in a cell of n × n (× n) primitive cells, "
|
|
346
|
+
"under a macroscopic strain. The symmetry group of the cell restricted to the loading, "
|
|
347
|
+
"its irreducible representations, the multiplicity of each among the fluctuations and "
|
|
348
|
+
"its lowest critical load, the first bifurcation (its irrep, multiplicity and wave "
|
|
349
|
+
"vectors), and the pattern of each axial isotropy subgroup (equivariant branching "
|
|
350
|
+
"lemma); the Bloch-wave buckling of the primitive cell over its Brillouin zone tells "
|
|
351
|
+
"the critical wavelength, hence the cell the patterns need (Geymonat, Müller & "
|
|
352
|
+
"Triantafyllidis 1993).",
|
|
353
|
+
[
|
|
354
|
+
Field("lattice", "choice", "honeycomb", choices=LATTICES),
|
|
355
|
+
Field(
|
|
356
|
+
"cells",
|
|
357
|
+
"int",
|
|
358
|
+
label="primitive cells per side",
|
|
359
|
+
doc="n × n in the plane (1 to 6), n × n × n in space (1 or 2); blank: 2 in the "
|
|
360
|
+
"plane, 1 in space",
|
|
361
|
+
),
|
|
362
|
+
Field(
|
|
363
|
+
"elements",
|
|
364
|
+
"int",
|
|
365
|
+
label="beams per wall",
|
|
366
|
+
doc="each wall or strut cut in (blank: 4 in the plane, 2 in space)",
|
|
367
|
+
),
|
|
368
|
+
Field(
|
|
369
|
+
"thickness",
|
|
370
|
+
"float",
|
|
371
|
+
0.05,
|
|
372
|
+
doc="of the walls, relative to their length",
|
|
373
|
+
when={"lattice": list(PLANE_LATTICES)},
|
|
374
|
+
),
|
|
375
|
+
Field(
|
|
376
|
+
"radius",
|
|
377
|
+
"float",
|
|
378
|
+
0.04,
|
|
379
|
+
doc="of the struts, relative to the edge of the cubic cell",
|
|
380
|
+
when={"lattice": list(SPACE_LATTICES)},
|
|
381
|
+
),
|
|
382
|
+
*_loading_fields(),
|
|
383
|
+
Field("patterns", "choice", "all", choices=PATTERNS, doc="the patterns computed"),
|
|
384
|
+
Field(
|
|
385
|
+
"bloch_grid",
|
|
386
|
+
"int",
|
|
387
|
+
label="Bloch-wave grid",
|
|
388
|
+
doc="wave vectors per reciprocal vector over the Brillouin zone of the primitive "
|
|
389
|
+
"cell (blank: 12 in the plane, 4 in space; 0: none)",
|
|
390
|
+
),
|
|
391
|
+
Field("video", "bool", True, doc="a video of each pattern of the first bifurcation"),
|
|
392
|
+
],
|
|
393
|
+
order=1,
|
|
394
|
+
menu="Bifurcations",
|
|
395
|
+
)
|
|
396
|
+
def frame_bifurcation(p: dict, ctx) -> dict:
|
|
397
|
+
from morphogen.homogenization.bifurcation import post_bifurcation
|
|
398
|
+
from morphogen.homogenization.frames import SPACE_LATTICES as STRUTS
|
|
399
|
+
from morphogen.homogenization.frames import Frame, SpaceFrame
|
|
400
|
+
from morphogen.symmetry import Group
|
|
401
|
+
|
|
402
|
+
kind = p["lattice"]
|
|
403
|
+
space = kind in SPACE_LATTICES
|
|
404
|
+
dim = 3 if space else 2
|
|
405
|
+
n = int(p["cells"] or (1 if space else 2))
|
|
406
|
+
elements = int(p["elements"] or (2 if space else 4))
|
|
407
|
+
limit = 2 if space else 6
|
|
408
|
+
if not 1 <= n <= limit:
|
|
409
|
+
raise ValueError(f"cells: from 1 to {limit} for a {'space' if space else 'plane'} frame")
|
|
410
|
+
if not 1 <= elements <= 16:
|
|
411
|
+
raise ValueError("beams per wall: from 1 to 16")
|
|
412
|
+
if space:
|
|
413
|
+
radius = float(p["radius"])
|
|
414
|
+
if not 0 < radius < 0.25:
|
|
415
|
+
raise ValueError("radius: between 0 and 0.25 of the cubic cell")
|
|
416
|
+
frame = SpaceFrame.lattice_of(kind, (n,) * 3, elements=elements, radius=radius)
|
|
417
|
+
cell = SpaceFrame.lattice_of(kind, (1,) * 3, elements=elements, radius=radius)
|
|
418
|
+
length = float(STRUTS[kind]["strut"])
|
|
419
|
+
else:
|
|
420
|
+
thickness = float(p["thickness"])
|
|
421
|
+
if not 0 < thickness < 0.5:
|
|
422
|
+
raise ValueError("thickness: between 0 and 0.5 of the walls")
|
|
423
|
+
frame = Frame.lattice_of(kind, (n, n), elements=elements, thickness=thickness)
|
|
424
|
+
cell = Frame.lattice_of(kind, (1, 1), elements=elements, thickness=thickness)
|
|
425
|
+
length = 1.0
|
|
426
|
+
strain, loading = _strain(p, dim)
|
|
427
|
+
grid = p["bloch_grid"]
|
|
428
|
+
grid = (4 if space else 12) if grid is None else int(grid)
|
|
429
|
+
if not 0 <= grid <= (8 if space else 48):
|
|
430
|
+
raise ValueError(f"Bloch-wave grid: from 0 to {8 if space else 48}")
|
|
431
|
+
ctx.progress(0.05, "axial forces of the beams")
|
|
432
|
+
forces, _ = frame.axial_forces(strain)
|
|
433
|
+
compressed = float(forces.min()) < -1e-9 * float(frame.axial.max())
|
|
434
|
+
expected = 1.0 + (frame.n_dofs / 400.0) ** 2
|
|
435
|
+
with _Busy(ctx, 0.1, 0.55, "group-theoretic analysis", expected):
|
|
436
|
+
if compressed:
|
|
437
|
+
b = post_bifurcation(frame, strain, patterns=p["patterns"])
|
|
438
|
+
else: # no beam in compression: no buckling, the patterns of the symmetry alone
|
|
439
|
+
group = Group.generate(frame.generators, frame.lattice, frame.centre)
|
|
440
|
+
group = group.subgroup(group.stabilizer_of(strain))
|
|
441
|
+
b = post_bifurcation(frame, None, group=group, patterns="all")
|
|
442
|
+
critical = _critical(b)
|
|
443
|
+
waves = _wave_vectors(b, (n,) * dim)
|
|
444
|
+
cells = " × ".join([str(n)] * dim)
|
|
445
|
+
values: dict = {
|
|
446
|
+
"lattice": kind,
|
|
447
|
+
"cell": f"{cells} primitive cells",
|
|
448
|
+
"beams": len(frame.beams),
|
|
449
|
+
"dofs": frame.n_dofs,
|
|
450
|
+
"group order": b.group.order,
|
|
451
|
+
"irreps": len(b.irreps),
|
|
452
|
+
}
|
|
453
|
+
first, sentence = _first(b, waves)
|
|
454
|
+
values.update(first)
|
|
455
|
+
if not compressed:
|
|
456
|
+
sentence = "No beam is in compression: no buckling; the patterns of the symmetry alone."
|
|
457
|
+
text = [
|
|
458
|
+
f"{kind.capitalize()}, a cell of {cells} primitive cells ({frame.n_dofs} dofs), "
|
|
459
|
+
f"{loading}: a group of {b.group.order} operations restricted to the loading, "
|
|
460
|
+
f"{len(b.irreps)} irreps.",
|
|
461
|
+
sentence,
|
|
462
|
+
]
|
|
463
|
+
if b.first is not None:
|
|
464
|
+
ratio = -b.first[0] * forces * length**2 / frame.bending
|
|
465
|
+
values["axial force N L²/EI"] = float(ratio.max())
|
|
466
|
+
text.append(
|
|
467
|
+
f"The most compressed walls then carry N L²/EI = {ratio.max():.4g} (Euler: π² "
|
|
468
|
+
"between pinned ends, 4π² clamped)."
|
|
469
|
+
)
|
|
470
|
+
ctx.table(_irrep_rows(b, critical, waves), "irreps", "irreducible representations")
|
|
471
|
+
if b.patterns:
|
|
472
|
+
ctx.table(_pattern_rows(b), "patterns", "patterns: the axial isotropy subgroups")
|
|
473
|
+
ctx.progress(0.6, "figures of the patterns")
|
|
474
|
+
if critical and any(q.irrep in critical for q in b.patterns):
|
|
475
|
+
ctx.figure(
|
|
476
|
+
b.figure(frame, irreps=critical), "patterns_first", "patterns of the first bifurcation"
|
|
477
|
+
)
|
|
478
|
+
if p["patterns"] == "all" and b.patterns and (len(critical) < len(b.irreps)):
|
|
479
|
+
drawn = _first_irreps(b, ALL_DRAWN)
|
|
480
|
+
title = (
|
|
481
|
+
"patterns of every irrep"
|
|
482
|
+
if len(drawn) == len({q.irrep for q in b.patterns})
|
|
483
|
+
else f"patterns of the {len(drawn)} first irreps"
|
|
484
|
+
)
|
|
485
|
+
ctx.figure(b.figure(frame, irreps=drawn), "patterns_all", title)
|
|
486
|
+
if p["video"] and critical:
|
|
487
|
+
from morphogen.viz.video import frame_pattern_frames
|
|
488
|
+
|
|
489
|
+
shown = _patterns_of(b, critical)[:SHOWN]
|
|
490
|
+
for k, pattern in enumerate(shown):
|
|
491
|
+
ctx.progress(0.7 + 0.1 * k / len(shown), "videos of the patterns")
|
|
492
|
+
frames = frame_pattern_frames(frame, pattern.mode, frames=FRAMES, size=420)
|
|
493
|
+
ctx.video(frames, f"pattern_{k + 1}", _title(pattern), mode="loop")
|
|
494
|
+
if grid and compressed:
|
|
495
|
+
ctx.progress(0.82, "Bloch waves of the primitive cell")
|
|
496
|
+
bloch = _frame_bloch(cell, strain, grid, space, b, n)
|
|
497
|
+
if bloch is not None:
|
|
498
|
+
values.update(bloch["values"])
|
|
499
|
+
text.append(bloch["text"])
|
|
500
|
+
ctx.figure(bloch["figure"], "bloch", "Bloch-wave buckling of the primitive cell")
|
|
501
|
+
ctx.table(bloch["rows"], "bloch", "Bloch-wave buckling (lowest loads first)")
|
|
502
|
+
return {"values": values, "text": " ".join(text)}
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _frame_bloch(cell, strain, n: int, space: bool, b, cells: int) -> dict | None:
|
|
506
|
+
"""The lowest load of the Bloch modes of the primitive cell over an ``n`` per side
|
|
507
|
+
grid of its Brillouin zone, the wave vector where it is reached and the cell that
|
|
508
|
+
holds it (the smallest of those of equal loads)."""
|
|
509
|
+
from matplotlib.figure import Figure
|
|
510
|
+
|
|
511
|
+
dim = 3 if space else 2
|
|
512
|
+
fractions = np.array(list(product(range(n), repeat=dim)), dtype=float) / n
|
|
513
|
+
recip = cell.reciprocal()
|
|
514
|
+
loads = cell.bloch_buckling(strain, fractions @ recip.T)[:, 0]
|
|
515
|
+
if not np.isfinite(loads).any():
|
|
516
|
+
return None
|
|
517
|
+
low = float(np.nanmin(loads))
|
|
518
|
+
|
|
519
|
+
def needed(f) -> int:
|
|
520
|
+
return lcm(*(Fraction(round(v * n), n).denominator for v in f))
|
|
521
|
+
|
|
522
|
+
near = np.flatnonzero(np.abs(loads - low) <= 1e-6 * low)
|
|
523
|
+
best = min(near, key=lambda i: (needed(fractions[i]), i))
|
|
524
|
+
f, m = fractions[best], needed(fractions[best])
|
|
525
|
+
frac = "(" + ", ".join(str(Fraction(round(v * n), n)) for v in f) + ")"
|
|
526
|
+
side = " × ".join([str(m)] * dim)
|
|
527
|
+
held = cells % m == 0
|
|
528
|
+
values = {
|
|
529
|
+
"Bloch: lowest load": low,
|
|
530
|
+
"Bloch: wave vector (b)": frac,
|
|
531
|
+
"Bloch: cell needed": side,
|
|
532
|
+
"Bloch: held by the cell": bool(held),
|
|
533
|
+
"Bloch: load at Γ": float(loads[0]),
|
|
534
|
+
}
|
|
535
|
+
text = (
|
|
536
|
+
f"Bloch waves of the primitive cell: the lowest load over a {n}^{dim} grid of the "
|
|
537
|
+
f"Brillouin zone, {low:.5g}, at k = {frac} in the reciprocal basis: a cell of {side} "
|
|
538
|
+
"primitive cells holds it"
|
|
539
|
+
)
|
|
540
|
+
if held:
|
|
541
|
+
text += ", as the analysed one does."
|
|
542
|
+
elif b.first is not None:
|
|
543
|
+
text += f"; the analysed cell does not (its first load {b.first[0]:.5g})."
|
|
544
|
+
else:
|
|
545
|
+
text += "; the analysed cell does not."
|
|
546
|
+
closest = np.minimum(f, 1.0 - f)
|
|
547
|
+
if any(closest) and closest.max() <= 1.0 / n + 1e-12:
|
|
548
|
+
text += (
|
|
549
|
+
" The lowest loads lie next to Γ: a long-wave (macroscopic) instability, which "
|
|
550
|
+
"no finite cell holds; refine the grid."
|
|
551
|
+
)
|
|
552
|
+
fig = Figure(figsize=(5.4, 4.2), layout="constrained")
|
|
553
|
+
ax = fig.subplots()
|
|
554
|
+
if space: # along the edges of the cube: Γ X M Γ R
|
|
555
|
+
corners = np.array([[0, 0, 0], [0.5, 0, 0], [0.5, 0.5, 0], [0, 0, 0], [0.5, 0.5, 0.5]])
|
|
556
|
+
steps = 4
|
|
557
|
+
path = [corners[0]]
|
|
558
|
+
for a, c in pairwise(corners):
|
|
559
|
+
path += [a + t * (c - a) for t in np.linspace(0, 1, steps + 1)[1:]]
|
|
560
|
+
path = np.array(path)
|
|
561
|
+
along = cell.bloch_buckling(strain, path @ recip.T)[:, 0]
|
|
562
|
+
ax.plot(np.arange(len(path)), along, color="C0", lw=1.4, label="primitive cell")
|
|
563
|
+
ax.set_xticks(np.arange(0, len(path), steps), ["Γ", "X", "M", "Γ", "R"])
|
|
564
|
+
ax.axhline(low, color="k", ls=":", lw=1.0, label=f"lowest of the grid, at {frac}")
|
|
565
|
+
if b.first is not None:
|
|
566
|
+
ax.axhline(b.first[0], color="C3", ls="--", lw=1.0, label="the analysed cell")
|
|
567
|
+
ax.set_ylabel("critical load λ")
|
|
568
|
+
ax.legend(fontsize=8, frameon=False)
|
|
569
|
+
ax.grid(alpha=0.3)
|
|
570
|
+
else:
|
|
571
|
+
image = (loads / low).reshape(n, n).T
|
|
572
|
+
shown = ax.imshow(
|
|
573
|
+
image,
|
|
574
|
+
origin="lower",
|
|
575
|
+
extent=(-0.5 / n, 1 - 0.5 / n, -0.5 / n, 1 - 0.5 / n),
|
|
576
|
+
vmin=1.0,
|
|
577
|
+
vmax=max(min(4.0, float(np.nanmax(image))), 1.01),
|
|
578
|
+
cmap="viridis_r",
|
|
579
|
+
)
|
|
580
|
+
fig.colorbar(shown, ax=ax, label="λ / lowest λ")
|
|
581
|
+
ax.plot(*f, "r+", ms=12, mew=2)
|
|
582
|
+
ax.set_xlabel("k · a1 / 2π")
|
|
583
|
+
ax.set_ylabel("k · a2 / 2π")
|
|
584
|
+
ax.set_title("Bloch-wave buckling of the primitive cell", fontsize=10)
|
|
585
|
+
order = np.argsort(np.where(np.isfinite(loads), loads, np.inf), kind="stable")
|
|
586
|
+
rows = [
|
|
587
|
+
{
|
|
588
|
+
**{f"k{i + 1} (b)": float(fractions[j, i]) for i in range(dim)},
|
|
589
|
+
"load λ": float(loads[j]) if np.isfinite(loads[j]) else None,
|
|
590
|
+
"cell needed": needed(fractions[j]),
|
|
591
|
+
}
|
|
592
|
+
for j in order
|
|
593
|
+
]
|
|
594
|
+
return {"values": values, "text": text, "figure": fig, "rows": rows}
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
# -- the cells of morphologies --------------------------------------------------------------
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
class _CellBody:
|
|
601
|
+
"""The primitive cell of a morphology as an implicit body of its level set (as
|
|
602
|
+
:class:`~morphogen.mesh.ImplicitBody`): the box ``[lower, lower + size]``, periodic;
|
|
603
|
+
a plane morphology as a slab ``thickness`` thick whose level set is that of its
|
|
604
|
+
mid-plane through the slab."""
|
|
605
|
+
|
|
606
|
+
def __init__(self, micro, lower, size, thickness: float | None = None):
|
|
607
|
+
from morphogen.domain import Domain
|
|
608
|
+
|
|
609
|
+
self.micro, self.thickness = micro, thickness
|
|
610
|
+
lower, size = np.array(lower, dtype=float), np.array(size, dtype=float)
|
|
611
|
+
if thickness is not None:
|
|
612
|
+
lower[2], size[2] = 0.0, float(thickness)
|
|
613
|
+
self.domain = Domain(size=tuple(size), origin=tuple(lower), periodic=True)
|
|
614
|
+
|
|
615
|
+
def level_set(self, shape=None, *, voxel_size=None, grid=None):
|
|
616
|
+
from morphogen.domain import Domain, Grid
|
|
617
|
+
from morphogen.image import VoxelImage
|
|
618
|
+
|
|
619
|
+
if grid is None:
|
|
620
|
+
grid = Grid.for_domain(self.domain, shape=shape, voxel_size=voxel_size)
|
|
621
|
+
if self.thickness is None:
|
|
622
|
+
return self.micro.level_set(grid=grid)
|
|
623
|
+
box, own = grid.domain, self.micro.domain
|
|
624
|
+
plane = Grid(
|
|
625
|
+
Domain(
|
|
626
|
+
size=(box.size[0], box.size[1], own.size[2]),
|
|
627
|
+
origin=(box.origin[0], box.origin[1], own.origin[2]),
|
|
628
|
+
periodic=False,
|
|
629
|
+
),
|
|
630
|
+
(grid.shape[0], grid.shape[1], 1),
|
|
631
|
+
)
|
|
632
|
+
values = np.asarray(self.micro.level_set(grid=plane).data)
|
|
633
|
+
data = np.ascontiguousarray(np.broadcast_to(values, grid.shape))
|
|
634
|
+
return VoxelImage(data, spacing=tuple(grid.spacing), origin=tuple(grid.origin))
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def _planar(micro) -> bool:
|
|
638
|
+
from morphogen.gui.api import _planar
|
|
639
|
+
|
|
640
|
+
return _planar(micro)
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def _periodic(item: dict) -> None:
|
|
644
|
+
"""Warn that a morphology generated in a window of the medium is taken as periodic."""
|
|
645
|
+
if not item["micro"].domain.periodic:
|
|
646
|
+
warnings.warn(
|
|
647
|
+
f"{item['title']} is not periodic: its cell is analysed as a periodic one, whose "
|
|
648
|
+
"opposite faces may not match",
|
|
649
|
+
stacklevel=2,
|
|
650
|
+
)
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def _primitive(item: dict, choice: str) -> tuple[np.ndarray, np.ndarray, str]:
|
|
654
|
+
"""The primitive cell of a morphology: the lower corner and edges of one unit cell of
|
|
655
|
+
its model (``choice`` "unit", for the models of :data:`UNIT_CELL_MODELS` whose box
|
|
656
|
+
holds a whole number of them) or of its box, and its description."""
|
|
657
|
+
micro = item["micro"]
|
|
658
|
+
lower = np.asarray(micro.domain.lower, dtype=float)
|
|
659
|
+
lengths = np.asarray(micro.domain.lengths, dtype=float)
|
|
660
|
+
model = item.get("model") or {}
|
|
661
|
+
if choice == "unit" and model.get("type") in UNIT_CELL_MODELS:
|
|
662
|
+
cell = np.array(np.broadcast_to(np.asarray(model.get("cell_size", 1.0), float), (3,)))
|
|
663
|
+
if _planar(micro):
|
|
664
|
+
cell[2] = lengths[2]
|
|
665
|
+
ratio = lengths / cell
|
|
666
|
+
whole = np.abs(ratio - np.rint(ratio)) <= 1e-6 * np.maximum(ratio, 1.0)
|
|
667
|
+
if np.all(whole) and np.all(np.rint(ratio) >= 1):
|
|
668
|
+
counts = " × ".join(f"{r:g}" for r in np.rint(ratio))
|
|
669
|
+
return lower, cell, f"a unit cell of its {model['type']} ({counts} in its box)"
|
|
670
|
+
return lower, lengths, "its box"
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def _mirrors(body, n: int = 24) -> tuple[list[int], list[tuple[int, int]]]:
|
|
674
|
+
"""The mid-planes of a cell about which its level set (sampled on ``n`` points per
|
|
675
|
+
edge) is symmetric, and the diagonal planes of pairs of them of equal edges about
|
|
676
|
+
which it is symmetric too (the chain of pairs of :func:`~morphogen.mesh.
|
|
677
|
+
mirrored_mesh`)."""
|
|
678
|
+
from morphogen.domain import Domain, Grid
|
|
679
|
+
|
|
680
|
+
box = body.domain
|
|
681
|
+
shape = (n, n, 2 if body.thickness is not None else n)
|
|
682
|
+
try:
|
|
683
|
+
sample = body.level_set(
|
|
684
|
+
grid=Grid(Domain(size=box.size, origin=box.origin, periodic=False), shape)
|
|
685
|
+
)
|
|
686
|
+
except NotImplementedError:
|
|
687
|
+
return [], []
|
|
688
|
+
v = np.asarray(sample.data, dtype=float)
|
|
689
|
+
scale = float(np.abs(v).max()) or 1.0
|
|
690
|
+
tol = SYMMETRY_TOLERANCE * scale
|
|
691
|
+
mirrors = [k for k in range(3) if np.abs(v - np.flip(v, axis=k)).max() <= tol]
|
|
692
|
+
lengths = np.asarray(box.size, dtype=float)
|
|
693
|
+
pairs = [
|
|
694
|
+
(a, b)
|
|
695
|
+
for a in mirrors
|
|
696
|
+
for b in mirrors
|
|
697
|
+
if a < b
|
|
698
|
+
and v.shape[a] == v.shape[b]
|
|
699
|
+
and abs(lengths[a] - lengths[b]) <= 1e-9 * lengths.max()
|
|
700
|
+
and np.abs(v - np.swapaxes(v, a, b)).max() <= tol
|
|
701
|
+
]
|
|
702
|
+
if len(pairs) == 3: # the cube: two of them generate the third
|
|
703
|
+
pairs = [(0, 1), (1, 2)]
|
|
704
|
+
return mirrors, pairs[:2]
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def _materials_of(item: dict, given) -> dict:
|
|
708
|
+
"""The materials of the phases of a morphology (``given``: those of the form, phase
|
|
709
|
+
-> "void" or isotropic constants; by default, as the forms of the page, void where the
|
|
710
|
+
phase is named so, else E = 1 for phase 0 and 10 for the others, ν = 0.3)."""
|
|
711
|
+
from morphogen.homogenization.materials import VOID, Material
|
|
712
|
+
|
|
713
|
+
names = {int(k): v for k, v in (item.get("phases") or {"0": "0", "1": "1"}).items()}
|
|
714
|
+
if given:
|
|
715
|
+
out = {}
|
|
716
|
+
for k, spec in given.items():
|
|
717
|
+
out[int(k)] = (
|
|
718
|
+
VOID
|
|
719
|
+
if spec == "void"
|
|
720
|
+
else Material(young=float(spec["young"]), poisson=float(spec["poisson"]))
|
|
721
|
+
)
|
|
722
|
+
else:
|
|
723
|
+
out = {
|
|
724
|
+
k: VOID if name == "void" else Material(young=1.0 if k == 0 else 10.0, poisson=0.3)
|
|
725
|
+
for k, name in names.items()
|
|
726
|
+
}
|
|
727
|
+
if all(m.void for m in out.values()):
|
|
728
|
+
raise ValueError("materials: every phase is void")
|
|
729
|
+
return out
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def _solid_phases(materials: dict) -> list[int]:
|
|
733
|
+
return sorted(k for k, m in materials.items() if not m.void)
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def _cell_sample(item: dict, p: dict, materials: dict, ctx) -> dict:
|
|
737
|
+
"""The periodic cell of a morphology for the analyses by group theory: a conforming
|
|
738
|
+
mesh of its level set, mirrored (the symmetries of the cell about its mid-planes
|
|
739
|
+
exact; ``p["mesh"]`` "mirrored", or "auto" when the cell is symmetric about one of
|
|
740
|
+
them at least), or the voxel image of its cell (``p["resolution"]`` voxels along its
|
|
741
|
+
shortest edge, even: the Kuhn triangulation is symmetric under translations by even
|
|
742
|
+
numbers of voxels); ``p["cells"]`` copies of the cell along each axis (1 or 2; the
|
|
743
|
+
plane ones along x and y only). Returns the sample, its cells, the phases kept and a
|
|
744
|
+
description."""
|
|
745
|
+
from morphogen.domain import Domain, Grid
|
|
746
|
+
from morphogen.image import VoxelImage
|
|
747
|
+
from morphogen.mesh import mirrored_mesh
|
|
748
|
+
|
|
749
|
+
micro = item["micro"]
|
|
750
|
+
planar = _planar(micro)
|
|
751
|
+
lower, size, origin = _primitive(item, p.get("cell") or "unit")
|
|
752
|
+
cells = p.get("cells") or ([2, 2, 1] if planar else [1, 1, 1])
|
|
753
|
+
cells = list(cells) * 3 if len(cells) == 1 else list(cells) # one count for all axes
|
|
754
|
+
if len(cells) != 3 or any(c not in (1, 2) for c in cells):
|
|
755
|
+
raise ValueError("cells: three counts of 1 or 2 primitive cells (x, y, z)")
|
|
756
|
+
if planar:
|
|
757
|
+
cells = [cells[0], cells[1], 1]
|
|
758
|
+
cells = tuple(int(c) for c in cells)
|
|
759
|
+
solid = _solid_phases(materials)
|
|
760
|
+
present = sorted(int(k) for k in (item.get("phases") or {"0": 0, "1": 1}))
|
|
761
|
+
missing = [k for k in present if k not in materials]
|
|
762
|
+
if missing:
|
|
763
|
+
raise ValueError(f"materials: none for phase(s) {missing}")
|
|
764
|
+
edge = float(size[:2].min() if planar else size.min())
|
|
765
|
+
kind = p.get("mesh") or "auto"
|
|
766
|
+
out = {"cells": cells, "planar": planar, "origin": origin}
|
|
767
|
+
two_phases = set(present) <= {0, 1}
|
|
768
|
+
if kind in ("auto", "mirrored"):
|
|
769
|
+
h = p.get("element_size") or edge / (8 if planar else 6)
|
|
770
|
+
if not 0 < h <= edge:
|
|
771
|
+
raise ValueError("element size: positive, at most the edge of the cell")
|
|
772
|
+
body = _CellBody(micro, lower, size, 2 * h if planar else None)
|
|
773
|
+
ctx.progress(0.03, "symmetries of the level set")
|
|
774
|
+
mirrors, pairs = _mirrors(body) if two_phases else ([], [])
|
|
775
|
+
if kind == "mirrored" and not two_phases:
|
|
776
|
+
raise ValueError(
|
|
777
|
+
"mesh: a conforming mesh of the level set has two phases; this "
|
|
778
|
+
"morphology has more (use voxels)"
|
|
779
|
+
)
|
|
780
|
+
if kind == "mirrored" and not mirrors:
|
|
781
|
+
raise ValueError(
|
|
782
|
+
"mesh: the level set of this cell is symmetric about none of its "
|
|
783
|
+
"mid-planes (or it has none): use voxels"
|
|
784
|
+
)
|
|
785
|
+
if mirrors:
|
|
786
|
+
meshed = "solid" if solid == [1] else "all"
|
|
787
|
+
ctx.progress(0.06, "conforming mesh (MMG), mirrored")
|
|
788
|
+
mesh = mirrored_mesh(
|
|
789
|
+
body,
|
|
790
|
+
size=h,
|
|
791
|
+
mirrors=mirrors,
|
|
792
|
+
diagonals=pairs,
|
|
793
|
+
cells=cells,
|
|
794
|
+
phases=meshed,
|
|
795
|
+
check=False,
|
|
796
|
+
)
|
|
797
|
+
planes = ", ".join("xyz"[k] for k in mirrors)
|
|
798
|
+
if pairs:
|
|
799
|
+
planes += "; diagonals " + ", ".join(f"{'xyz'[a]}{'xyz'[b]}" for a, b in pairs)
|
|
800
|
+
out.update(
|
|
801
|
+
sample=mesh,
|
|
802
|
+
phases=None,
|
|
803
|
+
kind="mirrored",
|
|
804
|
+
description=f"a conforming mesh of the level set of {origin} (elements "
|
|
805
|
+
f"of {h:.3g}), meshed in its irreducible part and mirrored about the "
|
|
806
|
+
f"planes {planes}",
|
|
807
|
+
)
|
|
808
|
+
return out
|
|
809
|
+
n = int(p.get("resolution") or 8)
|
|
810
|
+
n += n % 2
|
|
811
|
+
if not 2 <= n <= 64:
|
|
812
|
+
raise ValueError("voxels per edge: from 2 to 64")
|
|
813
|
+
h = edge / n
|
|
814
|
+
shape = np.maximum(1, np.rint(size / h)).astype(int)
|
|
815
|
+
if planar:
|
|
816
|
+
shape[2] = 1
|
|
817
|
+
grid = Grid(Domain(size=tuple(size), origin=tuple(lower), periodic=True), tuple(shape))
|
|
818
|
+
ctx.progress(0.05, "voxel image of the cell")
|
|
819
|
+
data = np.tile(np.asarray(micro.voxelize(grid=grid).data), cells)
|
|
820
|
+
spacing = (h, h, h) if planar else tuple(grid.spacing)
|
|
821
|
+
image = VoxelImage(data, spacing=spacing, origin=tuple(lower), periodic=True)
|
|
822
|
+
out.update(
|
|
823
|
+
sample=image,
|
|
824
|
+
phases=solid,
|
|
825
|
+
kind="voxels",
|
|
826
|
+
description=f"the voxel image of {origin}, {' × '.join(map(str, shape))} voxels "
|
|
827
|
+
"of six tetrahedra",
|
|
828
|
+
)
|
|
829
|
+
return out
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
def _cells_text(cells) -> str:
|
|
833
|
+
return " × ".join(map(str, cells))
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def _unresolved(exc: Exception, kind: str) -> Exception:
|
|
837
|
+
"""The error of a cell left without material (its solid in pieces that touch no face of
|
|
838
|
+
the box), with what to change; other errors as they are."""
|
|
839
|
+
if "material" not in str(exc):
|
|
840
|
+
return exc
|
|
841
|
+
hint = (
|
|
842
|
+
"more voxels per edge: these do not resolve the solid of the cell into a body that "
|
|
843
|
+
"reaches its faces (or a conforming mesh)"
|
|
844
|
+
if kind == "voxels"
|
|
845
|
+
else "a finer mesh (element size)"
|
|
846
|
+
)
|
|
847
|
+
return ValueError(f"{exc}: give {hint}")
|
|
848
|
+
|
|
849
|
+
|
|
850
|
+
def _check_size(sample, cells, order: int, phases, *, split: bool) -> None:
|
|
851
|
+
"""Refuse a cell whose dense bases of the isotypic subspaces would not fit in memory:
|
|
852
|
+
about a quarter of the fluctuations each (three arrays of them), those of a primitive
|
|
853
|
+
cell when the analysis splits the cell by its translations (``split``)."""
|
|
854
|
+
from morphogen.gui.api import check_memory
|
|
855
|
+
|
|
856
|
+
if hasattr(sample, "n_nodes"): # a mesh
|
|
857
|
+
nodes = float(sample.n_nodes) * (8 if order == 2 and sample.order == 1 else 1)
|
|
858
|
+
else: # about a node per voxel kept
|
|
859
|
+
kept = np.isin(sample.data, phases).mean() if phases else 1.0
|
|
860
|
+
nodes = float(np.prod(np.asarray(sample.shape) + 1)) * kept * (8 if order == 2 else 1)
|
|
861
|
+
dofs = 3.0 * nodes
|
|
862
|
+
block = dofs / int(np.prod(cells)) if split and dofs > 1500 else dofs
|
|
863
|
+
check_memory(6.0 * block * block, f"the bases of the analysis (about {dofs:.0f} dofs)")
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
# -- views of the patterns on meshes ----------------------------------------------------------
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
def _mesh_frames(mesh, u, *, planar: bool, frames: int = 1, phase: bool = False):
|
|
870
|
+
"""Views of a tetrahedral mesh deformed by a mode ``u`` (nodes x 3): one view, or the
|
|
871
|
+
mode oscillating over ``frames``; coloured by the norm of ``u`` (or by the phases,
|
|
872
|
+
undeformed: ``phase``), seen from above when ``planar``. VTK renders them when it can
|
|
873
|
+
here, else matplotlib."""
|
|
874
|
+
from morphogen.viz.video import deformed_view, field_frames, vtk_can_render
|
|
875
|
+
|
|
876
|
+
view = {"elevation": 0.0, "azimuth": 0.0} if planar else {} # VTK looks down z
|
|
877
|
+
if vtk_can_render():
|
|
878
|
+
if phase:
|
|
879
|
+
return [deformed_view(mesh, None, "phase", edges=True, **view)]
|
|
880
|
+
if frames == 1:
|
|
881
|
+
return [deformed_view(mesh, u, u, title="|u|", **view)]
|
|
882
|
+
return field_frames(mesh, u, frames=frames, title="|u|", **view)
|
|
883
|
+
return _matplotlib_frames(mesh, None if phase else u, planar=planar, frames=frames)
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
def _matplotlib_frames(mesh, u, *, planar: bool, frames: int = 1) -> list[np.ndarray]:
|
|
887
|
+
"""The views of :func:`_mesh_frames` drawn by matplotlib: the outer faces of the mesh
|
|
888
|
+
(its top face when planar), coloured by the norm of ``u`` (or by the phases)."""
|
|
889
|
+
from matplotlib import colormaps
|
|
890
|
+
from matplotlib.backends.backend_agg import FigureCanvasAgg
|
|
891
|
+
from matplotlib.collections import PolyCollection
|
|
892
|
+
from matplotlib.figure import Figure
|
|
893
|
+
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
|
|
894
|
+
|
|
895
|
+
faces = mesh.free_faces()[:, :3]
|
|
896
|
+
x0 = mesh.nodes
|
|
897
|
+
if planar:
|
|
898
|
+
faces = faces[np.all(np.abs(x0[faces, 2] - mesh.upper[2]) <= mesh.tolerance(), axis=1)]
|
|
899
|
+
if u is None: # the phases, undeformed
|
|
900
|
+
u = np.zeros_like(x0)
|
|
901
|
+
phase_of = np.zeros(mesh.n_nodes, dtype=int)
|
|
902
|
+
phase_of[mesh.elements[:, :4].ravel()] = np.repeat(mesh.phase, 4)
|
|
903
|
+
colours = colormaps["tab10"](phase_of[faces].max(axis=1) % 10)
|
|
904
|
+
else:
|
|
905
|
+
norm = np.linalg.norm(u, axis=1)
|
|
906
|
+
colours = colormaps["viridis"](norm[faces].mean(axis=1) / max(norm.max(), 1e-300))
|
|
907
|
+
peak = float(np.linalg.norm(u, axis=1).max())
|
|
908
|
+
m = 0.1 * float(np.ptp(x0, axis=0).max()) / max(peak, 1e-300)
|
|
909
|
+
fig = Figure(figsize=(5.6, 4.8), dpi=100)
|
|
910
|
+
canvas = FigureCanvasAgg(fig)
|
|
911
|
+
lo, hi = x0.min(axis=0) - m * peak, x0.max(axis=0) + m * peak
|
|
912
|
+
if planar:
|
|
913
|
+
ax = fig.add_axes((0, 0, 1, 1))
|
|
914
|
+
coll = PolyCollection(x0[faces][:, :, :2], facecolors=colours, edgecolors="face")
|
|
915
|
+
ax.add_collection(coll)
|
|
916
|
+
ax.set_xlim(lo[0], hi[0])
|
|
917
|
+
ax.set_ylim(lo[1], hi[1])
|
|
918
|
+
ax.set_aspect("equal")
|
|
919
|
+
else:
|
|
920
|
+
ax = fig.add_subplot(projection="3d")
|
|
921
|
+
coll = Poly3DCollection(x0[faces], facecolors=colours, edgecolors="none")
|
|
922
|
+
ax.add_collection3d(coll)
|
|
923
|
+
for setter, a, b in zip((ax.set_xlim, ax.set_ylim, ax.set_zlim), lo, hi, strict=True):
|
|
924
|
+
setter(a, b)
|
|
925
|
+
ax.set_box_aspect(tuple(np.maximum(hi - lo, 1e-9)))
|
|
926
|
+
ax.set_axis_off()
|
|
927
|
+
scales = [1.0] if frames == 1 else np.sin(2 * np.pi * np.arange(frames) / frames)
|
|
928
|
+
out = []
|
|
929
|
+
for s in scales:
|
|
930
|
+
x = x0 + s * m * u
|
|
931
|
+
coll.set_verts(x[faces][:, :, :2] if planar else x[faces])
|
|
932
|
+
canvas.draw()
|
|
933
|
+
out.append(np.asarray(canvas.buffer_rgba())[..., :3].copy())
|
|
934
|
+
return out
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
def _show_patterns(b, ctx, critical, *, planar: bool, video: bool, start: float) -> None:
|
|
938
|
+
"""Views of the analysed mesh and of the patterns of the critical irreps (the softest
|
|
939
|
+
first, :data:`SHOWN` at most) and videos of them oscillating."""
|
|
940
|
+
ctx.progress(start, "views of the mesh and of the patterns")
|
|
941
|
+
ctx.figure(
|
|
942
|
+
_mesh_frames(b.mesh, None, planar=planar, phase=True)[0],
|
|
943
|
+
"mesh",
|
|
944
|
+
"the analysed mesh (phases)",
|
|
945
|
+
)
|
|
946
|
+
shown = _patterns_of(b, critical)[:SHOWN]
|
|
947
|
+
for k, pattern in enumerate(shown):
|
|
948
|
+
u = b.displacement(pattern.mode)
|
|
949
|
+
ctx.figure(_mesh_frames(b.mesh, u, planar=planar)[0], f"pattern_{k + 1}", _title(pattern))
|
|
950
|
+
if video:
|
|
951
|
+
ctx.progress(start + (0.98 - start) * (k + 1) / len(shown), "videos of the patterns")
|
|
952
|
+
ctx.video(
|
|
953
|
+
_mesh_frames(b.mesh, u, planar=planar, frames=FRAMES),
|
|
954
|
+
f"pattern_{k + 1}",
|
|
955
|
+
_title(pattern),
|
|
956
|
+
mode="loop",
|
|
957
|
+
)
|
|
958
|
+
|
|
959
|
+
|
|
960
|
+
# -- morphologies ---------------------------------------------------------------------------
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
def _mesh_fields(default_mesh: str = "auto", resolution: int = 8) -> list:
|
|
964
|
+
return [
|
|
965
|
+
Field("cell", "choice", "unit", choices=CELLS, label="primitive cell"),
|
|
966
|
+
Field(
|
|
967
|
+
"cells",
|
|
968
|
+
"ints",
|
|
969
|
+
doc="primitive cells along x, y and z, 1 or 2 each, or one count for all (blank: "
|
|
970
|
+
"2 × 2 × 1 for a plane morphology, 1 × 1 × 1 otherwise)",
|
|
971
|
+
),
|
|
972
|
+
Field("mesh", "choice", default_mesh, choices=MESHES),
|
|
973
|
+
Field(
|
|
974
|
+
"element_size",
|
|
975
|
+
"float",
|
|
976
|
+
unit="length",
|
|
977
|
+
when={"mesh": ["auto", "mirrored"]},
|
|
978
|
+
doc="of the conforming mesh (blank: 1/8 of the shortest edge of a plane cell, 1/6 "
|
|
979
|
+
"in space)",
|
|
980
|
+
),
|
|
981
|
+
Field(
|
|
982
|
+
"resolution",
|
|
983
|
+
"int",
|
|
984
|
+
resolution,
|
|
985
|
+
label="voxels per edge",
|
|
986
|
+
when={"mesh": ["auto", "voxels"]},
|
|
987
|
+
doc="along the shortest edge of the primitive cell (even; a multiple of 4 keeps "
|
|
988
|
+
"the translations by half a cell)",
|
|
989
|
+
),
|
|
990
|
+
]
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
@tool(
|
|
994
|
+
"morphology_bifurcation",
|
|
995
|
+
"stability",
|
|
996
|
+
"Post-bifurcation of a morphology",
|
|
997
|
+
"The post-bifurcated patterns of a morphology of the workspace by group theory (Azulay "
|
|
998
|
+
"& Combescure 2024): its primitive cell (a unit cell of its model, or its box) "
|
|
999
|
+
"repeated 1 or 2 times along each axis, meshed conforming to its level set and "
|
|
1000
|
+
"mirrored when the cell is symmetric about its mid-planes (exact symmetries), or cut "
|
|
1001
|
+
"into six tetrahedra per voxel; its symmetry group (detected on the mesh) restricted "
|
|
1002
|
+
"to a macroscopic strain, the linear buckling of each irreducible representation "
|
|
1003
|
+
"(about the initial stress of the periodic linear solution), the first bifurcation, "
|
|
1004
|
+
"its patterns on the mesh and its wave vectors: the patterns of a wave vector of "
|
|
1005
|
+
"components π/a double the period along those axes. A plane morphology is a slab of "
|
|
1006
|
+
"two elements, periodic through its thickness.",
|
|
1007
|
+
[
|
|
1008
|
+
Field("source", "item", label="morphology", required=True),
|
|
1009
|
+
*_mesh_fields(),
|
|
1010
|
+
Field("order", "choice", "1", choices=ORDERS, label="elements"),
|
|
1011
|
+
Field("materials", "materials", of="source"),
|
|
1012
|
+
*_loading_fields(),
|
|
1013
|
+
Field("patterns", "choice", "critical", choices=PATTERNS, doc="the patterns computed"),
|
|
1014
|
+
Field("video", "bool", True, doc="a video of each pattern of the first bifurcation"),
|
|
1015
|
+
],
|
|
1016
|
+
order=2,
|
|
1017
|
+
menu="Bifurcations",
|
|
1018
|
+
)
|
|
1019
|
+
def morphology_bifurcation(p: dict, ctx) -> dict:
|
|
1020
|
+
from morphogen.homogenization.bifurcation import post_bifurcation
|
|
1021
|
+
|
|
1022
|
+
item = p["source"]
|
|
1023
|
+
_periodic(item)
|
|
1024
|
+
materials = _materials_of(item, p["materials"])
|
|
1025
|
+
strain, loading = _strain(p, 3)
|
|
1026
|
+
cell = _cell_sample(item, p, materials, ctx)
|
|
1027
|
+
order = int(p["order"] or 1)
|
|
1028
|
+
sample = cell["sample"]
|
|
1029
|
+
size = sample.n_nodes if hasattr(sample, "n_nodes") else int(np.prod(sample.shape))
|
|
1030
|
+
_check_size(sample, cell["cells"], order, cell["phases"], split=True)
|
|
1031
|
+
with _Busy(ctx, 0.1, 0.7, "group-theoretic analysis", 2.0 + size / 300.0 * order**2):
|
|
1032
|
+
try:
|
|
1033
|
+
b = post_bifurcation(
|
|
1034
|
+
sample,
|
|
1035
|
+
strain,
|
|
1036
|
+
materials=materials,
|
|
1037
|
+
cells=cell["cells"],
|
|
1038
|
+
order=order,
|
|
1039
|
+
phases=cell["phases"],
|
|
1040
|
+
patterns=p["patterns"],
|
|
1041
|
+
)
|
|
1042
|
+
except ValueError as exc:
|
|
1043
|
+
raise _unresolved(exc, cell["kind"]) from None
|
|
1044
|
+
critical = _critical(b)
|
|
1045
|
+
waves = _wave_vectors(b, cell["cells"])
|
|
1046
|
+
dofs = int(b.lift.shape[1])
|
|
1047
|
+
values: dict = {
|
|
1048
|
+
"mesh": cell["kind"],
|
|
1049
|
+
"cells": _cells_text(cell["cells"]),
|
|
1050
|
+
"elements": b.mesh.n_elements,
|
|
1051
|
+
"dofs": dofs,
|
|
1052
|
+
"group order": b.group.order,
|
|
1053
|
+
"irreps": len(b.irreps),
|
|
1054
|
+
}
|
|
1055
|
+
first, sentence = _first(b, waves)
|
|
1056
|
+
values.update(first)
|
|
1057
|
+
text = [
|
|
1058
|
+
f"{item['title']}: {cell['description']}; {_cells_text(cell['cells'])} primitive "
|
|
1059
|
+
f"cells, {b.mesh.n_elements} elements, {dofs} dofs. {loading.capitalize()}: a group "
|
|
1060
|
+
f"of {b.group.order} operations restricted to the loading, {len(b.irreps)} irreps.",
|
|
1061
|
+
sentence,
|
|
1062
|
+
]
|
|
1063
|
+
if b.group.order == 1:
|
|
1064
|
+
text.append("The mesh has no symmetry: every mode is in the trivial irrep.")
|
|
1065
|
+
ctx.table(_irrep_rows(b, critical, waves), "irreps", "irreducible representations")
|
|
1066
|
+
if b.patterns:
|
|
1067
|
+
ctx.table(_pattern_rows(b), "patterns", "patterns: the axial isotropy subgroups")
|
|
1068
|
+
b.write(ctx.path("patterns.vtu"), irreps=critical or None)
|
|
1069
|
+
_show_patterns(b, ctx, critical, planar=cell["planar"], video=p["video"], start=0.72)
|
|
1070
|
+
return {"values": values, "text": " ".join(text)}
|
|
1071
|
+
|
|
1072
|
+
|
|
1073
|
+
# -- along nonlinear paths --------------------------------------------------------------------
|
|
1074
|
+
|
|
1075
|
+
CELL_KINDS = (
|
|
1076
|
+
("holes", "a square array of circular holes (Mullin et al. 2007; Bertoldi et al. 2008)"),
|
|
1077
|
+
("morphology", "a morphology of the workspace"),
|
|
1078
|
+
)
|
|
1079
|
+
PATH_LOADINGS = (
|
|
1080
|
+
("uniaxial_stress", "uniaxial compression, the lateral stresses free"),
|
|
1081
|
+
("uniaxial_strain", "uniaxial compression, the lateral strains held"),
|
|
1082
|
+
("equibiaxial", "equibiaxial compression in the x-y plane"),
|
|
1083
|
+
("hydrostatic", "hydrostatic compression (equibiaxial in the plane)"),
|
|
1084
|
+
)
|
|
1085
|
+
BEHAVIOURS = (
|
|
1086
|
+
("elastic", "elastic: Hencky in finite strains"),
|
|
1087
|
+
("plastic", "von Mises elastoplastic, linear hardening"),
|
|
1088
|
+
)
|
|
1089
|
+
KINEMATICS = (("finite", "finite strains"), ("small", "small strains"))
|
|
1090
|
+
NAMES = ("11", "22", "33", "23", "31", "12")
|
|
1091
|
+
|
|
1092
|
+
|
|
1093
|
+
def _path(p: dict, planar: bool) -> tuple[dict, int, str]:
|
|
1094
|
+
"""The loading path of the form (a nominal compressive strain reached at the time 1,
|
|
1095
|
+
shears held at zero, the out-of-plane strain of a plane cell too), the loaded axis and
|
|
1096
|
+
a description."""
|
|
1097
|
+
eps, n = float(p["strain"]), int(p["increments"])
|
|
1098
|
+
if not 0 < eps < 0.9:
|
|
1099
|
+
raise ValueError("strain: a compression between 0 and 0.9")
|
|
1100
|
+
if not 2 <= n <= 400:
|
|
1101
|
+
raise ValueError("increments: from 2 to 400")
|
|
1102
|
+
kind = p["loading"]
|
|
1103
|
+
axis = "xyz".index(p.get("axis") or "y")
|
|
1104
|
+
if planar and axis == 2 and kind.startswith("uniaxial"):
|
|
1105
|
+
raise ValueError("axis: x or y for a plane cell")
|
|
1106
|
+
spec = {"23": 0.0, "31": 0.0, "12": 0.0}
|
|
1107
|
+
if planar:
|
|
1108
|
+
spec["33"] = 0.0
|
|
1109
|
+
if kind.startswith("uniaxial"):
|
|
1110
|
+
spec[NAMES[axis]] = -eps
|
|
1111
|
+
if kind == "uniaxial_strain":
|
|
1112
|
+
for k in range(3):
|
|
1113
|
+
spec.setdefault(NAMES[k], 0.0)
|
|
1114
|
+
text = f"uniaxial compression along {'xyz'[axis]}, the lateral " + (
|
|
1115
|
+
"strains held" if kind == "uniaxial_strain" else "stresses free"
|
|
1116
|
+
)
|
|
1117
|
+
elif kind == "equibiaxial" or planar:
|
|
1118
|
+
spec["11"] = spec["22"] = -eps
|
|
1119
|
+
axis, text = 0, "equibiaxial compression in the x-y plane"
|
|
1120
|
+
else:
|
|
1121
|
+
spec["11"] = spec["22"] = spec["33"] = -eps
|
|
1122
|
+
axis, text = 0, "hydrostatic compression"
|
|
1123
|
+
if planar:
|
|
1124
|
+
text += ", in plane strain"
|
|
1125
|
+
return {"times": [0, 1], "increments": n, "strain": spec}, axis, text
|
|
1126
|
+
|
|
1127
|
+
|
|
1128
|
+
def _behaviour(materials: dict, p: dict) -> dict:
|
|
1129
|
+
"""The materials with the behaviour of the form: von Mises plasticity of yield strain
|
|
1130
|
+
and hardening relative to the Young's modulus of each phase."""
|
|
1131
|
+
import dataclasses
|
|
1132
|
+
|
|
1133
|
+
from morphogen.homogenization.behaviours import Plasticity
|
|
1134
|
+
|
|
1135
|
+
if p["behaviour"] != "plastic":
|
|
1136
|
+
return materials
|
|
1137
|
+
strain, hardening = float(p["yield_strain"]), float(p["hardening"])
|
|
1138
|
+
if not strain > 0 or hardening < 0:
|
|
1139
|
+
raise ValueError("yield strain: positive; hardening: non-negative")
|
|
1140
|
+
return {
|
|
1141
|
+
k: m
|
|
1142
|
+
if m.void
|
|
1143
|
+
else dataclasses.replace(
|
|
1144
|
+
m, plasticity=Plasticity(strain * m.young, hardening=hardening * m.young)
|
|
1145
|
+
)
|
|
1146
|
+
for k, m in materials.items()
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
|
|
1150
|
+
def _holes(p: dict, ctx) -> dict:
|
|
1151
|
+
"""The 2 x 2 cell of a square array of circular holes (cells of edge 1, one layer):
|
|
1152
|
+
a conforming mesh mirrored with the diagonals of the square, or voxels."""
|
|
1153
|
+
from morphogen.domain import Domain
|
|
1154
|
+
from morphogen.image import VoxelImage
|
|
1155
|
+
from morphogen.mesh import ImplicitBody, mirrored_mesh
|
|
1156
|
+
|
|
1157
|
+
porosity = float(p["porosity"])
|
|
1158
|
+
if not 0 < porosity < np.pi / 4:
|
|
1159
|
+
raise ValueError("porosity: between 0 and π/4 (holes apart)")
|
|
1160
|
+
radius = float(np.sqrt(porosity / np.pi))
|
|
1161
|
+
out = {"cells": (2, 2, 1), "planar": True, "radius": radius}
|
|
1162
|
+
if p["mesh"] in ("auto", "mirrored"):
|
|
1163
|
+
h = float(p["element_size"] or 0.12)
|
|
1164
|
+
if not 0 < h <= 0.5:
|
|
1165
|
+
raise ValueError("element size: between 0 and 0.5 of the cell")
|
|
1166
|
+
|
|
1167
|
+
def solid(points):
|
|
1168
|
+
d = points[:, :2] % 1.0 - 0.5
|
|
1169
|
+
return radius - np.hypot(d[:, 0], d[:, 1])
|
|
1170
|
+
|
|
1171
|
+
ctx.progress(0.05, "conforming mesh (MMG), mirrored")
|
|
1172
|
+
body = ImplicitBody(Domain(size=(1.0, 1.0, 2 * h), periodic=True), solid)
|
|
1173
|
+
mesh = mirrored_mesh(body, size=h, diagonals=((0, 1),), cells=(2, 2, 1), phases="solid")
|
|
1174
|
+
out.update(
|
|
1175
|
+
sample=mesh,
|
|
1176
|
+
phases=None,
|
|
1177
|
+
kind="mirrored",
|
|
1178
|
+
band=0.5 * h,
|
|
1179
|
+
description=f"a conforming mesh of the holes (elements of {h:.3g} of the "
|
|
1180
|
+
"cell), mirrored with the diagonals of the square",
|
|
1181
|
+
)
|
|
1182
|
+
return out
|
|
1183
|
+
n = int(p["resolution"] or 12)
|
|
1184
|
+
n += n % 2
|
|
1185
|
+
if not 4 <= n <= 64:
|
|
1186
|
+
raise ValueError("voxels per edge: from 4 to 64")
|
|
1187
|
+
c = (np.arange(n) + 0.5) / n - 0.5
|
|
1188
|
+
solid = (np.hypot(c[:, None], c[None, :]) > radius).astype(np.uint8)
|
|
1189
|
+
data = np.tile(solid[:, :, None], (2, 2, 1))
|
|
1190
|
+
out.update(
|
|
1191
|
+
sample=VoxelImage(data, spacing=(1.0 / n,) * 3, periodic=True),
|
|
1192
|
+
phases=[1],
|
|
1193
|
+
kind="voxels",
|
|
1194
|
+
band=1.0 / n,
|
|
1195
|
+
description=f"voxels of the holes, {n} per edge of the cell",
|
|
1196
|
+
)
|
|
1197
|
+
return out
|
|
1198
|
+
|
|
1199
|
+
|
|
1200
|
+
def _ellipticities(nodes, u, radius: float, band: float) -> np.ndarray:
|
|
1201
|
+
"""The ellipticity of each hole of the 2 x 2 cell, (0, 0), (0, 1), (1, 0), (1, 1), under
|
|
1202
|
+
a displacement: its radial displacement along x less that along y (the nodes within
|
|
1203
|
+
``band`` of its edge)."""
|
|
1204
|
+
out = []
|
|
1205
|
+
for hx in (0, 1):
|
|
1206
|
+
for hy in (0, 1):
|
|
1207
|
+
d = nodes[:, :2] - np.array([hx + 0.5, hy + 0.5])
|
|
1208
|
+
rad = np.hypot(d[:, 0], d[:, 1])
|
|
1209
|
+
ring = np.abs(rad - radius) < band
|
|
1210
|
+
radial = (u[:, 0] * d[:, 0] + u[:, 1] * d[:, 1]) / np.maximum(rad, 1e-12)
|
|
1211
|
+
along_x = ring & (np.abs(d[:, 0]) > 0.9 * rad)
|
|
1212
|
+
along_y = ring & (np.abs(d[:, 1]) > 0.9 * rad)
|
|
1213
|
+
if not (along_x.any() and along_y.any()):
|
|
1214
|
+
return np.full(4, np.nan)
|
|
1215
|
+
out.append(radial[along_x].mean() - radial[along_y].mean())
|
|
1216
|
+
return np.array(out)
|
|
1217
|
+
|
|
1218
|
+
|
|
1219
|
+
@tool(
|
|
1220
|
+
"path_bifurcation",
|
|
1221
|
+
"stability",
|
|
1222
|
+
"Bifurcation along a nonlinear path",
|
|
1223
|
+
"The first bifurcation of a periodic cell along a nonlinear loading path (the stability "
|
|
1224
|
+
"of the principal path itself, beyond linear buckling): the cell is loaded in finite "
|
|
1225
|
+
"strains (Hencky elasticity, or von Mises elastoplasticity), and at each converged step "
|
|
1226
|
+
"its consistent tangent, the components of prescribed stress condensed, is "
|
|
1227
|
+
"block-diagonalized in the isotypic subspaces of its symmetry group restricted to the "
|
|
1228
|
+
"path; the first block whose lowest eigenvalue changes sign marks the bifurcation: its "
|
|
1229
|
+
"critical strain, irrep, multiplicity and patterns (the softest modes of the axial "
|
|
1230
|
+
"classes there). A square array of circular holes in compression turns its holes into "
|
|
1231
|
+
"alternating, mutually orthogonal ellipses (Mullin et al. 2007; Bertoldi et al. 2008), "
|
|
1232
|
+
"an irrep that doubles the period; on the bifurcated branch (an imperfection along the "
|
|
1233
|
+
"pattern), its stress levels off and its Poisson's ratio turns negative.",
|
|
1234
|
+
[
|
|
1235
|
+
Field("cell", "choice", "holes", choices=CELL_KINDS),
|
|
1236
|
+
Field("source", "item", label="morphology", required=True, when={"cell": "morphology"}),
|
|
1237
|
+
Field("porosity", "float", 0.5, when={"cell": "holes"}, doc="area fraction of the holes"),
|
|
1238
|
+
Field(
|
|
1239
|
+
"primitive",
|
|
1240
|
+
"choice",
|
|
1241
|
+
"unit",
|
|
1242
|
+
choices=CELLS,
|
|
1243
|
+
label="primitive cell",
|
|
1244
|
+
when={"cell": "morphology"},
|
|
1245
|
+
),
|
|
1246
|
+
Field(
|
|
1247
|
+
"cells",
|
|
1248
|
+
"ints",
|
|
1249
|
+
when={"cell": "morphology"},
|
|
1250
|
+
doc="primitive cells along x, y and z, 1 or 2 each, or one count for all (blank: "
|
|
1251
|
+
"2 × 2 × 1 for a plane morphology, 1 × 1 × 1 otherwise)",
|
|
1252
|
+
),
|
|
1253
|
+
Field("mesh", "choice", "voxels", choices=MESHES),
|
|
1254
|
+
Field(
|
|
1255
|
+
"element_size",
|
|
1256
|
+
"float",
|
|
1257
|
+
unit="length",
|
|
1258
|
+
when={"mesh": ["auto", "mirrored"]},
|
|
1259
|
+
doc="of the conforming mesh (blank: 0.12 of the cell of the holes; 1/8 of the "
|
|
1260
|
+
"shortest edge of a plane morphology, 1/6 in space)",
|
|
1261
|
+
),
|
|
1262
|
+
Field(
|
|
1263
|
+
"resolution",
|
|
1264
|
+
"int",
|
|
1265
|
+
12,
|
|
1266
|
+
label="voxels per edge",
|
|
1267
|
+
when={"mesh": ["auto", "voxels"]},
|
|
1268
|
+
doc="along the shortest edge of the primitive cell (even)",
|
|
1269
|
+
),
|
|
1270
|
+
Field("young", "float", 1.0, label="Young's modulus", when={"cell": "holes"}),
|
|
1271
|
+
Field("poisson", "float", 0.3, label="Poisson's ratio", when={"cell": "holes"}),
|
|
1272
|
+
Field("materials", "materials", of="source", when={"cell": "morphology"}),
|
|
1273
|
+
Field("behaviour", "choice", "elastic", choices=BEHAVIOURS),
|
|
1274
|
+
Field(
|
|
1275
|
+
"yield_strain",
|
|
1276
|
+
"float",
|
|
1277
|
+
0.01,
|
|
1278
|
+
when={"behaviour": "plastic"},
|
|
1279
|
+
doc="the yield stress over the Young's modulus of each phase",
|
|
1280
|
+
),
|
|
1281
|
+
Field(
|
|
1282
|
+
"hardening",
|
|
1283
|
+
"float",
|
|
1284
|
+
0.1,
|
|
1285
|
+
when={"behaviour": "plastic"},
|
|
1286
|
+
doc="the linear hardening modulus over the Young's modulus",
|
|
1287
|
+
),
|
|
1288
|
+
Field("kinematics", "choice", "finite", choices=KINEMATICS),
|
|
1289
|
+
Field(
|
|
1290
|
+
"order",
|
|
1291
|
+
"choice",
|
|
1292
|
+
"1",
|
|
1293
|
+
choices=ORDERS,
|
|
1294
|
+
label="elements",
|
|
1295
|
+
doc="10-node tetrahedra for plasticity (4-node ones lock under plastic flow)",
|
|
1296
|
+
),
|
|
1297
|
+
Field("loading", "choice", "uniaxial_stress", choices=PATH_LOADINGS),
|
|
1298
|
+
Field(
|
|
1299
|
+
"axis",
|
|
1300
|
+
"choice",
|
|
1301
|
+
"y",
|
|
1302
|
+
choices=AXES,
|
|
1303
|
+
when={"loading": ["uniaxial_stress", "uniaxial_strain"]},
|
|
1304
|
+
),
|
|
1305
|
+
Field(
|
|
1306
|
+
"strain",
|
|
1307
|
+
"float",
|
|
1308
|
+
0.12,
|
|
1309
|
+
label="largest strain",
|
|
1310
|
+
doc="the nominal compressive strain at the end of the path",
|
|
1311
|
+
),
|
|
1312
|
+
Field("increments", "int", 12, doc="steps of the path (divided when Newton fails)"),
|
|
1313
|
+
Field(
|
|
1314
|
+
"branch",
|
|
1315
|
+
"bool",
|
|
1316
|
+
False,
|
|
1317
|
+
label="follow the bifurcated branch",
|
|
1318
|
+
doc="the path followed again with an imperfection of 2 % of the cell along "
|
|
1319
|
+
"the critical pattern",
|
|
1320
|
+
),
|
|
1321
|
+
Field("video", "bool", True, doc="a video of the critical pattern oscillating"),
|
|
1322
|
+
],
|
|
1323
|
+
order=3,
|
|
1324
|
+
groups=(
|
|
1325
|
+
("Cell", "cell"),
|
|
1326
|
+
("Mesh", "mesh"),
|
|
1327
|
+
("Material", "young"),
|
|
1328
|
+
("Solver", "kinematics"),
|
|
1329
|
+
("Loading", "loading"),
|
|
1330
|
+
("Output", "video", True),
|
|
1331
|
+
),
|
|
1332
|
+
menu="Bifurcations",
|
|
1333
|
+
)
|
|
1334
|
+
def path_bifurcation_tool(p: dict, ctx) -> dict:
|
|
1335
|
+
from morphogen.homogenization.bifurcation import path_bifurcation
|
|
1336
|
+
from morphogen.homogenization.materials import Material
|
|
1337
|
+
|
|
1338
|
+
holes = p["cell"] == "holes"
|
|
1339
|
+
if holes:
|
|
1340
|
+
materials = {1: Material(young=float(p["young"]), poisson=float(p["poisson"]))}
|
|
1341
|
+
cell = _holes(p, ctx)
|
|
1342
|
+
title = f"A square array of circular holes (porosity {float(p['porosity']):g})"
|
|
1343
|
+
else:
|
|
1344
|
+
item = p["source"]
|
|
1345
|
+
_periodic(item)
|
|
1346
|
+
materials = _materials_of(item, p["materials"])
|
|
1347
|
+
cell = _cell_sample(item, {**p, "cell": p["primitive"]}, materials, ctx)
|
|
1348
|
+
title = item["title"]
|
|
1349
|
+
materials = _behaviour(materials, p)
|
|
1350
|
+
path, axis, loading = _path(p, cell["planar"])
|
|
1351
|
+
eps = float(p["strain"])
|
|
1352
|
+
order = int(p["order"] or 1)
|
|
1353
|
+
sample = cell["sample"]
|
|
1354
|
+
size = sample.n_nodes if hasattr(sample, "n_nodes") else int(np.prod(sample.shape))
|
|
1355
|
+
expected = 3.0 + size * int(p["increments"]) / 2000.0 * (2 if p["branch"] else 1) * order**3
|
|
1356
|
+
_check_size(sample, cell["cells"], order, cell["phases"], split=False)
|
|
1357
|
+
with _Busy(ctx, 0.1, 0.7, "following the loading path", expected):
|
|
1358
|
+
try:
|
|
1359
|
+
b = path_bifurcation(
|
|
1360
|
+
sample,
|
|
1361
|
+
path,
|
|
1362
|
+
materials=materials,
|
|
1363
|
+
kinematics=p["kinematics"],
|
|
1364
|
+
cells=cell["cells"],
|
|
1365
|
+
order=order,
|
|
1366
|
+
phases=cell["phases"],
|
|
1367
|
+
branch=0.02 if p["branch"] else None,
|
|
1368
|
+
)
|
|
1369
|
+
except ValueError as exc:
|
|
1370
|
+
raise _unresolved(exc, cell["kind"]) from None
|
|
1371
|
+
dofs = int(b.lift.shape[1])
|
|
1372
|
+
values: dict = {
|
|
1373
|
+
"mesh": cell["kind"],
|
|
1374
|
+
"cells": _cells_text(cell["cells"]),
|
|
1375
|
+
"elements": b.mesh.n_elements,
|
|
1376
|
+
"dofs": dofs,
|
|
1377
|
+
"group order": b.group.order,
|
|
1378
|
+
"irreps": len(b.irreps),
|
|
1379
|
+
"steps": len(b.times) - 1,
|
|
1380
|
+
}
|
|
1381
|
+
text = [
|
|
1382
|
+
f"{title}: {cell['description']}; {_cells_text(cell['cells'])} primitive cells, "
|
|
1383
|
+
f"{b.mesh.n_elements} elements, {dofs} dofs. {loading.capitalize()} to {eps:g} in "
|
|
1384
|
+
f"{p['kinematics']} strains: a group of {b.group.order} operations restricted to the "
|
|
1385
|
+
f"path, {len(b.irreps)} irreps."
|
|
1386
|
+
]
|
|
1387
|
+
critical = []
|
|
1388
|
+
waves = _wave_vectors(b, cell["cells"])
|
|
1389
|
+
if b.first is None:
|
|
1390
|
+
reached = -float(b.strains[-1, axis])
|
|
1391
|
+
values["bifurcation"] = "none"
|
|
1392
|
+
text.append(f"The principal path stays stable up to a nominal strain of {reached:.4g}.")
|
|
1393
|
+
else:
|
|
1394
|
+
t, i, count = b.first
|
|
1395
|
+
critical = np.flatnonzero(np.abs(b.loads - t) <= 1e-3 * abs(t)).tolist()
|
|
1396
|
+
values.update(
|
|
1397
|
+
{
|
|
1398
|
+
"critical nominal strain": -float(b.critical_strain[axis]),
|
|
1399
|
+
**{f"critical strain {NAMES[k]}": float(b.critical_strain[k]) for k in range(3)},
|
|
1400
|
+
"irrep of the first bifurcation": i + 1,
|
|
1401
|
+
"its dimension": b.irreps[i].dim,
|
|
1402
|
+
"multiplicity": count,
|
|
1403
|
+
}
|
|
1404
|
+
)
|
|
1405
|
+
doubled = _doubled(waves[i])
|
|
1406
|
+
if doubled:
|
|
1407
|
+
values["period doubled along"] = doubled
|
|
1408
|
+
sentence = (
|
|
1409
|
+
f"First bifurcation at a nominal strain of {-b.critical_strain[axis]:.4g} (the "
|
|
1410
|
+
f"strains {', '.join(f'{v:.4g}' for v in b.critical_strain[:3])}), in irrep "
|
|
1411
|
+
f"{i + 1} of dimension {b.irreps[i].dim}, multiplicity {count}"
|
|
1412
|
+
)
|
|
1413
|
+
if doubled and doubled != "none":
|
|
1414
|
+
sentence += f": its wave vectors {_waves(waves[i])} double the period along {doubled}"
|
|
1415
|
+
text.append(sentence + ".")
|
|
1416
|
+
# the loads of a path are the times of the crossings: in nominal strains
|
|
1417
|
+
load = "critical nominal strain"
|
|
1418
|
+
rows = _irrep_rows(b, critical, waves, load=load, scale=eps)
|
|
1419
|
+
ctx.table(rows, "irreps", "irreducible representations")
|
|
1420
|
+
if b.patterns:
|
|
1421
|
+
ctx.table(
|
|
1422
|
+
_pattern_rows(b, load=load, scale=eps),
|
|
1423
|
+
"patterns",
|
|
1424
|
+
"patterns: the axial isotropy subgroups",
|
|
1425
|
+
)
|
|
1426
|
+
ctx.progress(0.72, "figures")
|
|
1427
|
+
ctx.figure(
|
|
1428
|
+
_spectra_figure(b, axis, critical),
|
|
1429
|
+
"stability",
|
|
1430
|
+
"lowest eigenvalue of the tangent in each isotypic subspace",
|
|
1431
|
+
)
|
|
1432
|
+
ctx.table(_spectra_rows(b, axis), "spectra", "lowest eigenvalues along the path")
|
|
1433
|
+
ctx.figure(_response_figure(b, axis), "response", "response along the path")
|
|
1434
|
+
if holes and critical:
|
|
1435
|
+
pattern = _patterns_of(b, critical)[0]
|
|
1436
|
+
e = _ellipticities(b.mesh.nodes, b.displacement(pattern.mode), cell["radius"], cell["band"])
|
|
1437
|
+
if np.all(np.isfinite(e)) and np.abs(e).max() > 0:
|
|
1438
|
+
e = e / np.abs(e).max()
|
|
1439
|
+
alternating = bool(e[0] * e[1] < 0 and e[0] * e[2] < 0 and e[0] * e[3] > 0)
|
|
1440
|
+
values["holes"] = "alternating ellipses" if alternating else "other pattern"
|
|
1441
|
+
names = ("(0, 0)", "(0, 1)", "(1, 0)", "(1, 1)")
|
|
1442
|
+
ctx.table(
|
|
1443
|
+
[{"hole": h, "ellipticity": float(v)} for h, v in zip(names, e, strict=True)],
|
|
1444
|
+
"ellipticities",
|
|
1445
|
+
"ellipticity of the holes in the pattern (relative)",
|
|
1446
|
+
)
|
|
1447
|
+
if alternating:
|
|
1448
|
+
text.append("The holes turn into alternating, mutually orthogonal ellipses.")
|
|
1449
|
+
if b.branch is not None and b.first is not None:
|
|
1450
|
+
ctx.figure(_branch_figure(b, axis, eps), "branch", "the bifurcated branch")
|
|
1451
|
+
growth = abs(b.amplitudes[-1]) / max(abs(b.amplitudes[0]), 1e-300)
|
|
1452
|
+
stress = -b.branch.stress[:, axis] # compressive
|
|
1453
|
+
late = stress[b.branch.times > 1.6 * b.first[0]]
|
|
1454
|
+
values["branch: growth of the pattern"] = float(growth)
|
|
1455
|
+
sentence = f"On the bifurcated branch the amplitude of the pattern grows {growth:.3g} times"
|
|
1456
|
+
if late.size > 2 and abs(late.mean()) > 0:
|
|
1457
|
+
spread = float(np.ptp(late) / abs(late.mean()))
|
|
1458
|
+
values["branch: stress spread"] = spread
|
|
1459
|
+
sentence += (
|
|
1460
|
+
f", the stress varying by {100 * spread:.2g} % past 1.6 times the critical strain"
|
|
1461
|
+
)
|
|
1462
|
+
for k in (k for k in range(3) if NAMES[k] not in path["strain"]): # the free strains
|
|
1463
|
+
values[f"branch: final strain {NAMES[k]}"] = float(b.branch.strain[-1, k])
|
|
1464
|
+
sentence += f"; the strain {NAMES[k]} ends at {b.branch.strain[-1, k]:.4g}"
|
|
1465
|
+
if b.branch.strain[-1, k] < 0:
|
|
1466
|
+
sentence += " (a negative Poisson's ratio)"
|
|
1467
|
+
text.append(sentence + ".")
|
|
1468
|
+
if p["behaviour"] == "plastic" and order == 1:
|
|
1469
|
+
text.append("4-node tetrahedra lock under plastic flow: prefer 10-node ones.")
|
|
1470
|
+
if critical:
|
|
1471
|
+
_show_patterns(b, ctx, critical, planar=cell["planar"], video=p["video"], start=0.78)
|
|
1472
|
+
return {"values": values, "text": " ".join(text)}
|
|
1473
|
+
|
|
1474
|
+
|
|
1475
|
+
def _spectra_figure(b, axis: int, critical):
|
|
1476
|
+
"""The lowest eigenvalue of the tangent in each isotypic subspace along the path, over
|
|
1477
|
+
its value in the natural state: a block that loses its positive definiteness crosses 0."""
|
|
1478
|
+
from matplotlib.figure import Figure
|
|
1479
|
+
|
|
1480
|
+
fig = Figure(figsize=(5.6, 4.0), layout="constrained")
|
|
1481
|
+
ax = fig.subplots()
|
|
1482
|
+
strain = -b.strains[:, axis]
|
|
1483
|
+
for i in range(len(b.irreps)):
|
|
1484
|
+
lam = b.spectra[:, i, 0]
|
|
1485
|
+
if not np.isfinite(lam).any() or not lam[0] > 0:
|
|
1486
|
+
continue
|
|
1487
|
+
bold = i in critical
|
|
1488
|
+
ax.plot(
|
|
1489
|
+
strain,
|
|
1490
|
+
lam / lam[0],
|
|
1491
|
+
lw=2.0 if bold else 0.9,
|
|
1492
|
+
color=None if bold else "0.6",
|
|
1493
|
+
label=f"irrep {i + 1}" if bold else None,
|
|
1494
|
+
zorder=3 if bold else 2,
|
|
1495
|
+
)
|
|
1496
|
+
ax.axhline(0.0, color="k", lw=0.8)
|
|
1497
|
+
if b.critical_strain is not None:
|
|
1498
|
+
ax.axvline(-b.critical_strain[axis], color="C3", ls="--", lw=1.0, label="bifurcation")
|
|
1499
|
+
ax.set_xlabel(f"nominal compressive strain {NAMES[axis]}")
|
|
1500
|
+
ax.set_ylabel("lowest eigenvalue / its natural value")
|
|
1501
|
+
ax.set_title("stability of the principal path (irreps in grey)", fontsize=10)
|
|
1502
|
+
ax.grid(alpha=0.3)
|
|
1503
|
+
if ax.get_legend_handles_labels()[0]:
|
|
1504
|
+
ax.legend(fontsize=8, frameon=False)
|
|
1505
|
+
return fig
|
|
1506
|
+
|
|
1507
|
+
|
|
1508
|
+
def _spectra_rows(b, axis: int) -> list[dict]:
|
|
1509
|
+
present = [i for i in range(len(b.irreps)) if np.isfinite(b.spectra[:, i, 0]).any()]
|
|
1510
|
+
return [
|
|
1511
|
+
{
|
|
1512
|
+
"time": float(t),
|
|
1513
|
+
"nominal strain": -float(e[axis]),
|
|
1514
|
+
**{f"irrep {i + 1}": float(row[i, 0]) for i in present},
|
|
1515
|
+
}
|
|
1516
|
+
for t, e, row in zip(b.times, b.strains, b.spectra, strict=True)
|
|
1517
|
+
]
|
|
1518
|
+
|
|
1519
|
+
|
|
1520
|
+
def _response_figure(b, axis: int):
|
|
1521
|
+
from matplotlib.figure import Figure
|
|
1522
|
+
|
|
1523
|
+
fig = Figure(figsize=(5.4, 3.8), layout="constrained")
|
|
1524
|
+
ax = fig.subplots()
|
|
1525
|
+
paths = [("principal path", b.principal)]
|
|
1526
|
+
if b.branch is not None:
|
|
1527
|
+
paths.append(("bifurcated branch", b.branch))
|
|
1528
|
+
for label, result in paths:
|
|
1529
|
+
ax.plot(-result.strain[:, axis], -result.stress[:, axis], lw=1.6, label=label)
|
|
1530
|
+
if b.critical_strain is not None:
|
|
1531
|
+
ax.axvline(-b.critical_strain[axis], color="C3", ls="--", lw=1.0, label="bifurcation")
|
|
1532
|
+
ax.set_xlabel(f"nominal compressive strain {NAMES[axis]}")
|
|
1533
|
+
ax.set_ylabel(f"nominal compressive stress {NAMES[axis]}")
|
|
1534
|
+
ax.grid(alpha=0.3)
|
|
1535
|
+
ax.legend(fontsize=8, frameon=False)
|
|
1536
|
+
return fig
|
|
1537
|
+
|
|
1538
|
+
|
|
1539
|
+
def _branch_figure(b, axis: int, eps: float):
|
|
1540
|
+
from matplotlib.figure import Figure
|
|
1541
|
+
|
|
1542
|
+
fig = Figure(figsize=(5.4, 3.8), layout="constrained")
|
|
1543
|
+
ax = fig.subplots()
|
|
1544
|
+
ax.semilogy(b.branch_times * eps, np.abs(b.amplitudes), lw=1.6, color="C1")
|
|
1545
|
+
if b.critical_strain is not None:
|
|
1546
|
+
ax.axvline(-b.critical_strain[axis], color="C3", ls="--", lw=1.0)
|
|
1547
|
+
ax.set_xlabel(f"nominal compressive strain {NAMES[axis]}")
|
|
1548
|
+
ax.set_ylabel("amplitude of the pattern")
|
|
1549
|
+
ax.set_title("the pattern along the bifurcated branch", fontsize=10)
|
|
1550
|
+
ax.grid(alpha=0.3, which="both")
|
|
1551
|
+
return fig
|
|
1552
|
+
|
|
1553
|
+
|
|
1554
|
+
# -- Bloch waves ------------------------------------------------------------------------------
|
|
1555
|
+
|
|
1556
|
+
BAND_MESHES = (
|
|
1557
|
+
("voxels", "six tetrahedra per voxel of its voxel image"),
|
|
1558
|
+
("conforming", "a conforming mesh of its level set (MMG, matching faces)"),
|
|
1559
|
+
)
|
|
1560
|
+
|
|
1561
|
+
|
|
1562
|
+
def _corners(text: str | None, planar: bool) -> list[str]:
|
|
1563
|
+
"""The corners of the Brillouin zone of a path written ``G X M G R``."""
|
|
1564
|
+
from morphogen.homogenization.bloch import POINTS
|
|
1565
|
+
|
|
1566
|
+
text = text or ("G X M G" if planar else "G X M G R")
|
|
1567
|
+
names = [
|
|
1568
|
+
("G" if c in ("Γ", "g") else c.upper())
|
|
1569
|
+
for c in text.replace(",", " ").replace("-", " ").replace("–", " ").split()
|
|
1570
|
+
]
|
|
1571
|
+
unknown = [c for c in names if c not in POINTS]
|
|
1572
|
+
if unknown or len(names) < 2:
|
|
1573
|
+
raise ValueError(f"path: two corners at least among {', '.join(POINTS)}")
|
|
1574
|
+
return names
|
|
1575
|
+
|
|
1576
|
+
|
|
1577
|
+
@tool(
|
|
1578
|
+
"band_structure",
|
|
1579
|
+
"stability",
|
|
1580
|
+
"Bloch-wave band structure",
|
|
1581
|
+
"The dispersion of the elastic waves of a periodic morphology: the angular frequencies "
|
|
1582
|
+
"of its Bloch waves (finite elements of its primitive cell, its consistent mass) along "
|
|
1583
|
+
"the edges of the irreducible Brillouin zone (Γ–X–M–Γ–R for a cubic cell), in units of "
|
|
1584
|
+
"2π c_T / L (c_T the shear wave speed of the first solid phase, L the edge of the cell "
|
|
1585
|
+
"along x), and its band gaps: the ranges between two bands where no wave propagates "
|
|
1586
|
+
"along the path (complete band gaps when the path holds the extrema of the bands).",
|
|
1587
|
+
[
|
|
1588
|
+
Field("source", "item", label="morphology", required=True),
|
|
1589
|
+
Field("cell", "choice", "unit", choices=CELLS, label="primitive cell"),
|
|
1590
|
+
Field("mesh", "choice", "voxels", choices=BAND_MESHES),
|
|
1591
|
+
Field(
|
|
1592
|
+
"resolution",
|
|
1593
|
+
"int",
|
|
1594
|
+
6,
|
|
1595
|
+
label="voxels per edge",
|
|
1596
|
+
when={"mesh": "voxels"},
|
|
1597
|
+
doc="along the shortest edge of the primitive cell",
|
|
1598
|
+
),
|
|
1599
|
+
Field(
|
|
1600
|
+
"element_size",
|
|
1601
|
+
"float",
|
|
1602
|
+
unit="length",
|
|
1603
|
+
when={"mesh": "conforming"},
|
|
1604
|
+
doc="of the conforming mesh (blank: 1/4 of the shortest edge of the cell)",
|
|
1605
|
+
),
|
|
1606
|
+
Field("order", "choice", "2", choices=ORDERS, label="elements"),
|
|
1607
|
+
Field("materials", "materials", of="source"),
|
|
1608
|
+
Field("densities", "floats", doc="of the phases 0, 1, ... (blank: 1 for every phase)"),
|
|
1609
|
+
Field(
|
|
1610
|
+
"path",
|
|
1611
|
+
"str",
|
|
1612
|
+
doc="corners of the Brillouin zone among G (Γ), X, Y, Z, M, R (blank: G X M G R; "
|
|
1613
|
+
"G X M G in the plane)",
|
|
1614
|
+
),
|
|
1615
|
+
Field("points", "int", 3, doc="wave vectors per segment of the path"),
|
|
1616
|
+
Field("bands", "int", 8),
|
|
1617
|
+
],
|
|
1618
|
+
order=4,
|
|
1619
|
+
menu="Waves",
|
|
1620
|
+
)
|
|
1621
|
+
def band_structure_tool(p: dict, ctx) -> dict:
|
|
1622
|
+
import dataclasses
|
|
1623
|
+
|
|
1624
|
+
from morphogen.domain import Domain, Grid
|
|
1625
|
+
from morphogen.homogenization.bloch import (
|
|
1626
|
+
BandStructure,
|
|
1627
|
+
band_structure,
|
|
1628
|
+
brillouin_path,
|
|
1629
|
+
voxel_tet_mesh,
|
|
1630
|
+
)
|
|
1631
|
+
from morphogen.image import VoxelImage
|
|
1632
|
+
from morphogen.mesh import conforming_mesh
|
|
1633
|
+
|
|
1634
|
+
item = p["source"]
|
|
1635
|
+
_periodic(item)
|
|
1636
|
+
micro = item["micro"]
|
|
1637
|
+
planar = _planar(micro)
|
|
1638
|
+
materials = _materials_of(item, p["materials"])
|
|
1639
|
+
phases = sorted(materials)
|
|
1640
|
+
densities = p["densities"] or [1.0] * (max(phases) + 1)
|
|
1641
|
+
if len(densities) < max(phases) + 1 or any(not r > 0 for r in densities):
|
|
1642
|
+
raise ValueError(f"densities: {max(phases) + 1} positive values, one per phase")
|
|
1643
|
+
materials = {
|
|
1644
|
+
k: m if m.void else dataclasses.replace(m, density=float(densities[k]))
|
|
1645
|
+
for k, m in materials.items()
|
|
1646
|
+
}
|
|
1647
|
+
solid = _solid_phases(materials)
|
|
1648
|
+
corners = _corners(p["path"], planar)
|
|
1649
|
+
points, bands, order = int(p["points"]), int(p["bands"]), int(p["order"] or 2)
|
|
1650
|
+
if not 1 <= points <= 24 or not 1 <= bands <= 40:
|
|
1651
|
+
raise ValueError("points: from 1 to 24 per segment; bands: from 1 to 40")
|
|
1652
|
+
lower, size, origin = _primitive(item, p["cell"] or "unit")
|
|
1653
|
+
edge = float(size[:2].min() if planar else size.min())
|
|
1654
|
+
if p["mesh"] == "conforming":
|
|
1655
|
+
h = float(p["element_size"] or edge / 4)
|
|
1656
|
+
if not 0 < h <= edge:
|
|
1657
|
+
raise ValueError("element size: positive, at most the edge of the cell")
|
|
1658
|
+
ctx.progress(0.03, "conforming mesh (MMG)")
|
|
1659
|
+
body = _CellBody(micro, lower, size, 2 * h if planar else None)
|
|
1660
|
+
meshed = "solid" if solid == [1] else "all"
|
|
1661
|
+
mesh = conforming_mesh(body, size=h, phases=meshed, periodic=True)
|
|
1662
|
+
description = f"a conforming mesh of the level set of {origin} (elements of {h:.3g})"
|
|
1663
|
+
else:
|
|
1664
|
+
n = int(p["resolution"] or 6)
|
|
1665
|
+
if not 2 <= n <= 32:
|
|
1666
|
+
raise ValueError("voxels per edge: from 2 to 32")
|
|
1667
|
+
h = edge / n
|
|
1668
|
+
shape = np.maximum(1, np.rint(size / h)).astype(int)
|
|
1669
|
+
if planar:
|
|
1670
|
+
shape[2] = 1
|
|
1671
|
+
grid = Grid(Domain(size=tuple(size), origin=tuple(lower), periodic=True), tuple(shape))
|
|
1672
|
+
data = np.asarray(micro.voxelize(grid=grid).data)
|
|
1673
|
+
spacing = (h, h, h) if planar else tuple(grid.spacing)
|
|
1674
|
+
mesh = voxel_tet_mesh(
|
|
1675
|
+
VoxelImage(data, spacing=spacing, origin=tuple(lower), periodic=True), solid
|
|
1676
|
+
)
|
|
1677
|
+
description = f"the voxel image of {origin}, {' × '.join(map(str, shape))} voxels"
|
|
1678
|
+
ks, distance, labels = brillouin_path(mesh.size, corners, points)
|
|
1679
|
+
frequencies = []
|
|
1680
|
+
for s in range(len(corners) - 1): # one segment at a time, for the progress
|
|
1681
|
+
ctx.progress(
|
|
1682
|
+
0.05 + 0.85 * s / (len(corners) - 1), f"Bloch waves {corners[s]}–{corners[s + 1]}"
|
|
1683
|
+
)
|
|
1684
|
+
chunk = ks[(0 if s == 0 else 1 + s * points) : 1 + (s + 1) * points]
|
|
1685
|
+
try:
|
|
1686
|
+
bands_of = band_structure(mesh, materials, chunk, bands=bands, order=order)
|
|
1687
|
+
except ValueError as exc:
|
|
1688
|
+
raise _unresolved(exc, p["mesh"]) from None
|
|
1689
|
+
frequencies.append(bands_of.frequencies)
|
|
1690
|
+
result = BandStructure(ks, distance, np.vstack(frequencies), labels)
|
|
1691
|
+
reference = materials[solid[0]]
|
|
1692
|
+
speed = float(np.sqrt(reference.young / (2 * (1 + reference.poisson)) / reference.density))
|
|
1693
|
+
length = float(size[0])
|
|
1694
|
+
scale = length / (2 * np.pi * speed)
|
|
1695
|
+
ctx.progress(0.92, "figures")
|
|
1696
|
+
from matplotlib.figure import Figure
|
|
1697
|
+
|
|
1698
|
+
fig = Figure(figsize=(5.6, 4.4), layout="constrained")
|
|
1699
|
+
ax = fig.subplots()
|
|
1700
|
+
result.plot(ax, scale=scale, ylabel="ω L / 2π c_T")
|
|
1701
|
+
ax.set_title(f"band structure (c_T of phase {solid[0]})", fontsize=10)
|
|
1702
|
+
ctx.figure(fig, "bands", "band structure")
|
|
1703
|
+
gaps = result.gaps()
|
|
1704
|
+
rows = [
|
|
1705
|
+
{
|
|
1706
|
+
"bands": f"{n_} – {n_ + 1}",
|
|
1707
|
+
"low": low * scale,
|
|
1708
|
+
"high": high * scale,
|
|
1709
|
+
"width": (high - low) * scale,
|
|
1710
|
+
"relative width": 2 * (high - low) / (high + low),
|
|
1711
|
+
"low ω": low,
|
|
1712
|
+
"high ω": high,
|
|
1713
|
+
}
|
|
1714
|
+
for n_, low, high in gaps
|
|
1715
|
+
]
|
|
1716
|
+
ctx.table(rows, "gaps", "band gaps (ω L / 2π c_T)")
|
|
1717
|
+
names = {round(float(d), 12): name for d, name in labels}
|
|
1718
|
+
ctx.table(
|
|
1719
|
+
[
|
|
1720
|
+
{
|
|
1721
|
+
"corner": names.get(round(float(d), 12), ""),
|
|
1722
|
+
"distance": float(d),
|
|
1723
|
+
**{f"k{'xyz'[a]}": float(k[a]) for a in range(3)},
|
|
1724
|
+
**{f"band {j + 1}": float(w) * scale for j, w in enumerate(f)},
|
|
1725
|
+
}
|
|
1726
|
+
for d, k, f in zip(distance, ks, result.frequencies, strict=True)
|
|
1727
|
+
],
|
|
1728
|
+
"frequencies",
|
|
1729
|
+
"frequencies along the path (ω L / 2π c_T)",
|
|
1730
|
+
)
|
|
1731
|
+
values: dict = {
|
|
1732
|
+
"mesh": "conforming" if p["mesh"] == "conforming" else "voxels",
|
|
1733
|
+
"elements": mesh.n_elements,
|
|
1734
|
+
"wave vectors": len(ks),
|
|
1735
|
+
"bands": bands,
|
|
1736
|
+
"band gaps": len(gaps),
|
|
1737
|
+
"c_T": speed,
|
|
1738
|
+
"L": length,
|
|
1739
|
+
}
|
|
1740
|
+
text = [
|
|
1741
|
+
f"{item['title']}: {description}, {mesh.n_elements} elements of order {order}; "
|
|
1742
|
+
f"{len(ks)} wave vectors along {'–'.join('Γ' if c == 'G' else c for c in corners)}, "
|
|
1743
|
+
f"{bands} bands."
|
|
1744
|
+
]
|
|
1745
|
+
if gaps:
|
|
1746
|
+
widest = max(rows, key=lambda r: r["relative width"])
|
|
1747
|
+
values["widest gap: bands"] = widest["bands"]
|
|
1748
|
+
values["widest gap: relative width"] = widest["relative width"]
|
|
1749
|
+
text.append(
|
|
1750
|
+
f"{len(gaps)} band gap{'s' if len(gaps) > 1 else ''} along the path; the widest "
|
|
1751
|
+
f"between the bands {widest['bands']}, from {widest['low']:.4g} to "
|
|
1752
|
+
f"{widest['high']:.4g} (relative width {widest['relative width']:.3g})."
|
|
1753
|
+
)
|
|
1754
|
+
else:
|
|
1755
|
+
text.append("No band gap along the path among these bands.")
|
|
1756
|
+
return {"values": values, "text": " ".join(text)}
|