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
morphogen/viz/figures.py
ADDED
|
@@ -0,0 +1,707 @@
|
|
|
1
|
+
"""Figures of microstructures, automata, optimizations, frames of beams and textures
|
|
2
|
+
(matplotlib, optional extra ``[plot]``). Figures are built without pyplot
|
|
3
|
+
(``matplotlib.figure.Figure``): they work headless and can be saved with
|
|
4
|
+
``fig.savefig(path)``."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from morphogen.image import VoxelImage
|
|
11
|
+
from morphogen.models.base import Microstructure
|
|
12
|
+
from morphogen.viz.png import PALETTE, slice_of
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _figure(width: float = 6.0, height: float = 4.0):
|
|
16
|
+
try:
|
|
17
|
+
from matplotlib.figure import Figure
|
|
18
|
+
except ImportError as exc: # pragma: no cover - depends on the environment
|
|
19
|
+
raise ImportError("figures need matplotlib: pip install 'morphogen[plot]'") from exc
|
|
20
|
+
return Figure(figsize=(width, height), dpi=120, layout="constrained")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def as_array(source, shape=None, *, labels: bool = False) -> np.ndarray:
|
|
24
|
+
"""3D array of a microstructure (voxelized on ``shape`` or its own lattice), of a
|
|
25
|
+
voxel image or of an array; ``labels`` takes the cell labels of the structure."""
|
|
26
|
+
if isinstance(source, Microstructure):
|
|
27
|
+
if labels:
|
|
28
|
+
if not source.has_labels:
|
|
29
|
+
raise ValueError("this microstructure has no cell labels")
|
|
30
|
+
img = (
|
|
31
|
+
source.labels()
|
|
32
|
+
if shape is None and hasattr(source, "shape")
|
|
33
|
+
else source.labels(shape=shape or 64)
|
|
34
|
+
)
|
|
35
|
+
return img.data
|
|
36
|
+
if shape is None and hasattr(source, "lattice"):
|
|
37
|
+
return source.voxelize().data
|
|
38
|
+
return source.voxelize(shape=shape or 64).data
|
|
39
|
+
if isinstance(source, VoxelImage):
|
|
40
|
+
return source.data
|
|
41
|
+
a = np.asarray(source)
|
|
42
|
+
return a[:, :, None] if a.ndim == 2 else a
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _show(ax, plane, kind: str, title: str = ""):
|
|
46
|
+
from morphogen.viz.png import to_rgb
|
|
47
|
+
|
|
48
|
+
ax.imshow(to_rgb(plane, kind), interpolation="nearest")
|
|
49
|
+
ax.set_xticks([])
|
|
50
|
+
ax.set_yticks([])
|
|
51
|
+
if title:
|
|
52
|
+
ax.set_title(title, fontsize=9)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _kind(data: np.ndarray, labels: bool) -> str:
|
|
56
|
+
if labels:
|
|
57
|
+
return "labels"
|
|
58
|
+
return "phase" if data.dtype.kind in "biu" and data.max(initial=0) < 8 else "field"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def slices_figure(source, *, shape=None, labels: bool = False, title: str | None = None):
|
|
62
|
+
"""Middle sections normal to x, y and z (one image for planar structures)."""
|
|
63
|
+
data = as_array(source, shape, labels=labels)
|
|
64
|
+
kind = _kind(data, labels)
|
|
65
|
+
planar = data.shape[2] == 1
|
|
66
|
+
fig = _figure(3.2 if planar else 9.0, 3.4)
|
|
67
|
+
if planar:
|
|
68
|
+
ax = fig.add_subplot(1, 1, 1)
|
|
69
|
+
_show(ax, slice_of(data, 2), kind, "x-y")
|
|
70
|
+
else:
|
|
71
|
+
for i, (axis, name) in enumerate(((0, "y-z"), (1, "x-z"), (2, "x-y"))):
|
|
72
|
+
_show(fig.add_subplot(1, 3, i + 1), slice_of(data, axis), kind, f"{name} section")
|
|
73
|
+
if title:
|
|
74
|
+
fig.suptitle(title, fontsize=10)
|
|
75
|
+
return fig
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def field_figure(data, *, cmap="viridis", clim=None, title: str | None = None, label: str = ""):
|
|
79
|
+
"""Middle sections normal to x, y and z of a field on a voxel grid (one for planar
|
|
80
|
+
grids), on one colour range with a colour bar titled ``label``."""
|
|
81
|
+
values = np.asarray(data.data if isinstance(data, VoxelImage) else data, dtype=float)
|
|
82
|
+
values = values[:, :, None] if values.ndim == 2 else values
|
|
83
|
+
from morphogen.viz.video import _range
|
|
84
|
+
|
|
85
|
+
lo, hi = clim or _range(values, None, None, cmap)
|
|
86
|
+
planar = values.shape[2] == 1
|
|
87
|
+
sections = ((2, "x-y"),) if planar else ((0, "y-z"), (1, "x-z"), (2, "x-y"))
|
|
88
|
+
fig = _figure(4.0 if planar else 10.0, 3.4)
|
|
89
|
+
axes = []
|
|
90
|
+
for i, (axis, name) in enumerate(sections):
|
|
91
|
+
ax = fig.add_subplot(1, len(sections), i + 1)
|
|
92
|
+
shown = ax.imshow(
|
|
93
|
+
slice_of(values, axis), cmap=cmap, vmin=lo, vmax=hi, interpolation="nearest"
|
|
94
|
+
)
|
|
95
|
+
ax.set_xticks([])
|
|
96
|
+
ax.set_yticks([])
|
|
97
|
+
ax.set_title(f"{name} section", fontsize=9)
|
|
98
|
+
axes.append(ax)
|
|
99
|
+
bar = fig.colorbar(shown, ax=axes, shrink=0.85)
|
|
100
|
+
if label:
|
|
101
|
+
bar.set_label(label, fontsize=9)
|
|
102
|
+
if title:
|
|
103
|
+
fig.suptitle(title, fontsize=10)
|
|
104
|
+
return fig
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def mesh_figure(mesh, *, axis: int = 2, position: float | None = None, values=None,
|
|
108
|
+
cmap="viridis", label: str = "", title: str | None = None): # fmt: skip
|
|
109
|
+
"""The cut of a tetrahedral mesh by a plane normal to ``axis`` (through the middle of
|
|
110
|
+
its box, or at the coordinate ``position``): the polygons of the elements that the
|
|
111
|
+
plane crosses, in the colours of their phases or coloured by ``values`` (one per
|
|
112
|
+
element, with a colour bar titled ``label``), their edges drawn — the elements of a
|
|
113
|
+
conforming mesh following the interfaces. See :func:`mesh_section` for the polygons."""
|
|
114
|
+
from matplotlib.collections import PolyCollection
|
|
115
|
+
|
|
116
|
+
polygons, elements = mesh_section(mesh, axis, position)
|
|
117
|
+
lower, upper = np.asarray(mesh.nodes).min(axis=0), np.asarray(mesh.nodes).max(axis=0)
|
|
118
|
+
u, v = [a for a in range(3) if a != axis]
|
|
119
|
+
width, height = upper[u] - lower[u], upper[v] - lower[v]
|
|
120
|
+
fig = _figure(4.6 * width / max(width, height) + (0.9 if values is not None else 0.0),
|
|
121
|
+
4.6 * height / max(width, height) + 0.4) # fmt: skip
|
|
122
|
+
ax = fig.add_subplot(1, 1, 1)
|
|
123
|
+
if values is None:
|
|
124
|
+
phase = np.asarray(mesh.phase)[elements]
|
|
125
|
+
colours = PALETTE[np.minimum(phase, len(PALETTE) - 1)] / 255.0
|
|
126
|
+
cut = PolyCollection(polygons, facecolors=colours, edgecolors="0.15", linewidths=0.25)
|
|
127
|
+
else:
|
|
128
|
+
cut = PolyCollection(polygons, array=np.asarray(values, dtype=float)[elements], cmap=cmap,
|
|
129
|
+
edgecolors="0.15", linewidths=0.25) # fmt: skip
|
|
130
|
+
bar = fig.colorbar(cut, ax=ax, shrink=0.85)
|
|
131
|
+
if label:
|
|
132
|
+
bar.set_label(label, fontsize=9)
|
|
133
|
+
ax.add_collection(cut)
|
|
134
|
+
ax.set_xlim(lower[u], upper[u])
|
|
135
|
+
ax.set_ylim(lower[v], upper[v])
|
|
136
|
+
ax.set_aspect("equal")
|
|
137
|
+
ax.set_xticks([])
|
|
138
|
+
ax.set_yticks([])
|
|
139
|
+
names = "xyz"
|
|
140
|
+
ax.set_title(title or f"{names[u]}-{names[v]} section of the mesh", fontsize=9)
|
|
141
|
+
return fig
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def mesh_section(mesh, axis: int = 2, position: float | None = None):
|
|
145
|
+
"""The cut of the elements of a tetrahedral mesh by the plane normal to ``axis`` at
|
|
146
|
+
the coordinate ``position`` (the middle of its box by default): the polygons (3 or 4
|
|
147
|
+
points each, in the two other coordinates, in order around them) and the indices of
|
|
148
|
+
their elements. Their areas sum to the section of the mesh: a face that lies in the
|
|
149
|
+
plane is the cut of the element below it."""
|
|
150
|
+
if axis not in (0, 1, 2):
|
|
151
|
+
raise ValueError(f"mesh_section: axis 0, 1 or 2, got {axis!r}")
|
|
152
|
+
nodes = np.asarray(mesh.nodes, dtype=float)
|
|
153
|
+
corners = np.asarray(mesh.elements)[:, :4]
|
|
154
|
+
along = nodes[:, axis]
|
|
155
|
+
z = 0.5 * (along.min() + along.max()) if position is None else float(position)
|
|
156
|
+
d = along[corners] - z
|
|
157
|
+
# the nodes on the plane count as above it: a face in the plane is cut once
|
|
158
|
+
crossed = np.flatnonzero((d.min(axis=1) < 0.0) & (d.max(axis=1) >= 0.0))
|
|
159
|
+
plane = [a for a in range(3) if a != axis]
|
|
160
|
+
tiny = 1e-12 * float(np.prod(np.ptp(nodes[:, plane], axis=0)))
|
|
161
|
+
polygons, kept = [], []
|
|
162
|
+
for e in crossed:
|
|
163
|
+
points = []
|
|
164
|
+
for a, b in ((0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)):
|
|
165
|
+
da, db = d[e, a], d[e, b]
|
|
166
|
+
if (da < 0.0) != (db < 0.0): # the edge crosses the plane
|
|
167
|
+
t = da / (da - db)
|
|
168
|
+
pa, pb = nodes[corners[e, a]], nodes[corners[e, b]]
|
|
169
|
+
points.append((pa + t * (pb - pa))[plane])
|
|
170
|
+
points = np.array(points)
|
|
171
|
+
centre = points.mean(axis=0)
|
|
172
|
+
order = np.argsort(np.arctan2(points[:, 1] - centre[1], points[:, 0] - centre[0]))
|
|
173
|
+
points = points[order]
|
|
174
|
+
x, y = points[:, 0], points[:, 1]
|
|
175
|
+
if 0.5 * abs(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1))) > tiny:
|
|
176
|
+
polygons.append(points) # (an element that touches the plane has no cut)
|
|
177
|
+
kept.append(e)
|
|
178
|
+
return polygons, np.array(kept, dtype=np.int64)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def path_figure(result, *, title: str | None = None):
|
|
182
|
+
"""Curves of a loading path (:class:`~morphogen.homogenization.paths.PathResult`): the
|
|
183
|
+
macroscopic stresses that vary against the strain component that varies most (in
|
|
184
|
+
finite strains, the true stresses against the logarithmic strains), and the mean
|
|
185
|
+
cumulated plastic strain against time when the materials yield."""
|
|
186
|
+
from morphogen.homogenization.elements import VOIGT_NAMES
|
|
187
|
+
|
|
188
|
+
true = result.finite and result.log_strain is not None and result.cauchy is not None
|
|
189
|
+
strain = np.asarray(result.log_strain if true else result.strain, dtype=float)
|
|
190
|
+
stress = np.asarray(result.cauchy if true else result.stress, dtype=float)
|
|
191
|
+
e_name, s_name = ("LE", "TS") if true else ("E", "S")
|
|
192
|
+
i = int(np.argmax(np.ptp(strain, axis=0)))
|
|
193
|
+
spans = np.ptp(stress, axis=0)
|
|
194
|
+
shown = [j for j in range(6) if spans[j] > 0.01 * spans.max()] or [i]
|
|
195
|
+
plastic = np.asarray(result.plastic, dtype=float)
|
|
196
|
+
yielding = bool(plastic.size and plastic.max() > 0.0)
|
|
197
|
+
fig = _figure(9.0 if yielding else 5.0, 3.6)
|
|
198
|
+
ax = fig.add_subplot(1, 2 if yielding else 1, 1)
|
|
199
|
+
for j in shown:
|
|
200
|
+
ax.plot(strain[:, i], stress[:, j], marker=".", ms=4, lw=1.4, label=s_name + VOIGT_NAMES[j])
|
|
201
|
+
ax.set_xlabel(e_name + VOIGT_NAMES[i])
|
|
202
|
+
ax.set_ylabel("Cauchy stress" if true else "stress")
|
|
203
|
+
ax.grid(alpha=0.3)
|
|
204
|
+
ax.legend(fontsize=8)
|
|
205
|
+
if yielding:
|
|
206
|
+
ax2 = fig.add_subplot(1, 2, 2)
|
|
207
|
+
ax2.plot(result.times, plastic, marker=".", ms=4, lw=1.4, color="#d6604d")
|
|
208
|
+
ax2.set_xlabel("time")
|
|
209
|
+
ax2.set_ylabel("mean cumulated plastic strain p")
|
|
210
|
+
ax2.grid(alpha=0.3)
|
|
211
|
+
if title:
|
|
212
|
+
fig.suptitle(title, fontsize=10)
|
|
213
|
+
return fig
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def tiled_figure(source, *, tiles: int = 3, shape=None, title: str | None = None, axis=None):
|
|
217
|
+
"""Periodic tiling (``tiles`` x ``tiles``) of the middle sections of a cell: those
|
|
218
|
+
normal to x, y and z (the x-y section alone for a planar structure), or the one
|
|
219
|
+
normal to ``axis`` (0, 1 or 2)."""
|
|
220
|
+
data = as_array(source, shape)
|
|
221
|
+
kind = _kind(data, False)
|
|
222
|
+
if axis is None:
|
|
223
|
+
axes = (2,) if data.shape[2] == 1 else (0, 1, 2)
|
|
224
|
+
elif axis in (0, 1, 2):
|
|
225
|
+
axes = (int(axis),)
|
|
226
|
+
else:
|
|
227
|
+
raise ValueError("axis: 0, 1 or 2 (the normal of the section)")
|
|
228
|
+
fig = _figure(4.0 * len(axes), 4.0)
|
|
229
|
+
names = ("y-z", "x-z", "x-y")
|
|
230
|
+
for i, a in enumerate(axes):
|
|
231
|
+
plane = np.tile(slice_of(data, a), (tiles, tiles))
|
|
232
|
+
_show(fig.add_subplot(1, len(axes), i + 1), plane, kind,
|
|
233
|
+
f"{names[a]} section" if len(axes) > 1 else "") # fmt: skip
|
|
234
|
+
if title:
|
|
235
|
+
fig.suptitle(title, fontsize=10)
|
|
236
|
+
return fig
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def surface_figure(source, *, shape=None, phase: int = 1, title: str | None = None):
|
|
240
|
+
"""3D view of the boundary of a phase (marching cubes with scikit-image, voxel faces
|
|
241
|
+
otherwise)."""
|
|
242
|
+
data = as_array(source, shape)
|
|
243
|
+
if data.shape[2] == 1:
|
|
244
|
+
raise ValueError("planar structures: use slices_figure")
|
|
245
|
+
fig = _figure(5.0, 5.0)
|
|
246
|
+
ax = fig.add_subplot(1, 1, 1, projection="3d")
|
|
247
|
+
mask = (data == phase).astype(np.float32)
|
|
248
|
+
try:
|
|
249
|
+
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
|
|
250
|
+
from skimage.measure import marching_cubes
|
|
251
|
+
|
|
252
|
+
padded = np.pad(mask, 1)
|
|
253
|
+
verts, faces, _, _ = marching_cubes(padded, 0.5)
|
|
254
|
+
mesh = Poly3DCollection(verts[faces] - 1, linewidths=0.0, alpha=1.0)
|
|
255
|
+
shade = 0.45 + 0.55 * np.abs(_normals(verts, faces)[:, 2])
|
|
256
|
+
mesh.set_facecolor(np.column_stack([0.12 * shade, 0.31 * shade, 0.47 * shade]))
|
|
257
|
+
ax.add_collection3d(mesh)
|
|
258
|
+
for setter, n in zip((ax.set_xlim, ax.set_ylim, ax.set_zlim), data.shape, strict=True):
|
|
259
|
+
setter(0, n)
|
|
260
|
+
except ImportError:
|
|
261
|
+
step = max(1, max(data.shape) // 48)
|
|
262
|
+
ax.voxels(mask[::step, ::step, ::step] > 0, facecolors="#1f4e79", edgecolor="none")
|
|
263
|
+
ax.set_box_aspect(data.shape)
|
|
264
|
+
ax.set_axis_off()
|
|
265
|
+
if title:
|
|
266
|
+
ax.set_title(title, fontsize=10)
|
|
267
|
+
return fig
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _normals(verts, faces) -> np.ndarray:
|
|
271
|
+
a, b, c = verts[faces[:, 0]], verts[faces[:, 1]], verts[faces[:, 2]]
|
|
272
|
+
n = np.cross(b - a, c - a)
|
|
273
|
+
return n / np.maximum(np.linalg.norm(n, axis=1, keepdims=True), 1e-12)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def history_figure(history: dict, keys=None, *, title: str | None = None):
|
|
277
|
+
"""Curves of a history (automaton, optimization...) against its first column."""
|
|
278
|
+
columns = list(history)
|
|
279
|
+
x_key = columns[0]
|
|
280
|
+
keys = [k for k in (keys or columns[1:]) if k in history and k != x_key]
|
|
281
|
+
fig = _figure(6.0, 1.8 * max(1, len(keys)))
|
|
282
|
+
x = np.asarray(history[x_key], dtype=float)
|
|
283
|
+
for i, key in enumerate(keys):
|
|
284
|
+
ax = fig.add_subplot(len(keys), 1, i + 1)
|
|
285
|
+
ax.plot(x, np.asarray(history[key], dtype=float), color="#1f4e79", lw=1.5)
|
|
286
|
+
ax.set_ylabel(key, fontsize=8)
|
|
287
|
+
ax.tick_params(labelsize=7)
|
|
288
|
+
ax.grid(alpha=0.3)
|
|
289
|
+
if i == len(keys) - 1:
|
|
290
|
+
ax.set_xlabel(x_key, fontsize=8)
|
|
291
|
+
if title:
|
|
292
|
+
fig.suptitle(title, fontsize=10)
|
|
293
|
+
return fig
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def kinetics_figure(micro, domain=None):
|
|
297
|
+
"""Transformed fraction against time of a nucleation-growth structure, with the
|
|
298
|
+
Avrami law."""
|
|
299
|
+
k = micro.attributes.get("kinetics")
|
|
300
|
+
if k is None:
|
|
301
|
+
raise ValueError("this structure has no transformation kinetics")
|
|
302
|
+
fig = _figure(5.0, 3.2)
|
|
303
|
+
ax = fig.add_subplot(1, 1, 1)
|
|
304
|
+
t = np.asarray(k["time"])
|
|
305
|
+
ax.plot(t, k["transformed"], "o", ms=3, color="#1f4e79", label="automaton")
|
|
306
|
+
model = micro.model
|
|
307
|
+
if model is not None and hasattr(model, "transformed_fraction"):
|
|
308
|
+
fine = np.linspace(0, t.max(), 200)
|
|
309
|
+
ax.plot(
|
|
310
|
+
fine, model.transformed_fraction(fine, micro.domain), color="#d6604d", label="Avrami"
|
|
311
|
+
)
|
|
312
|
+
ax.set_xlabel("time")
|
|
313
|
+
ax.set_ylabel("transformed fraction")
|
|
314
|
+
ax.grid(alpha=0.3)
|
|
315
|
+
ax.legend(fontsize=8)
|
|
316
|
+
return fig
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def softening_figure(studies, *, title: str | None = None):
|
|
320
|
+
"""Replicas of networks of non-identical beams
|
|
321
|
+
(:class:`~morphogen.homogenization.networks.Softening`, one or a list, a mode each):
|
|
322
|
+
the mean ``E / E_0`` of the replicas against the coefficient of variation with its
|
|
323
|
+
standard errors (filled: corrected by the control variate; open: the plain mean) and
|
|
324
|
+
the second-order mean ``1 - s CV²``; the scatter ``σ_E² / E_0²`` of the replicas
|
|
325
|
+
against ``v CV²`` (its standard error for normal draws) and the diagonal."""
|
|
326
|
+
from morphogen.homogenization.networks import Softening
|
|
327
|
+
|
|
328
|
+
studies = [studies] if isinstance(studies, Softening) else list(studies)
|
|
329
|
+
fig = _figure(9.6, 3.9)
|
|
330
|
+
left, right = fig.subplots(1, 2)
|
|
331
|
+
top = 0.0
|
|
332
|
+
for k, study in enumerate(studies):
|
|
333
|
+
colour = f"C{k % 10}"
|
|
334
|
+
rows = study.rows()
|
|
335
|
+
s, v = study.coefficients["mean"], study.coefficients["variance"]
|
|
336
|
+
cv = np.linspace(0.0, 1.05 * float(study.cv.max()), 100)
|
|
337
|
+
left.plot(cv, 1.0 - s * cv**2, color=colour, lw=1.4,
|
|
338
|
+
label=f"{study.mode}: 1 − s CV², s = {s:.3g}") # fmt: skip
|
|
339
|
+
left.errorbar(study.cv, study.corrected, yerr=study.error, fmt="o", ms=5, color=colour,
|
|
340
|
+
capsize=3) # fmt: skip
|
|
341
|
+
left.errorbar(study.cv, study.mean, yerr=[r["mean_error"] for r in rows], fmt="o", ms=7,
|
|
342
|
+
mfc="none", color=colour, capsize=3, alpha=0.7) # fmt: skip
|
|
343
|
+
x, y = study.predicted_scatter(), study.scatter()
|
|
344
|
+
errors = np.array([r["scatter_error"] for r in rows])
|
|
345
|
+
right.errorbar(x, y, yerr=errors, fmt="o", ms=5, color=colour, capsize=3,
|
|
346
|
+
label=f"{study.mode}: v = {v:.3g}") # fmt: skip
|
|
347
|
+
top = max(top, float(x.max()), float((y + errors).max()))
|
|
348
|
+
for fill, name in (("0.35", "replicas, control variate"), ("none", "replicas, plain mean")):
|
|
349
|
+
left.plot([], [], "o", color="0.35", mfc=fill, label=name)
|
|
350
|
+
left.set_xlabel("coefficient of variation CV")
|
|
351
|
+
left.set_ylabel("⟨E⟩ / E₀")
|
|
352
|
+
left.set_xlim(left=0.0)
|
|
353
|
+
left.set_title("mean Young's modulus", fontsize=9)
|
|
354
|
+
top = 1.08 * top if top > 0 else 1.0
|
|
355
|
+
right.plot([0.0, top], [0.0, top], color="0.4", lw=1.0, ls="--", label="σ_E²/E₀² = v CV²")
|
|
356
|
+
right.set_xlim(0.0, top)
|
|
357
|
+
right.set_ylim(0.0, top)
|
|
358
|
+
right.set_xlabel("v CV² (second order)")
|
|
359
|
+
right.set_ylabel("σ_E² / E₀² (replicas)")
|
|
360
|
+
right.set_title("scatter of the Young's modulus", fontsize=9)
|
|
361
|
+
for ax in (left, right):
|
|
362
|
+
ax.grid(alpha=0.3)
|
|
363
|
+
ax.legend(fontsize=7, frameon=False)
|
|
364
|
+
if title:
|
|
365
|
+
fig.suptitle(title, fontsize=10)
|
|
366
|
+
return fig
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
#: The beams of a frame drawn as vectors at most in its vector files (.svg, .pdf); those
|
|
370
|
+
#: of larger frames are rasterized there (the axes, the colour bar and the texts not)
|
|
371
|
+
VECTOR_BEAMS = 2000
|
|
372
|
+
#: The scales of the values of the beams of :func:`frame_figure`
|
|
373
|
+
FRAME_SCALES = ("linear", "symmetric", "log")
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _cell_segments(frame) -> tuple[np.ndarray, np.ndarray]:
|
|
377
|
+
"""The beams of a periodic frame as segments in its cell: each from its first node
|
|
378
|
+
(brought into the cell), cut where it leaves the cell and its pieces brought back by
|
|
379
|
+
the periods (pieces x 2 x dimension), with the beam of each piece."""
|
|
380
|
+
lattice = np.asarray(frame.lattice, dtype=float)
|
|
381
|
+
inverse = np.linalg.inv(lattice)
|
|
382
|
+
reduced = np.asarray(frame.nodes, dtype=float)[frame.beams[:, 0]] @ inverse.T
|
|
383
|
+
reduced -= np.floor(reduced)
|
|
384
|
+
step = frame.vectors() @ inverse.T
|
|
385
|
+
end = reduced + step
|
|
386
|
+
inside = np.all((end >= 0.0) & (end <= 1.0), axis=1)
|
|
387
|
+
pieces = [np.stack([reduced[inside], end[inside]], axis=1)]
|
|
388
|
+
owners = [np.flatnonzero(inside)]
|
|
389
|
+
for k in np.flatnonzero(~inside):
|
|
390
|
+
a, b = reduced[k], end[k]
|
|
391
|
+
cuts = [0.0, 1.0]
|
|
392
|
+
for c in range(len(a)):
|
|
393
|
+
lo, hi = sorted((a[c], b[c]))
|
|
394
|
+
cuts += [(n - a[c]) / (b[c] - a[c]) for n in range(int(np.floor(lo)) + 1,
|
|
395
|
+
int(np.ceil(hi)))] # fmt: skip
|
|
396
|
+
points = a + np.unique(cuts)[:, None] * (b - a)
|
|
397
|
+
shift = np.floor(0.5 * (points[1:] + points[:-1]))
|
|
398
|
+
pieces.append(np.stack([points[:-1] - shift, points[1:] - shift], axis=1))
|
|
399
|
+
owners.append(np.full(len(shift), k))
|
|
400
|
+
return np.concatenate(pieces) @ lattice.T, np.concatenate(owners)
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def frame_figure(frame, values=None, *, scale: str = "linear", label: str = "",
|
|
404
|
+
title: str | None = None): # fmt: skip
|
|
405
|
+
"""The beams of a periodic frame as segments in its cell (a
|
|
406
|
+
:class:`~morphogen.homogenization.frames.Frame` in its plane, a
|
|
407
|
+
:class:`~morphogen.homogenization.frames.SpaceFrame` in an orthographic 3D view),
|
|
408
|
+
each cut where it leaves the cell and its pieces brought back by the periods, with the
|
|
409
|
+
outline of the cell; coloured by one value per beam (``values``, the colour bar
|
|
410
|
+
titled ``label``; none: the beams alone), the strongest drawn widest and on top, on a
|
|
411
|
+
``scale``: ``linear`` (from zero), ``symmetric`` (about zero, as the axial forces of
|
|
412
|
+
:func:`~morphogen.homogenization.networks.beam_forces`: tension red, compression blue)
|
|
413
|
+
up to the 99th percentile of their magnitudes, or ``log`` (three decades below the
|
|
414
|
+
largest, as the energies of the beams). The beams of frames of more than
|
|
415
|
+
:data:`VECTOR_BEAMS` pieces are rasterized in the vector files."""
|
|
416
|
+
from matplotlib import colormaps
|
|
417
|
+
from matplotlib.colors import LogNorm, Normalize
|
|
418
|
+
|
|
419
|
+
if scale not in FRAME_SCALES:
|
|
420
|
+
raise ValueError(f"scale: one of {FRAME_SCALES}")
|
|
421
|
+
segments, owners = _cell_segments(frame)
|
|
422
|
+
dim = segments.shape[2]
|
|
423
|
+
if values is None:
|
|
424
|
+
colours, widths, norm, cmap = "0.2", np.full(len(owners), 0.7), None, None
|
|
425
|
+
order = np.arange(len(owners))
|
|
426
|
+
else:
|
|
427
|
+
v = np.asarray(values, dtype=float).ravel()
|
|
428
|
+
if v.shape != (len(frame.beams),) or not np.all(np.isfinite(v)):
|
|
429
|
+
raise ValueError("values: one finite value per beam")
|
|
430
|
+
if scale == "log":
|
|
431
|
+
top = float(v.max()) if np.any(v > 0) else 1.0
|
|
432
|
+
norm, cmap = LogNorm(1e-3 * top, top), colormaps["magma_r"]
|
|
433
|
+
v = np.clip(v, 1e-3 * top, top)
|
|
434
|
+
t = np.log10(v / top) / 3.0 + 1.0
|
|
435
|
+
else:
|
|
436
|
+
top = float(np.percentile(np.abs(v), 99)) or float(np.abs(v).max()) or 1.0
|
|
437
|
+
symmetric = scale == "symmetric"
|
|
438
|
+
norm = Normalize(-top if symmetric else min(0.0, float(v.min())), top)
|
|
439
|
+
cmap = colormaps["RdBu_r" if symmetric else "magma_r"]
|
|
440
|
+
t = np.minimum(np.abs(v) / top, 1.0)
|
|
441
|
+
t, values = t[owners], v[owners]
|
|
442
|
+
order = np.argsort(t, kind="stable")
|
|
443
|
+
colours, widths = None, 0.3 + 1.9 * t
|
|
444
|
+
fig = _figure(5.8 if values is not None else 5.0, 5.0)
|
|
445
|
+
corners = np.array(list(np.ndindex(*(2,) * dim)), dtype=float)
|
|
446
|
+
edges = [(i, j) for i in range(len(corners)) for j in range(i + 1, len(corners))
|
|
447
|
+
if np.abs(corners[i] - corners[j]).sum() == 1] # fmt: skip
|
|
448
|
+
outline = (corners @ np.asarray(frame.lattice, dtype=float).T)[np.array(edges)]
|
|
449
|
+
if dim == 3:
|
|
450
|
+
from mpl_toolkits.mplot3d.art3d import Line3DCollection as Lines
|
|
451
|
+
|
|
452
|
+
ax = fig.add_subplot(projection="3d")
|
|
453
|
+
ax.set_proj_type("ortho")
|
|
454
|
+
add = ax.add_collection3d
|
|
455
|
+
else:
|
|
456
|
+
from matplotlib.collections import LineCollection as Lines
|
|
457
|
+
|
|
458
|
+
ax = fig.add_subplot()
|
|
459
|
+
add = ax.add_collection
|
|
460
|
+
add(Lines(outline, colors="0.6", linewidths=0.6))
|
|
461
|
+
beams = Lines(segments[order], linewidths=widths[order])
|
|
462
|
+
if values is None:
|
|
463
|
+
beams.set_color(colours)
|
|
464
|
+
else:
|
|
465
|
+
beams.set_array(values[order])
|
|
466
|
+
beams.set_cmap(cmap)
|
|
467
|
+
beams.set_norm(norm)
|
|
468
|
+
beams.set_rasterized(len(owners) > VECTOR_BEAMS)
|
|
469
|
+
add(beams)
|
|
470
|
+
lo = np.minimum(segments.reshape(-1, dim).min(axis=0), outline.reshape(-1, dim).min(axis=0))
|
|
471
|
+
hi = np.maximum(segments.reshape(-1, dim).max(axis=0), outline.reshape(-1, dim).max(axis=0))
|
|
472
|
+
ax.set_xlim(lo[0], hi[0])
|
|
473
|
+
ax.set_ylim(lo[1], hi[1])
|
|
474
|
+
if dim == 3:
|
|
475
|
+
ax.set_zlim(lo[2], hi[2])
|
|
476
|
+
ax.set_box_aspect(tuple(np.maximum(hi - lo, 1e-9)))
|
|
477
|
+
else:
|
|
478
|
+
ax.set_aspect("equal")
|
|
479
|
+
ax.set_axis_off()
|
|
480
|
+
if values is not None:
|
|
481
|
+
fig.colorbar(beams, ax=ax, shrink=0.75, label=label)
|
|
482
|
+
if title:
|
|
483
|
+
ax.set_title(title, fontsize=10)
|
|
484
|
+
return fig
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
# -- textures ------------------------------------------------------------------------------
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _indices_name(indices, plane: bool) -> str:
|
|
491
|
+
"""The name of a family of planes or directions: ``{111}``, ``<110>``, a bar over
|
|
492
|
+
the negative indices."""
|
|
493
|
+
text = "".join(f"{-v}̅" if v < 0 else str(v) for v in indices)
|
|
494
|
+
return f"{{{text}}}" if plane else f"⟨{text}⟩"
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def pole_figures_figure(figures, *, axes=("x", "y"), cmap: str = "viridis",
|
|
498
|
+
vmax: float | None = None, title: str | None = None): # fmt: skip
|
|
499
|
+
"""Pole figures side by side (:func:`morphogen.texture.pole_figure`, one or several)
|
|
500
|
+
on one colour range, in multiples of a random texture: the disc of each projection
|
|
501
|
+
with the names ``axes`` of the first and second axes of the sample on its rim, the
|
|
502
|
+
family and the largest density above it."""
|
|
503
|
+
from morphogen.texture import PoleFigure
|
|
504
|
+
|
|
505
|
+
shown_figures = [figures] if isinstance(figures, PoleFigure) else list(figures)
|
|
506
|
+
if not shown_figures:
|
|
507
|
+
raise ValueError("no pole figure to draw")
|
|
508
|
+
top = float(vmax) if vmax else max(f.maximum for f in shown_figures)
|
|
509
|
+
fig = _figure(3.0 * len(shown_figures) + 0.9, 3.3)
|
|
510
|
+
circle = np.linspace(0.0, 2.0 * np.pi, 361)
|
|
511
|
+
drawn, shown = [], None
|
|
512
|
+
for k, f in enumerate(shown_figures):
|
|
513
|
+
ax = fig.add_subplot(1, len(shown_figures), k + 1)
|
|
514
|
+
shown = ax.pcolormesh(f.x, f.x, f.density.T, cmap=cmap, vmin=0.0, vmax=top,
|
|
515
|
+
shading="nearest", rasterized=True) # fmt: skip
|
|
516
|
+
ax.plot(np.cos(circle), np.sin(circle), color="black", linewidth=0.8)
|
|
517
|
+
ax.set_aspect("equal")
|
|
518
|
+
ax.set_xlim(-1.12, 1.12)
|
|
519
|
+
ax.set_ylim(-1.12, 1.12)
|
|
520
|
+
ax.set_axis_off()
|
|
521
|
+
ax.text(1.04, 0.0, axes[0], ha="left", va="center", fontsize=8)
|
|
522
|
+
ax.text(0.0, 1.04, axes[1], ha="center", va="bottom", fontsize=8)
|
|
523
|
+
ax.set_title(f"{_indices_name(f.indices, f.plane)} max {f.maximum:.1f}", fontsize=9)
|
|
524
|
+
drawn.append(ax)
|
|
525
|
+
bar = fig.colorbar(shown, ax=drawn, shrink=0.8)
|
|
526
|
+
bar.set_label("multiples of a random texture", fontsize=8)
|
|
527
|
+
if title:
|
|
528
|
+
fig.suptitle(title, fontsize=10)
|
|
529
|
+
return fig
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _sector_outline(lattice: str, n: int = 60) -> np.ndarray:
|
|
533
|
+
"""The outline of the fundamental sector of a lattice in the plane of an inverse pole
|
|
534
|
+
figure (:func:`morphogen.texture.sector_points`)."""
|
|
535
|
+
from morphogen.texture import SECTOR_CORNERS, sector_points
|
|
536
|
+
|
|
537
|
+
corners = [np.array(c, dtype=float) for c, _ in SECTOR_CORNERS[lattice]]
|
|
538
|
+
points = []
|
|
539
|
+
for a, b in zip(corners, corners[1:] + corners[:1], strict=True):
|
|
540
|
+
t = np.linspace(0.0, 1.0, n)[:, None]
|
|
541
|
+
points.append(sector_points((1.0 - t) * a / np.linalg.norm(a) + t * b / np.linalg.norm(b),
|
|
542
|
+
lattice)) # fmt: skip
|
|
543
|
+
return np.concatenate(points)
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def _sector_names(ax, lattice: str, fontsize: float = 8) -> None:
|
|
547
|
+
from morphogen.texture import SECTOR_CORNERS, sector_points
|
|
548
|
+
|
|
549
|
+
places = (("right", "top"), ("left", "top"), ("left", "bottom"))
|
|
550
|
+
for (corner, name), (ha, va) in zip(SECTOR_CORNERS[lattice], places, strict=True):
|
|
551
|
+
x, y = sector_points(np.array(corner), lattice)[0]
|
|
552
|
+
text = "".join(f"{c}̅" if minus else c for minus, c in _signed(name))
|
|
553
|
+
ax.text(x, y, f" {text} ", ha=ha, va=va, fontsize=fontsize)
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _signed(name: str):
|
|
557
|
+
"""The digits of indices written with minus signs, each with whether it is negative."""
|
|
558
|
+
minus = False
|
|
559
|
+
for c in name:
|
|
560
|
+
if c == "-":
|
|
561
|
+
minus = True
|
|
562
|
+
continue
|
|
563
|
+
yield minus, c
|
|
564
|
+
minus = False
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def ipf_key(ax, lattice: str = "cubic", *, resolution: int = 240) -> None:
|
|
568
|
+
"""Draws the colour key of the inverse pole figure maps of a lattice on ``ax``: the
|
|
569
|
+
fundamental sector with the colour of each direction of the crystal
|
|
570
|
+
(:func:`morphogen.texture.direction_colours`) and the names of its corners."""
|
|
571
|
+
from morphogen.texture import _sector_directions, direction_colours
|
|
572
|
+
|
|
573
|
+
outline = _sector_outline(lattice)
|
|
574
|
+
width, height = outline[:, 0].max(), outline[:, 1].max()
|
|
575
|
+
x = np.linspace(0.0, width, resolution)
|
|
576
|
+
y = np.linspace(0.0, height, max(3, round(resolution * height / width)))
|
|
577
|
+
grid = np.stack(np.meshgrid(x, y, indexing="xy"), axis=-1).reshape(-1, 2)
|
|
578
|
+
directions, inside = _sector_directions(grid, lattice)
|
|
579
|
+
rgba = np.zeros((len(grid), 4))
|
|
580
|
+
rgba[inside, :3] = direction_colours(directions[inside], lattice)
|
|
581
|
+
rgba[inside, 3] = 1.0
|
|
582
|
+
ax.imshow(rgba.reshape(len(y), len(x), 4), origin="lower", extent=(0.0, width, 0.0, height),
|
|
583
|
+
interpolation="bilinear") # fmt: skip
|
|
584
|
+
ax.plot(outline[:, 0], outline[:, 1], color="black", linewidth=0.6)
|
|
585
|
+
ax.set_aspect("equal")
|
|
586
|
+
ax.set_xlim(-0.08 * width, 1.12 * width)
|
|
587
|
+
ax.set_ylim(-0.12 * height, 1.15 * height)
|
|
588
|
+
ax.set_axis_off()
|
|
589
|
+
_sector_names(ax, lattice, 7)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def inverse_pole_figure_figure(figure, *, points=None, cmap: str = "viridis",
|
|
593
|
+
vmax: float | None = None, title: str | None = None): # fmt: skip
|
|
594
|
+
"""An inverse pole figure (:func:`morphogen.texture.inverse_pole_figure`): its
|
|
595
|
+
density over the fundamental sector, in multiples of a random texture, with the
|
|
596
|
+
names of the corners; ``points``: directions of crystals ``(n, 3)`` drawn over it
|
|
597
|
+
(:func:`morphogen.texture.inverse_poles`: the crystals one by one, or the way of one
|
|
598
|
+
of them along a loading path)."""
|
|
599
|
+
from morphogen.texture import sector_points
|
|
600
|
+
|
|
601
|
+
outline = _sector_outline(figure.lattice)
|
|
602
|
+
fig = _figure(4.6, 3.6 if figure.lattice == "cubic" else 2.9)
|
|
603
|
+
ax = fig.add_subplot(1, 1, 1)
|
|
604
|
+
shown = ax.pcolormesh(figure.x, figure.y, figure.density.T, cmap=cmap, vmin=0.0,
|
|
605
|
+
vmax=float(vmax) if vmax else figure.maximum, shading="nearest",
|
|
606
|
+
rasterized=True) # fmt: skip
|
|
607
|
+
ax.plot(outline[:, 0], outline[:, 1], color="black", linewidth=0.8)
|
|
608
|
+
if points is not None:
|
|
609
|
+
p = sector_points(points, figure.lattice)
|
|
610
|
+
ax.plot(p[:, 0], p[:, 1], ".", color="white", markersize=3, markeredgecolor="black",
|
|
611
|
+
markeredgewidth=0.3) # fmt: skip
|
|
612
|
+
ax.set_aspect("equal")
|
|
613
|
+
width, height = outline[:, 0].max(), outline[:, 1].max()
|
|
614
|
+
ax.set_xlim(-0.1 * width, 1.15 * width)
|
|
615
|
+
ax.set_ylim(-0.12 * height, 1.15 * height)
|
|
616
|
+
ax.set_axis_off()
|
|
617
|
+
_sector_names(ax, figure.lattice)
|
|
618
|
+
bar = fig.colorbar(shown, ax=ax, shrink=0.8)
|
|
619
|
+
bar.set_label("multiples of a random texture", fontsize=8)
|
|
620
|
+
d = figure.direction
|
|
621
|
+
name = {(1.0, 0.0, 0.0): "x", (0.0, 1.0, 0.0): "y", (0.0, 0.0, 1.0): "z"}.get(
|
|
622
|
+
tuple(round(v, 9) + 0.0 for v in d), f"({d[0]:.2f}, {d[1]:.2f}, {d[2]:.2f})"
|
|
623
|
+
)
|
|
624
|
+
ax.set_title(title or f"crystal directions along {name} max {figure.maximum:.1f}", fontsize=9)
|
|
625
|
+
return fig
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def _boundary_lines(labels, step, height: float):
|
|
629
|
+
"""The sides between points of different grains of a map, as one broken line (NaN
|
|
630
|
+
between its segments): the grain boundaries, in the axes of the image."""
|
|
631
|
+
lab = np.asarray(labels)
|
|
632
|
+
dx, dy = step
|
|
633
|
+
rows, cols = np.nonzero(lab[:, 1:] != lab[:, :-1]) # vertical sides
|
|
634
|
+
xs = np.stack([(cols + 1) * dx, (cols + 1) * dx, np.full(len(cols), np.nan)], axis=1)
|
|
635
|
+
ys = np.stack(
|
|
636
|
+
[height - rows * dy, height - (rows + 1) * dy, np.full(len(rows), np.nan)], axis=1
|
|
637
|
+
)
|
|
638
|
+
rows2, cols2 = np.nonzero(lab[1:, :] != lab[:-1, :]) # horizontal sides
|
|
639
|
+
xs2 = np.stack([cols2 * dx, (cols2 + 1) * dx, np.full(len(cols2), np.nan)], axis=1)
|
|
640
|
+
y = height - (rows2 + 1) * dy
|
|
641
|
+
ys2 = np.stack([y, y, np.full(len(rows2), np.nan)], axis=1)
|
|
642
|
+
return np.concatenate([xs.ravel(), xs2.ravel()]), np.concatenate([ys.ravel(), ys2.ravel()])
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
def ipf_map_figure(ebsd, direction=(0.0, 0.0, 1.0), *, grains=None, title: str | None = None):
|
|
646
|
+
"""An orientation map (:class:`morphogen.io.ebsd.EBSDMap`) in the colours of the
|
|
647
|
+
direction of each crystal along a direction of the sample (the third axis by
|
|
648
|
+
default: the normal of the map), black where it was not indexed, in the axes of its
|
|
649
|
+
image; with the boundaries of its ``grains`` (:meth:`~morphogen.io.ebsd.EBSDMap.grains`)
|
|
650
|
+
and the colour key of its lattice."""
|
|
651
|
+
width, height = ebsd.size
|
|
652
|
+
fig = _figure(6.6, max(2.4, 5.0 * height / width + 0.6))
|
|
653
|
+
ax, key = fig.subplots(1, 2, width_ratios=(5.0, 1.0))
|
|
654
|
+
ax.imshow(ebsd.colours(direction), extent=(0.0, width, 0.0, height), interpolation="nearest")
|
|
655
|
+
if grains is not None:
|
|
656
|
+
ax.plot(*_boundary_lines(grains.labels, ebsd.step, height), color="black", linewidth=0.5)
|
|
657
|
+
ax.set_xlabel(f"x ({ebsd.unit})", fontsize=8)
|
|
658
|
+
ax.set_ylabel(f"y ({ebsd.unit})", fontsize=8)
|
|
659
|
+
ax.tick_params(labelsize=7)
|
|
660
|
+
present = [p.lattice for k, p in enumerate(ebsd.phases, start=1) if np.any(ebsd.phase == k)]
|
|
661
|
+
hexagonal = present and all(name in ("hexagonal", "6/m") for name in present)
|
|
662
|
+
ipf_key(key, "hexagonal" if hexagonal else "cubic")
|
|
663
|
+
if title:
|
|
664
|
+
ax.set_title(title, fontsize=10)
|
|
665
|
+
return fig
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def disorientation_figure(angles, weights=None, *, lattice: str = "cubic", bins: int = 21,
|
|
669
|
+
title: str | None = None): # fmt: skip
|
|
670
|
+
"""The distribution of disorientations (degrees; ``weights``: the lengths of the
|
|
671
|
+
boundaries, :func:`morphogen.texture.boundary_disorientations`) as a histogram, with
|
|
672
|
+
for cubic crystals the density of crystals at random (Mackenzie)."""
|
|
673
|
+
from morphogen.texture import MACKENZIE_ANGLES, mackenzie
|
|
674
|
+
|
|
675
|
+
top = {"cubic": 63.0, "m-3": 63.0, "hexagonal": 94.0}.get(lattice, 180.0)
|
|
676
|
+
fig = _figure(4.6, 3.2)
|
|
677
|
+
ax = fig.add_subplot(1, 1, 1)
|
|
678
|
+
ax.hist(np.asarray(angles, dtype=float), bins=bins, range=(0.0, top), weights=weights,
|
|
679
|
+
density=True, color="#7a9cc6", edgecolor="white", linewidth=0.5,
|
|
680
|
+
label="boundaries") # fmt: skip
|
|
681
|
+
if lattice == "cubic":
|
|
682
|
+
t = np.linspace(0.0, MACKENZIE_ANGLES[3], 400)
|
|
683
|
+
ax.plot(t, mackenzie(t), color="black", linewidth=1.0, label="at random (Mackenzie)")
|
|
684
|
+
ax.set_xlabel("disorientation (degrees)", fontsize=9)
|
|
685
|
+
ax.set_ylabel("density (1/degree)", fontsize=9)
|
|
686
|
+
ax.tick_params(labelsize=8)
|
|
687
|
+
ax.legend(fontsize=8, frameon=False)
|
|
688
|
+
if title:
|
|
689
|
+
ax.set_title(title, fontsize=10)
|
|
690
|
+
return fig
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
def save_gif(frames, path, *, fps: int = 8, kind: str = "auto", scale: int = 4) -> None:
|
|
694
|
+
"""Animated GIF of 2D frames (Pillow, installed with matplotlib)."""
|
|
695
|
+
try:
|
|
696
|
+
from PIL import Image
|
|
697
|
+
except ImportError as exc: # pragma: no cover - depends on the environment
|
|
698
|
+
raise ImportError("animations need Pillow: pip install 'morphogen[plot]'") from exc
|
|
699
|
+
from morphogen.viz.png import to_rgb, upscale
|
|
700
|
+
|
|
701
|
+
frames = [np.asarray(f) for f in frames]
|
|
702
|
+
if not frames:
|
|
703
|
+
raise ValueError("no frame to animate")
|
|
704
|
+
lo = min(float(f.min()) for f in frames)
|
|
705
|
+
hi = max(float(f.max()) for f in frames)
|
|
706
|
+
images = [Image.fromarray(upscale(to_rgb(f, kind, lo, hi), scale)) for f in frames]
|
|
707
|
+
images[0].save(path, save_all=True, append_images=images[1:], duration=int(1000 / fps), loop=0)
|