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,1654 @@
|
|
|
1
|
+
"""The tools of the tab Solvers & formats: the inputs of other solvers for a morphology of
|
|
2
|
+
the workspace, and its files in the formats of other programs (the common files, geometry,
|
|
3
|
+
sections, VTK images, STL surface and conforming mesh .vtu, are those of the tab Export):
|
|
4
|
+
|
|
5
|
+
* AMITEX_FFTP (:func:`morphogen.io.write_amitex`): the voxel image of a morphology, the
|
|
6
|
+
materials of its phases (AMITEX's elastic laws; MFront laws of the ``umat`` interface
|
|
7
|
+
for the nonlinear behaviours, and for every phase in finite strains), the six unit
|
|
8
|
+
strains of the apparent stiffness and a loading path; and the results of its runs read
|
|
9
|
+
back (:func:`morphogen.io.read_amitex_run`: the averages of each run, the apparent
|
|
10
|
+
stiffness and its moduli);
|
|
11
|
+
* Abaqus (:func:`morphogen.io.write_inp_tet`, :func:`morphogen.io.write_inp`): the
|
|
12
|
+
conforming or voxel mesh of a morphology with the materials of its phases
|
|
13
|
+
(``*ELASTIC``, isotropic or in the axes of the crystal of each grain with its
|
|
14
|
+
``*ORIENTATION``; MFront laws of the ``abaqus`` interface), the periodic equations of
|
|
15
|
+
three reference nodes (:func:`morphogen.io.write_periodic_equations`; uniform strains on
|
|
16
|
+
the faces of the box, KUBC, when the morphology is not periodic) and a step per segment
|
|
17
|
+
of a loading path;
|
|
18
|
+
* meshes and images in other formats: Gmsh, Medit, FEniCSx, the periodic node pairs, Neper
|
|
19
|
+
and DAMASK for tessellations, TIFF stacks and MetaImage;
|
|
20
|
+
* the MFront sources of morphoGen's behaviours (:func:`morphogen.io.mfront_source`), and
|
|
21
|
+
the material files of Z-set translated, and those of the behaviours of the workspace
|
|
22
|
+
written (:mod:`morphogen.homogenization.zmat`).
|
|
23
|
+
|
|
24
|
+
The tools write their files in the folder of their result, with a README of the commands
|
|
25
|
+
to run and an archive of them all (``.zip``, their folders kept); they list them for the
|
|
26
|
+
page (``files``: the inputs of the solvers are of kinds the page does not know). The
|
|
27
|
+
loadings are given in morphoGen's components (Voigt order 11, 22, 33, 23, 31, 12 with
|
|
28
|
+
engineering shear strains; in finite strains the components 11, 22, 33, 23, 13, 12 of the
|
|
29
|
+
gradient, upper triangular, and of the nominal stress): strains ``E`` or stresses ``S`` at
|
|
30
|
+
the times of a path (:meth:`morphogen.homogenization.LoadingPath.parse`)."""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import re
|
|
35
|
+
import shutil
|
|
36
|
+
import tempfile
|
|
37
|
+
import warnings
|
|
38
|
+
import zipfile
|
|
39
|
+
from pathlib import Path
|
|
40
|
+
|
|
41
|
+
import numpy as np
|
|
42
|
+
|
|
43
|
+
from morphogen.gui.tools import Field, elastic_tables, tab, tool
|
|
44
|
+
|
|
45
|
+
tab(
|
|
46
|
+
"interop",
|
|
47
|
+
"Solvers & formats",
|
|
48
|
+
"The inputs of other solvers for a morphology of the workspace: AMITEX_FFTP (its voxel "
|
|
49
|
+
"image, the materials of its phases and the loadings; the results of the runs read "
|
|
50
|
+
"back) and Abaqus (its conforming or voxel mesh, materials, crystal orientations, "
|
|
51
|
+
"periodic equations and loading steps); its meshes and images in other formats (Gmsh, "
|
|
52
|
+
"Medit, FEniCSx, Neper, DAMASK, TIFF, MetaImage); the MFront sources of morphoGen's "
|
|
53
|
+
"behaviours and the material files of Z-set. Each result has a README of the commands "
|
|
54
|
+
"to run and an archive of its files.",
|
|
55
|
+
order=85,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
#: The kinematics of the exports of materials (MFront laws for all in finite strains)
|
|
59
|
+
KINEMATICS = (
|
|
60
|
+
("small", "small strains"),
|
|
61
|
+
("finite", "finite strains (every phase an MFront law)"),
|
|
62
|
+
)
|
|
63
|
+
#: The keys of a material of the configurations that give its elasticity: a behaviour of
|
|
64
|
+
#: the form with none of them completes the elastic constants of its phase, else replaces
|
|
65
|
+
#: them
|
|
66
|
+
ELASTIC_KEYS = frozenset(
|
|
67
|
+
{"young", "poisson", "bulk", "shear", "cubic", "hexagonal", "stiffness", "zmat"}
|
|
68
|
+
)
|
|
69
|
+
BEHAVIOURS_DOC = (
|
|
70
|
+
"phase -> a material of the configurations, completing or replacing its elastic "
|
|
71
|
+
'constants: {"1": {"plasticity": {"yield": 300, "hardening": 1000}}} (von Mises), '
|
|
72
|
+
'{"1": {"cubic": [168e3, 121e3, 75e3], "crystal_plasticity": {"tau0": 40, "K": 20, '
|
|
73
|
+
'"n": 12}}} (a crystal, turned by the orientation of each grain), {"1": {"zmat": '
|
|
74
|
+
'"alloy.mat"}} (Z-set)'
|
|
75
|
+
)
|
|
76
|
+
COMPONENTS_DOC = (
|
|
77
|
+
"strains E11 ... E12 (engineering shears; in finite strains the gradient) and "
|
|
78
|
+
"stresses S11 ... S12 at the times after the first (one value: reached at the end of "
|
|
79
|
+
"the first segment and held; E11=0.01,0,-0.01: a cycle); the components not given "
|
|
80
|
+
"are free (zero stress)"
|
|
81
|
+
)
|
|
82
|
+
#: The kinds of the files of the results, for the page (the others: data)
|
|
83
|
+
FILE_KINDS = {
|
|
84
|
+
".zip": "archive",
|
|
85
|
+
".md": "report",
|
|
86
|
+
".csv": "table",
|
|
87
|
+
".png": "figure",
|
|
88
|
+
".svg": "figure",
|
|
89
|
+
".mp4": "video",
|
|
90
|
+
".gif": "video",
|
|
91
|
+
".inp": "configuration",
|
|
92
|
+
".xml": "configuration",
|
|
93
|
+
".sh": "configuration",
|
|
94
|
+
".mfront": "configuration",
|
|
95
|
+
".yaml": "configuration",
|
|
96
|
+
".json": "configuration",
|
|
97
|
+
".mat": "configuration",
|
|
98
|
+
}
|
|
99
|
+
#: Voxels per edge of the voxel meshes (8-node hexahedra, written as text)
|
|
100
|
+
MAX_VOXEL_MESH = 128
|
|
101
|
+
#: morphoGen's Voigt components
|
|
102
|
+
VOIGT = ("11", "22", "33", "23", "31", "12")
|
|
103
|
+
#: The row i (degree of freedom) and column j (reference node REF_X, REF_Y, REF_Z) of the
|
|
104
|
+
#: displacement gradient H, upper triangular, of each Voigt component: u_i(REF_j) =
|
|
105
|
+
#: H_ij L_j, and the force on that degree of freedom is A_j sigma_ij (A_j: the area of
|
|
106
|
+
#: the face normal to j)
|
|
107
|
+
GRADIENT = ((0, 0), (1, 1), (2, 2), (1, 2), (0, 2), (0, 1))
|
|
108
|
+
REFERENCES = ("REF_X", "REF_Y", "REF_Z")
|
|
109
|
+
#: Lines of a source shown in the page (the file holds it all)
|
|
110
|
+
SHOWN_LINES = 120
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# -- common ----------------------------------------------------------------------------------
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _name(value, item: dict | None = None) -> str:
|
|
117
|
+
"""The stem of the files of a result: the name of the form, or the model of the
|
|
118
|
+
morphology (letters, digits, '_' and '-')."""
|
|
119
|
+
model = (item or {}).get("model") or {}
|
|
120
|
+
text = str(value or "").strip() or model.get("type") or "morphology"
|
|
121
|
+
return re.sub(r"[^A-Za-z0-9_-]+", "_", text).strip("_") or "morphology"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _count(n: int, noun: str) -> str:
|
|
125
|
+
return f"{n} {noun}{'' if n == 1 else 's'}"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _head(text: str, name: str) -> str:
|
|
129
|
+
"""The first :data:`SHOWN_LINES` lines of a text (the file ``name`` holds it all)."""
|
|
130
|
+
lines = text.splitlines()
|
|
131
|
+
if len(lines) <= SHOWN_LINES:
|
|
132
|
+
return text
|
|
133
|
+
rest = len(lines) - SHOWN_LINES
|
|
134
|
+
return "\n".join([*lines[:SHOWN_LINES], f"... ({rest} more lines in {name})"]) + "\n"
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _edge(micro) -> float:
|
|
138
|
+
return float(np.max(micro.domain.lengths))
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _image(micro, n, what: str, limit: int | None = None):
|
|
142
|
+
"""The voxel image of the phases of a morphology, ``n`` voxels along its longest edge
|
|
143
|
+
(the memory checked)."""
|
|
144
|
+
from morphogen.gui.api import MAX_SHAPE, _voxels
|
|
145
|
+
|
|
146
|
+
limit = limit or MAX_SHAPE
|
|
147
|
+
n = int(n)
|
|
148
|
+
if not 2 <= n <= limit:
|
|
149
|
+
raise ValueError(f"voxels per edge: from 2 to {limit}")
|
|
150
|
+
_voxels(micro.domain, n, 24.0, what)
|
|
151
|
+
return micro.voxelize(shape=n)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
#: A behaviour of the workspace given to one phase (with its own elasticity)
|
|
155
|
+
KEPT_FIELDS = (
|
|
156
|
+
Field(
|
|
157
|
+
"kept",
|
|
158
|
+
"item",
|
|
159
|
+
label="behaviour of the workspace",
|
|
160
|
+
items=("behaviour",),
|
|
161
|
+
none="none: the materials above",
|
|
162
|
+
doc="a material point or an import of Z-set (B), given to the phase below with its "
|
|
163
|
+
"own elasticity",
|
|
164
|
+
),
|
|
165
|
+
Field("kept_phase", "int", 1, label="its phase"),
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _specs(p: dict, phases) -> dict:
|
|
170
|
+
"""The materials of the form for the ``phases`` (their configurations): the elastic
|
|
171
|
+
constants (a contrast of 10 without them), completed or replaced by the behaviours,
|
|
172
|
+
and by the behaviour of the workspace chosen for one phase."""
|
|
173
|
+
phases = sorted(int(q) for q in phases)
|
|
174
|
+
spec = {int(k): v for k, v in (p.get("materials") or {}).items()}
|
|
175
|
+
if not spec:
|
|
176
|
+
spec = {q: {"young": 1.0 if k == 0 else 10.0, "poisson": 0.3} for k, q in enumerate(phases)}
|
|
177
|
+
extra = p.get("behaviours") or {}
|
|
178
|
+
if not isinstance(extra, dict):
|
|
179
|
+
raise ValueError('behaviours: a mapping phase -> material, {"1": {...}}')
|
|
180
|
+
for key, value in extra.items():
|
|
181
|
+
try:
|
|
182
|
+
phase = int(key)
|
|
183
|
+
except (TypeError, ValueError):
|
|
184
|
+
raise ValueError(f"behaviours: the phases are integers, got {key!r}") from None
|
|
185
|
+
base = spec.get(phase)
|
|
186
|
+
if isinstance(value, dict) and isinstance(base, dict) and not ELASTIC_KEYS & set(value):
|
|
187
|
+
value = {**base, **value}
|
|
188
|
+
spec[phase] = value
|
|
189
|
+
if p.get("kept"):
|
|
190
|
+
phase = p.get("kept_phase")
|
|
191
|
+
if phase is None or int(phase) not in phases:
|
|
192
|
+
raise ValueError(f"its phase: one of the phases {phases}")
|
|
193
|
+
spec[int(phase)] = p["kept"]["material"]
|
|
194
|
+
return spec
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _materials(p: dict, phases, *, required: bool = True) -> dict:
|
|
198
|
+
"""The :class:`~morphogen.homogenization.Material` of each of the ``phases`` (see
|
|
199
|
+
:func:`_specs`); a phase without one is an error (``required``) or left out."""
|
|
200
|
+
from morphogen.homogenization.materials import materials_from_config
|
|
201
|
+
|
|
202
|
+
spec = _specs(p, phases)
|
|
203
|
+
phases = sorted(int(q) for q in phases)
|
|
204
|
+
missing = [q for q in phases if q not in spec]
|
|
205
|
+
if missing and required:
|
|
206
|
+
raise ValueError(f"phases {missing}: no material (give their elastic constants)")
|
|
207
|
+
chosen = {q: spec[q] for q in phases if q in spec}
|
|
208
|
+
return materials_from_config(chosen) if chosen else {}
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _path(p: dict):
|
|
212
|
+
"""The loading path of the form: the components at the times, the increments of each
|
|
213
|
+
segment."""
|
|
214
|
+
from morphogen.homogenization.paths import LoadingPath
|
|
215
|
+
|
|
216
|
+
components = str(p.get("components") or "").strip()
|
|
217
|
+
if not components:
|
|
218
|
+
raise ValueError(f"components: {COMPONENTS_DOC}")
|
|
219
|
+
times = p.get("times") or [0.0, 1.0]
|
|
220
|
+
increments = p.get("increments") or [10]
|
|
221
|
+
text = (
|
|
222
|
+
f"t={','.join(repr(float(t)) for t in times)} "
|
|
223
|
+
f"n={','.join(str(int(n)) for n in increments)} {components}"
|
|
224
|
+
)
|
|
225
|
+
path = LoadingPath.parse(text)
|
|
226
|
+
if any(path.temperature):
|
|
227
|
+
raise ValueError("components: the changes of temperature (dT) are not exported")
|
|
228
|
+
return path
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _path_fields(when: dict) -> list[Field]:
|
|
232
|
+
return [
|
|
233
|
+
Field("components", "str", "E11=0.01", when=when, doc=COMPONENTS_DOC),
|
|
234
|
+
Field("times", "floats", [0.0, 1.0], when=when, doc="the times of the path, from 0"),
|
|
235
|
+
Field(
|
|
236
|
+
"increments",
|
|
237
|
+
"ints",
|
|
238
|
+
[10],
|
|
239
|
+
when=when,
|
|
240
|
+
doc="the increments of each segment (one number: the same for all)",
|
|
241
|
+
),
|
|
242
|
+
]
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _segments(path) -> list[dict]:
|
|
246
|
+
"""The rows of a table of the segments of a path."""
|
|
247
|
+
rows = []
|
|
248
|
+
for k in range(len(path.times) - 1):
|
|
249
|
+
row = {
|
|
250
|
+
"segment": k + 1,
|
|
251
|
+
"from": path.times[k],
|
|
252
|
+
"to": path.times[k + 1],
|
|
253
|
+
"increments": path.increments[k],
|
|
254
|
+
}
|
|
255
|
+
for name, value, strain in zip(VOIGT, path.values[k + 1], path.controls, strict=True):
|
|
256
|
+
row[("E" if strain else "S") + name] = value
|
|
257
|
+
rows.append(row)
|
|
258
|
+
return rows
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _section(ctx, data, kind: str, name: str, title: str) -> None:
|
|
262
|
+
"""A figure of the middle x-y section of a voxel array."""
|
|
263
|
+
from morphogen.viz.png import slice_of, to_rgb, upscale
|
|
264
|
+
|
|
265
|
+
rgb = to_rgb(slice_of(np.asarray(data), 2), kind)
|
|
266
|
+
ctx.figure(upscale(rgb, max(1, 320 // max(rgb.shape[:2]))), name, title)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _listing(ctx) -> list[dict]:
|
|
270
|
+
"""The files of a result for the page, those of its folders too, by kind."""
|
|
271
|
+
out = []
|
|
272
|
+
for path in sorted(ctx.folder.rglob("*")):
|
|
273
|
+
if path.is_file():
|
|
274
|
+
name = path.relative_to(ctx.folder).as_posix()
|
|
275
|
+
kind = FILE_KINDS.get(path.suffix.lower(), "data")
|
|
276
|
+
out.append({"name": name, "kind": kind, "url": ctx.url(name)})
|
|
277
|
+
return out
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _finish(ctx, archive: str, out: dict) -> dict:
|
|
281
|
+
"""An archive of the files of a result (``<archive>.zip``, their folders kept) and the
|
|
282
|
+
list of the files (the inputs of the solvers, of kinds the page does not know)."""
|
|
283
|
+
files = [p for p in sorted(ctx.folder.rglob("*")) if p.is_file()]
|
|
284
|
+
target = ctx.path(f"{archive}.zip")
|
|
285
|
+
with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as zf:
|
|
286
|
+
for path in files:
|
|
287
|
+
zf.write(path, path.relative_to(ctx.folder).as_posix())
|
|
288
|
+
out["archive"] = ctx.url(target.name)
|
|
289
|
+
out["files"] = _listing(ctx)
|
|
290
|
+
return out
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _conforming(micro, p: dict, materials: dict | None = None):
|
|
294
|
+
"""The conforming mesh of a morphology (its grains for tessellations), of its phases
|
|
295
|
+
that are not voids: phase 1 alone when phase 0 is void, otherwise the mesh of all its
|
|
296
|
+
phases without the voids."""
|
|
297
|
+
from morphogen.mesh import conforming_mesh
|
|
298
|
+
|
|
299
|
+
edge = _edge(micro)
|
|
300
|
+
size = p.get("element_size") or edge / 12
|
|
301
|
+
if not edge / 200 <= size <= edge:
|
|
302
|
+
raise ValueError(f"element size: between {edge / 200:g} and {edge:g}")
|
|
303
|
+
void = {q for q, m in (materials or {}).items() if m.void}
|
|
304
|
+
phases = "solid" if 0 in void and 1 not in void else "all"
|
|
305
|
+
mesh = conforming_mesh(micro, size=float(size), order=int(p.get("order") or 1), phases=phases)
|
|
306
|
+
present = set(np.unique(mesh.phase).tolist())
|
|
307
|
+
if present & void:
|
|
308
|
+
if not present - void:
|
|
309
|
+
raise ValueError("every phase of the mesh is void")
|
|
310
|
+
mesh = mesh.subset(sorted(present - void))
|
|
311
|
+
return mesh
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
# -- AMITEX_FFTP -----------------------------------------------------------------------------
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
@tool(
|
|
318
|
+
"amitex_inputs",
|
|
319
|
+
"interop",
|
|
320
|
+
"AMITEX_FFTP inputs",
|
|
321
|
+
"The inputs of AMITEX_FFTP, the FFT solver of the CEA, for a morphology: the material "
|
|
322
|
+
"and zone of each voxel of its image (legacy VTK), the materials of its phases (the "
|
|
323
|
+
"laws elasiso and elasaniso; crystals turned by the orientation of each grain; the "
|
|
324
|
+
"nonlinear behaviours, and every phase in finite strains, MFront laws of the umat "
|
|
325
|
+
"interface, their sources in mfront/), the algorithm, a loading file per run (the six "
|
|
326
|
+
"unit strains of the apparent stiffness, a loading path) and the script compiling the "
|
|
327
|
+
"laws and running them all with MPI.",
|
|
328
|
+
[
|
|
329
|
+
Field("source", "item", label="morphology", required=True),
|
|
330
|
+
Field(
|
|
331
|
+
"resolution", "int", 32, label="voxels per edge", doc="of the image (its longest edge)"
|
|
332
|
+
),
|
|
333
|
+
Field("materials", "materials", of="source"),
|
|
334
|
+
Field("behaviours", "json", label="behaviours of the phases", doc=BEHAVIOURS_DOC),
|
|
335
|
+
*KEPT_FIELDS,
|
|
336
|
+
Field("kinematics", "choice", "small", choices=KINEMATICS),
|
|
337
|
+
Field(
|
|
338
|
+
"loading",
|
|
339
|
+
"choice",
|
|
340
|
+
"stiffness",
|
|
341
|
+
label="runs",
|
|
342
|
+
choices=(
|
|
343
|
+
("stiffness", "the six unit strains: the apparent stiffness (elastic phases)"),
|
|
344
|
+
("path", "a loading path"),
|
|
345
|
+
("both", "the unit strains and a loading path (elastic phases)"),
|
|
346
|
+
),
|
|
347
|
+
),
|
|
348
|
+
*_path_fields({"loading": ["path", "both"]}),
|
|
349
|
+
Field(
|
|
350
|
+
"elastic_only",
|
|
351
|
+
"bool",
|
|
352
|
+
False,
|
|
353
|
+
label="elasticity only",
|
|
354
|
+
doc="the elasticity of the nonlinear phases instead of their MFront laws",
|
|
355
|
+
),
|
|
356
|
+
Field("fields", "bool", False, doc="the stress and strain fields of every increment"),
|
|
357
|
+
Field(
|
|
358
|
+
"tolerance", "float", doc="convergence criterion, below 1e-3 (blank: AMITEX's, 1e-4)"
|
|
359
|
+
),
|
|
360
|
+
Field(
|
|
361
|
+
"processes", "int", 4, label="MPI processes", doc="of the script (NP=... overrides it)"
|
|
362
|
+
),
|
|
363
|
+
Field(
|
|
364
|
+
"library",
|
|
365
|
+
"str",
|
|
366
|
+
"",
|
|
367
|
+
label="library of the native laws",
|
|
368
|
+
doc="the path of libUmatAmitex.so (blank: found through AMITEX_PATH)",
|
|
369
|
+
),
|
|
370
|
+
Field("name", "str", "", doc="of the files (blank: the model of the morphology)"),
|
|
371
|
+
],
|
|
372
|
+
order=1,
|
|
373
|
+
menu="AMITEX_FFTP",
|
|
374
|
+
)
|
|
375
|
+
def amitex_inputs(p: dict, ctx) -> dict:
|
|
376
|
+
import json
|
|
377
|
+
|
|
378
|
+
from morphogen import io
|
|
379
|
+
from morphogen.homogenization.materials import any_oriented
|
|
380
|
+
|
|
381
|
+
item = p["source"]
|
|
382
|
+
micro = item["micro"]
|
|
383
|
+
name = _name(p["name"], item)
|
|
384
|
+
loading = p["loading"]
|
|
385
|
+
paths = {"path": _path(p)} if loading in ("path", "both") else {}
|
|
386
|
+
tolerance = p["tolerance"]
|
|
387
|
+
if tolerance is not None and not 0.0 < tolerance < 1e-3:
|
|
388
|
+
raise ValueError("tolerance: a positive number below 1e-3 (AMITEX)")
|
|
389
|
+
if p["processes"] < 1:
|
|
390
|
+
raise ValueError("MPI processes: at least one")
|
|
391
|
+
ctx.progress(0.05, "voxel image")
|
|
392
|
+
image = _image(micro, p["resolution"], "AMITEX image")
|
|
393
|
+
materials = _materials(p, np.unique(image.data))
|
|
394
|
+
grains = {}
|
|
395
|
+
orientations = getattr(micro, "orientations", None)
|
|
396
|
+
if any_oriented(materials) and orientations is not None and micro.has_labels:
|
|
397
|
+
grains = {"grains": micro.labels(grid=image.grid()).data, "orientations": orientations}
|
|
398
|
+
if not micro.domain.periodic:
|
|
399
|
+
warnings.warn(
|
|
400
|
+
f"{item['title']} is not periodic: AMITEX's FFT solver makes its image periodic",
|
|
401
|
+
stacklevel=2,
|
|
402
|
+
)
|
|
403
|
+
ctx.progress(0.3, "AMITEX files")
|
|
404
|
+
export = io.write_amitex(
|
|
405
|
+
ctx.folder,
|
|
406
|
+
image,
|
|
407
|
+
materials,
|
|
408
|
+
paths=paths,
|
|
409
|
+
stiffness=loading in ("stiffness", "both"),
|
|
410
|
+
name=name,
|
|
411
|
+
fields=p["fields"],
|
|
412
|
+
tolerance=tolerance,
|
|
413
|
+
library=p["library"] or "",
|
|
414
|
+
processes=p["processes"],
|
|
415
|
+
elastic_only=p["elastic_only"],
|
|
416
|
+
kinematics=p["kinematics"],
|
|
417
|
+
**grains,
|
|
418
|
+
)
|
|
419
|
+
manifest = json.loads((ctx.folder / f"{name}_amitex.json").read_text(encoding="utf-8"))
|
|
420
|
+
ctx.progress(0.8, "README and archive")
|
|
421
|
+
names = item.get("phases") or {}
|
|
422
|
+
rows = [
|
|
423
|
+
{
|
|
424
|
+
"material": m["material"],
|
|
425
|
+
"phase": m["phase"],
|
|
426
|
+
"name": names.get(str(m["phase"]), ""),
|
|
427
|
+
"law": m.get("law", ""),
|
|
428
|
+
"zones": m.get("zones", 1),
|
|
429
|
+
"MFront source": m.get("mfront", ""),
|
|
430
|
+
}
|
|
431
|
+
for m in manifest["materials"]
|
|
432
|
+
]
|
|
433
|
+
ctx.table(rows, "materials", "materials of the export")
|
|
434
|
+
if paths:
|
|
435
|
+
ctx.table(_segments(paths["path"]), "path", "segments of the loading path")
|
|
436
|
+
_section(ctx, image.data, "phase", "image", "x-y section of the image (phases)")
|
|
437
|
+
if grains:
|
|
438
|
+
_section(ctx, grains["grains"], "labels", "grains", "x-y section of the grains (zones)")
|
|
439
|
+
readme = _amitex_readme(item, export, manifest)
|
|
440
|
+
ctx.path("README.md").write_text(readme, encoding="utf-8")
|
|
441
|
+
values = {
|
|
442
|
+
"voxels": " x ".join(str(n) for n in manifest["shape"]),
|
|
443
|
+
"materials": len(manifest["materials"]),
|
|
444
|
+
"runs": ", ".join(manifest["runs"]),
|
|
445
|
+
"MFront laws": len(list((ctx.folder / "mfront").glob("*.mfront"))),
|
|
446
|
+
"kinematics": manifest["kinematics"],
|
|
447
|
+
}
|
|
448
|
+
if grains:
|
|
449
|
+
values["grains"] = len(np.unique(grains["grains"]))
|
|
450
|
+
return _finish(ctx, f"{name}_amitex", {"values": values, "text": readme})
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _amitex_readme(item: dict, export, manifest: dict) -> str:
|
|
454
|
+
name = export.name
|
|
455
|
+
script = (export.directory / f"{name}_run.sh").read_text(encoding="utf-8").splitlines()
|
|
456
|
+
commands = [line for line in script if "mfront --obuild" in line or line.startswith("mpirun")]
|
|
457
|
+
shape = " x ".join(str(n) for n in manifest["shape"])
|
|
458
|
+
spacing = ", ".join(f"{v:.6g}" for v in manifest["spacing"])
|
|
459
|
+
runs = ", ".join(f"{key} ({run['loading']})" for key, run in manifest["runs"].items())
|
|
460
|
+
laws = sorted({m["mfront"] for m in manifest["materials"] if "mfront" in m})
|
|
461
|
+
lines = [
|
|
462
|
+
f"# AMITEX_FFTP runs of {item['title']}",
|
|
463
|
+
"",
|
|
464
|
+
f"Written by morphoGen {manifest['morphogen']}, in {manifest['kinematics']} strains: "
|
|
465
|
+
f"the material and zone of each of the {shape} voxels (of {spacing}) in "
|
|
466
|
+
f"{name}_materials.vtk and {name}_zones.vtk, "
|
|
467
|
+
f"{_count(len(manifest['materials']), 'material')} in {name}_material.xml, the "
|
|
468
|
+
f"algorithm in {name}_algorithm.xml and a loading file per run: {runs}. "
|
|
469
|
+
f"{name}_amitex.json describes the export.",
|
|
470
|
+
"",
|
|
471
|
+
"## Run",
|
|
472
|
+
"",
|
|
473
|
+
"On a machine with AMITEX_FFTP and MPI (this folder, or its archive unzipped):",
|
|
474
|
+
"",
|
|
475
|
+
" source <AMITEX>/env_amitex.sh # AMITEX_PATH",
|
|
476
|
+
f" sh {name}_run.sh # NP=16 sh {name}_run.sh: 16 MPI processes",
|
|
477
|
+
"",
|
|
478
|
+
"The script runs, from its folder:",
|
|
479
|
+
"",
|
|
480
|
+
*[f" {line}" for line in commands],
|
|
481
|
+
"",
|
|
482
|
+
]
|
|
483
|
+
if laws:
|
|
484
|
+
lines += [
|
|
485
|
+
f"The MFront laws ({', '.join(laws)}) are compiled first by TFEL's mfront (on "
|
|
486
|
+
"the PATH) with the umat interface (mfront/src/libUmatBehaviour.so); their "
|
|
487
|
+
"internal variables start at zero.",
|
|
488
|
+
"",
|
|
489
|
+
]
|
|
490
|
+
lines += [
|
|
491
|
+
"## Results",
|
|
492
|
+
"",
|
|
493
|
+
f"AMITEX writes the averages of each run in results/{name}_<run>.std (per material: "
|
|
494
|
+
".mstd, per zone: .zstd; the fields: .vtk). Read them back with the tool AMITEX_FFTP "
|
|
495
|
+
"results of the tab Solvers & formats (the path of this folder), or",
|
|
496
|
+
"",
|
|
497
|
+
" morphogen amitex read <this folder>",
|
|
498
|
+
"",
|
|
499
|
+
"which gives the averages of the runs and the apparent stiffness of the unit strains "
|
|
500
|
+
"with its moduli. AMITEX orders the components xx, yy, zz, xy, xz, yz (engineering "
|
|
501
|
+
"shear strains), morphoGen 11, 22, 33, 23, 31, 12.",
|
|
502
|
+
]
|
|
503
|
+
return "\n".join(lines) + "\n"
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
@tool(
|
|
507
|
+
"amitex_results",
|
|
508
|
+
"interop",
|
|
509
|
+
"AMITEX_FFTP results",
|
|
510
|
+
"The results of the runs of an AMITEX_FFTP export, read back from its folder (the "
|
|
511
|
+
"averages of each run over the unit cell, in morphoGen's components; the apparent "
|
|
512
|
+
"stiffness of the six unit strains, its moduli and engineering constants; the averages "
|
|
513
|
+
"of the materials), or of a single run (its .std file).",
|
|
514
|
+
[
|
|
515
|
+
Field(
|
|
516
|
+
"directory",
|
|
517
|
+
"str",
|
|
518
|
+
required=True,
|
|
519
|
+
label="folder of the export",
|
|
520
|
+
doc="where <name>_amitex.json is, with results/ after the runs; or a .std file",
|
|
521
|
+
browse="folder",
|
|
522
|
+
),
|
|
523
|
+
Field("name", "str", "", label="name of the export", doc="blank: the only export there"),
|
|
524
|
+
],
|
|
525
|
+
order=2,
|
|
526
|
+
menu="AMITEX_FFTP",
|
|
527
|
+
)
|
|
528
|
+
def amitex_results(p: dict, ctx) -> dict:
|
|
529
|
+
from morphogen import io
|
|
530
|
+
|
|
531
|
+
target = Path(str(p["directory"]).strip().strip('"')).expanduser()
|
|
532
|
+
if target.suffix == ".std":
|
|
533
|
+
if not target.is_file():
|
|
534
|
+
raise ValueError(f"no file {target}")
|
|
535
|
+
prefix = target.with_suffix("")
|
|
536
|
+
runs = {prefix.name: (io.read_amitex(prefix), prefix)}
|
|
537
|
+
kinds = {prefix.name: "stiffness" if prefix.name.endswith("_stiffness") else "path"}
|
|
538
|
+
stiffness, properties, missing = None, {}, []
|
|
539
|
+
else:
|
|
540
|
+
if not target.is_dir():
|
|
541
|
+
raise ValueError(f"no folder {target}")
|
|
542
|
+
run = io.read_amitex_run(target, p["name"] or None)
|
|
543
|
+
manifest = run.manifest
|
|
544
|
+
runs = {k: (r, target / manifest["runs"][k]["results"]) for k, r in run.results.items()}
|
|
545
|
+
kinds = {k: v["kind"] for k, v in manifest["runs"].items()}
|
|
546
|
+
stiffness, properties = run.stiffness, run.properties
|
|
547
|
+
missing = sorted(set(manifest["runs"]) - set(run.results))
|
|
548
|
+
if not runs:
|
|
549
|
+
raise ValueError(
|
|
550
|
+
f"no results yet in {target / 'results'} (runs {', '.join(manifest['runs'])}): "
|
|
551
|
+
f"run {manifest['name']}_run.sh there first"
|
|
552
|
+
)
|
|
553
|
+
if missing:
|
|
554
|
+
warnings.warn(f"runs without results: {', '.join(missing)}", stacklevel=2)
|
|
555
|
+
if stiffness is not None: # in morphoGen's order (read_amitex turns AMITEX's xy, xz, yz)
|
|
556
|
+
elastic_tables(ctx, stiffness, "(AMITEX_FFTP)", kind="apparent")
|
|
557
|
+
for k, (key, (res, prefix)) in enumerate(runs.items()):
|
|
558
|
+
ctx.progress(k / len(runs), key)
|
|
559
|
+
_amitex_run(ctx, key, res, prefix, kinds.get(key) != "stiffness")
|
|
560
|
+
values = {k: float(v) for k, v in properties.items()}
|
|
561
|
+
values["runs"] = ", ".join(runs)
|
|
562
|
+
return {"values": values}
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def _amitex_run(ctx, key: str, res, prefix: Path, curves: bool) -> None:
|
|
566
|
+
"""The tables of the averages of a run (of its materials too, when AMITEX wrote them)
|
|
567
|
+
and the stress-strain curves of the components that vary along it (``curves``)."""
|
|
568
|
+
from morphogen.io.amitex import read_amitex_materials
|
|
569
|
+
|
|
570
|
+
finite = res.kinematics == "finite"
|
|
571
|
+
names = ("11", "22", "33", "23", "13", "12") if finite else VOIGT
|
|
572
|
+
strain, stress = ("H", "P") if finite else ("E", "S")
|
|
573
|
+
stem = _name(key) # the names of the files of the result
|
|
574
|
+
|
|
575
|
+
def columns(r, step):
|
|
576
|
+
out = {strain + c: float(r.strain[step, i]) for i, c in enumerate(names)}
|
|
577
|
+
out.update({stress + c: float(r.stress[step, i]) for i, c in enumerate(names)})
|
|
578
|
+
return out
|
|
579
|
+
|
|
580
|
+
rows = []
|
|
581
|
+
for step, t in enumerate(res.times):
|
|
582
|
+
row = {"time": float(t), **columns(res, step)}
|
|
583
|
+
if res.iterations is not None:
|
|
584
|
+
row["iterations"] = int(res.iterations[step])
|
|
585
|
+
rows.append(row)
|
|
586
|
+
ctx.table(rows, f"run_{stem}", f"averages of the run {key}")
|
|
587
|
+
if (prefix.parent / f"{prefix.name}.mstd").exists():
|
|
588
|
+
per = read_amitex_materials(prefix, kinematics=res.kinematics)
|
|
589
|
+
rows = [
|
|
590
|
+
{"material": m, "time": float(r.times[-1]), **columns(r, -1)} for m, r in per.items()
|
|
591
|
+
]
|
|
592
|
+
ctx.table(rows, f"materials_{stem}", f"averages of the materials at the end of {key}")
|
|
593
|
+
if not curves:
|
|
594
|
+
return
|
|
595
|
+
try:
|
|
596
|
+
from matplotlib.figure import Figure
|
|
597
|
+
except ImportError: # an optional dependency: the tables only
|
|
598
|
+
warnings.warn("no curves without matplotlib: pip install 'morphogen[plot]'", stacklevel=2)
|
|
599
|
+
return
|
|
600
|
+
fig = Figure(figsize=(5.4, 3.8), layout="constrained")
|
|
601
|
+
ax = fig.subplots()
|
|
602
|
+
for i, c in enumerate(names):
|
|
603
|
+
if np.ptp(res.strain[:, i]) > 0 or np.ptp(res.stress[:, i]) > 0:
|
|
604
|
+
ax.plot(res.strain[:, i], res.stress[:, i], marker=".", lw=1.4, label=c)
|
|
605
|
+
ax.set_xlabel(f"{strain}ij")
|
|
606
|
+
ax.set_ylabel(f"{stress}ij")
|
|
607
|
+
ax.set_title(f"run {key}", fontsize=10)
|
|
608
|
+
ax.grid(alpha=0.3)
|
|
609
|
+
if ax.lines:
|
|
610
|
+
ax.legend(fontsize=8, frameon=False)
|
|
611
|
+
ctx.figure(fig, f"curves_{stem}", f"stress-strain curves of {key}")
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
# -- Abaqus ----------------------------------------------------------------------------------
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
@tool(
|
|
618
|
+
"abaqus_input",
|
|
619
|
+
"interop",
|
|
620
|
+
"Abaqus input",
|
|
621
|
+
"The input of Abaqus for a morphology: its conforming mesh (tetrahedra; the grains of "
|
|
622
|
+
"tessellations) or voxel mesh (hexahedra), the materials of its phases (*ELASTIC, "
|
|
623
|
+
"isotropic or anisotropic in the axes of the crystal of each grain with its "
|
|
624
|
+
"*ORIENTATION; the nonlinear behaviours, and every phase in finite strains, MFront laws "
|
|
625
|
+
"of the abaqus interface, their sources in <name>_mfront/), the periodic equations of "
|
|
626
|
+
"the reference nodes REF_X, REF_Y, REF_Z (uniform strains on the faces, KUBC, when the "
|
|
627
|
+
"morphology is not periodic) and a step per segment of a loading path.",
|
|
628
|
+
[
|
|
629
|
+
Field("source", "item", label="morphology", required=True),
|
|
630
|
+
Field(
|
|
631
|
+
"mesh",
|
|
632
|
+
"choice",
|
|
633
|
+
"conforming",
|
|
634
|
+
choices=(
|
|
635
|
+
("conforming", "conforming tetrahedra (the grains of tessellations)"),
|
|
636
|
+
("voxels", "voxels: 8-node hexahedra"),
|
|
637
|
+
),
|
|
638
|
+
),
|
|
639
|
+
Field(
|
|
640
|
+
"element_size",
|
|
641
|
+
"float",
|
|
642
|
+
unit="length",
|
|
643
|
+
when={"mesh": "conforming"},
|
|
644
|
+
doc="the largest element (blank: 1/12 of the longest edge)",
|
|
645
|
+
),
|
|
646
|
+
Field(
|
|
647
|
+
"order",
|
|
648
|
+
"choice",
|
|
649
|
+
"1",
|
|
650
|
+
when={"mesh": "conforming"},
|
|
651
|
+
choices=(("1", "linear: C3D4"), ("2", "quadratic: C3D10")),
|
|
652
|
+
),
|
|
653
|
+
Field(
|
|
654
|
+
"resolution",
|
|
655
|
+
"int",
|
|
656
|
+
24,
|
|
657
|
+
label="voxels per edge",
|
|
658
|
+
when={"mesh": "voxels"},
|
|
659
|
+
doc=f"of the voxel mesh (at most {MAX_VOXEL_MESH})",
|
|
660
|
+
),
|
|
661
|
+
Field("materials", "materials", of="source"),
|
|
662
|
+
Field("behaviours", "json", label="behaviours of the phases", doc=BEHAVIOURS_DOC),
|
|
663
|
+
*KEPT_FIELDS,
|
|
664
|
+
Field("kinematics", "choice", "small", choices=KINEMATICS),
|
|
665
|
+
Field(
|
|
666
|
+
"loading",
|
|
667
|
+
"choice",
|
|
668
|
+
"path",
|
|
669
|
+
label="steps",
|
|
670
|
+
choices=(
|
|
671
|
+
("path", "a loading path: a step per segment"),
|
|
672
|
+
("none", "none: the model only (mesh, materials, equations)"),
|
|
673
|
+
),
|
|
674
|
+
),
|
|
675
|
+
*_path_fields({"loading": "path"}),
|
|
676
|
+
Field("name", "str", "", doc="of the files (blank: the model of the morphology)"),
|
|
677
|
+
],
|
|
678
|
+
order=3,
|
|
679
|
+
menu="Abaqus and meshes",
|
|
680
|
+
)
|
|
681
|
+
def abaqus_input(p: dict, ctx) -> dict:
|
|
682
|
+
from morphogen import io
|
|
683
|
+
|
|
684
|
+
item = p["source"]
|
|
685
|
+
micro = item["micro"]
|
|
686
|
+
name = _name(p["name"], item)
|
|
687
|
+
kinematics = p["kinematics"]
|
|
688
|
+
path = _path(p) if p["loading"] == "path" else None
|
|
689
|
+
target = ctx.path(f"{name}.inp")
|
|
690
|
+
ctx.progress(0.05, "mesh")
|
|
691
|
+
mesh, materials, element = _abaqus_mesh(p, item, target, ctx)
|
|
692
|
+
ctx.progress(0.6, "boundary conditions")
|
|
693
|
+
lower = np.asarray(micro.domain.lower, dtype=float)
|
|
694
|
+
lengths = np.asarray(micro.domain.lengths, dtype=float)
|
|
695
|
+
periodic, equations = False, 0
|
|
696
|
+
if micro.domain.periodic:
|
|
697
|
+
scratch = ctx.path(f"{name}_equations.inp")
|
|
698
|
+
try:
|
|
699
|
+
io.write_periodic_equations(scratch, mesh)
|
|
700
|
+
except ValueError as exc:
|
|
701
|
+
warnings.warn(
|
|
702
|
+
f"no periodic equations ({exc}): the faces under uniform strains (KUBC)",
|
|
703
|
+
stacklevel=2,
|
|
704
|
+
)
|
|
705
|
+
else:
|
|
706
|
+
text = scratch.read_text(encoding="ascii")
|
|
707
|
+
equations = text.count("*EQUATION")
|
|
708
|
+
with target.open("a", encoding="ascii", newline="\n") as f:
|
|
709
|
+
f.write(text)
|
|
710
|
+
periodic = True
|
|
711
|
+
finally:
|
|
712
|
+
scratch.unlink(missing_ok=True)
|
|
713
|
+
if path is not None:
|
|
714
|
+
# the nodes start at 293.15 K when a material expands: the steps keep them there (the
|
|
715
|
+
# paths have no change of temperature), CalculiX failing on a step without one
|
|
716
|
+
initial = re.search(r"^\*INITIAL CONDITIONS, TYPE=TEMPERATURE\n(.+)$",
|
|
717
|
+
target.read_text(encoding="ascii"), re.MULTILINE) # fmt: skip
|
|
718
|
+
with target.open("a", encoding="ascii", newline="\n") as f:
|
|
719
|
+
f.write(_abaqus_steps(path, mesh, kinematics, periodic, lower, lengths,
|
|
720
|
+
initial.group(1) if initial else None)) # fmt: skip
|
|
721
|
+
ctx.table(_segments(path), "steps", "steps of the loading path")
|
|
722
|
+
finite = kinematics == "finite"
|
|
723
|
+
names = item.get("phases") or {}
|
|
724
|
+
rows = []
|
|
725
|
+
for q, m in materials.items():
|
|
726
|
+
if m.nonlinear or finite:
|
|
727
|
+
kind = "MFront law (abaqus interface)"
|
|
728
|
+
elif m.stiffness is not None:
|
|
729
|
+
kind = "elastic, anisotropic in the axes of the crystal"
|
|
730
|
+
else:
|
|
731
|
+
kind = "elastic, isotropic"
|
|
732
|
+
rows.append({"phase": q, "name": names.get(str(q), ""), "material": kind})
|
|
733
|
+
ctx.table(rows, "materials", "materials of the phases (the voids have no element)")
|
|
734
|
+
laws = sorted(f.name for f in (ctx.folder / f"{name}_mfront").glob("*.mfront"))
|
|
735
|
+
if periodic:
|
|
736
|
+
conditions = "periodic equations"
|
|
737
|
+
else:
|
|
738
|
+
conditions = "KUBC (the faces)" if path is not None else "none"
|
|
739
|
+
readme = _abaqus_readme(item, target, mesh, element, conditions, equations, path, laws, finite)
|
|
740
|
+
ctx.path("README.md").write_text(readme, encoding="utf-8")
|
|
741
|
+
values = {
|
|
742
|
+
"nodes": int(mesh.n_nodes),
|
|
743
|
+
"elements": int(mesh.n_elements),
|
|
744
|
+
"element type": element,
|
|
745
|
+
"boundary conditions": conditions,
|
|
746
|
+
"equations": equations,
|
|
747
|
+
"steps": 0 if path is None else len(path.times) - 1,
|
|
748
|
+
"MFront laws": len(laws),
|
|
749
|
+
}
|
|
750
|
+
cells = getattr(mesh, "cell", None)
|
|
751
|
+
cells = getattr(mesh, "label", None) if cells is None else cells
|
|
752
|
+
if cells is not None:
|
|
753
|
+
values["grains"] = len(np.unique(cells))
|
|
754
|
+
return _finish(ctx, f"{name}_abaqus", {"values": values, "text": readme})
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def _abaqus_mesh(p: dict, item: dict, target: Path, ctx):
|
|
758
|
+
"""The mesh of the tool Abaqus input written to ``target`` with the materials of its
|
|
759
|
+
phases (the voids left out): its mesh, its materials and its type of elements."""
|
|
760
|
+
from morphogen import io
|
|
761
|
+
from morphogen.homogenization.materials import any_oriented
|
|
762
|
+
|
|
763
|
+
micro = item["micro"]
|
|
764
|
+
kinematics = p["kinematics"]
|
|
765
|
+
if p["mesh"] == "voxels":
|
|
766
|
+
from morphogen.mesh.voxel import voxel_mesh
|
|
767
|
+
|
|
768
|
+
image = _image(micro, p["resolution"], "voxel mesh", MAX_VOXEL_MESH)
|
|
769
|
+
materials = _materials(p, np.unique(image.data))
|
|
770
|
+
solid = sorted(q for q, m in materials.items() if not m.void)
|
|
771
|
+
if not solid:
|
|
772
|
+
raise ValueError("every phase is void")
|
|
773
|
+
labels = micro.labels(grid=image.grid()) if micro.has_labels else None
|
|
774
|
+
mesh = voxel_mesh(image, None if len(solid) == len(materials) else solid, labels=labels)
|
|
775
|
+
orientations = getattr(micro, "orientations", None)
|
|
776
|
+
oriented = labels is not None and orientations is not None and any_oriented(materials)
|
|
777
|
+
ctx.progress(0.4, "Abaqus input")
|
|
778
|
+
io.write_inp(
|
|
779
|
+
target,
|
|
780
|
+
mesh,
|
|
781
|
+
materials=materials,
|
|
782
|
+
kinematics=kinematics,
|
|
783
|
+
label_sets=labels is not None,
|
|
784
|
+
orientations=orientations if oriented else None,
|
|
785
|
+
)
|
|
786
|
+
return mesh, {q: materials[q] for q in solid}, "C3D8"
|
|
787
|
+
candidates = {int(k) for k in (item.get("phases") or {})} | {0, 1}
|
|
788
|
+
candidates |= {int(k) for k in (p.get("materials") or {})}
|
|
789
|
+
materials = _materials(p, candidates, required=False)
|
|
790
|
+
mesh = _conforming(micro, p, materials)
|
|
791
|
+
present = sorted(set(np.unique(mesh.phase).tolist()))
|
|
792
|
+
missing = [q for q in present if q not in materials]
|
|
793
|
+
if missing:
|
|
794
|
+
raise ValueError(f"phases {missing}: no material (give their elastic constants)")
|
|
795
|
+
materials = {q: materials[q] for q in present}
|
|
796
|
+
ctx.progress(0.4, "Abaqus input")
|
|
797
|
+
io.write_inp_tet(target, mesh, materials=materials, kinematics=kinematics)
|
|
798
|
+
return mesh, materials, "C3D4" if mesh.order == 1 else "C3D10"
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def _faces(mesh) -> list[str]:
|
|
802
|
+
"""The node sets of the upper faces of a mesh that it writes (those with nodes)."""
|
|
803
|
+
if hasattr(mesh, "node_sets"):
|
|
804
|
+
return [k.upper() for k in ("x1", "y1", "z1") if len(mesh.node_sets.get(k, ()))]
|
|
805
|
+
return [f"{'XYZ'[a]}1" for a in range(3) if mesh.face_nodes(a, 1).size]
|
|
806
|
+
|
|
807
|
+
|
|
808
|
+
def _abaqus_steps(path, mesh, kinematics: str, periodic: bool, lower, lengths,
|
|
809
|
+
temperature: str | None = None) -> str: # fmt: skip
|
|
810
|
+
"""The steps of a loading path, one per segment: on the reference nodes of the
|
|
811
|
+
periodic equations (their rotation and a corner fixed; strains as displacements,
|
|
812
|
+
stresses as forces), or on the nodes of the faces (KUBC: strains only).
|
|
813
|
+
``temperature``: the data line of ``*TEMPERATURE`` in each step (the nodes at their
|
|
814
|
+
initial temperature when a material expands; CalculiX asks each step for one)."""
|
|
815
|
+
if not periodic and not all(path.controls):
|
|
816
|
+
raise ValueError(
|
|
817
|
+
"stresses: the reference nodes of the periodic equations (a periodic morphology); "
|
|
818
|
+
"the faces under uniform strains (KUBC) take strains only"
|
|
819
|
+
)
|
|
820
|
+
area = np.prod(lengths) / lengths
|
|
821
|
+
boundary = None
|
|
822
|
+
if not periodic:
|
|
823
|
+
if hasattr(mesh, "boundary_nodes"):
|
|
824
|
+
boundary = mesh.boundary_nodes()
|
|
825
|
+
else:
|
|
826
|
+
boundary = np.unique(np.concatenate(list(mesh.node_sets.values())))
|
|
827
|
+
nlgeom = "YES" if kinematics == "finite" else "NO"
|
|
828
|
+
lines = [
|
|
829
|
+
"**",
|
|
830
|
+
"** the loading path: the macroscopic displacement gradient H, upper triangular (the",
|
|
831
|
+
"** strains, engineering shears in small strains), and the mean stresses",
|
|
832
|
+
]
|
|
833
|
+
for k in range(len(path.times) - 1):
|
|
834
|
+
t0, t1, n = path.times[k], path.times[k + 1], path.increments[k]
|
|
835
|
+
period = t1 - t0
|
|
836
|
+
dt = period / n
|
|
837
|
+
values = path.values[k + 1]
|
|
838
|
+
lines += [
|
|
839
|
+
"**",
|
|
840
|
+
f"** segment {k + 1}: from t = {t0:g} to {t1:g}, {n} increments",
|
|
841
|
+
f"*STEP, NAME=SEGMENT_{k + 1}, NLGEOM={nlgeom}, INC={max(100, 10 * n)}",
|
|
842
|
+
"*STATIC",
|
|
843
|
+
f"{dt:.9g}, {period:.9g}, {dt * 1e-5:.9g}, {dt:.9g}",
|
|
844
|
+
"*BOUNDARY",
|
|
845
|
+
]
|
|
846
|
+
if periodic:
|
|
847
|
+
lines += ["CORNER, 1, 3, 0.", "REF_X, 2, 3, 0.", "REF_Y, 3, 3, 0."]
|
|
848
|
+
loads = []
|
|
849
|
+
for (i, j), value, strain in zip(GRADIENT, values, path.controls, strict=True):
|
|
850
|
+
if strain:
|
|
851
|
+
lines.append(f"{REFERENCES[j]}, {i + 1}, {i + 1}, {value * lengths[j]:.12g}")
|
|
852
|
+
else:
|
|
853
|
+
loads.append(f"{REFERENCES[j]}, {i + 1}, {value * area[j]:.12g}")
|
|
854
|
+
if loads:
|
|
855
|
+
lines += ["*CLOAD", *loads]
|
|
856
|
+
else:
|
|
857
|
+
h = np.zeros((3, 3))
|
|
858
|
+
for (i, j), value in zip(GRADIENT, values, strict=True):
|
|
859
|
+
h[i, j] = value
|
|
860
|
+
u = (np.asarray(mesh.nodes)[boundary] - lower) @ h.T
|
|
861
|
+
for node, row in zip(boundary, u, strict=True):
|
|
862
|
+
lines += [f"{node + 1}, {i + 1}, {i + 1}, {row[i]:.12g}" for i in range(3)]
|
|
863
|
+
if temperature:
|
|
864
|
+
lines += ["*TEMPERATURE", temperature]
|
|
865
|
+
lines.append("*OUTPUT, FIELD, VARIABLE=PRESELECT")
|
|
866
|
+
if periodic:
|
|
867
|
+
for ref in REFERENCES:
|
|
868
|
+
lines += [f"*NODE PRINT, NSET={ref}", "U, RF"]
|
|
869
|
+
else:
|
|
870
|
+
for face in _faces(mesh):
|
|
871
|
+
lines += [f"*NODE PRINT, NSET={face}, TOTALS=YES", "RF"]
|
|
872
|
+
lines.append("*END STEP")
|
|
873
|
+
return "\n".join(lines) + "\n"
|
|
874
|
+
|
|
875
|
+
|
|
876
|
+
def _abaqus_readme(item, target: Path, mesh, element, conditions, equations, path, laws, finite):
|
|
877
|
+
"""The README of an Abaqus input (``target``)."""
|
|
878
|
+
name = target.stem
|
|
879
|
+
steps = 0 if path is None else len(path.times) - 1
|
|
880
|
+
text = target.read_text(encoding="ascii")
|
|
881
|
+
sets = "PHASE_<p>"
|
|
882
|
+
if "*ELSET, ELSET=CELL_" in text:
|
|
883
|
+
sets += " and CELL_<c> (the grains"
|
|
884
|
+
sets += ", their orientations ORI_<c>)" if "*ORIENTATION" in text else ")"
|
|
885
|
+
if getattr(mesh, "whole", False):
|
|
886
|
+
faces = "OUTER, the boundary of the whole periodic cells"
|
|
887
|
+
else:
|
|
888
|
+
faces = "of the faces X0, X1, Y0, Y1, Z0, Z1"
|
|
889
|
+
lines = [
|
|
890
|
+
f"# Abaqus input of {item['title']}",
|
|
891
|
+
"",
|
|
892
|
+
f"{name}.inp: {mesh.n_nodes} nodes, {mesh.n_elements} {element} elements in the "
|
|
893
|
+
f"element sets {sets}, the materials and their solid sections (the voids have no "
|
|
894
|
+
f"element), the node sets {faces}"
|
|
895
|
+
+ (f", {equations} periodic equations" if equations else "")
|
|
896
|
+
+ f", {_count(steps, 'step')}.",
|
|
897
|
+
"",
|
|
898
|
+
"## Run",
|
|
899
|
+
"",
|
|
900
|
+
]
|
|
901
|
+
if laws:
|
|
902
|
+
lines += [
|
|
903
|
+
f"The {'' if finite else 'nonlinear '}materials are MFront laws ({name}_mfront/: "
|
|
904
|
+
f"{', '.join(laws)}); compile them with TFEL, then run with the umat of MFront "
|
|
905
|
+
"from this folder (the laws read their <behaviour>-parameters.txt there):",
|
|
906
|
+
"",
|
|
907
|
+
f" cd {name}_mfront && mfront --obuild --interface=abaqus {' '.join(laws)} && cd ..",
|
|
908
|
+
f" export LD_LIBRARY_PATH=$PWD/{name}_mfront/src:$LD_LIBRARY_PATH",
|
|
909
|
+
f" abaqus job={name} input={name}.inp "
|
|
910
|
+
"user=<TFEL>/share/doc/mfront/abaqus/umat.cpp interactive",
|
|
911
|
+
]
|
|
912
|
+
else:
|
|
913
|
+
lines.append(f" abaqus job={name} input={name}.inp interactive")
|
|
914
|
+
calculix = (
|
|
915
|
+
f"CalculiX (ccx -i {name}) reads it as well with its elastic materials (it ignores "
|
|
916
|
+
"the parameter NAME of *STEP and those of *OUTPUT)"
|
|
917
|
+
)
|
|
918
|
+
if conditions == "periodic equations":
|
|
919
|
+
calculix += (
|
|
920
|
+
", but its reaction forces leave out those of the equations: average the "
|
|
921
|
+
"stresses of the elements instead (*EL PRINT: S, with EVOL for their volumes)"
|
|
922
|
+
)
|
|
923
|
+
lines += ["", calculix + ".", "", "## Loading", ""]
|
|
924
|
+
mean = "the mean nominal stresses" if finite else "the mean stresses"
|
|
925
|
+
if conditions == "periodic equations":
|
|
926
|
+
lines.append(
|
|
927
|
+
"The periodic equations tie each node of the upper faces to its image and to the "
|
|
928
|
+
"reference nodes REF_X, REF_Y, REF_Z: u_i(REF_j) = H_ij L_j, H the macroscopic "
|
|
929
|
+
"displacement gradient, upper triangular (its rotation fixed: REF_X 2 and 3, "
|
|
930
|
+
"REF_Y 3), and CORNER is fixed. A strain prescribes the displacement of a "
|
|
931
|
+
"reference node, a stress the force A_j S_ij on it (A_j: the area of the face "
|
|
932
|
+
f"normal to j); in Abaqus, their reaction forces over A_j are {mean} (*NODE PRINT "
|
|
933
|
+
"of REF_X, REF_Y, REF_Z)."
|
|
934
|
+
)
|
|
935
|
+
elif conditions != "none":
|
|
936
|
+
lines.append(
|
|
937
|
+
"The nodes of the faces of the box follow the uniform strain u = H (x - x0) "
|
|
938
|
+
f"(KUBC); the total reaction forces of the faces X1, Y1, Z1 over their areas are "
|
|
939
|
+
f"{mean}."
|
|
940
|
+
)
|
|
941
|
+
else:
|
|
942
|
+
lines.append("No step: add yours after the model.")
|
|
943
|
+
if path is not None:
|
|
944
|
+
lines += [
|
|
945
|
+
"",
|
|
946
|
+
"Components: morphoGen's (11, 22, 33, 23, 31, 12; engineering shears in small "
|
|
947
|
+
"strains, the gradient in finite strains, NLGEOM=YES); a step per segment of the "
|
|
948
|
+
"path, its times as the times of the steps.",
|
|
949
|
+
]
|
|
950
|
+
return "\n".join(lines) + "\n"
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
# -- other formats ---------------------------------------------------------------------------
|
|
954
|
+
|
|
955
|
+
FORMATS = (
|
|
956
|
+
("msh", "Gmsh .msh: the conforming mesh"),
|
|
957
|
+
("medit", "Medit .mesh (MMG): the conforming mesh"),
|
|
958
|
+
("xdmf", "FEniCSx .xdmf: the conforming mesh, its cell and facet tags"),
|
|
959
|
+
("pairs", "periodic node pairs .csv of the conforming mesh"),
|
|
960
|
+
("voxel_msh", "Gmsh .msh: the voxel mesh (hexahedra)"),
|
|
961
|
+
("voxel_pairs", "periodic node pairs .csv of the voxel mesh"),
|
|
962
|
+
("neper", "Neper: the seeds, weights and orientations of a tessellation, its command"),
|
|
963
|
+
("damask", "DAMASK: the grid .vti and material.yaml of a polycrystal"),
|
|
964
|
+
("tif", "TIFF stack: a page per z section"),
|
|
965
|
+
("mhd", "MetaImage: .mhd header and .raw data"),
|
|
966
|
+
)
|
|
967
|
+
_CONFORMING = {"msh", "medit", "xdmf", "pairs"}
|
|
968
|
+
_VOXELS = {"voxel_msh", "voxel_pairs", "damask", "tif", "mhd"}
|
|
969
|
+
_NOTES = {
|
|
970
|
+
"msh": "Gmsh 2.2 (ASCII): the physical volumes phase_<p> (tag p + 1; the elementary "
|
|
971
|
+
"tag: the grain + 1), the physical surfaces x0 ... z1 (tags 101-106) or outer (107: "
|
|
972
|
+
"the boundary of whole periodic cells); Gmsh, meshio, Code_Aster, Elmer",
|
|
973
|
+
"mesh": "Medit (MMG): the tetrahedra of reference phase + 1 (grain + 1), the boundary "
|
|
974
|
+
"triangles 1-6 (faces x0, x1, ..., z1) or 1 (whole cells); MMG, meshio, FreeFEM",
|
|
975
|
+
"xdmf": 'FEniCSx: XDMFFile(MPI.COMM_WORLD, path, "r"), read_mesh(name="mesh"), '
|
|
976
|
+
'read_meshtags(mesh, name="phase") (and "grain"), the facets "faces" (1-6: x0 ... z1)',
|
|
977
|
+
"csv": "periodic node pairs (1-based ids, as in .msh and .inp files): axis, the node on "
|
|
978
|
+
"the lower face, the node on the upper face; whole periodic cells: node, image and shift "
|
|
979
|
+
"(x_node = x_image + shift * edges)",
|
|
980
|
+
"neper": "Neper: sh <name>_neper.sh builds the tessellation (-morphooptiini from the "
|
|
981
|
+
"seeds and weights, the orientations as Bunge angles)",
|
|
982
|
+
"damask": "DAMASK: DAMASK_grid --geom <name>_damask.vti --material "
|
|
983
|
+
"<name>_damask_material.yaml --load <load>.yaml (complete the phases of the material "
|
|
984
|
+
"file: lattice, elastic and plastic behaviours)",
|
|
985
|
+
"tif": "TIFF stack (ImageJ, Fiji: a page per z section, the voxel size in its metadata)",
|
|
986
|
+
"mhd": "MetaImage: ITK, ParaView, Fiji, 3D Slicer (the .mhd header, the .raw data)",
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
|
|
990
|
+
@tool(
|
|
991
|
+
"mesh_formats",
|
|
992
|
+
"interop",
|
|
993
|
+
"Meshes and images in other formats",
|
|
994
|
+
"The meshes and images of a morphology in the formats of other programs: its "
|
|
995
|
+
"conforming mesh (Gmsh, Medit, FEniCSx; its periodic node pairs), its voxel mesh "
|
|
996
|
+
"(Gmsh, periodic node pairs), the files of Neper (tessellations) and DAMASK "
|
|
997
|
+
"(polycrystals), its voxel image as a TIFF stack or a MetaImage.",
|
|
998
|
+
[
|
|
999
|
+
Field("source", "item", label="morphology", required=True),
|
|
1000
|
+
Field("formats", "choices", ["msh", "mhd"], choices=FORMATS),
|
|
1001
|
+
Field(
|
|
1002
|
+
"element_size",
|
|
1003
|
+
"float",
|
|
1004
|
+
unit="length",
|
|
1005
|
+
doc="conforming meshes: the largest element (blank: 1/12 of the longest edge)",
|
|
1006
|
+
),
|
|
1007
|
+
Field(
|
|
1008
|
+
"order",
|
|
1009
|
+
"choice",
|
|
1010
|
+
"1",
|
|
1011
|
+
choices=(("1", "linear tetrahedra"), ("2", "quadratic tetrahedra (Gmsh)")),
|
|
1012
|
+
),
|
|
1013
|
+
Field(
|
|
1014
|
+
"resolution",
|
|
1015
|
+
"int",
|
|
1016
|
+
64,
|
|
1017
|
+
label="voxels per edge",
|
|
1018
|
+
doc=f"images and voxel meshes (voxel meshes: at most {MAX_VOXEL_MESH})",
|
|
1019
|
+
),
|
|
1020
|
+
Field(
|
|
1021
|
+
"image",
|
|
1022
|
+
"choice",
|
|
1023
|
+
"phases",
|
|
1024
|
+
label="image of",
|
|
1025
|
+
choices=(
|
|
1026
|
+
("phases", "the phases (8 bits)"),
|
|
1027
|
+
("labels", "the cells of tessellations and grain structures (16 or 32 bits)"),
|
|
1028
|
+
(
|
|
1029
|
+
"level_set",
|
|
1030
|
+
"the level set (32-bit floats; the implicit function of each phase of a "
|
|
1031
|
+
"morphology of several phases, one file per phase)",
|
|
1032
|
+
),
|
|
1033
|
+
),
|
|
1034
|
+
),
|
|
1035
|
+
],
|
|
1036
|
+
order=4,
|
|
1037
|
+
menu="Abaqus and meshes",
|
|
1038
|
+
)
|
|
1039
|
+
def mesh_formats(p: dict, ctx) -> dict:
|
|
1040
|
+
from morphogen import io
|
|
1041
|
+
from morphogen.models.tessellation import Tessellation
|
|
1042
|
+
|
|
1043
|
+
item = p["source"]
|
|
1044
|
+
micro = item["micro"]
|
|
1045
|
+
name = _name("", item)
|
|
1046
|
+
chosen = set(p["formats"] or [])
|
|
1047
|
+
if not chosen:
|
|
1048
|
+
raise ValueError("formats: choose at least one")
|
|
1049
|
+
orientations = getattr(micro, "orientations", None)
|
|
1050
|
+
if "neper" in chosen and not isinstance(micro, Tessellation):
|
|
1051
|
+
raise ValueError("Neper: the seeds of tessellations (Voronoi, Laguerre)")
|
|
1052
|
+
if "damask" in chosen and (not micro.has_labels or orientations is None):
|
|
1053
|
+
raise ValueError("DAMASK: polycrystals (tessellations with crystal orientations)")
|
|
1054
|
+
images = {"tif", "mhd"} & chosen
|
|
1055
|
+
if images and p["image"] == "labels" and not micro.has_labels:
|
|
1056
|
+
raise ValueError("image of the cells: tessellations and grain structures only")
|
|
1057
|
+
values: dict = {}
|
|
1058
|
+
notes: list[tuple[str, str]] = []
|
|
1059
|
+
if _CONFORMING & chosen:
|
|
1060
|
+
ctx.progress(0.05, "conforming mesh")
|
|
1061
|
+
mesh = _conforming(micro, p)
|
|
1062
|
+
values.update({"mesh nodes": int(mesh.n_nodes), "mesh elements": int(mesh.n_elements)})
|
|
1063
|
+
if "msh" in chosen:
|
|
1064
|
+
io.write_msh_tet(ctx.path(f"{name}.msh"), mesh)
|
|
1065
|
+
notes.append((f"{name}.msh", _NOTES["msh"]))
|
|
1066
|
+
if "medit" in chosen:
|
|
1067
|
+
io.write_medit_tet(ctx.path(f"{name}.mesh"), mesh)
|
|
1068
|
+
notes.append((f"{name}.mesh", _NOTES["mesh"]))
|
|
1069
|
+
if "xdmf" in chosen:
|
|
1070
|
+
io.write_fenicsx(ctx.path(f"{name}.xdmf"), mesh)
|
|
1071
|
+
notes.append((f"{name}.xdmf", _NOTES["xdmf"]))
|
|
1072
|
+
if "pairs" in chosen:
|
|
1073
|
+
if not mesh.periodic:
|
|
1074
|
+
warnings.warn(
|
|
1075
|
+
"the conforming mesh is not periodic: its pairs are the nodes facing "
|
|
1076
|
+
"each other",
|
|
1077
|
+
stacklevel=2,
|
|
1078
|
+
)
|
|
1079
|
+
io.write_periodic_pairs(ctx.path(f"{name}_periodic.csv"), mesh)
|
|
1080
|
+
notes.append((f"{name}_periodic.csv", _NOTES["csv"]))
|
|
1081
|
+
if _VOXELS & chosen:
|
|
1082
|
+
ctx.progress(0.5, "voxel image")
|
|
1083
|
+
meshed = {"voxel_msh", "voxel_pairs"} & chosen
|
|
1084
|
+
image = _image(micro, p["resolution"], "voxel image", MAX_VOXEL_MESH if meshed else None)
|
|
1085
|
+
values["voxels"] = " x ".join(str(n) for n in image.shape)
|
|
1086
|
+
labels = micro.labels(grid=image.grid()) if micro.has_labels else None
|
|
1087
|
+
if meshed:
|
|
1088
|
+
from morphogen.mesh.voxel import voxel_mesh
|
|
1089
|
+
|
|
1090
|
+
vmesh = voxel_mesh(image, labels=labels)
|
|
1091
|
+
values["voxel mesh nodes"] = int(vmesh.n_nodes)
|
|
1092
|
+
values["voxel mesh elements"] = int(vmesh.n_elements)
|
|
1093
|
+
if "voxel_msh" in chosen:
|
|
1094
|
+
io.write_msh(ctx.path(f"{name}_voxels.msh"), vmesh)
|
|
1095
|
+
notes.append((f"{name}_voxels.msh", _NOTES["msh"]))
|
|
1096
|
+
if "voxel_pairs" in chosen:
|
|
1097
|
+
io.write_periodic_pairs(ctx.path(f"{name}_voxels_periodic.csv"), vmesh)
|
|
1098
|
+
notes.append((f"{name}_voxels_periodic.csv", _NOTES["csv"]))
|
|
1099
|
+
if "damask" in chosen:
|
|
1100
|
+
phases = {int(k): v for k, v in (item.get("phases") or {}).items()}
|
|
1101
|
+
io.write_damask(
|
|
1102
|
+
ctx.path(f"{name}_damask"),
|
|
1103
|
+
labels,
|
|
1104
|
+
orientations,
|
|
1105
|
+
getattr(micro, "cell_phases", None),
|
|
1106
|
+
phase_names=phases,
|
|
1107
|
+
)
|
|
1108
|
+
notes.append((f"{name}_damask.vti, {name}_damask_material.yaml", _NOTES["damask"]))
|
|
1109
|
+
if images:
|
|
1110
|
+
kind = {"phases": "phase", "labels": "labels", "level_set": "field"}[p["image"]]
|
|
1111
|
+
for suffix, data in _images_of(micro, image, labels, p["image"]):
|
|
1112
|
+
if "tif" in chosen:
|
|
1113
|
+
io.write_tiff(ctx.path(f"{name}{suffix}.tif"), data)
|
|
1114
|
+
notes.append((f"{name}{suffix}.tif", _NOTES["tif"]))
|
|
1115
|
+
if "mhd" in chosen:
|
|
1116
|
+
io.write_mhd(ctx.path(f"{name}{suffix}.mhd"), data)
|
|
1117
|
+
notes.append((f"{name}{suffix}.mhd, {name}{suffix}.raw", _NOTES["mhd"]))
|
|
1118
|
+
what = f"{p['image']}{suffix.replace('_', ' ')}"
|
|
1119
|
+
_section(
|
|
1120
|
+
ctx, data.data, kind, f"image{suffix}", f"x-y section of the image ({what})"
|
|
1121
|
+
)
|
|
1122
|
+
if "neper" in chosen:
|
|
1123
|
+
io.write_neper(ctx.path(name), micro)
|
|
1124
|
+
notes.append((f"{name}_seeds.txt, {name}_neper.sh", _NOTES["neper"]))
|
|
1125
|
+
lines = [f"# {item['title']} in other formats", ""]
|
|
1126
|
+
lines += [f"* {files}: {text.replace('<name>', name)}." for files, text in notes]
|
|
1127
|
+
readme = "\n".join(lines) + "\n"
|
|
1128
|
+
ctx.path("README.md").write_text(readme, encoding="utf-8")
|
|
1129
|
+
return _finish(ctx, f"{name}_formats", {"values": values, "text": readme})
|
|
1130
|
+
|
|
1131
|
+
|
|
1132
|
+
def _images_of(micro, image, labels, kind: str) -> list[tuple[str, object]]:
|
|
1133
|
+
"""The images to write on the grid of ``image``, each with the suffix of its files:
|
|
1134
|
+
the image of the phases, of the cells (16 bits when they fit) or of the level set
|
|
1135
|
+
(32-bit floats; for a morphology of several phases, the implicit function of each
|
|
1136
|
+
phase, ``_phase<k>``)."""
|
|
1137
|
+
from morphogen.models.implicit import implicit_functions
|
|
1138
|
+
|
|
1139
|
+
if kind == "phases":
|
|
1140
|
+
return [("", image)]
|
|
1141
|
+
if kind == "labels":
|
|
1142
|
+
data = np.asarray(labels.data)
|
|
1143
|
+
cells = labels.with_data(data.astype(np.uint16 if data.max() < 2**16 else np.int32))
|
|
1144
|
+
return [("", cells)]
|
|
1145
|
+
try:
|
|
1146
|
+
functions = implicit_functions(micro, grid=image.grid())
|
|
1147
|
+
except NotImplementedError:
|
|
1148
|
+
raise ValueError(f"{type(micro).__name__}: no level set; choose its phases") from None
|
|
1149
|
+
return [(s, f.with_data(np.asarray(f.data, dtype=np.float32))) for s, f in functions]
|
|
1150
|
+
|
|
1151
|
+
|
|
1152
|
+
# -- MFront and Z-set ------------------------------------------------------------------------
|
|
1153
|
+
|
|
1154
|
+
#: The default names of the behaviours of the tool MFront sources
|
|
1155
|
+
BEHAVIOUR_NAMES = {
|
|
1156
|
+
"vonmises": "MorphogenVonMises",
|
|
1157
|
+
"crystal": "MorphogenCrystal",
|
|
1158
|
+
"elastic": "MorphogenHencky",
|
|
1159
|
+
"material": "MorphogenMaterial",
|
|
1160
|
+
"workspace": "MorphogenBehaviour",
|
|
1161
|
+
}
|
|
1162
|
+
_CRYSTAL = {"behaviour": "crystal"}
|
|
1163
|
+
_MISES = {"behaviour": "vonmises"}
|
|
1164
|
+
FAMILIES = (
|
|
1165
|
+
("octahedral", "octahedral {111}<110> (FCC)"),
|
|
1166
|
+
("cube", "cube {100}<110>"),
|
|
1167
|
+
("bcc110", "{110}<111> (BCC)"),
|
|
1168
|
+
("bcc112", "{112}<111> (BCC)"),
|
|
1169
|
+
)
|
|
1170
|
+
|
|
1171
|
+
|
|
1172
|
+
@tool(
|
|
1173
|
+
"mfront_sources",
|
|
1174
|
+
"interop",
|
|
1175
|
+
"MFront sources",
|
|
1176
|
+
"The MFront source of a behaviour of morphoGen, for the codes of MFront's interfaces "
|
|
1177
|
+
"(AMITEX_FFTP and Cast3M with umat, Abaqus, Code_Aster, MGIS): von Mises "
|
|
1178
|
+
"elasto-(visco)plasticity (the brick StandardElastoViscoPlasticity: linear and Voce "
|
|
1179
|
+
"isotropic hardening, Armstrong-Frederick and Prager kinematic hardening, Norton's "
|
|
1180
|
+
"flow), Méric-Cailletaud crystal plasticity (morphoGen's slip systems and interactions; "
|
|
1181
|
+
"in finite strains its kernel), Hencky's elasticity in finite strains, or a material of "
|
|
1182
|
+
"the configurations; with the material of morphoGen whose behaviour it is.",
|
|
1183
|
+
[
|
|
1184
|
+
Field(
|
|
1185
|
+
"behaviour",
|
|
1186
|
+
"choice",
|
|
1187
|
+
"vonmises",
|
|
1188
|
+
choices=(
|
|
1189
|
+
("vonmises", "von Mises elasto-(visco)plasticity"),
|
|
1190
|
+
("crystal", "Méric-Cailletaud crystal plasticity"),
|
|
1191
|
+
("elastic", "Hencky elasticity (finite strains)"),
|
|
1192
|
+
("material", "a material of the configurations (JSON)"),
|
|
1193
|
+
("workspace", "a behaviour of the workspace (B: a material point, Z-set)"),
|
|
1194
|
+
),
|
|
1195
|
+
),
|
|
1196
|
+
Field(
|
|
1197
|
+
"kept",
|
|
1198
|
+
"item",
|
|
1199
|
+
label="behaviour of the workspace",
|
|
1200
|
+
items=("behaviour",),
|
|
1201
|
+
required=True,
|
|
1202
|
+
when={"behaviour": "workspace"},
|
|
1203
|
+
),
|
|
1204
|
+
Field(
|
|
1205
|
+
"kinematics",
|
|
1206
|
+
"choice",
|
|
1207
|
+
"small",
|
|
1208
|
+
choices=(("small", "small strains"), ("finite", "finite strains")),
|
|
1209
|
+
),
|
|
1210
|
+
Field("name", "str", "", doc="of the behaviour: letters and digits (blank: its kind)"),
|
|
1211
|
+
Field(
|
|
1212
|
+
"elasticity",
|
|
1213
|
+
"choice",
|
|
1214
|
+
"isotropic",
|
|
1215
|
+
when={"behaviour": ["vonmises", "crystal", "elastic"]},
|
|
1216
|
+
choices=(("isotropic", "isotropic: E, ν"), ("cubic", "cubic crystal: C11, C12, C44")),
|
|
1217
|
+
),
|
|
1218
|
+
Field(
|
|
1219
|
+
"young", "float", 200000.0, label="E", unit="stress", when={"elasticity": "isotropic"}
|
|
1220
|
+
),
|
|
1221
|
+
Field("poisson", "float", 0.3, label="ν", when={"elasticity": "isotropic"}),
|
|
1222
|
+
Field(
|
|
1223
|
+
"cubic",
|
|
1224
|
+
"floats",
|
|
1225
|
+
[168000.0, 121000.0, 75000.0],
|
|
1226
|
+
label="C11, C12, C44",
|
|
1227
|
+
unit="stress",
|
|
1228
|
+
when={"elasticity": "cubic"},
|
|
1229
|
+
),
|
|
1230
|
+
Field("yield_stress", "float", 300.0, label="yield stress R0", unit="stress", when=_MISES),
|
|
1231
|
+
Field("hardening", "float", 1000.0, label="linear hardening H", unit="stress", when=_MISES),
|
|
1232
|
+
Field(
|
|
1233
|
+
"voce",
|
|
1234
|
+
"floats",
|
|
1235
|
+
label="Voce terms Q, b",
|
|
1236
|
+
when=_MISES,
|
|
1237
|
+
doc="pairs Q1, b1, Q2, b2 (at most three): R = R0 + H p + Σ Q (1 - exp(-b p))",
|
|
1238
|
+
),
|
|
1239
|
+
Field(
|
|
1240
|
+
"kinematic",
|
|
1241
|
+
"floats",
|
|
1242
|
+
label="kinematic terms C, D",
|
|
1243
|
+
when=_MISES,
|
|
1244
|
+
doc="pairs C1, D1, ... (at most four; D = 0: Prager): X = 2/3 C α",
|
|
1245
|
+
),
|
|
1246
|
+
Field(
|
|
1247
|
+
"norton",
|
|
1248
|
+
"floats",
|
|
1249
|
+
label="Norton K, n",
|
|
1250
|
+
when=_MISES,
|
|
1251
|
+
doc="viscoplasticity, dp/dt = <f / K>^n (blank: rate-independent)",
|
|
1252
|
+
),
|
|
1253
|
+
Field(
|
|
1254
|
+
"families",
|
|
1255
|
+
"choices",
|
|
1256
|
+
["octahedral"],
|
|
1257
|
+
label="slip families",
|
|
1258
|
+
choices=FAMILIES,
|
|
1259
|
+
when=_CRYSTAL,
|
|
1260
|
+
),
|
|
1261
|
+
Field(
|
|
1262
|
+
"tau0",
|
|
1263
|
+
"float",
|
|
1264
|
+
40.0,
|
|
1265
|
+
label="τ0",
|
|
1266
|
+
unit="stress",
|
|
1267
|
+
when=_CRYSTAL,
|
|
1268
|
+
doc="critical resolved shear stress",
|
|
1269
|
+
),
|
|
1270
|
+
Field(
|
|
1271
|
+
"Q",
|
|
1272
|
+
"float",
|
|
1273
|
+
0.0,
|
|
1274
|
+
unit="stress",
|
|
1275
|
+
when=_CRYSTAL,
|
|
1276
|
+
doc="r = τ0 + Q Σ h_sr (1 - exp(-b v_r))",
|
|
1277
|
+
),
|
|
1278
|
+
Field("b", "float", 0.0, when=_CRYSTAL),
|
|
1279
|
+
Field("C", "float", 0.0, unit="stress", when=_CRYSTAL, doc="x = C α, dα = dγ - D α |dγ|"),
|
|
1280
|
+
Field("D", "float", 0.0, when=_CRYSTAL),
|
|
1281
|
+
Field(
|
|
1282
|
+
"K", "float", 20.0, unit="stress", when=_CRYSTAL, doc="dγ/dt = <(|τ - x| - r) / K>^n"
|
|
1283
|
+
),
|
|
1284
|
+
Field("n", "float", 12.0, when=_CRYSTAL),
|
|
1285
|
+
Field(
|
|
1286
|
+
"interaction",
|
|
1287
|
+
"floats",
|
|
1288
|
+
when=_CRYSTAL,
|
|
1289
|
+
doc="h_self, h_latent, or the six coefficients self, coplanar, Hirth, collinear, "
|
|
1290
|
+
"glissile, Lomer of the octahedral systems (blank: all 1)",
|
|
1291
|
+
),
|
|
1292
|
+
Field(
|
|
1293
|
+
"material",
|
|
1294
|
+
"json",
|
|
1295
|
+
when={"behaviour": "material"},
|
|
1296
|
+
doc='e.g. {"young": 70e3, "poisson": 0.33, "plasticity": {"yield": 100, '
|
|
1297
|
+
'"isotropic": [{"Q": 50, "b": 20}], "norton": {"K": 50, "n": 5}}}',
|
|
1298
|
+
),
|
|
1299
|
+
Field(
|
|
1300
|
+
"compile",
|
|
1301
|
+
"bool",
|
|
1302
|
+
False,
|
|
1303
|
+
label="compile it",
|
|
1304
|
+
doc="with MFront's generic interface, when mfront is on the PATH",
|
|
1305
|
+
),
|
|
1306
|
+
],
|
|
1307
|
+
order=5,
|
|
1308
|
+
menu="Behaviours of materials",
|
|
1309
|
+
)
|
|
1310
|
+
def mfront_sources(p: dict, ctx) -> dict:
|
|
1311
|
+
import yaml
|
|
1312
|
+
|
|
1313
|
+
from morphogen._utils import to_jsonable
|
|
1314
|
+
from morphogen.io.mfront import (
|
|
1315
|
+
identifier,
|
|
1316
|
+
mfront_state_size,
|
|
1317
|
+
mfront_strain_measure,
|
|
1318
|
+
mfront_symmetry,
|
|
1319
|
+
umat_function,
|
|
1320
|
+
write_mfront,
|
|
1321
|
+
)
|
|
1322
|
+
|
|
1323
|
+
kinematics = p["kinematics"]
|
|
1324
|
+
if p["behaviour"] == "elastic" and kinematics == "small":
|
|
1325
|
+
raise ValueError(
|
|
1326
|
+
"Hencky elasticity: finite strains (in small strains, the elastic phases need no "
|
|
1327
|
+
"MFront law: the codes have their own)"
|
|
1328
|
+
)
|
|
1329
|
+
material = _behaviour(p)
|
|
1330
|
+
name = identifier(p["name"] or BEHAVIOUR_NAMES[p["behaviour"]])
|
|
1331
|
+
source = write_mfront(material, ctx.path(f"{name}.mfront"), name=name, kinematics=kinematics)
|
|
1332
|
+
config = {"materials": {1: to_jsonable(material.to_config())}}
|
|
1333
|
+
ctx.path("material.yaml").write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8")
|
|
1334
|
+
states = mfront_state_size(material, kinematics)
|
|
1335
|
+
symmetry = mfront_symmetry(material, kinematics)
|
|
1336
|
+
measure = mfront_strain_measure(material, kinematics)
|
|
1337
|
+
gradient = "the deformation gradient" if kinematics == "finite" else "the small strain"
|
|
1338
|
+
values = {
|
|
1339
|
+
"behaviour": name,
|
|
1340
|
+
"kinematics": kinematics,
|
|
1341
|
+
"symmetry": symmetry,
|
|
1342
|
+
"internal state variables": states,
|
|
1343
|
+
"strain measure": measure or gradient,
|
|
1344
|
+
"umat function": umat_function(name, measure),
|
|
1345
|
+
"Abaqus material": f"ABAQUSBEHAVIOUR_{name.upper()}_3D",
|
|
1346
|
+
}
|
|
1347
|
+
if p["compile"]:
|
|
1348
|
+
if shutil.which("mfront") is None:
|
|
1349
|
+
warnings.warn("mfront is not on the PATH: the source is not compiled", stacklevel=2)
|
|
1350
|
+
else:
|
|
1351
|
+
from morphogen.homogenization.mfront import compile_mfront
|
|
1352
|
+
|
|
1353
|
+
ctx.progress(0.3, "compiling with MFront")
|
|
1354
|
+
values["library"] = str(compile_mfront(source))
|
|
1355
|
+
readme = _mfront_readme(name, kinematics, symmetry, states, measure, values)
|
|
1356
|
+
ctx.path("README.md").write_text(readme, encoding="utf-8")
|
|
1357
|
+
text = _head(source.read_text(encoding="utf-8"), source.name)
|
|
1358
|
+
return _finish(ctx, name, {"values": values, "text": readme + "\n" + text})
|
|
1359
|
+
|
|
1360
|
+
|
|
1361
|
+
def _behaviour(p: dict):
|
|
1362
|
+
"""The material of the form of the tool MFront sources."""
|
|
1363
|
+
from morphogen.homogenization.crystal import PARAMS
|
|
1364
|
+
from morphogen.homogenization.materials import Material
|
|
1365
|
+
|
|
1366
|
+
kind = p["behaviour"]
|
|
1367
|
+
if kind == "workspace":
|
|
1368
|
+
return Material.from_config(p["kept"]["material"])
|
|
1369
|
+
if kind == "material":
|
|
1370
|
+
if not p["material"]:
|
|
1371
|
+
raise ValueError("material: a material of the configurations (JSON)")
|
|
1372
|
+
return Material.from_config(p["material"])
|
|
1373
|
+
if p["elasticity"] == "cubic":
|
|
1374
|
+
constants = p["cubic"] or []
|
|
1375
|
+
if len(constants) != 3:
|
|
1376
|
+
raise ValueError("C11, C12, C44: the three constants of the cubic crystal")
|
|
1377
|
+
spec: dict = {"cubic": constants}
|
|
1378
|
+
else:
|
|
1379
|
+
spec = {"young": p["young"], "poisson": p["poisson"]}
|
|
1380
|
+
if kind == "vonmises":
|
|
1381
|
+
plasticity: dict = {"yield": p["yield_stress"], "hardening": p["hardening"] or 0.0}
|
|
1382
|
+
for key, terms, a, b in (
|
|
1383
|
+
("isotropic", p["voce"], "Q", "b"),
|
|
1384
|
+
("kinematic", p["kinematic"], "C", "D"),
|
|
1385
|
+
):
|
|
1386
|
+
terms = terms or []
|
|
1387
|
+
if len(terms) % 2:
|
|
1388
|
+
raise ValueError(f"{key} terms: pairs {a}, {b}")
|
|
1389
|
+
if terms:
|
|
1390
|
+
pairs = zip(terms[::2], terms[1::2], strict=True)
|
|
1391
|
+
plasticity[key] = [{a: x, b: y} for x, y in pairs]
|
|
1392
|
+
if p["norton"]:
|
|
1393
|
+
if len(p["norton"]) != 2:
|
|
1394
|
+
raise ValueError("Norton: K and n")
|
|
1395
|
+
plasticity["norton"] = {"K": p["norton"][0], "n": p["norton"][1]}
|
|
1396
|
+
spec["plasticity"] = plasticity
|
|
1397
|
+
elif kind == "crystal":
|
|
1398
|
+
cp = {"families": p["families"] or ["octahedral"], **{k: p[k] for k in PARAMS}}
|
|
1399
|
+
if p["interaction"]:
|
|
1400
|
+
cp["interaction"] = p["interaction"]
|
|
1401
|
+
spec["crystal_plasticity"] = cp
|
|
1402
|
+
return Material.from_config(spec)
|
|
1403
|
+
|
|
1404
|
+
|
|
1405
|
+
def _mfront_readme(name, kinematics, symmetry, states, measure, values) -> str:
|
|
1406
|
+
finite = kinematics == "finite"
|
|
1407
|
+
orthotropic = symmetry == "orthotropic"
|
|
1408
|
+
axes = " + 6, the axes of the crystal" if finite and orthotropic else ""
|
|
1409
|
+
lines = [
|
|
1410
|
+
f"# MFront behaviour {name}",
|
|
1411
|
+
"",
|
|
1412
|
+
f"{name}.mfront: {kinematics} strains, {symmetry}, {states} internal state variables"
|
|
1413
|
+
+ (f", the strain measure {measure}" if measure else "")
|
|
1414
|
+
+ ". material.yaml: the material of morphoGen's configurations whose behaviour it is "
|
|
1415
|
+
"(here, of phase 1; its elastic constants for the linear problems and the reference "
|
|
1416
|
+
"media), which morphoGen integrates with its own kernels.",
|
|
1417
|
+
"",
|
|
1418
|
+
"## Compile",
|
|
1419
|
+
"",
|
|
1420
|
+
f" mfront --obuild --interface=generic {name}.mfront # MGIS",
|
|
1421
|
+
f" mfront --obuild --interface=umat {name}.mfront # AMITEX_FFTP, Cast3M",
|
|
1422
|
+
f" mfront --obuild --interface=abaqus {name}.mfront # Abaqus",
|
|
1423
|
+
f" mfront --obuild --interface=aster {name}.mfront # Code_Aster",
|
|
1424
|
+
"",
|
|
1425
|
+
"## Use",
|
|
1426
|
+
"",
|
|
1427
|
+
f"* morphoGen: the material {{mfront: {{source: {name}.mfront}}}} beside its elastic "
|
|
1428
|
+
"constants (MGIS integrates it, compiled on first use);",
|
|
1429
|
+
f"* umat (AMITEX_FFTP, Cast3M): the function {values['umat function']} of "
|
|
1430
|
+
"src/libUmatBehaviour.so, with the coefficients that the interface imposes (YOUN, NU, "
|
|
1431
|
+
"RHO, ALPH; orthotropic: YG1 ... G13, the axes V1, V2 of the crystal, RHO, ALP1 ... "
|
|
1432
|
+
f"ALP3) and {max(states, 1)} internal variables;",
|
|
1433
|
+
f"* Abaqus: the material {values['Abaqus material']} (*DEPVAR {states}{axes}; "
|
|
1434
|
+
"*USER MATERIAL, CONSTANTS=1: 0.) with the umat.cpp of TFEL (share/doc/mfront/abaqus) "
|
|
1435
|
+
"and src/libABAQUSBEHAVIOUR.so on LD_LIBRARY_PATH"
|
|
1436
|
+
+ ("; the axes of each grain: *ORIENTATION" if orthotropic and not finite else "")
|
|
1437
|
+
+ (": its steps need NLGEOM=YES" if finite else "")
|
|
1438
|
+
+ ".",
|
|
1439
|
+
]
|
|
1440
|
+
return "\n".join(lines) + "\n"
|
|
1441
|
+
|
|
1442
|
+
|
|
1443
|
+
@tool(
|
|
1444
|
+
"zmat_import",
|
|
1445
|
+
"interop",
|
|
1446
|
+
"Z-set material files",
|
|
1447
|
+
"A material file of Z-mat (Z-set) translated: a gen_evp behaviour of one von Mises "
|
|
1448
|
+
"potential (Norton or rate-independent flow, the isotropic and kinematic hardenings of "
|
|
1449
|
+
"morphoGen) and the porous_plastic behaviours run on morphoGen's kernels; the other "
|
|
1450
|
+
"gen_evp behaviours (Hill's criterion, other flows and hardenings, several potentials) "
|
|
1451
|
+
"become an MFront behaviour of the brick StandardElastoViscoPlasticity; linear_elastic: "
|
|
1452
|
+
"any elasticity. With the material of the configurations, the MFront source and the "
|
|
1453
|
+
"coverage of Z-mat's library. The behaviour joins the workspace (B), for the other "
|
|
1454
|
+
"tools.",
|
|
1455
|
+
[
|
|
1456
|
+
Field(
|
|
1457
|
+
"text",
|
|
1458
|
+
"text",
|
|
1459
|
+
required=True,
|
|
1460
|
+
label="material file",
|
|
1461
|
+
doc="the text of a material file of Z-mat (***behavior gen_evp ... ***return)",
|
|
1462
|
+
),
|
|
1463
|
+
Field("behaviour", "int", 0, label="behaviour number", doc="in the file, from 0"),
|
|
1464
|
+
Field(
|
|
1465
|
+
"native",
|
|
1466
|
+
"bool",
|
|
1467
|
+
True,
|
|
1468
|
+
label="morphoGen's kernels",
|
|
1469
|
+
doc="when they integrate it (otherwise MFront: for the exports to other codes)",
|
|
1470
|
+
),
|
|
1471
|
+
Field("name", "str", "", doc="of the MFront behaviour (blank: ZmatBehaviour)"),
|
|
1472
|
+
],
|
|
1473
|
+
order=6,
|
|
1474
|
+
menu="Behaviours of materials",
|
|
1475
|
+
)
|
|
1476
|
+
def zmat_import(p: dict, ctx) -> dict:
|
|
1477
|
+
import yaml
|
|
1478
|
+
|
|
1479
|
+
from morphogen._utils import to_jsonable
|
|
1480
|
+
from morphogen.gui.api import behaviour_summary
|
|
1481
|
+
from morphogen.homogenization import zmat
|
|
1482
|
+
|
|
1483
|
+
text = str(p["text"])
|
|
1484
|
+
behaviours = zmat.read_zmat(text)
|
|
1485
|
+
index = p["behaviour"]
|
|
1486
|
+
if not 0 <= index < len(behaviours):
|
|
1487
|
+
raise ValueError(f"behaviour number: the file has {len(behaviours)} (from 0)")
|
|
1488
|
+
b = behaviours[index]
|
|
1489
|
+
stem = zmat.mfront_name(p["name"] or "ZmatBehaviour")
|
|
1490
|
+
ctx.path("zmat.mat").write_text(text, encoding="utf-8")
|
|
1491
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
1492
|
+
material = zmat.zmat_material(
|
|
1493
|
+
text, behaviour=index, name=stem, directory=tmp, native=p["native"]
|
|
1494
|
+
)
|
|
1495
|
+
config = to_jsonable(material.to_config())
|
|
1496
|
+
if material.mfront is not None:
|
|
1497
|
+
shutil.copyfile(material.mfront.source, ctx.path(f"{stem}.mfront"))
|
|
1498
|
+
config["mfront"]["source"] = f"{stem}.mfront"
|
|
1499
|
+
described = zmat.describe(text, index)
|
|
1500
|
+
porous = b.kind == "porous_plastic"
|
|
1501
|
+
if material.mfront is not None:
|
|
1502
|
+
translation = "mfront"
|
|
1503
|
+
why = described.get("reason") or "native: false, MFront for the exports to other codes"
|
|
1504
|
+
else:
|
|
1505
|
+
translation = "native"
|
|
1506
|
+
why = "morphoGen's kernels"
|
|
1507
|
+
if b.potentials and not porous: # the brick of MFront, for the other codes
|
|
1508
|
+
ctx.path(f"{stem}.mfront").write_text(zmat.zmat_mfront_source(b, stem), "utf-8")
|
|
1509
|
+
kind = "elastic" if not b.potentials else ("porous" if porous else "plastic")
|
|
1510
|
+
material_text = yaml.safe_dump({"materials": {1: config}}, sort_keys=False)
|
|
1511
|
+
ctx.path("material.yaml").write_text(material_text, encoding="utf-8")
|
|
1512
|
+
ctx.table(_bricks(b), "bricks", f"the behaviour {b.kind} read")
|
|
1513
|
+
coverage = [
|
|
1514
|
+
{"category": a, "Z-mat": z, "morphoGen": s, "how": h} for a, z, s, h in zmat.COVERAGE
|
|
1515
|
+
]
|
|
1516
|
+
ctx.table(coverage, "coverage", "coverage of Z-mat's library", shown=len(coverage))
|
|
1517
|
+
lines = [
|
|
1518
|
+
f"# The behaviour {index} ({b.kind}) of a material file of Z-mat",
|
|
1519
|
+
"",
|
|
1520
|
+
f"Translation: {translation} ({why}).",
|
|
1521
|
+
*[f"Note: {note}." for note in described.get("notes") or []],
|
|
1522
|
+
"",
|
|
1523
|
+
"material.yaml, the material of a configuration (here, of phase 1):",
|
|
1524
|
+
"",
|
|
1525
|
+
*[f" {line}" for line in material_text.splitlines()],
|
|
1526
|
+
]
|
|
1527
|
+
if ctx.path(f"{stem}.mfront").exists():
|
|
1528
|
+
what = (
|
|
1529
|
+
"its behaviour"
|
|
1530
|
+
if translation == "mfront"
|
|
1531
|
+
else "the same behaviour for the codes of MFront (AMITEX_FFTP, Abaqus, Code_Aster)"
|
|
1532
|
+
)
|
|
1533
|
+
lines += [
|
|
1534
|
+
"",
|
|
1535
|
+
f"{stem}.mfront: {what}, compiled by mfront --obuild --interface=generic (MGIS), "
|
|
1536
|
+
"umat, abaqus or aster.",
|
|
1537
|
+
]
|
|
1538
|
+
readme = "\n".join(lines) + "\n"
|
|
1539
|
+
ctx.path("README.md").write_text(readme, encoding="utf-8")
|
|
1540
|
+
values = {
|
|
1541
|
+
"translation": translation,
|
|
1542
|
+
"kind": kind,
|
|
1543
|
+
"behaviours in the file": len(behaviours),
|
|
1544
|
+
"potentials": len(b.potentials),
|
|
1545
|
+
}
|
|
1546
|
+
# the behaviour joins the workspace (B), the run with it: for the other tools
|
|
1547
|
+
label, info = behaviour_summary(config)
|
|
1548
|
+
item = ctx.session.add(ctx.key, "behaviour", f"{label} (Z-set {b.kind} {index})",
|
|
1549
|
+
material=config, info=info) # fmt: skip
|
|
1550
|
+
out = {"values": values, "text": readme, "items": [ctx.session.public(item)]}
|
|
1551
|
+
return _finish(ctx, "zmat", out)
|
|
1552
|
+
|
|
1553
|
+
|
|
1554
|
+
@tool(
|
|
1555
|
+
"zmat_export",
|
|
1556
|
+
"interop",
|
|
1557
|
+
"Z-set file of a behaviour",
|
|
1558
|
+
"A behaviour of the workspace (B: identified on the response of a morphology, kept by a "
|
|
1559
|
+
"material point, imported) written as a material file of Z-mat for Z-set: "
|
|
1560
|
+
"linear_elastic (isotropic, cubic or anisotropic elasticity), gen_evp of one potential "
|
|
1561
|
+
"of von Mises or Hill (a Norton or rate-independent flow, the isotropic hardening constant, "
|
|
1562
|
+
"linear, nonlinear, linear_nonlinear or nonlinear_sum, the kinematic terms linear or "
|
|
1563
|
+
"nonlinear) with its isotropic thermal strain, or porous_plastic (Gurson with its "
|
|
1564
|
+
"coalescence, Rousselier, the elliptic criterion, the nucleation, the initial "
|
|
1565
|
+
"porosity); the numbers in full, read back as the same material. Crystal plasticity, "
|
|
1566
|
+
"MFront behaviours: their MFront sources.",
|
|
1567
|
+
[
|
|
1568
|
+
Field(
|
|
1569
|
+
"behaviour",
|
|
1570
|
+
"item",
|
|
1571
|
+
items=("behaviour",),
|
|
1572
|
+
required=True,
|
|
1573
|
+
doc="identified, kept by a material point or imported",
|
|
1574
|
+
),
|
|
1575
|
+
Field("name", "str", "", label="file name", doc="blank: behaviour.mat"),
|
|
1576
|
+
Field(
|
|
1577
|
+
"digits",
|
|
1578
|
+
"int",
|
|
1579
|
+
0,
|
|
1580
|
+
label="significant digits",
|
|
1581
|
+
doc="of the numbers (0: in full, read back exactly)",
|
|
1582
|
+
),
|
|
1583
|
+
],
|
|
1584
|
+
order=7,
|
|
1585
|
+
menu="Behaviours of materials",
|
|
1586
|
+
)
|
|
1587
|
+
def zmat_export(p: dict, ctx) -> dict:
|
|
1588
|
+
from morphogen.homogenization import zmat
|
|
1589
|
+
|
|
1590
|
+
item = p["behaviour"]
|
|
1591
|
+
name = (p["name"] or "").strip().removesuffix(".mat")
|
|
1592
|
+
stem = re.sub(r"[^\w-]", "_", name).strip("_") or "behaviour" # one name, in the folder
|
|
1593
|
+
digits = p["digits"] or None
|
|
1594
|
+
text = zmat.write_zmat(item["material"], ctx.path(f"{stem}.mat"), title=item["title"],
|
|
1595
|
+
digits=digits) # fmt: skip
|
|
1596
|
+
(behaviour,) = zmat.read_zmat(text)
|
|
1597
|
+
lines = [
|
|
1598
|
+
f"# {item['title']}: a material file of Z-mat",
|
|
1599
|
+
"",
|
|
1600
|
+
f"{stem}.mat: the behaviour {behaviour.kind} for Z-set, its numbers "
|
|
1601
|
+
+ (f"to {digits} significant digits" if digits else "in full")
|
|
1602
|
+
+ " (a material file, or its lines after ***material in an input file).",
|
|
1603
|
+
"",
|
|
1604
|
+
*[f" {line}" for line in text.splitlines()],
|
|
1605
|
+
]
|
|
1606
|
+
readme = "\n".join(lines) + "\n"
|
|
1607
|
+
ctx.path("README.md").write_text(readme, encoding="utf-8")
|
|
1608
|
+
values = {"behaviour": behaviour.kind, "potentials": len(behaviour.potentials)}
|
|
1609
|
+
return _finish(ctx, stem, {"values": values, "text": readme})
|
|
1610
|
+
|
|
1611
|
+
|
|
1612
|
+
def _coefficients(values: dict) -> str:
|
|
1613
|
+
out = []
|
|
1614
|
+
for key, value in values.items():
|
|
1615
|
+
if isinstance(value, tuple) and value[:1] == ("table",):
|
|
1616
|
+
out.append(f"{key}: table of {value[1]} ({len(value[2])} rows)")
|
|
1617
|
+
elif isinstance(value, (int, float)):
|
|
1618
|
+
out.append(f"{key} {value:g}")
|
|
1619
|
+
else:
|
|
1620
|
+
out.append(f"{key} {value}")
|
|
1621
|
+
return ", ".join(out)
|
|
1622
|
+
|
|
1623
|
+
|
|
1624
|
+
def _bricks(b) -> list[dict]:
|
|
1625
|
+
"""The bricks of a behaviour of Z-mat as read, for a table."""
|
|
1626
|
+
rows = [
|
|
1627
|
+
{
|
|
1628
|
+
"brick": "elasticity",
|
|
1629
|
+
"type": b.elasticity[0],
|
|
1630
|
+
"coefficients": _coefficients(b.elasticity[1]),
|
|
1631
|
+
}
|
|
1632
|
+
]
|
|
1633
|
+
if b.thermal_strain is not None:
|
|
1634
|
+
kind, coefficients = b.thermal_strain
|
|
1635
|
+
rows.append(
|
|
1636
|
+
{"brick": "thermal_strain", "type": kind, "coefficients": _coefficients(coefficients)}
|
|
1637
|
+
)
|
|
1638
|
+
for pot in b.potentials:
|
|
1639
|
+
bricks = [("criterion", pot.criterion), ("flow", pot.flow)]
|
|
1640
|
+
bricks += [("isotropic", x) for x in pot.isotropic]
|
|
1641
|
+
bricks += [("kinematic", x) for x in pot.kinematic]
|
|
1642
|
+
if pot.nucleation is not None:
|
|
1643
|
+
bricks.append(("nucleation", pot.nucleation[:2]))
|
|
1644
|
+
for brick, (kind, coefficients) in bricks:
|
|
1645
|
+
rows.append(
|
|
1646
|
+
{
|
|
1647
|
+
"brick": f"potential {pot.name}: {brick}",
|
|
1648
|
+
"type": kind,
|
|
1649
|
+
"coefficients": _coefficients(coefficients),
|
|
1650
|
+
}
|
|
1651
|
+
)
|
|
1652
|
+
if b.modifier:
|
|
1653
|
+
rows.append({"brick": "modifier", "type": b.modifier, "coefficients": ""})
|
|
1654
|
+
return rows
|