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,595 @@
|
|
|
1
|
+
"""The tools of the tab Learning: a behaviour learned from data (:mod:`morphogen.learning`).
|
|
2
|
+
The responses of a behaviour at a material point, or the homogenized responses of a
|
|
3
|
+
morphology of the workspace (FFT on its voxels), along random strain paths; a network
|
|
4
|
+
trained on them in the background (its losses reported epoch by epoch); its learning
|
|
5
|
+
curves and its law along a validation path against the reference; the model saved
|
|
6
|
+
(``learned.npz``) and its learned law kept in the workspace (B), from which the loading
|
|
7
|
+
paths of morphologies give it to a phase.
|
|
8
|
+
|
|
9
|
+
The fields of the paths, of the model and of the training are those of the sections
|
|
10
|
+
``data``, ``model`` and ``training`` of the configurations of ``morphogen learn``
|
|
11
|
+
(:mod:`morphogen.learning.run`), with their defaults; the run writes the configuration that
|
|
12
|
+
learns the law again (a material point, or a morphology of isotropic phases: its voxel
|
|
13
|
+
image)."""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import time
|
|
19
|
+
from dataclasses import replace
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
from morphogen.gui.tools import Field, elastic_tables, tab, tool
|
|
24
|
+
from morphogen.gui.tools.mechanics import (
|
|
25
|
+
BEHAVIOURS_FIELD,
|
|
26
|
+
COMPONENTS,
|
|
27
|
+
SHADES,
|
|
28
|
+
_behaviour,
|
|
29
|
+
_behaviour_fields,
|
|
30
|
+
_check_voxels,
|
|
31
|
+
_json,
|
|
32
|
+
_materials,
|
|
33
|
+
_path,
|
|
34
|
+
_path_fields,
|
|
35
|
+
)
|
|
36
|
+
from morphogen.learning.run import DATA, MODEL, TRAINING
|
|
37
|
+
|
|
38
|
+
tab(
|
|
39
|
+
"learning",
|
|
40
|
+
"Learning",
|
|
41
|
+
"Behaviours learned from data: the responses of a behaviour at a material point, or "
|
|
42
|
+
"the homogenized responses of a morphology, along random strain paths; a perceptron, "
|
|
43
|
+
"a learned convex potential (hyperelastic) or a recurrent network (path-dependent "
|
|
44
|
+
"laws: plasticity) trained on them in the background, its learning curves and its law "
|
|
45
|
+
"along a validation path against the reference; the model saved and its law kept in "
|
|
46
|
+
"the workspace (B), the behaviour of a phase in the loading paths of morphologies.",
|
|
47
|
+
order=45,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
POINT = {"data": "point"}
|
|
51
|
+
MORPHOLOGY = {"data": "morphology"}
|
|
52
|
+
#: The rotations of the mini-batches of the form (``rotate`` of the training)
|
|
53
|
+
ROTATIONS = {"false": False, "true": True, "cubic": "cubic"}
|
|
54
|
+
#: The models (:data:`morphogen.learning.KINDS`)
|
|
55
|
+
MODELS = (
|
|
56
|
+
("recurrent", "recurrent: a gated recurrent unit, learned internal variables (plasticity)"),
|
|
57
|
+
(
|
|
58
|
+
"standard",
|
|
59
|
+
"standard: a learned convex free energy and dissipation of learned internal "
|
|
60
|
+
"variables (plasticity, viscosity; thermodynamically consistent)",
|
|
61
|
+
),
|
|
62
|
+
("potential", "potential: the stress of a learned convex energy (hyperelasticity)"),
|
|
63
|
+
("feedforward", "perceptron: the stress a function of the strain (nonlinear elasticity)"),
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _fields(section: dict, specs: dict) -> list[Field]:
|
|
68
|
+
"""The fields of a section of the configurations of ``morphogen learn``, their
|
|
69
|
+
defaults those of ``section``: ``specs`` maps each key of the section to the options of
|
|
70
|
+
its :class:`~morphogen.gui.tools.Field` (``name``: that of the form, by default the
|
|
71
|
+
key)."""
|
|
72
|
+
out = []
|
|
73
|
+
for key, spec in specs.items():
|
|
74
|
+
spec = dict(spec)
|
|
75
|
+
out.append(Field(spec.pop("name", key), default=spec.pop("default", section[key]), **spec))
|
|
76
|
+
return out
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
#: The fields of the random paths (the section ``data``)
|
|
80
|
+
PATH_FIELDS = _fields(
|
|
81
|
+
DATA,
|
|
82
|
+
{
|
|
83
|
+
"paths": {"kind": "int", "doc": "random strain paths, their responses the data"},
|
|
84
|
+
"segments": {"kind": "int", "doc": "linear segments of a path, from the natural state"},
|
|
85
|
+
"increments": {"kind": "int", "label": "increments of a segment"},
|
|
86
|
+
"amplitude": {
|
|
87
|
+
"kind": "float",
|
|
88
|
+
"label": "strain amplitude",
|
|
89
|
+
"doc": "of the tensor components (a random walk held within it)",
|
|
90
|
+
},
|
|
91
|
+
"volumetric": {
|
|
92
|
+
"kind": "float",
|
|
93
|
+
"label": "volumetric ratio",
|
|
94
|
+
"doc": "of the volumetric strains: 0.2 for metals (elastic, small volume "
|
|
95
|
+
"changes), 1 for porous media",
|
|
96
|
+
},
|
|
97
|
+
"kind": {
|
|
98
|
+
"kind": "choice",
|
|
99
|
+
"label": "paths",
|
|
100
|
+
"choices": (
|
|
101
|
+
("walk", "random walks: each strain the previous one plus a random step"),
|
|
102
|
+
("linear", "independent strains: each component uniform"),
|
|
103
|
+
),
|
|
104
|
+
},
|
|
105
|
+
"components": {
|
|
106
|
+
"kind": "choices",
|
|
107
|
+
"default": list(COMPONENTS),
|
|
108
|
+
"label": "components driven",
|
|
109
|
+
"choices": COMPONENTS,
|
|
110
|
+
"doc": "the others held at zero strain, or free; a learned law runs the paths "
|
|
111
|
+
"of the components of its data only",
|
|
112
|
+
},
|
|
113
|
+
"free": {
|
|
114
|
+
"kind": "bool",
|
|
115
|
+
"label": "the others free",
|
|
116
|
+
"doc": "the components not driven at zero stress, rather than at zero strain "
|
|
117
|
+
"(a tension-torsion test drives 11 and 12)",
|
|
118
|
+
},
|
|
119
|
+
"rate": {
|
|
120
|
+
"kind": "float",
|
|
121
|
+
"label": "strain rate",
|
|
122
|
+
"unit": "1/time",
|
|
123
|
+
"doc": "the largest rate of a component on each segment (blank: a unit time "
|
|
124
|
+
"each); rate-dependent behaviours",
|
|
125
|
+
},
|
|
126
|
+
"seed": {"kind": "int", "label": "seed of the paths"},
|
|
127
|
+
"validation": {
|
|
128
|
+
"kind": "float",
|
|
129
|
+
"label": "validation fraction",
|
|
130
|
+
"doc": "the paths of the early stopping and of the errors, kept out of the training",
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
)
|
|
134
|
+
#: The fields of the model (the section ``model``)
|
|
135
|
+
MODEL_FIELDS = _fields(
|
|
136
|
+
MODEL,
|
|
137
|
+
{
|
|
138
|
+
"kind": {"name": "model", "kind": "choice", "choices": MODELS},
|
|
139
|
+
"hidden": {
|
|
140
|
+
"kind": "ints",
|
|
141
|
+
"label": "hidden sizes",
|
|
142
|
+
"doc": "the size of the state of a recurrent network, the ridges of the free "
|
|
143
|
+
"energy of a standard model, or the hidden layers of the others (blank: 32; 32, "
|
|
144
|
+
"32)",
|
|
145
|
+
},
|
|
146
|
+
"rate": {
|
|
147
|
+
"name": "model_rate",
|
|
148
|
+
"kind": "bool",
|
|
149
|
+
"label": "time step as an input",
|
|
150
|
+
"when": {"model": ["recurrent", "standard"]},
|
|
151
|
+
"doc": "rate-dependent behaviours (viscoplasticity; a viscous dissipation of a "
|
|
152
|
+
"standard model)",
|
|
153
|
+
},
|
|
154
|
+
"internal": {
|
|
155
|
+
"kind": "int",
|
|
156
|
+
"label": "internal variables",
|
|
157
|
+
"when": {"model": "standard"},
|
|
158
|
+
"doc": "of a standard model (blank: 8)",
|
|
159
|
+
},
|
|
160
|
+
"strain": {
|
|
161
|
+
"name": "energy_strain",
|
|
162
|
+
"kind": "choice",
|
|
163
|
+
"default": "logarithmic",
|
|
164
|
+
"label": "strain of the law",
|
|
165
|
+
"when": {"kinematics": "finite"},
|
|
166
|
+
"choices": (
|
|
167
|
+
(
|
|
168
|
+
"logarithmic",
|
|
169
|
+
"logarithmic: ½ ln C and its conjugate stress T, S = Jᵀ T, as the Hencky "
|
|
170
|
+
"points (plasticity, Hencky's elasticity)",
|
|
171
|
+
),
|
|
172
|
+
("green-lagrange", "Green-Lagrange: E and the second Piola-Kirchhoff stress"),
|
|
173
|
+
),
|
|
174
|
+
"doc": "in finite strains, the strain the model sees: the input of a perceptron or "
|
|
175
|
+
"of a recurrent network (its increments), the strain of a potential or of the free "
|
|
176
|
+
"energy of a standard model (its internal variables additive in it)",
|
|
177
|
+
},
|
|
178
|
+
"seed": {"name": "model_seed", "kind": "int", "label": "seed of the parameters"},
|
|
179
|
+
},
|
|
180
|
+
)
|
|
181
|
+
#: The fields of the training (the section ``training``)
|
|
182
|
+
TRAINING_FIELDS = _fields(
|
|
183
|
+
TRAINING,
|
|
184
|
+
{
|
|
185
|
+
"epochs": {"kind": "int"},
|
|
186
|
+
"batch": {
|
|
187
|
+
"kind": "int",
|
|
188
|
+
"label": "mini-batch",
|
|
189
|
+
"doc": "paths of a recurrent model, points of the others",
|
|
190
|
+
},
|
|
191
|
+
"learning_rate": {"kind": "float", "label": "learning rate", "doc": "of Adam"},
|
|
192
|
+
"final": {
|
|
193
|
+
"kind": "float",
|
|
194
|
+
"label": "final rate",
|
|
195
|
+
"doc": "a fraction of the first, reached geometrically at the last epoch",
|
|
196
|
+
},
|
|
197
|
+
"patience": {
|
|
198
|
+
"kind": "int",
|
|
199
|
+
"doc": "epochs without a better validation loss before it stops (blank: all)",
|
|
200
|
+
},
|
|
201
|
+
"clip": {"kind": "float", "label": "gradient clipping", "doc": "its global norm"},
|
|
202
|
+
"rotate": {
|
|
203
|
+
"kind": "choice",
|
|
204
|
+
"default": "false",
|
|
205
|
+
"label": "random rotations",
|
|
206
|
+
"choices": (
|
|
207
|
+
("false", "none"),
|
|
208
|
+
("true", "uniform: an isotropic behaviour, data of every direction"),
|
|
209
|
+
("cubic", "of the cube: a cubic crystal in its axes (24 rotations)"),
|
|
210
|
+
),
|
|
211
|
+
"doc": "each mini-batch turned at each epoch by symmetries of the behaviour: "
|
|
212
|
+
"data without more responses",
|
|
213
|
+
},
|
|
214
|
+
"seed": {"name": "training_seed", "kind": "int", "label": "seed of the shuffles"},
|
|
215
|
+
},
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
@tool(
|
|
220
|
+
"learn",
|
|
221
|
+
"learning",
|
|
222
|
+
"Learn a behaviour",
|
|
223
|
+
"A behaviour learned from data: the responses of a behaviour at a material point, or "
|
|
224
|
+
"the homogenized responses of a morphology (FFT on its voxels), along random strain "
|
|
225
|
+
"paths, then a network trained on them in the background (Adam, early stopping on the "
|
|
226
|
+
"validation paths; its losses reported at each epoch). Its learning curves, its errors "
|
|
227
|
+
"on the validation paths and its law at a material point along a validation path "
|
|
228
|
+
"against the reference; the model saved (learned.npz, with the data and the "
|
|
229
|
+
"configuration that learns it again), and the learned law joins the workspace (B): the "
|
|
230
|
+
"loading paths of morphologies give it to a phase (a behaviour of the workspace).",
|
|
231
|
+
[
|
|
232
|
+
Field(
|
|
233
|
+
"data",
|
|
234
|
+
"choice",
|
|
235
|
+
"point",
|
|
236
|
+
label="data of",
|
|
237
|
+
choices=(
|
|
238
|
+
("point", "a behaviour at a material point"),
|
|
239
|
+
("morphology", "a morphology: its homogenized responses (FFT on its voxels)"),
|
|
240
|
+
),
|
|
241
|
+
),
|
|
242
|
+
Field("source", "item", label="morphology", required=True, when=MORPHOLOGY),
|
|
243
|
+
Field(
|
|
244
|
+
"materials",
|
|
245
|
+
"materials",
|
|
246
|
+
of="source",
|
|
247
|
+
when=MORPHOLOGY,
|
|
248
|
+
doc="elastic constants of the phases (the unit of the stresses), or voids",
|
|
249
|
+
),
|
|
250
|
+
Field(
|
|
251
|
+
"phase",
|
|
252
|
+
"int",
|
|
253
|
+
label="phase of the behaviour",
|
|
254
|
+
when=MORPHOLOGY,
|
|
255
|
+
doc="blank: the first phase that is not a void",
|
|
256
|
+
),
|
|
257
|
+
Field("young", "float", 1.0, label="Young's modulus E", unit="stress", when=POINT),
|
|
258
|
+
Field("poisson", "float", 0.3, label="Poisson's ratio ν", when=POINT),
|
|
259
|
+
*_behaviour_fields("learned: at the point, or that phase of the morphology"),
|
|
260
|
+
Field(
|
|
261
|
+
"material",
|
|
262
|
+
"text",
|
|
263
|
+
label="material of the configurations (JSON)",
|
|
264
|
+
when=POINT,
|
|
265
|
+
doc='replaces the behaviour of the form: e.g. {"young": 1, "poisson": 0.3, '
|
|
266
|
+
'"plasticity": {"yield": 0.002, "hardening": 0.05}}',
|
|
267
|
+
),
|
|
268
|
+
replace(BEHAVIOURS_FIELD, when=MORPHOLOGY),
|
|
269
|
+
Field("voxels", "int", 8, label="voxels per edge", when=MORPHOLOGY),
|
|
270
|
+
Field(
|
|
271
|
+
"integration",
|
|
272
|
+
"choice",
|
|
273
|
+
"bbar",
|
|
274
|
+
when=MORPHOLOGY,
|
|
275
|
+
choices=(
|
|
276
|
+
("bbar", "B-bar (F-bar in finite strains): no locking under plastic flow"),
|
|
277
|
+
("full", "full: 8 Gauss points per voxel"),
|
|
278
|
+
),
|
|
279
|
+
),
|
|
280
|
+
Field(
|
|
281
|
+
"kinematics",
|
|
282
|
+
"choice",
|
|
283
|
+
"small",
|
|
284
|
+
choices=(
|
|
285
|
+
("small", "small strains"),
|
|
286
|
+
(
|
|
287
|
+
"finite",
|
|
288
|
+
"finite strains: the Green-Lagrange strain, the second Piola-Kirchhoff stress",
|
|
289
|
+
),
|
|
290
|
+
),
|
|
291
|
+
),
|
|
292
|
+
*PATH_FIELDS,
|
|
293
|
+
*MODEL_FIELDS,
|
|
294
|
+
*TRAINING_FIELDS,
|
|
295
|
+
*_path_fields("cycle", prefix="check_"),
|
|
296
|
+
Field(
|
|
297
|
+
"check_orientation",
|
|
298
|
+
"floats",
|
|
299
|
+
label="orientation of the validation point",
|
|
300
|
+
unit="degrees",
|
|
301
|
+
when=POINT,
|
|
302
|
+
doc="Bunge angles φ1, Φ, φ2: the behaviour and its learned law turned by them "
|
|
303
|
+
"(a crystal learned in its axes, checked in another frame); blank: the axes of "
|
|
304
|
+
"the data",
|
|
305
|
+
),
|
|
306
|
+
],
|
|
307
|
+
order=1,
|
|
308
|
+
groups=(
|
|
309
|
+
("Data", "data"),
|
|
310
|
+
("Behaviour", "behaviour"),
|
|
311
|
+
("Solver", "voxels"),
|
|
312
|
+
("Random paths", "paths"),
|
|
313
|
+
("Model", "model"),
|
|
314
|
+
("Training", "epochs", True),
|
|
315
|
+
("Validation path", "check_loading"),
|
|
316
|
+
),
|
|
317
|
+
)
|
|
318
|
+
def learn_behaviour(p: dict, ctx) -> dict:
|
|
319
|
+
from morphogen.gui.api import behaviour_summary
|
|
320
|
+
from morphogen.homogenization.paths import LoadingPath
|
|
321
|
+
from morphogen.learning import (
|
|
322
|
+
errors,
|
|
323
|
+
generate,
|
|
324
|
+
learned_material,
|
|
325
|
+
random_paths,
|
|
326
|
+
responder,
|
|
327
|
+
train,
|
|
328
|
+
)
|
|
329
|
+
from morphogen.learning.run import compare_path, reference_elasticity
|
|
330
|
+
|
|
331
|
+
kinematics = p["kinematics"]
|
|
332
|
+
name, check = _path(p, "check_")
|
|
333
|
+
check = LoadingPath.from_spec(check)
|
|
334
|
+
orientation = p.get("check_orientation") or None
|
|
335
|
+
if orientation is not None and len(orientation) != 3:
|
|
336
|
+
raise ValueError("orientation of the validation point: three Bunge angles φ1, Φ, φ2")
|
|
337
|
+
rotate = ROTATIONS[p["rotate"]]
|
|
338
|
+
respond, source, sample, origin = _source(p, ctx, kinematics, len(check.schedule()))
|
|
339
|
+
options = {k: p[k] for k in ("segments", "increments", "amplitude", "volumetric", "kind")}
|
|
340
|
+
options.update(components=p["components"] or None, free=bool(p["free"]), rate=p["rate"],
|
|
341
|
+
seed=p["seed"]) # fmt: skip
|
|
342
|
+
if not 0.0 < p["validation"] < 1.0 or p["paths"] < 2:
|
|
343
|
+
raise ValueError("validation fraction: between 0 and 1, of two paths at least")
|
|
344
|
+
paths = random_paths(p["paths"], **options)
|
|
345
|
+
model = _model(p)
|
|
346
|
+
info = {"source": source, "kinematics": kinematics, "paths": {"count": p["paths"], **options}}
|
|
347
|
+
|
|
348
|
+
def generated(done, total):
|
|
349
|
+
ctx.progress(0.02 + 0.38 * done / total, f"data: path {done} of {total}")
|
|
350
|
+
|
|
351
|
+
started = time.perf_counter()
|
|
352
|
+
data = generate(respond, paths, kinematics=kinematics, info=info, callback=generated)
|
|
353
|
+
data_s = time.perf_counter() - started
|
|
354
|
+
train_set, valid = data.split(p["validation"], seed=p["seed"])
|
|
355
|
+
epochs = p["epochs"]
|
|
356
|
+
|
|
357
|
+
def trained(epoch, loss, check_loss):
|
|
358
|
+
ctx.progress(0.4 + 0.55 * (epoch + 1) / epochs,
|
|
359
|
+
f"epoch {epoch + 1} of {epochs}: loss {loss:.3g}, validation "
|
|
360
|
+
f"{check_loss:.3g}") # fmt: skip
|
|
361
|
+
|
|
362
|
+
model.metadata["data"] = info
|
|
363
|
+
fit = train(model, train_set, valid, epochs=epochs, batch=p["batch"],
|
|
364
|
+
learning_rate=p["learning_rate"], final=p["final"], patience=p["patience"],
|
|
365
|
+
clip=p["clip"], rotate=rotate, seed=p["training_seed"],
|
|
366
|
+
callback=trained) # fmt: skip
|
|
367
|
+
scores = errors(model, valid)
|
|
368
|
+
model.metadata["validation"] = {k: v for k, v in scores.items() if k != "paths"}
|
|
369
|
+
path = model.save(ctx.folder / "learned.npz")
|
|
370
|
+
data.save(ctx.folder / "data.npz")
|
|
371
|
+
ctx.progress(0.96, f"validation path {name}")
|
|
372
|
+
elastic = reference_elasticity(source) if p["data"] == "point" else {}
|
|
373
|
+
material = learned_material(model, **elastic)
|
|
374
|
+
if orientation is not None: # the behaviour at the point turned with its law
|
|
375
|
+
respond = responder(source, kinematics, orientation)
|
|
376
|
+
ref, got, gaps = compare_path(material, respond, check, kinematics, orientation)
|
|
377
|
+
ctx.figure(_curves_figure(fit), "learning_curves", "learning curves")
|
|
378
|
+
ctx.figure(_check_figure(ref, got, f"validation path {name}"), "validation_path",
|
|
379
|
+
f"validation path {name}: the learned law against the reference") # fmt: skip
|
|
380
|
+
ctx.table([{"epoch": k + 1, "training loss": a, "validation loss": b} for k, (a, b) in
|
|
381
|
+
enumerate(zip(fit.train_loss, fit.validation_loss, strict=True))],
|
|
382
|
+
"learning_curves", "learning curves") # fmt: skip
|
|
383
|
+
ctx.table([{"path": k + 1, "relative error": e} for k, e in enumerate(scores["paths"])],
|
|
384
|
+
"validation_paths", "errors of the validation paths") # fmt: skip
|
|
385
|
+
ctx.table(ref.rows(), f"reference_{name}", f"reference along the path {name}")
|
|
386
|
+
_elastic_comparison(ctx, model, source if p["data"] == "point" else None)
|
|
387
|
+
if got is not None:
|
|
388
|
+
ctx.table(got.rows(), f"learned_{name}", f"learned law along the path {name}")
|
|
389
|
+
else:
|
|
390
|
+
import warnings
|
|
391
|
+
|
|
392
|
+
warnings.warn(f"the learned law along the path {name}: {gaps['failed']}", stacklevel=1)
|
|
393
|
+
# the behaviour of the workspace: the model by its name in the folder of the run
|
|
394
|
+
config = material.to_config()
|
|
395
|
+
config["learned"] = {**config["learned"], "model": path.name}
|
|
396
|
+
(ctx.folder / "material.json").write_text(json.dumps(config, indent=1), encoding="utf-8")
|
|
397
|
+
_configuration(p, ctx, source, sample, options, name, check)
|
|
398
|
+
label, details = behaviour_summary(config)
|
|
399
|
+
details.update(model=model.kind, data=data.measure, validation=round(scores["relative"], 4))
|
|
400
|
+
item = ctx.session.add(ctx.key, "behaviour", f"{label} ({model.kind}) of {origin}",
|
|
401
|
+
material=config, info=details) # fmt: skip
|
|
402
|
+
values = {
|
|
403
|
+
"paths": data.n_paths,
|
|
404
|
+
"points per path": data.n_points,
|
|
405
|
+
"epochs": fit.epochs,
|
|
406
|
+
"best epoch": fit.best_epoch + 1,
|
|
407
|
+
"training loss": fit.train_loss[fit.best_epoch],
|
|
408
|
+
"validation loss": fit.best_loss,
|
|
409
|
+
"validation error": scores["relative"],
|
|
410
|
+
"validation error, worst path": scores["max"],
|
|
411
|
+
f"stress gap along {name}": gaps["stress"],
|
|
412
|
+
f"strain gap along {name}": gaps["strain"],
|
|
413
|
+
"data_s": round(data_s, 2),
|
|
414
|
+
"training_s": round(fit.time_s, 2),
|
|
415
|
+
"young": material.young,
|
|
416
|
+
"poisson": material.poisson,
|
|
417
|
+
}
|
|
418
|
+
return {"values": values, "items": [ctx.session.public(item)]}
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _elastic_comparison(ctx, model, reference) -> None:
|
|
422
|
+
"""The elasticity of the learned law, its tangent at the natural state (stiffness and
|
|
423
|
+
compliance, ``tangent_stiffness.csv`` and ``tangent_compliance.csv``), beside that of
|
|
424
|
+
the reference material of a material point (``reference_stiffness.csv``...; none for
|
|
425
|
+
a morphology, or a law without elastic constants of its own)."""
|
|
426
|
+
from morphogen.homogenization.materials import Material
|
|
427
|
+
from morphogen.learning.behaviour import initial_tangent
|
|
428
|
+
|
|
429
|
+
names = ("tangent_stiffness", "tangent_compliance")
|
|
430
|
+
try:
|
|
431
|
+
elastic_tables(ctx, initial_tangent(model), "of the learned law at the natural state",
|
|
432
|
+
names=names, kind="tangent") # fmt: skip
|
|
433
|
+
except np.linalg.LinAlgError: # a learned law without a stiffness at the natural state
|
|
434
|
+
pass
|
|
435
|
+
try:
|
|
436
|
+
material = Material.from_config(reference) if reference is not None else None
|
|
437
|
+
except (ValueError, TypeError, KeyError, OSError):
|
|
438
|
+
material = None
|
|
439
|
+
if material is not None and material.elastic:
|
|
440
|
+
elastic_tables(ctx, material.matrix("elastic"), "of the reference",
|
|
441
|
+
names=("reference_stiffness", "reference_compliance")) # fmt: skip
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _source(p: dict, ctx, kinematics: str, steps: int):
|
|
445
|
+
"""The response to a path of the source of the form (``respond``), its description
|
|
446
|
+
(the material of a material point, or the morphology and its materials), the voxel
|
|
447
|
+
image of a morphology (None at a material point, or when its grains are turned) and
|
|
448
|
+
the name of the source in the title of the learned law."""
|
|
449
|
+
from morphogen.gui.api import behaviour_summary
|
|
450
|
+
from morphogen.homogenization.materials import Material
|
|
451
|
+
from morphogen.learning import responder
|
|
452
|
+
|
|
453
|
+
if p["data"] == "point":
|
|
454
|
+
spec = _json(p.get("material"), "material of the configurations")
|
|
455
|
+
kept = p["kept"] if spec is None and p["behaviour"] == "workspace" else None
|
|
456
|
+
if spec is None:
|
|
457
|
+
spec = _behaviour(p, {"young": p["young"], "poisson": p["poisson"]}, ctx.folder)
|
|
458
|
+
Material.from_config(spec) # checked
|
|
459
|
+
origin = kept["title"] if kept else behaviour_summary(spec)[0]
|
|
460
|
+
return responder(spec, kinematics), spec, None, origin
|
|
461
|
+
from morphogen.homogenization import materials_from_config
|
|
462
|
+
from morphogen.homogenization.fft_nonlinear import NonlinearFFTProblem
|
|
463
|
+
from morphogen.homogenization.materials import any_oriented
|
|
464
|
+
|
|
465
|
+
item = p["source"]
|
|
466
|
+
micro = item["micro"]
|
|
467
|
+
materials, phase = _materials(p, item, ctx.folder)
|
|
468
|
+
n = p["voxels"]
|
|
469
|
+
if not 4 <= n <= 64:
|
|
470
|
+
raise ValueError("voxels per edge: from 4 to 64 for the data of a learned law")
|
|
471
|
+
_check_voxels(micro, n, steps, "learning on voxels")
|
|
472
|
+
image = micro.voxelize(shape=n)
|
|
473
|
+
mats = materials_from_config(materials)
|
|
474
|
+
grains = {}
|
|
475
|
+
if any_oriented(mats) and getattr(micro, "orientations", None) is not None:
|
|
476
|
+
grains = {"grains": micro.labels(grid=image.grid()), "orientations": micro.orientations}
|
|
477
|
+
problem = NonlinearFFTProblem(image, mats, "periodic", kinematics=kinematics,
|
|
478
|
+
integration=p["integration"], **grains) # fmt: skip
|
|
479
|
+
source = {"morphology": item["title"], "phase": phase, "voxels": n,
|
|
480
|
+
"materials": {str(k): v for k, v in materials.items()}} # fmt: skip
|
|
481
|
+
return problem.run, source, None if grains else image, f"#{item['number']}"
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _model(p: dict):
|
|
485
|
+
"""The model of the form (:func:`~morphogen.learning.make_model`)."""
|
|
486
|
+
from morphogen.learning import make_model
|
|
487
|
+
|
|
488
|
+
options = {"seed": p["model_seed"]}
|
|
489
|
+
if p.get("energy_strain"): # in finite strains
|
|
490
|
+
options["strain"] = p["energy_strain"]
|
|
491
|
+
hidden = p.get("hidden")
|
|
492
|
+
if p["model"] in ("recurrent", "standard"):
|
|
493
|
+
options["rate"] = bool(p.get("model_rate"))
|
|
494
|
+
if p["model"] == "standard" and p.get("internal"):
|
|
495
|
+
options["internal"] = p["internal"]
|
|
496
|
+
if hidden:
|
|
497
|
+
if len(hidden) != 1:
|
|
498
|
+
raise ValueError("hidden sizes: one, the size of the state of a recurrent "
|
|
499
|
+
"network or the ridges of a standard model") # fmt: skip
|
|
500
|
+
options["hidden"] = hidden[0]
|
|
501
|
+
elif hidden:
|
|
502
|
+
options["hidden"] = list(hidden)
|
|
503
|
+
return make_model(p["model"], **options)
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def _curves_figure(fit):
|
|
507
|
+
"""The losses of the training and validation sets at each epoch, the best one marked."""
|
|
508
|
+
from matplotlib.figure import Figure
|
|
509
|
+
|
|
510
|
+
fig = Figure(figsize=(5.4, 3.8), layout="constrained")
|
|
511
|
+
ax = fig.subplots()
|
|
512
|
+
epochs = np.arange(1, fit.epochs + 1)
|
|
513
|
+
ax.semilogy(epochs, fit.train_loss, "-", lw=1.6, color=SHADES[1], label="training paths")
|
|
514
|
+
ax.semilogy(epochs, fit.validation_loss, "-", lw=1.6, color=SHADES[0],
|
|
515
|
+
label="validation paths") # fmt: skip
|
|
516
|
+
best = fit.best_epoch + 1
|
|
517
|
+
ax.axvline(best, color="0.5", ls=":", lw=1.0)
|
|
518
|
+
ax.plot([best], [fit.best_loss], "o", color=SHADES[0], ms=5,
|
|
519
|
+
label=f"kept: epoch {best}, {fit.best_loss:.3g}") # fmt: skip
|
|
520
|
+
ax.set_xlabel("epoch")
|
|
521
|
+
ax.set_ylabel("mean square of the normalized stress gaps")
|
|
522
|
+
ax.set_title(f"training of the {fit.model.kind} model", fontsize=10)
|
|
523
|
+
ax.grid(alpha=0.3, which="both")
|
|
524
|
+
ax.legend(fontsize=8, frameon=False)
|
|
525
|
+
return fig
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _check_figure(ref, got, title: str):
|
|
529
|
+
"""The learned law (dashed) against the reference (solid) along a path: the stress of
|
|
530
|
+
the strain that varies most, and the stresses that vary against time."""
|
|
531
|
+
from matplotlib.figure import Figure
|
|
532
|
+
|
|
533
|
+
from morphogen.gui.tools.mechanics import _driven
|
|
534
|
+
|
|
535
|
+
fig = Figure(figsize=(9.6, 3.8), layout="constrained")
|
|
536
|
+
ax, ax2 = fig.subplots(1, 2)
|
|
537
|
+
strain, stress, e_name, s_name, i = _driven(ref)
|
|
538
|
+
j = int(np.argmax(np.ptp(stress, axis=0)))
|
|
539
|
+
ax.plot(strain[:, i], stress[:, j], "k-", lw=1.8, marker=".", ms=4, label="reference")
|
|
540
|
+
ptp = np.ptp(stress, axis=0)
|
|
541
|
+
shown = [c for c in range(6) if ptp[c] > 0.05 * ptp.max()]
|
|
542
|
+
for k, c in enumerate(shown):
|
|
543
|
+
shade = SHADES[k % len(SHADES)]
|
|
544
|
+
label = f"{s_name}{COMPONENTS[c]}"
|
|
545
|
+
ax2.plot(ref.times, stress[:, c], "-", lw=1.8, color=shade, label=label)
|
|
546
|
+
if got is not None:
|
|
547
|
+
e2, s2, *_ = _driven(got)
|
|
548
|
+
ax.plot(e2[:, i], s2[:, j], "--", color=SHADES[0], lw=1.8, label="learned law")
|
|
549
|
+
for k, c in enumerate(shown):
|
|
550
|
+
ax2.plot(got.times, s2[:, c], "--", lw=1.4, color=SHADES[k % len(SHADES)])
|
|
551
|
+
ax.set_xlabel(e_name + COMPONENTS[i])
|
|
552
|
+
ax.set_ylabel(s_name + COMPONENTS[j])
|
|
553
|
+
ax.locator_params(axis="x", nbins=5)
|
|
554
|
+
ax2.set_xlabel("time")
|
|
555
|
+
ax2.set_ylabel("stress (solid: reference, dashed: learned)")
|
|
556
|
+
for a in (ax, ax2):
|
|
557
|
+
a.grid(alpha=0.3)
|
|
558
|
+
a.legend(fontsize=8, frameon=False)
|
|
559
|
+
fig.suptitle(title + ("" if got is not None else ": the learned law failed"), fontsize=10)
|
|
560
|
+
return fig
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _configuration(p: dict, ctx, source, sample, options: dict, name: str, check) -> None:
|
|
564
|
+
"""The configuration of ``morphogen learn`` that learns the law again (beside the files
|
|
565
|
+
it names): at a material point, or on the voxel image of a morphology (not of turned
|
|
566
|
+
grains)."""
|
|
567
|
+
import yaml
|
|
568
|
+
|
|
569
|
+
from morphogen import io
|
|
570
|
+
|
|
571
|
+
cfg: dict = {}
|
|
572
|
+
if p["data"] == "point":
|
|
573
|
+
cfg["material"] = source
|
|
574
|
+
elif sample is not None:
|
|
575
|
+
io.save_image(sample, ctx.folder / "sample.vti")
|
|
576
|
+
cfg.update(sample="sample.vti", materials=source["materials"], bc="periodic")
|
|
577
|
+
else:
|
|
578
|
+
return
|
|
579
|
+
model = {"kind": p["model"], "hidden": p.get("hidden") or None, "seed": p["model_seed"]}
|
|
580
|
+
if p["model"] in ("recurrent", "standard"):
|
|
581
|
+
model["rate"] = bool(p.get("model_rate"))
|
|
582
|
+
if model["hidden"]:
|
|
583
|
+
model["hidden"] = model["hidden"][0]
|
|
584
|
+
if p["model"] == "standard" and p.get("internal"):
|
|
585
|
+
model["internal"] = p["internal"]
|
|
586
|
+
if p.get("energy_strain"):
|
|
587
|
+
model["strain"] = p["energy_strain"]
|
|
588
|
+
training = {k: p[k] for k in ("epochs", "batch", "learning_rate", "final", "patience", "clip")}
|
|
589
|
+
training.update(rotate=ROTATIONS[p["rotate"]], seed=p["training_seed"])
|
|
590
|
+
cfg.update(kinematics=p["kinematics"],
|
|
591
|
+
data={"paths": p["paths"], **options, "validation": p["validation"]},
|
|
592
|
+
model=model, training=training, paths={name: check.to_dict()},
|
|
593
|
+
output="learned.npz", save_data="data.npz") # fmt: skip
|
|
594
|
+
text = yaml.safe_dump({"learning": json.loads(json.dumps(cfg))}, sort_keys=False)
|
|
595
|
+
(ctx.folder / "learning.yaml").write_text(text, encoding="utf-8")
|