morphogen 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- morphogen/__init__.py +60 -0
- morphogen/__main__.py +7 -0
- morphogen/_platform.py +55 -0
- morphogen/_public.py +153 -0
- morphogen/_utils.py +80 -0
- morphogen/_version.py +1 -0
- morphogen/analysis/__init__.py +174 -0
- morphogen/analysis/anisotropy.py +135 -0
- morphogen/analysis/basic.py +38 -0
- morphogen/analysis/cells.py +54 -0
- morphogen/analysis/connectivity.py +156 -0
- morphogen/analysis/correlation.py +195 -0
- morphogen/analysis/covariance.py +80 -0
- morphogen/analysis/fractal.py +54 -0
- morphogen/analysis/measures.py +188 -0
- morphogen/analysis/morphology.py +265 -0
- morphogen/analysis/particles.py +160 -0
- morphogen/analysis/percolation.py +2034 -0
- morphogen/analysis/power_laws.py +143 -0
- morphogen/analysis/random_sets.py +351 -0
- morphogen/analysis/stereology.py +289 -0
- morphogen/analysis/surface.py +107 -0
- morphogen/analysis/topology.py +92 -0
- morphogen/automata/__init__.py +74 -0
- morphogen/automata/engine.py +211 -0
- morphogen/automata/growth.py +686 -0
- morphogen/automata/lattice.py +143 -0
- morphogen/automata/reaction.py +255 -0
- morphogen/automata/rules.py +353 -0
- morphogen/automata/tilings.py +1715 -0
- morphogen/cli.py +3526 -0
- morphogen/config.py +2167 -0
- morphogen/contact/__init__.py +113 -0
- morphogen/contact/experiments.py +368 -0
- morphogen/contact/hertz.py +104 -0
- morphogen/contact/kernels.py +827 -0
- morphogen/contact/periodic.py +278 -0
- morphogen/contact/problem.py +578 -0
- morphogen/contact/surfaces.py +310 -0
- morphogen/coupling/__init__.py +43 -0
- morphogen/coupling/ageing.py +143 -0
- morphogen/coupling/diffusion.py +226 -0
- morphogen/coupling/fenicsx.py +484 -0
- morphogen/coupling/oxidation.py +447 -0
- morphogen/coupling/plates.py +247 -0
- morphogen/design/__init__.py +51 -0
- morphogen/design/csp.py +616 -0
- morphogen/design/frames.py +277 -0
- morphogen/design/search.py +287 -0
- morphogen/design/tiles.py +336 -0
- morphogen/distributions.py +312 -0
- morphogen/domain.py +203 -0
- morphogen/dynamics/__init__.py +179 -0
- morphogen/dynamics/model.py +638 -0
- morphogen/dynamics/openradioss.py +643 -0
- morphogen/dynamics/results.py +515 -0
- morphogen/fracture/__init__.py +170 -0
- morphogen/fracture/bulk.py +349 -0
- morphogen/fracture/cohesive.py +1614 -0
- morphogen/fracture/ductile.py +557 -0
- morphogen/fracture/lefm.py +1168 -0
- morphogen/fracture/mixed.py +1178 -0
- morphogen/fracture/periodic.py +733 -0
- morphogen/fracture/phasefield.py +714 -0
- morphogen/fracture/phasefield_finite.py +368 -0
- morphogen/fracture/surface.py +572 -0
- morphogen/fracture/toughness.py +566 -0
- morphogen/gpu.py +108 -0
- morphogen/gui/__init__.py +8 -0
- morphogen/gui/api.py +1927 -0
- morphogen/gui/desktop.py +387 -0
- morphogen/gui/icon.png +0 -0
- morphogen/gui/index.html +1909 -0
- morphogen/gui/server.py +229 -0
- morphogen/gui/tools/__init__.py +629 -0
- morphogen/gui/tools/compare.py +149 -0
- morphogen/gui/tools/contact.py +391 -0
- morphogen/gui/tools/couplings.py +1085 -0
- morphogen/gui/tools/crackfront.py +245 -0
- morphogen/gui/tools/design.py +224 -0
- morphogen/gui/tools/dynamics.py +824 -0
- morphogen/gui/tools/fracture.py +2586 -0
- morphogen/gui/tools/interop.py +1654 -0
- morphogen/gui/tools/learning.py +595 -0
- morphogen/gui/tools/mechanics.py +3881 -0
- morphogen/gui/tools/nonlocal_damage.py +1321 -0
- morphogen/gui/tools/phasefield.py +215 -0
- morphogen/gui/tools/physics.py +597 -0
- morphogen/gui/tools/stability.py +1756 -0
- morphogen/gui/tools/statistics.py +1408 -0
- morphogen/gui/viewer.js +1100 -0
- morphogen/homogenization/__init__.py +210 -0
- morphogen/homogenization/acoustics.py +566 -0
- morphogen/homogenization/amg.py +1005 -0
- morphogen/homogenization/apparent.py +1046 -0
- morphogen/homogenization/behaviours.cu +2285 -0
- morphogen/homogenization/behaviours.py +944 -0
- morphogen/homogenization/beremin.py +263 -0
- morphogen/homogenization/bifurcation.py +1085 -0
- morphogen/homogenization/bloch.py +507 -0
- morphogen/homogenization/bounds.py +226 -0
- morphogen/homogenization/core.py +458 -0
- morphogen/homogenization/coupled.py +1135 -0
- morphogen/homogenization/crystal.py +2967 -0
- morphogen/homogenization/dilatation.py +454 -0
- morphogen/homogenization/elements.py +157 -0
- morphogen/homogenization/fatigue.py +768 -0
- morphogen/homogenization/fe.py +1739 -0
- morphogen/homogenization/fenicsx.py +307 -0
- morphogen/homogenization/fft.py +499 -0
- morphogen/homogenization/fft_nonlinear.py +391 -0
- morphogen/homogenization/finite.py +613 -0
- morphogen/homogenization/flow.py +361 -0
- morphogen/homogenization/frames.py +1125 -0
- morphogen/homogenization/gpu.py +1241 -0
- morphogen/homogenization/harmonic.py +427 -0
- morphogen/homogenization/identification.py +579 -0
- morphogen/homogenization/kernels.py +760 -0
- morphogen/homogenization/laws.py +2061 -0
- morphogen/homogenization/materials.py +1080 -0
- morphogen/homogenization/mfront.py +589 -0
- morphogen/homogenization/networks.py +880 -0
- morphogen/homogenization/nonlinear.py +2612 -0
- morphogen/homogenization/ntfa.py +577 -0
- morphogen/homogenization/paths.py +476 -0
- morphogen/homogenization/photonic.py +467 -0
- morphogen/homogenization/poroelastic.py +212 -0
- morphogen/homogenization/porous.py +1120 -0
- morphogen/homogenization/postprocess.py +290 -0
- morphogen/homogenization/solvers.py +1140 -0
- morphogen/homogenization/tensors.py +240 -0
- morphogen/homogenization/voxel_fe.py +457 -0
- morphogen/homogenization/xfem.py +1016 -0
- morphogen/homogenization/zmat.py +1258 -0
- morphogen/iga/__init__.py +48 -0
- morphogen/iga/analysis.py +508 -0
- morphogen/iga/basis.py +214 -0
- morphogen/iga/geometry.py +501 -0
- morphogen/iga/homogenization.py +219 -0
- morphogen/iga/optimization.py +700 -0
- morphogen/iga/shapes.py +331 -0
- morphogen/image.py +128 -0
- morphogen/io/__init__.py +246 -0
- morphogen/io/amitex.py +741 -0
- morphogen/io/ebsd.py +881 -0
- morphogen/io/export.py +196 -0
- morphogen/io/geometry.py +158 -0
- morphogen/io/medit.py +147 -0
- morphogen/io/meshes.py +844 -0
- morphogen/io/metaimage.py +97 -0
- morphogen/io/mfront.py +1104 -0
- morphogen/io/native.py +57 -0
- morphogen/io/radioss.py +764 -0
- morphogen/io/solvers.py +371 -0
- morphogen/io/tables.py +278 -0
- morphogen/io/tiff.py +66 -0
- morphogen/io/vtk.py +701 -0
- morphogen/io/xdmf.py +200 -0
- morphogen/kernels/__init__.py +5 -0
- morphogen/kernels/annealing.py +192 -0
- morphogen/kernels/cells.py +69 -0
- morphogen/kernels/collective.py +87 -0
- morphogen/kernels/force_biased.py +595 -0
- morphogen/kernels/implicit.py +145 -0
- morphogen/kernels/leaves.py +132 -0
- morphogen/kernels/packing.py +304 -0
- morphogen/kernels/raster.py +279 -0
- morphogen/kernels/rsa.py +371 -0
- morphogen/kernels/union.py +135 -0
- morphogen/kernels/watershed.py +190 -0
- morphogen/laser/__init__.py +234 -0
- morphogen/laser/architectures.py +375 -0
- morphogen/laser/bending.py +216 -0
- morphogen/laser/cells.py +1694 -0
- morphogen/laser/design.py +940 -0
- morphogen/laser/figures.py +227 -0
- morphogen/laser/heat.py +804 -0
- morphogen/laser/materials.py +691 -0
- morphogen/laser/mechanics.py +1670 -0
- morphogen/laser/metallurgy.py +615 -0
- morphogen/laser/patterns.py +828 -0
- morphogen/laser/periodic.py +392 -0
- morphogen/laser/process.py +362 -0
- morphogen/laser/run.py +534 -0
- morphogen/laser/solid.py +216 -0
- morphogen/laser/specimen.py +200 -0
- morphogen/laser/structures.py +708 -0
- morphogen/learning/__init__.py +81 -0
- morphogen/learning/behaviour.py +398 -0
- morphogen/learning/data.py +328 -0
- morphogen/learning/learned.cpp +668 -0
- morphogen/learning/logarithmic.py +202 -0
- morphogen/learning/mfront.py +409 -0
- morphogen/learning/networks.py +767 -0
- morphogen/learning/run.py +212 -0
- morphogen/learning/standard.py +814 -0
- morphogen/learning/training.py +235 -0
- morphogen/mesh/__init__.py +29 -0
- morphogen/mesh/conforming.py +1423 -0
- morphogen/mesh/curved.py +600 -0
- morphogen/mesh/exact.py +1717 -0
- morphogen/mesh/octree.py +350 -0
- morphogen/mesh/polycrystal.py +1041 -0
- morphogen/mesh/polyhedra.py +677 -0
- morphogen/mesh/regularize.py +570 -0
- morphogen/mesh/surface.py +97 -0
- morphogen/mesh/tetra.py +512 -0
- morphogen/mesh/voxel.py +124 -0
- morphogen/micromorphic/__init__.py +31 -0
- morphogen/micromorphic/damage.py +359 -0
- morphogen/micromorphic/ductile.py +534 -0
- morphogen/micromorphic/finite.py +220 -0
- morphogen/micromorphic/microfoam.py +787 -0
- morphogen/micromorphic/space.py +341 -0
- morphogen/models/__init__.py +195 -0
- morphogen/models/affine.py +384 -0
- morphogen/models/automata.py +592 -0
- morphogen/models/base.py +500 -0
- morphogen/models/boolean.py +310 -0
- morphogen/models/bouligand.py +331 -0
- morphogen/models/branching.py +241 -0
- morphogen/models/combination.py +430 -0
- morphogen/models/deadleaves.py +766 -0
- morphogen/models/design.py +289 -0
- morphogen/models/ebsd.py +206 -0
- morphogen/models/fibers.py +1476 -0
- morphogen/models/foam.py +594 -0
- morphogen/models/gaussian.py +314 -0
- morphogen/models/growth.py +459 -0
- morphogen/models/hardcore.py +317 -0
- morphogen/models/hierarchical.py +269 -0
- morphogen/models/honeycomb.py +749 -0
- morphogen/models/implicit.py +177 -0
- morphogen/models/laminate.py +470 -0
- morphogen/models/lattice.py +351 -0
- morphogen/models/lattice_field.py +345 -0
- morphogen/models/levelset_foam.py +563 -0
- morphogen/models/nacre.py +411 -0
- morphogen/models/nested.py +924 -0
- morphogen/models/osteons.py +374 -0
- morphogen/models/pieces.py +167 -0
- morphogen/models/planar.py +126 -0
- morphogen/models/reconstruction.py +203 -0
- morphogen/models/scale_rich.py +1409 -0
- morphogen/models/scale_rich_3d.py +1616 -0
- morphogen/models/tessellation.py +735 -0
- morphogen/models/tiling_field.py +302 -0
- morphogen/models/tpms.py +197 -0
- morphogen/models/transparent.py +406 -0
- morphogen/models/union.py +141 -0
- morphogen/optimization/__init__.py +43 -0
- morphogen/optimization/cell.py +295 -0
- morphogen/optimization/filters.py +115 -0
- morphogen/optimization/mma.py +226 -0
- morphogen/optimization/run.py +219 -0
- morphogen/optimization/topology.py +632 -0
- morphogen/orientations.py +568 -0
- morphogen/parallel.py +599 -0
- morphogen/pipeline.py +978 -0
- morphogen/primitives.py +188 -0
- morphogen/results.py +564 -0
- morphogen/rve/__init__.py +73 -0
- morphogen/rve/report.py +627 -0
- morphogen/rve/scaling.py +363 -0
- morphogen/rve/study.py +1054 -0
- morphogen/rve/windows.py +345 -0
- morphogen/seeding.py +51 -0
- morphogen/settings.py +118 -0
- morphogen/stopping.py +48 -0
- morphogen/symmetry.py +384 -0
- morphogen/templates/activator_inhibitor.yaml +22 -0
- morphogen/templates/aggregation.yaml +23 -0
- morphogen/templates/boolean_cylinders.yaml +20 -0
- morphogen/templates/boolean_spheres.yaml +22 -0
- morphogen/templates/bouligand.yaml +28 -0
- morphogen/templates/cellular_automaton.yaml +25 -0
- morphogen/templates/coated_spheres.yaml +26 -0
- morphogen/templates/contact_fibers.yaml +27 -0
- morphogen/templates/cox_nanocomposite.yaml +22 -0
- morphogen/templates/cross_linked_fibers.yaml +26 -0
- morphogen/templates/curved_arcs.yaml +28 -0
- morphogen/templates/curved_fibers.yaml +24 -0
- morphogen/templates/dead_leaves.yaml +22 -0
- morphogen/templates/delaunay_network.yaml +22 -0
- morphogen/templates/dense_packing.yaml +22 -0
- morphogen/templates/diffusion.yaml +33 -0
- morphogen/templates/ebsd.yaml +34 -0
- morphogen/templates/ebsd_map.ctf +3087 -0
- morphogen/templates/fracture_composite.yaml +42 -0
- morphogen/templates/fracture_rubber.yaml +47 -0
- morphogen/templates/gaussian_excursion.yaml +17 -0
- morphogen/templates/graded_lattice.yaml +24 -0
- morphogen/templates/hardcore_fibers.yaml +22 -0
- morphogen/templates/hardcore_spheres.yaml +22 -0
- morphogen/templates/hierarchical_lattice.yaml +22 -0
- morphogen/templates/homogenization_acoustic_foam.yaml +36 -0
- morphogen/templates/homogenization_beremin.yaml +50 -0
- morphogen/templates/homogenization_cleavage.yaml +51 -0
- morphogen/templates/homogenization_cleavage_band.yaml +55 -0
- morphogen/templates/homogenization_contact.yaml +43 -0
- morphogen/templates/homogenization_crack_closure.yaml +49 -0
- morphogen/templates/homogenization_crystal_plasticity.yaml +50 -0
- morphogen/templates/homogenization_crystal_plasticity_fft.yaml +52 -0
- morphogen/templates/homogenization_crystallization.yaml +30 -0
- morphogen/templates/homogenization_debonding.yaml +43 -0
- morphogen/templates/homogenization_detwinning.yaml +58 -0
- morphogen/templates/homogenization_ductile_damage.yaml +47 -0
- morphogen/templates/homogenization_fatigue.yaml +40 -0
- morphogen/templates/homogenization_grain_fracture.yaml +56 -0
- morphogen/templates/homogenization_gyroid.yaml +30 -0
- morphogen/templates/homogenization_intergranular.yaml +43 -0
- morphogen/templates/homogenization_interphase.yaml +42 -0
- morphogen/templates/homogenization_mixed_loading.yaml +33 -0
- morphogen/templates/homogenization_ntfa.yaml +56 -0
- morphogen/templates/homogenization_piezoelectric.yaml +27 -0
- morphogen/templates/homogenization_polycrystal.yaml +30 -0
- morphogen/templates/homogenization_polycrystal_inclusions.yaml +30 -0
- morphogen/templates/homogenization_poroelastic.yaml +26 -0
- morphogen/templates/homogenization_rubber.yaml +40 -0
- morphogen/templates/homogenization_slip_cleavage.yaml +50 -0
- morphogen/templates/homogenization_spheres.yaml +31 -0
- morphogen/templates/homogenization_transport.yaml +29 -0
- morphogen/templates/homogenization_twinning.yaml +54 -0
- morphogen/templates/homogenization_viscoelastic.yaml +34 -0
- morphogen/templates/homogenization_viscoplastic.yaml +42 -0
- morphogen/templates/homogenization_voronoi.yaml +26 -0
- morphogen/templates/homogenization_xfem.yaml +23 -0
- morphogen/templates/hyperuniform_cells.yaml +24 -0
- morphogen/templates/laguerre.yaml +18 -0
- morphogen/templates/laser_bending.yaml +35 -0
- morphogen/templates/laser_cells.yaml +38 -0
- morphogen/templates/laser_corrugated.yaml +36 -0
- morphogen/templates/level_set_foam.yaml +29 -0
- morphogen/templates/menger_sponge.yaml +17 -0
- morphogen/templates/nacre.yaml +25 -0
- morphogen/templates/nucleation_growth.yaml +25 -0
- morphogen/templates/optimize_auxetic.yaml +29 -0
- morphogen/templates/optimize_auxetic_3d.yaml +27 -0
- morphogen/templates/optimize_bulk.yaml +23 -0
- morphogen/templates/optimize_conductivity.yaml +20 -0
- morphogen/templates/osteons.yaml +28 -0
- morphogen/templates/penetrable_spheres.yaml +21 -0
- morphogen/templates/poisson_fibers.yaml +21 -0
- morphogen/templates/random_laminate.yaml +26 -0
- morphogen/templates/random_lattice.yaml +27 -0
- morphogen/templates/random_walk_fibers.yaml +26 -0
- morphogen/templates/reaction_diffusion.yaml +22 -0
- morphogen/templates/reconstruction.yaml +22 -0
- morphogen/templates/rve_cellular_automaton.yaml +23 -0
- morphogen/templates/rve_crystal_plasticity_fft.yaml +51 -0
- morphogen/templates/rve_multiphysics.yaml +43 -0
- morphogen/templates/rve_poisson_fibers.yaml +22 -0
- morphogen/templates/rve_poisson_fibers_fe.yaml +33 -0
- morphogen/templates/rve_voronoi_windows.yaml +20 -0
- morphogen/templates/scale_rich_network.yaml +29 -0
- morphogen/templates/scale_rich_plates.yaml +30 -0
- morphogen/templates/sequential_dead_leaves.yaml +25 -0
- morphogen/templates/strut_lattice.yaml +21 -0
- morphogen/templates/tile_assembly.yaml +28 -0
- morphogen/templates/tpms.yaml +19 -0
- morphogen/templates/trabecular_bone.yaml +29 -0
- morphogen/templates/transparent_dead_leaves.yaml +23 -0
- morphogen/templates/vascular_tree.yaml +23 -0
- morphogen/templates/voronoi.yaml +20 -0
- morphogen/templates/wood.yaml +34 -0
- morphogen/templates/workflow.yaml +56 -0
- morphogen/texture.py +665 -0
- morphogen/theory.py +162 -0
- morphogen/viz/__init__.py +12 -0
- morphogen/viz/export.py +244 -0
- morphogen/viz/figures.py +707 -0
- morphogen/viz/png.py +148 -0
- morphogen/viz/sections.py +696 -0
- morphogen/viz/surfaces.py +1352 -0
- morphogen/viz/video.py +904 -0
- morphogen/viz/workflow.py +488 -0
- morphogen-1.0.0.dist-info/METADATA +2316 -0
- morphogen-1.0.0.dist-info/RECORD +381 -0
- morphogen-1.0.0.dist-info/WHEEL +4 -0
- morphogen-1.0.0.dist-info/entry_points.txt +5 -0
- morphogen-1.0.0.dist-info/licenses/LICENSE +674 -0
morphogen/gui/api.py
ADDED
|
@@ -0,0 +1,1927 @@
|
|
|
1
|
+
"""Actions of the web interface, as plain functions of JSON-like data (testable without a
|
|
2
|
+
server). Images are PNG data URLs or files of the session folder.
|
|
3
|
+
|
|
4
|
+
The interface follows the work on a microstructure: a morphology is generated (or comes
|
|
5
|
+
out of an optimization), simulated, then exported. Each result is kept in the workspace
|
|
6
|
+
of the session (:class:`Session`) under a key, so that a morphology can be sent to the
|
|
7
|
+
simulation, to the export or to the optimization, and a simulation to the export or to
|
|
8
|
+
the optimization. The views of a morphology are sections of its level set
|
|
9
|
+
(:mod:`morphogen.viz.sections`, anti-aliased, up to 2048 pixels per edge without a voxel
|
|
10
|
+
image of the volume); voxel images are made on demand, by the exports and the FFT
|
|
11
|
+
simulations.
|
|
12
|
+
|
|
13
|
+
The simulations run the steps of the configurations of the command line on the
|
|
14
|
+
morphology of the workspace; their configuration is downloadable, to rerun them with
|
|
15
|
+
``morphogen run`` (a morphology generated with a seed is the realization 0 of a run with
|
|
16
|
+
that seed). The figures, videos and files are drawn from the fields of a simulation by the
|
|
17
|
+
export, without solving again (:func:`export`)."""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import base64
|
|
22
|
+
import csv
|
|
23
|
+
import itertools
|
|
24
|
+
import os
|
|
25
|
+
import re
|
|
26
|
+
import shutil
|
|
27
|
+
import subprocess
|
|
28
|
+
import sys
|
|
29
|
+
import threading
|
|
30
|
+
import time
|
|
31
|
+
import uuid
|
|
32
|
+
import warnings
|
|
33
|
+
import zipfile
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
|
|
36
|
+
import numpy as np
|
|
37
|
+
import yaml
|
|
38
|
+
|
|
39
|
+
from morphogen import analysis, io
|
|
40
|
+
from morphogen.domain import Domain
|
|
41
|
+
from morphogen.models.base import get_model, list_models, model_from_config
|
|
42
|
+
from morphogen.seeding import derive_seed
|
|
43
|
+
from morphogen.viz.png import encode_png, slice_of, to_rgb, upscale
|
|
44
|
+
|
|
45
|
+
#: Limits that keep the interface responsive (it is meant for exploration), besides the
|
|
46
|
+
#: free memory (:func:`check_memory`).
|
|
47
|
+
MAX_RESOLUTION = 2048 # pixels per edge of the sections of the level sets
|
|
48
|
+
MAX_SHAPE = 2048 # voxels per edge of the voxel images of the exports
|
|
49
|
+
MAX_FFT_SHAPE = 256 # voxels per edge of the FFT simulations
|
|
50
|
+
MAX_FRAMES = 60
|
|
51
|
+
MAX_OPT_VOXELS = 64**3
|
|
52
|
+
#: Resolution of the measures of the level sets (cells per edge)
|
|
53
|
+
MEASURE_RESOLUTION = 128
|
|
54
|
+
#: Sections larger than this are files of the session, smaller ones data URLs
|
|
55
|
+
INLINE_PIXELS = 512
|
|
56
|
+
#: Gaussian smoothing (voxels) of the level sets of the optimized designs
|
|
57
|
+
DESIGN_SMOOTHING = 1.0
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def png_url(plane: np.ndarray, kind: str = "auto", size: int = 320, vmin=None, vmax=None) -> str:
|
|
61
|
+
rgb = to_rgb(plane, kind, vmin, vmax)
|
|
62
|
+
rgb = upscale(rgb, max(1, size // max(rgb.shape[:2])))
|
|
63
|
+
return _data_url(rgb)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _data_url(rgb: np.ndarray) -> str:
|
|
67
|
+
return "data:image/png;base64," + base64.b64encode(encode_png(rgb)).decode("ascii")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def sections(volume: np.ndarray, kind: str = "auto", **kw) -> list[dict]:
|
|
71
|
+
"""Middle sections of a voxel array (one for planar volumes) as PNG data URLs."""
|
|
72
|
+
if volume.shape[2] == 1:
|
|
73
|
+
return [{"title": "x-y", "png": png_url(slice_of(volume, 2), kind, **kw)}]
|
|
74
|
+
names = ((0, "y-z section"), (1, "x-z section"), (2, "x-y section"))
|
|
75
|
+
return [{"title": t, "png": png_url(slice_of(volume, a), kind, **kw)} for a, t in names]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def available_memory() -> float | None:
|
|
79
|
+
"""Bytes of physical memory available (None when unknown)."""
|
|
80
|
+
try:
|
|
81
|
+
if sys.platform == "win32":
|
|
82
|
+
import ctypes
|
|
83
|
+
|
|
84
|
+
class Status(ctypes.Structure):
|
|
85
|
+
_fields_ = [ # the layout of MEMORYSTATUSEX
|
|
86
|
+
("length", ctypes.c_ulong),
|
|
87
|
+
("load", ctypes.c_ulong),
|
|
88
|
+
("total", ctypes.c_ulonglong),
|
|
89
|
+
("available", ctypes.c_ulonglong),
|
|
90
|
+
("total_page", ctypes.c_ulonglong),
|
|
91
|
+
("available_page", ctypes.c_ulonglong),
|
|
92
|
+
("total_virtual", ctypes.c_ulonglong),
|
|
93
|
+
("available_virtual", ctypes.c_ulonglong),
|
|
94
|
+
("extended", ctypes.c_ulonglong),
|
|
95
|
+
]
|
|
96
|
+
|
|
97
|
+
status = Status()
|
|
98
|
+
status.length = ctypes.sizeof(Status)
|
|
99
|
+
if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
|
|
100
|
+
return float(status.available)
|
|
101
|
+
return None
|
|
102
|
+
if sys.platform == "darwin": # no SC_AVPHYS_PAGES: the pages vm_stat counts free
|
|
103
|
+
return _vm_stat_available(_vm_stat())
|
|
104
|
+
return float(os.sysconf("SC_AVPHYS_PAGES") * os.sysconf("SC_PAGE_SIZE"))
|
|
105
|
+
except (AttributeError, ValueError, OSError, subprocess.SubprocessError):
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _vm_stat() -> str:
|
|
110
|
+
"""The output of macOS's ``vm_stat`` (the statistics of the virtual memory)."""
|
|
111
|
+
return subprocess.run(["vm_stat"], capture_output=True, text=True, timeout=10,
|
|
112
|
+
check=True).stdout # fmt: skip
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _vm_stat_available(text: str) -> float | None:
|
|
116
|
+
"""Bytes of memory available by the output of macOS's ``vm_stat``: its free,
|
|
117
|
+
speculative and inactive pages (psutil's measure); None if it does not give them."""
|
|
118
|
+
size = re.search(r"page size of (\d+) bytes", text)
|
|
119
|
+
pages = dict(re.findall(r"^Pages (free|inactive|speculative):\s+(\d+)\.?\s*$", text, re.M))
|
|
120
|
+
if size is None or not {"free", "inactive"} <= pages.keys():
|
|
121
|
+
return None
|
|
122
|
+
return float(int(size.group(1)) * sum(int(n) for n in pages.values()))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def shown_warnings(caught) -> list[str]:
|
|
126
|
+
"""The warnings of a computation worth showing in the page: those of morphoGen and its
|
|
127
|
+
models, not the deprecations of the libraries (e.g. raised while Numba compiles)."""
|
|
128
|
+
noise = (DeprecationWarning, PendingDeprecationWarning, FutureWarning, ImportWarning)
|
|
129
|
+
out: list[str] = []
|
|
130
|
+
for w in caught:
|
|
131
|
+
module = getattr(w.category, "__module__", "") or ""
|
|
132
|
+
if issubclass(w.category, noise) or module.startswith(("numba", "llvmlite")):
|
|
133
|
+
continue
|
|
134
|
+
if str(w.message) not in out:
|
|
135
|
+
out.append(str(w.message))
|
|
136
|
+
return out
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def check_memory(nbytes: float, what: str) -> None:
|
|
140
|
+
"""Refuse a computation that would need more than half the free memory."""
|
|
141
|
+
free = available_memory()
|
|
142
|
+
if free is not None and nbytes > 0.5 * free:
|
|
143
|
+
raise ValueError(
|
|
144
|
+
f"{what}: about {nbytes / 2**30:.1f} GB, more than half of the free memory "
|
|
145
|
+
f"({free / 2**30:.1f} GB); choose a lower resolution"
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def examples() -> dict[str, dict]:
|
|
150
|
+
"""The example configuration of each model (the template of its name, else the first
|
|
151
|
+
template of that model): its parameters (``params``) and its domain (``domain``,
|
|
152
|
+
whose scale its parameters assume), which fill the forms of the interface, so that a
|
|
153
|
+
model can be run as it opens."""
|
|
154
|
+
from importlib import resources
|
|
155
|
+
|
|
156
|
+
folder = resources.files("morphogen") / "templates"
|
|
157
|
+
files = sorted((p for p in folder.iterdir() if p.name.endswith(".yaml")), key=lambda p: p.name)
|
|
158
|
+
out: dict[str, dict] = {}
|
|
159
|
+
for exact in (True, False):
|
|
160
|
+
for path in files:
|
|
161
|
+
try:
|
|
162
|
+
spec = yaml.safe_load(path.read_text(encoding="utf-8"))
|
|
163
|
+
except yaml.YAMLError:
|
|
164
|
+
continue
|
|
165
|
+
model = spec.get("model") if isinstance(spec, dict) else None
|
|
166
|
+
if not isinstance(model, dict) or not isinstance(model.get("type"), str):
|
|
167
|
+
continue
|
|
168
|
+
name = model["type"]
|
|
169
|
+
if name in out or exact != (path.name == f"{name}.yaml"):
|
|
170
|
+
continue
|
|
171
|
+
domain = spec.get("domain") if isinstance(spec.get("domain"), dict) else {}
|
|
172
|
+
out[name] = {
|
|
173
|
+
"params": {k: v for k, v in model.items() if k != "type"},
|
|
174
|
+
"domain": {k: domain[k] for k in ("size", "periodic") if k in domain},
|
|
175
|
+
}
|
|
176
|
+
return out
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
#: The families of the models: the groups of the menu of the models, in this order (the
|
|
180
|
+
#: models of no family come last, under "Other models")
|
|
181
|
+
MODEL_FAMILIES = {
|
|
182
|
+
"Random sets and particles": (
|
|
183
|
+
"boolean_spheres", "penetrable_spheres", "hardcore_spheres", "cox_spheres",
|
|
184
|
+
"dead_leaves", "transparent_dead_leaves", "gaussian_excursion", "reconstruction",
|
|
185
|
+
),
|
|
186
|
+
"Fibres and layers": (
|
|
187
|
+
"boolean_cylinders", "poisson_fibers", "hardcore_fibers", "curved_fibers",
|
|
188
|
+
"random_walk_fibers", "cross_linked_fibers", "delaunay_network", "random_laminate",
|
|
189
|
+
),
|
|
190
|
+
"Tessellations and foams": (
|
|
191
|
+
"voronoi", "laguerre", "ebsd", "open_foam", "level_set_foam", "honeycomb",
|
|
192
|
+
),
|
|
193
|
+
"Lattices and TPMS": (
|
|
194
|
+
"strut_lattice", "random_lattice", "hierarchical_lattice", "scale_rich_network", "tpms",
|
|
195
|
+
"fractal_sponge",
|
|
196
|
+
),
|
|
197
|
+
"Bio-inspired": ("nacre", "bouligand", "osteons"),
|
|
198
|
+
"Growth and patterns": (
|
|
199
|
+
"cellular_automaton", "activator_inhibitor", "reaction_diffusion", "nucleation_growth",
|
|
200
|
+
"aggregation", "branching",
|
|
201
|
+
),
|
|
202
|
+
"Assemblies and combinations": ("tile_assembly", "combination", "coating"),
|
|
203
|
+
} # fmt: skip
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _family(name: str) -> tuple[int, str]:
|
|
207
|
+
for k, (family, names) in enumerate(MODEL_FAMILIES.items()):
|
|
208
|
+
if name in names:
|
|
209
|
+
return k, family
|
|
210
|
+
return len(MODEL_FAMILIES), "Other models"
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _summary(doc: str) -> str:
|
|
214
|
+
"""The first paragraph of a docstring as one line, without its marks of code."""
|
|
215
|
+
first = doc.strip().split("\n\n")[0]
|
|
216
|
+
return " ".join(line.strip() for line in first.splitlines()).replace("``", "")
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def models() -> list[dict]:
|
|
220
|
+
"""Every model with its documentation, its summary (the first paragraph of it), family,
|
|
221
|
+
phases, parameters and the example values of its parameters, by family
|
|
222
|
+
(:data:`MODEL_FAMILIES`) and name."""
|
|
223
|
+
out = []
|
|
224
|
+
example = examples()
|
|
225
|
+
for name in sorted(list_models(), key=lambda n: (_family(n)[0], n)):
|
|
226
|
+
cls = get_model(name)
|
|
227
|
+
doc = (cls.__doc__ or "").strip()
|
|
228
|
+
parameters = cls.parameters()
|
|
229
|
+
names = {p["name"] for p in parameters}
|
|
230
|
+
given = example.get(name, {"params": {}, "domain": {}})
|
|
231
|
+
out.append(
|
|
232
|
+
{
|
|
233
|
+
"name": name,
|
|
234
|
+
"family": _family(name)[1],
|
|
235
|
+
"summary": _summary(doc) or name,
|
|
236
|
+
"doc": doc,
|
|
237
|
+
"phases": {str(k): v for k, v in cls.phases.items()},
|
|
238
|
+
"parameters": parameters,
|
|
239
|
+
"example": {k: v for k, v in given["params"].items() if k in names},
|
|
240
|
+
"example_domain": given["domain"],
|
|
241
|
+
"evolution": hasattr(cls, "evolution"),
|
|
242
|
+
# conforming meshes: the implicit functions of the phases of every model
|
|
243
|
+
"meshable": True,
|
|
244
|
+
}
|
|
245
|
+
)
|
|
246
|
+
return out
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _clean(params: dict) -> dict:
|
|
250
|
+
"""Parameters from the form: empty values are left to their defaults."""
|
|
251
|
+
return {k: v for k, v in params.items() if v not in (None, "")}
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _domain(spec: dict) -> Domain:
|
|
255
|
+
size = spec.get("size", 10.0)
|
|
256
|
+
return Domain(size=size, periodic=bool(spec.get("periodic", True)))
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _seed(value) -> int:
|
|
260
|
+
"""The seed of the form, or a fresh one (recorded, so that the realization can be
|
|
261
|
+
simulated and rerun)."""
|
|
262
|
+
if value in (None, ""):
|
|
263
|
+
return int(np.random.SeedSequence().entropy % 2**31)
|
|
264
|
+
return int(value)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _resolution(value, default: int = 512) -> int:
|
|
268
|
+
n = default if value in (None, "", 0) else int(value)
|
|
269
|
+
if not 8 <= n <= MAX_RESOLUTION:
|
|
270
|
+
raise ValueError(f"resolution: from 8 to {MAX_RESOLUTION} pixels per edge")
|
|
271
|
+
return n
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _shape(value, limit: int = MAX_SHAPE) -> int | None:
|
|
275
|
+
if value in (None, "", 0):
|
|
276
|
+
return None
|
|
277
|
+
n = int(value)
|
|
278
|
+
if not 2 <= n <= limit:
|
|
279
|
+
raise ValueError(f"voxels per edge: from 2 to {limit}")
|
|
280
|
+
return n
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _voxels(domain: Domain, n: int, bytes_per_voxel: float, what: str) -> None:
|
|
284
|
+
"""Check the memory of a voxel image of ``n`` voxels along the longest edge."""
|
|
285
|
+
lengths = np.asarray(domain.lengths, dtype=float)
|
|
286
|
+
count = float(np.prod(np.maximum(1, np.rint(lengths / (lengths.max() / n)))))
|
|
287
|
+
check_memory(count * bytes_per_voxel, what)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
class Session:
|
|
291
|
+
"""The files written by the interface (one folder per result) and its workspace: the
|
|
292
|
+
morphologies, simulations, behaviours (of materials) and results of the tools of the
|
|
293
|
+
session, under the keys of their folders, with their objects in memory (the
|
|
294
|
+
microstructures)."""
|
|
295
|
+
|
|
296
|
+
#: The fields of the items sent to the page
|
|
297
|
+
PUBLIC = (
|
|
298
|
+
"key",
|
|
299
|
+
"kind",
|
|
300
|
+
"number",
|
|
301
|
+
"title",
|
|
302
|
+
"origin",
|
|
303
|
+
"source",
|
|
304
|
+
"thumbnail",
|
|
305
|
+
"info",
|
|
306
|
+
"phases",
|
|
307
|
+
"files",
|
|
308
|
+
"property",
|
|
309
|
+
"planar",
|
|
310
|
+
"fraction",
|
|
311
|
+
"materials",
|
|
312
|
+
"tool",
|
|
313
|
+
"tab",
|
|
314
|
+
"view3d",
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
def __init__(self, root: Path):
|
|
318
|
+
self.root = Path(root)
|
|
319
|
+
self.root.mkdir(parents=True, exist_ok=True)
|
|
320
|
+
self.items: dict[str, dict] = {}
|
|
321
|
+
self._count = 0 # the numbers given, never given again (after a removal)
|
|
322
|
+
self._lock = threading.Lock()
|
|
323
|
+
|
|
324
|
+
def folder(self) -> tuple[str, Path]:
|
|
325
|
+
key = uuid.uuid4().hex[:12]
|
|
326
|
+
path = self.root / key
|
|
327
|
+
path.mkdir()
|
|
328
|
+
return key, path
|
|
329
|
+
|
|
330
|
+
def file(self, key: str, name: str) -> Path:
|
|
331
|
+
path = (self.root / key / name).resolve()
|
|
332
|
+
if self.root.resolve() not in path.parents or not path.is_file():
|
|
333
|
+
raise FileNotFoundError(name)
|
|
334
|
+
return path
|
|
335
|
+
|
|
336
|
+
def add(self, key: str, kind: str, title: str, **data) -> dict:
|
|
337
|
+
"""Keep a result in the workspace (``kind``: "morphology", "simulation",
|
|
338
|
+
"behaviour": the material of a material point or of an import of Z-set, see
|
|
339
|
+
:func:`behaviour_material`, or "result": the run of a tool, see
|
|
340
|
+
:class:`morphogen.gui.tools.ToolJob`)."""
|
|
341
|
+
with self._lock:
|
|
342
|
+
self._count += 1
|
|
343
|
+
number = self._count
|
|
344
|
+
item = {"key": key, "kind": kind, "number": number, "title": f"#{number} {title}"}
|
|
345
|
+
item.update(data)
|
|
346
|
+
self.items[key] = item
|
|
347
|
+
return item
|
|
348
|
+
|
|
349
|
+
def item(self, key, kinds=("morphology", "simulation")) -> dict:
|
|
350
|
+
with self._lock:
|
|
351
|
+
item = self.items.get(str(key))
|
|
352
|
+
if item is None or item["kind"] not in kinds:
|
|
353
|
+
raise ValueError(f"no {' or '.join(kinds)} {key!r} in the workspace of this session")
|
|
354
|
+
return item
|
|
355
|
+
|
|
356
|
+
def remove(self, key) -> None:
|
|
357
|
+
"""Take an item out of the workspace (its files stay in the session folder)."""
|
|
358
|
+
with self._lock:
|
|
359
|
+
if self.items.pop(str(key), None) is None:
|
|
360
|
+
raise ValueError(f"no item {key!r} in the workspace of this session")
|
|
361
|
+
|
|
362
|
+
def rename(self, key, title) -> dict:
|
|
363
|
+
"""Give an item another title (after its number, which it keeps)."""
|
|
364
|
+
title = " ".join(str(title or "").split())
|
|
365
|
+
if not title:
|
|
366
|
+
raise ValueError("title: some text")
|
|
367
|
+
with self._lock:
|
|
368
|
+
item = self.items.get(str(key))
|
|
369
|
+
if item is None:
|
|
370
|
+
raise ValueError(f"no item {key!r} in the workspace of this session")
|
|
371
|
+
item["title"] = f"#{item['number']} {title[:120]}"
|
|
372
|
+
return item
|
|
373
|
+
|
|
374
|
+
def morphology_of(self, key) -> dict:
|
|
375
|
+
"""The morphology of an item: itself, or that of a simulation."""
|
|
376
|
+
item = self.item(key)
|
|
377
|
+
return item if item["kind"] == "morphology" else self.item(item["source"], ("morphology",))
|
|
378
|
+
|
|
379
|
+
def public(self, item: dict) -> dict:
|
|
380
|
+
out = {k: v for k, v in item.items() if k in self.PUBLIC}
|
|
381
|
+
out["traits"] = item_traits(item)
|
|
382
|
+
return out
|
|
383
|
+
|
|
384
|
+
def workspace(self) -> list[dict]:
|
|
385
|
+
"""The items of the workspace for the page (without their objects), newest first."""
|
|
386
|
+
with self._lock:
|
|
387
|
+
items = sorted(self.items.values(), key=lambda i: -i["number"])
|
|
388
|
+
return [self.public(i) for i in items]
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
#: The traits of the morphologies that some tools need (``Field(needs=...)``): the page
|
|
392
|
+
#: offers them only the items that have them
|
|
393
|
+
TRAITS = {
|
|
394
|
+
"model": "the realization of a model (generated in Generate)",
|
|
395
|
+
"grains": "a polycrystal (a Voronoi or Laguerre tessellation)",
|
|
396
|
+
"curves": "the run of a loading path, a material point, an identification, a learned "
|
|
397
|
+
"law or a dynamic test (its curves)",
|
|
398
|
+
"framework": "a network of fibres or struts (a realization of delaunay_network, open_foam "
|
|
399
|
+
"or random_lattice, which keep their framework for a frame of beams)",
|
|
400
|
+
}
|
|
401
|
+
#: The tools whose runs have curves (:func:`curves_of`), and the names of their tables
|
|
402
|
+
CURVE_TOOLS = {
|
|
403
|
+
"path": "sample_0000_*_*.csv",
|
|
404
|
+
"point": "point_*.csv",
|
|
405
|
+
"identify": "identified_*.csv",
|
|
406
|
+
"learn": "learned_*.csv",
|
|
407
|
+
"radioss_test": "curves.csv",
|
|
408
|
+
"radioss_results": "curves.csv",
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def item_traits(item: dict) -> list[str]:
|
|
413
|
+
"""The traits of an item of the workspace (:data:`TRAITS`)."""
|
|
414
|
+
micro = item.get("micro")
|
|
415
|
+
out = ["model"] if item.get("model") else []
|
|
416
|
+
if micro is not None and hasattr(micro, "cell_of") and hasattr(micro, "germs"):
|
|
417
|
+
out.append("grains")
|
|
418
|
+
if micro is not None and (getattr(micro, "metadata", None) or {}).get("framework"):
|
|
419
|
+
out.append("framework")
|
|
420
|
+
if item.get("tool") in CURVE_TOOLS:
|
|
421
|
+
out.append("curves")
|
|
422
|
+
return out
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def curves_of(item: dict, root) -> Path:
|
|
426
|
+
"""The table of the curves of the run of a loading path, a material point or an
|
|
427
|
+
identification (the first of a path under several boundary conditions)."""
|
|
428
|
+
pattern = CURVE_TOOLS.get(item.get("tool"))
|
|
429
|
+
found = sorted((Path(root) / item["key"]).glob(pattern)) if pattern else []
|
|
430
|
+
if not found:
|
|
431
|
+
raise ValueError(
|
|
432
|
+
f"{item['title']}: no curves (a loading path, a material point, an identification)"
|
|
433
|
+
)
|
|
434
|
+
return found[0]
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
# -- behaviours ----------------------------------------------------------------------------
|
|
438
|
+
|
|
439
|
+
#: The names of the behaviours of the materials (their keys in the configurations)
|
|
440
|
+
BEHAVIOUR_NAMES = {
|
|
441
|
+
"crystal_plasticity": "crystal plasticity",
|
|
442
|
+
"porous_plasticity": "porous plasticity",
|
|
443
|
+
"plasticity": "von Mises plasticity",
|
|
444
|
+
"mfront": "MFront behaviour",
|
|
445
|
+
"learned": "learned law",
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def behaviour_summary(config: dict) -> tuple[str, dict]:
|
|
450
|
+
"""The name of the behaviour of a material (a mapping of the configurations of
|
|
451
|
+
:meth:`~morphogen.homogenization.materials.Material.from_config`) and its main
|
|
452
|
+
constants, for the behaviours of the workspace."""
|
|
453
|
+
kind = next((k for k in BEHAVIOUR_NAMES if k in config), None)
|
|
454
|
+
name = BEHAVIOUR_NAMES.get(kind, "elasticity")
|
|
455
|
+
hill = (config.get("plasticity") or {}).get("hill") if kind == "plasticity" else None
|
|
456
|
+
if hill is not None: # the hardenings of von Mises on Hill's criterion
|
|
457
|
+
name = "Hill plasticity"
|
|
458
|
+
info: dict = {"behaviour": name}
|
|
459
|
+
if "young" in config:
|
|
460
|
+
info.update(E=config["young"], ν=config.get("poisson"))
|
|
461
|
+
elif "cubic" in config:
|
|
462
|
+
info["C11, C12, C44"] = ", ".join(f"{c:.4g}" for c in config["cubic"])
|
|
463
|
+
plastic = config.get("plasticity") or config.get("porous_plasticity") or {}
|
|
464
|
+
if "yield" in plastic:
|
|
465
|
+
info["R0"] = plastic["yield"]
|
|
466
|
+
if hill is not None:
|
|
467
|
+
from morphogen.homogenization.behaviours import HILL_COMPONENTS
|
|
468
|
+
|
|
469
|
+
if isinstance(hill, dict): # by component, 1 where not given
|
|
470
|
+
hill = {str(k): v for k, v in hill.items()}
|
|
471
|
+
hill = [hill.get(c, 1.0) for c in HILL_COMPONENTS]
|
|
472
|
+
info[", ".join(f"h{c}" for c in HILL_COMPONENTS)] = ", ".join(
|
|
473
|
+
f"{float(h):.4g}" for h in hill
|
|
474
|
+
)
|
|
475
|
+
if "porosity" in plastic:
|
|
476
|
+
info["f0"] = plastic["porosity"]
|
|
477
|
+
families = (config.get("crystal_plasticity") or {}).get("families") or {}
|
|
478
|
+
if families:
|
|
479
|
+
params = next(iter(families.values()))
|
|
480
|
+
info.update(families=", ".join(families), τ0=params.get("tau0"))
|
|
481
|
+
if kind == "mfront":
|
|
482
|
+
info["MFront"] = config["mfront"].get("behaviour")
|
|
483
|
+
return name, {k: v for k, v in info.items() if v is not None}
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def behaviour_config(config: dict, folder) -> dict:
|
|
487
|
+
"""A material (a mapping of the configurations) made the behaviour of the workspace of
|
|
488
|
+
``folder``: its MFront source (or the model of its learned law) copied there and named
|
|
489
|
+
by its name (its library, if any, kept where it is), so that the behaviour is saved
|
|
490
|
+
and opened with the workspace."""
|
|
491
|
+
import copy
|
|
492
|
+
|
|
493
|
+
config = copy.deepcopy(config)
|
|
494
|
+
for key, name in (("mfront", "source"), ("learned", "model")):
|
|
495
|
+
spec = config.get(key) if isinstance(config, dict) else None
|
|
496
|
+
if isinstance(spec, dict) and spec.get(name):
|
|
497
|
+
source = Path(spec[name])
|
|
498
|
+
if source.is_absolute() and source.is_file():
|
|
499
|
+
target = Path(folder) / source.name
|
|
500
|
+
if not target.exists():
|
|
501
|
+
shutil.copyfile(source, target)
|
|
502
|
+
spec[name] = source.name
|
|
503
|
+
return config
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def behaviour_material(item: dict, root) -> dict:
|
|
507
|
+
"""The material of a behaviour of the workspace (a mapping of the configurations), the
|
|
508
|
+
files it names by their names in its folder (the MFront source of an import of
|
|
509
|
+
Z-set, the model of a learned law) given by their paths under ``root``, the folder of
|
|
510
|
+
the session."""
|
|
511
|
+
import copy
|
|
512
|
+
|
|
513
|
+
material = copy.deepcopy(item["material"])
|
|
514
|
+
mfront = material.get("mfront") if isinstance(material, dict) else None
|
|
515
|
+
if isinstance(mfront, dict):
|
|
516
|
+
for key in ("source", "library"):
|
|
517
|
+
if mfront.get(key) and not Path(mfront[key]).is_absolute():
|
|
518
|
+
mfront[key] = str(Path(root) / item["key"] / mfront[key])
|
|
519
|
+
learned = material.get("learned") if isinstance(material, dict) else None
|
|
520
|
+
if isinstance(learned, dict) and learned.get("model"):
|
|
521
|
+
if not Path(learned["model"]).is_absolute():
|
|
522
|
+
learned["model"] = str(Path(root) / item["key"] / learned["model"])
|
|
523
|
+
return material
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
# -- morphologies --------------------------------------------------------------------------
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
def _png(rgb: np.ndarray, folder: Path | None, key: str | None, name: str) -> str:
|
|
530
|
+
"""A view: a data URL when small (or without a session), else a file of the session."""
|
|
531
|
+
if folder is None or max(rgb.shape[:2]) <= INLINE_PIXELS:
|
|
532
|
+
return _data_url(rgb)
|
|
533
|
+
(folder / name).write_bytes(encode_png(rgb))
|
|
534
|
+
return f"/files/{key}/{name}?inline"
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _thumbnail(rgb: np.ndarray, size: int = 96) -> str:
|
|
538
|
+
step = max(1, max(rgb.shape[:2]) // size)
|
|
539
|
+
return _data_url(np.ascontiguousarray(rgb[::step, ::step]))
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def morphology_views(micro, resolution: int, folder: Path | None = None, key=None) -> dict:
|
|
543
|
+
"""Sections of the implicit functions of a morphology (anti-aliased boundaries: of its
|
|
544
|
+
level set, or of the functions of its phases when it has several; else the phases of
|
|
545
|
+
the pixel centres) at ``resolution`` pixels along the longest edge, its cells, its
|
|
546
|
+
measures (of the level set, at :data:`MEASURE_RESOLUTION` cells per edge; else of a
|
|
547
|
+
voxel image) and a thumbnail. ``level_set``: whether the sections are those of
|
|
548
|
+
implicit functions; ``implicit_phases``: how many phases have theirs."""
|
|
549
|
+
from morphogen.viz import sections as vs
|
|
550
|
+
|
|
551
|
+
cuts = vs.sections(micro, resolution)
|
|
552
|
+
level_set = all(s.level_set is not None for s in cuts) # one function: two phases
|
|
553
|
+
out: dict = {
|
|
554
|
+
"sections": [],
|
|
555
|
+
"level_set": level_set or all(bool(s.coverages) for s in cuts),
|
|
556
|
+
"implicit_phases": len(micro.implicit_phases()),
|
|
557
|
+
}
|
|
558
|
+
xy = None
|
|
559
|
+
for s in cuts:
|
|
560
|
+
rgb = vs.render(s, "phase")
|
|
561
|
+
name = f"{s.names[0]}-{s.names[1]} section"
|
|
562
|
+
out["sections"].append(
|
|
563
|
+
{"title": name, "png": _png(rgb, folder, key, f"section_{''.join(s.names)}.png")}
|
|
564
|
+
)
|
|
565
|
+
if s.axis == 2:
|
|
566
|
+
xy = rgb
|
|
567
|
+
if any(s.labels is not None for s in cuts):
|
|
568
|
+
out["labels"] = [
|
|
569
|
+
{
|
|
570
|
+
"title": f"{s.names[0]}-{s.names[1]} cells",
|
|
571
|
+
"png": _png(vs.render(s, "labels"), folder, key, f"cells_{''.join(s.names)}.png"),
|
|
572
|
+
}
|
|
573
|
+
for s in cuts
|
|
574
|
+
if s.labels is not None
|
|
575
|
+
]
|
|
576
|
+
out["thumbnail"] = _thumbnail(xy if xy is not None else vs.render(cuts[-1], "phase"))
|
|
577
|
+
n = min(resolution, MEASURE_RESOLUTION)
|
|
578
|
+
if level_set:
|
|
579
|
+
measures = vs.level_set_measures(micro, n)
|
|
580
|
+
out["measures"] = _finite({f"{k} (level set)": v for k, v in measures.items()})
|
|
581
|
+
out["fraction"] = float(measures.get("volume_fraction", np.nan))
|
|
582
|
+
else:
|
|
583
|
+
image = micro.voxelize(shape=n)
|
|
584
|
+
measures = analysis.measure(image, ["phase_fractions", "specific_surface"])
|
|
585
|
+
out["measures"] = _finite({f"{k} ({n} voxels)": v for k, v in measures.items()})
|
|
586
|
+
out["fraction"] = float(measures.get("fraction_1", np.nan))
|
|
587
|
+
return out
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def _title(model, seed: int) -> str:
|
|
591
|
+
return f"{model.name} (seed {seed})"
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
#: The stiffness of the frame of beams in the summaries of the network models
|
|
595
|
+
#: (``frame_stiffness: true``: :meth:`~morphogen.homogenization.networks.FrameStiffness.
|
|
596
|
+
#: summary`), labelled as the page shows it, and how they compute it
|
|
597
|
+
FRAME_SUMMARY = {
|
|
598
|
+
"frame_young": "E / E_s",
|
|
599
|
+
"frame_poisson": "Poisson's ratio",
|
|
600
|
+
"frame_affinity": "E / E affine",
|
|
601
|
+
"frame_stretching": "stretching energy",
|
|
602
|
+
"frame_nonaffinity": "non-affinity",
|
|
603
|
+
"frame_young_per_density": "E / (E_s φ)",
|
|
604
|
+
}
|
|
605
|
+
FRAME_NOTE = (
|
|
606
|
+
"Euler–Bernoulli beams along the fibres (E_s = 1, ν = 0.3) under a uniaxial stress, the "
|
|
607
|
+
"means over the axes; Timoshenko beams, rigid joints and the softening of non-identical "
|
|
608
|
+
"beams in Mechanics, Stiffness of the frame of beams"
|
|
609
|
+
)
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def frame_summary(summary: dict) -> dict:
|
|
613
|
+
"""The stiffness of the frame of beams in the summary of a realization, labelled
|
|
614
|
+
(:data:`FRAME_SUMMARY`; empty without it)."""
|
|
615
|
+
return {label: summary[k] for k, label in FRAME_SUMMARY.items() if k in summary}
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
def frame_matrices(summary: dict) -> tuple[np.ndarray, np.ndarray] | None:
|
|
619
|
+
"""The stiffness and compliance of the frame of beams in the summary of a realization
|
|
620
|
+
(its entries ``frame_C11``... and ``frame_S11``..., 6 x 6 or 3 x 3 in the plane), or
|
|
621
|
+
None without them."""
|
|
622
|
+
if "frame_C11" not in summary:
|
|
623
|
+
return None
|
|
624
|
+
n = 6 if "frame_C66" in summary else 3
|
|
625
|
+
out = []
|
|
626
|
+
for prefix in ("frame_C", "frame_S"):
|
|
627
|
+
m = np.zeros((n, n))
|
|
628
|
+
for i in range(n):
|
|
629
|
+
for j in range(i, n):
|
|
630
|
+
m[i, j] = m[j, i] = summary[f"{prefix}{i + 1}{j + 1}"]
|
|
631
|
+
out.append(m)
|
|
632
|
+
return out[0], out[1]
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
def generate(request: dict, session: Session | None = None) -> dict:
|
|
636
|
+
"""One realization (the realization 0 of a run with its seed): sections of its level
|
|
637
|
+
set at ``resolution`` pixels per edge, summary, theory and measures; kept as a
|
|
638
|
+
morphology in the workspace of the ``session``."""
|
|
639
|
+
model = model_from_config({"type": request["model"], **_clean(request.get("params", {}))})
|
|
640
|
+
spec = request.get("domain", {})
|
|
641
|
+
domain = _domain(spec)
|
|
642
|
+
seed = _seed(request.get("seed"))
|
|
643
|
+
resolution = _resolution(request.get("resolution"))
|
|
644
|
+
key = folder = None
|
|
645
|
+
if session is not None:
|
|
646
|
+
key, folder = session.folder()
|
|
647
|
+
t0 = time.perf_counter()
|
|
648
|
+
with warnings.catch_warnings(record=True) as caught: # shown with the results
|
|
649
|
+
warnings.simplefilter("always")
|
|
650
|
+
micro = model.generate(domain, derive_seed(seed, 0))
|
|
651
|
+
views = morphology_views(micro, resolution, folder, key)
|
|
652
|
+
elapsed = time.perf_counter() - t0
|
|
653
|
+
out = {
|
|
654
|
+
"model": model.to_config(),
|
|
655
|
+
"seed": seed,
|
|
656
|
+
"summary": micro.summary(),
|
|
657
|
+
"theory": _finite(model.theory(domain)),
|
|
658
|
+
"measures": views["measures"],
|
|
659
|
+
"resolution": resolution,
|
|
660
|
+
"level_set": views["level_set"],
|
|
661
|
+
"implicit_phases": views["implicit_phases"],
|
|
662
|
+
"sections": views["sections"],
|
|
663
|
+
"time_s": round(elapsed, 3),
|
|
664
|
+
"warnings": shown_warnings(caught),
|
|
665
|
+
}
|
|
666
|
+
if "labels" in views:
|
|
667
|
+
out["labels"] = views["labels"]
|
|
668
|
+
frame = frame_summary(out["summary"])
|
|
669
|
+
if frame:
|
|
670
|
+
out["frame"] = {"values": frame, "note": FRAME_NOTE}
|
|
671
|
+
matrices = frame_matrices(out["summary"])
|
|
672
|
+
if matrices is not None and folder is not None: # its C and S, as the tools show them
|
|
673
|
+
from morphogen.gui.tools import Context, elastic_tables
|
|
674
|
+
|
|
675
|
+
ctx = Context(session, key, folder)
|
|
676
|
+
units = ("units of the modulus of the fibres", "their inverse")
|
|
677
|
+
if len(matrices[0]) == 3:
|
|
678
|
+
units = ("per unit area: units of the modulus of the fibres times a length",
|
|
679
|
+
"their inverse") # fmt: skip
|
|
680
|
+
elastic_tables(ctx, matrices[0], "of the frame", names=("frame_stiffness",
|
|
681
|
+
"frame_compliance"), units=units, compliance=matrices[1]) # fmt: skip
|
|
682
|
+
out["frame"]["tables"] = ctx.tables
|
|
683
|
+
if session is not None:
|
|
684
|
+
io.save_microstructure(micro, folder / "microstructure.json")
|
|
685
|
+
files = {"geometry": f"/files/{key}/microstructure.json"}
|
|
686
|
+
info = {"model": model.name, "seed": seed}
|
|
687
|
+
if views["level_set"] and views["implicit_phases"] > 2: # one function per phase
|
|
688
|
+
info["implicit functions"] = f"of its {views['implicit_phases']} phases"
|
|
689
|
+
else:
|
|
690
|
+
info["level set"] = views["level_set"]
|
|
691
|
+
if "E / E_s" in frame: # the frame of beams of a network model
|
|
692
|
+
info["frame E / E_s"] = frame["E / E_s"]
|
|
693
|
+
item = session.add(
|
|
694
|
+
key,
|
|
695
|
+
"morphology",
|
|
696
|
+
_title(model, seed),
|
|
697
|
+
micro=micro,
|
|
698
|
+
origin="generate",
|
|
699
|
+
model=model.to_config(),
|
|
700
|
+
domain={"size": spec.get("size", 10.0), "periodic": domain.periodic},
|
|
701
|
+
seed=seed,
|
|
702
|
+
phases={str(k): v for k, v in model.active_phases().items()},
|
|
703
|
+
thumbnail=views["thumbnail"],
|
|
704
|
+
fraction=views["fraction"],
|
|
705
|
+
planar=_planar(micro),
|
|
706
|
+
info=info,
|
|
707
|
+
files=files,
|
|
708
|
+
)
|
|
709
|
+
out["item"] = session.public(item)
|
|
710
|
+
out["files"] = files
|
|
711
|
+
return out
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
def _planar(micro) -> bool:
|
|
715
|
+
"""Whether a morphology is a plane structure (one cell through the thickness)."""
|
|
716
|
+
lengths = np.asarray(micro.domain.lengths, dtype=float)
|
|
717
|
+
return bool(lengths[2] < 0.05 * lengths[:2].max())
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
def formation(request: dict) -> dict:
|
|
721
|
+
"""Middle sections of a structure along its formation (automata, reaction-diffusion,
|
|
722
|
+
nucleation and growth, aggregation), from the initial state to the realization."""
|
|
723
|
+
model = model_from_config({"type": request["model"], **_clean(request.get("params", {}))})
|
|
724
|
+
if not hasattr(model, "evolution"):
|
|
725
|
+
raise ValueError(f"model {model.name} has no formation history (automata and growth do)")
|
|
726
|
+
frames = int(request.get("frames", 20))
|
|
727
|
+
if not 2 <= frames <= MAX_FRAMES:
|
|
728
|
+
raise ValueError(f"frames: from 2 to {MAX_FRAMES}")
|
|
729
|
+
domain = _domain(request.get("domain", {}))
|
|
730
|
+
seed = request.get("seed")
|
|
731
|
+
seed = None if seed in (None, "") else derive_seed(int(seed), 0)
|
|
732
|
+
states = model.evolution(domain, seed, frames)
|
|
733
|
+
labels = states[-1].dtype == np.int32
|
|
734
|
+
kind = "labels" if labels else ("phase" if states[-1].dtype == np.uint8 else "field")
|
|
735
|
+
lo = min(float(s.min()) for s in states)
|
|
736
|
+
hi = max(float(s.max()) for s in states)
|
|
737
|
+
images = [png_url(slice_of(s, 2), kind, vmin=lo, vmax=hi) for s in states]
|
|
738
|
+
changes = [float(np.mean(b != a)) for a, b in itertools.pairwise(states)]
|
|
739
|
+
return {"frames": images, "kind": kind, "changes": changes}
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
evolve = formation # the former name of the action
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
def count(request: dict) -> dict:
|
|
746
|
+
"""Exact number of compatible assemblies, and one assembly drawn by WFC."""
|
|
747
|
+
from morphogen.design import (
|
|
748
|
+
count_assemblies,
|
|
749
|
+
count_polarized_blocks,
|
|
750
|
+
polarized_blocks,
|
|
751
|
+
wave_function_collapse,
|
|
752
|
+
)
|
|
753
|
+
from morphogen.design.tiles import TILE_SETS
|
|
754
|
+
|
|
755
|
+
name = request.get("tiles", "polarized")
|
|
756
|
+
if name not in TILE_SETS:
|
|
757
|
+
raise ValueError(f"tiles: one of {list(TILE_SETS)}")
|
|
758
|
+
shape = tuple(int(n) for n in request.get("shape", (3, 3, 3)))
|
|
759
|
+
periodic = bool(request.get("periodic", False))
|
|
760
|
+
tiles = polarized_blocks(8) if name == "polarized" else TILE_SETS[name](8)
|
|
761
|
+
out: dict = {"tiles": name, "n_tiles": tiles.n_tiles, "shape": list(shape)}
|
|
762
|
+
try:
|
|
763
|
+
if name == "polarized":
|
|
764
|
+
n = count_polarized_blocks(shape, periodic=periodic)
|
|
765
|
+
else:
|
|
766
|
+
n = count_assemblies(tiles, shape, periodic=periodic, max_states=5000)
|
|
767
|
+
out["count"] = str(n)
|
|
768
|
+
out["log2_count"] = float(np.log2(n)) if n > 0 else None
|
|
769
|
+
except (ValueError, OverflowError) as exc:
|
|
770
|
+
out["count_error"] = str(exc)
|
|
771
|
+
try:
|
|
772
|
+
rng = np.random.default_rng(request.get("seed"))
|
|
773
|
+
assembly = wave_function_collapse(tiles, shape, rng, periodic=periodic)
|
|
774
|
+
out["assembly"] = sections(tiles.assemble(assembly), "phase")
|
|
775
|
+
except ValueError as exc:
|
|
776
|
+
out["assembly_error"] = str(exc)
|
|
777
|
+
return out
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
def _finite(values: dict) -> dict:
|
|
781
|
+
return {k: v for k, v in values.items() if isinstance(v, (int, float)) and np.isfinite(v)}
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
# -- optimization ----------------------------------------------------------------------------
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
class OptimizationJob:
|
|
788
|
+
"""A topology optimization running in a thread, with its progress; it starts from a
|
|
789
|
+
void ball, noise, or a morphology of the workspace (``start``: its key, or that of a
|
|
790
|
+
simulation, whose morphology and solid material it takes), and keeps its design in the
|
|
791
|
+
workspace as a morphology (its level set: the densities about 1/2), also when it is
|
|
792
|
+
stopped (:meth:`stop`: the design of its last iteration)."""
|
|
793
|
+
|
|
794
|
+
def __init__(self, request: dict, session: Session | None = None):
|
|
795
|
+
from morphogen.homogenization.materials import Material
|
|
796
|
+
from morphogen.optimization import CellOptimization, initial_density
|
|
797
|
+
from morphogen.optimization.topology import INITIAL
|
|
798
|
+
|
|
799
|
+
grid = request.get("grid", [48, 48, 1])
|
|
800
|
+
grid = [int(grid)] * 3 if np.ndim(grid) == 0 else [int(n) for n in grid]
|
|
801
|
+
if int(np.prod(grid)) > MAX_OPT_VOXELS:
|
|
802
|
+
raise ValueError(f"grid: at most {MAX_OPT_VOXELS} voxels in the interface")
|
|
803
|
+
settings = _clean(request.get("settings", {}))
|
|
804
|
+
start = request.get("start") or settings.pop("initial", None) or "centered_void"
|
|
805
|
+
self.source = None
|
|
806
|
+
if start not in INITIAL:
|
|
807
|
+
if session is None:
|
|
808
|
+
raise ValueError("start: a morphology needs the workspace of a session")
|
|
809
|
+
item = session.item(start)
|
|
810
|
+
morphology = session.morphology_of(start)
|
|
811
|
+
phase = int(request.get("solid_phase", 1))
|
|
812
|
+
settings["initial"] = initial_density(morphology["micro"], grid, phase=phase)
|
|
813
|
+
solid = (item.get("materials") or {}).get(str(phase))
|
|
814
|
+
if isinstance(solid, dict) and "material" not in settings:
|
|
815
|
+
settings["material"] = Material(
|
|
816
|
+
young=float(solid["young"]), poisson=float(solid["poisson"]), conductivity=1.0
|
|
817
|
+
)
|
|
818
|
+
self.source = (item, morphology)
|
|
819
|
+
else:
|
|
820
|
+
settings["initial"] = start
|
|
821
|
+
volume = request.get("volume_fraction")
|
|
822
|
+
if volume in (None, "") and self.source is not None:
|
|
823
|
+
volume = float(np.mean(settings["initial"]))
|
|
824
|
+
self.optimization = CellOptimization(tuple(grid), float(volume), **settings)
|
|
825
|
+
self.seed = request.get("seed")
|
|
826
|
+
self.session = session
|
|
827
|
+
self.state = "running"
|
|
828
|
+
self.progress: dict = {"iteration": 0, "objective": [], "volume": []}
|
|
829
|
+
self.image = None
|
|
830
|
+
self.result: dict | None = None
|
|
831
|
+
self.error: str | None = None
|
|
832
|
+
self._lock = threading.Lock()
|
|
833
|
+
self._stop = threading.Event()
|
|
834
|
+
self.thread = threading.Thread(target=self._run, daemon=True)
|
|
835
|
+
|
|
836
|
+
def start(self) -> OptimizationJob:
|
|
837
|
+
self.thread.start()
|
|
838
|
+
return self
|
|
839
|
+
|
|
840
|
+
def stop(self) -> None:
|
|
841
|
+
"""Stop at the end of the iteration under way, the design so far kept."""
|
|
842
|
+
self._stop.set()
|
|
843
|
+
|
|
844
|
+
def _callback(self, iteration, density, objective):
|
|
845
|
+
with self._lock:
|
|
846
|
+
self.progress["iteration"] = iteration
|
|
847
|
+
self.progress["objective"].append(float(objective))
|
|
848
|
+
self.progress["volume"].append(float(density.mean()))
|
|
849
|
+
if iteration % 3 == 1:
|
|
850
|
+
self.image = density.copy()
|
|
851
|
+
return self._stop.is_set() # True: the optimizer stops there
|
|
852
|
+
|
|
853
|
+
def _domain(self, design) -> Domain | None:
|
|
854
|
+
"""The domain of the design: that of its morphology (its plane: one voxel thick)."""
|
|
855
|
+
if self.source is None:
|
|
856
|
+
return None
|
|
857
|
+
domain = self.source[1]["micro"].domain
|
|
858
|
+
lengths = np.asarray(domain.lengths, dtype=float)
|
|
859
|
+
shape = design.density.shape
|
|
860
|
+
if shape[2] == 1:
|
|
861
|
+
lengths[2] = min(lengths[0] / shape[0], lengths[1] / shape[1])
|
|
862
|
+
return Domain(size=tuple(float(v) for v in lengths), periodic=True)
|
|
863
|
+
|
|
864
|
+
def _run(self):
|
|
865
|
+
try:
|
|
866
|
+
design = self.optimization.run(np.random.default_rng(self.seed), self._callback)
|
|
867
|
+
result = {
|
|
868
|
+
"iterations": design.iterations,
|
|
869
|
+
"converged": design.converged,
|
|
870
|
+
"stopped": self._stop.is_set() and not design.converged,
|
|
871
|
+
"volume_fraction": design.volume_fraction,
|
|
872
|
+
"binary_fraction": design.binary_fraction,
|
|
873
|
+
"properties": _finite(design.properties()),
|
|
874
|
+
"refined_properties": _finite(design.refined_properties(2)),
|
|
875
|
+
"hinges": design.hinges,
|
|
876
|
+
"time_s": round(design.time_s, 2),
|
|
877
|
+
}
|
|
878
|
+
if self.session is not None:
|
|
879
|
+
key, folder = self.session.folder()
|
|
880
|
+
micro = design.to_microstructure(self._domain(design), smoothing=DESIGN_SMOOTHING)
|
|
881
|
+
io.save_microstructure(micro, folder / "design.json")
|
|
882
|
+
files = {"geometry": f"/files/{key}/design.json"}
|
|
883
|
+
tensor = design.binary_tensor
|
|
884
|
+
if np.shape(tensor) == (6, 6) and np.all(np.isfinite(tensor)): # C, S as .csv
|
|
885
|
+
from morphogen.gui.tools import Context, elastic_tables
|
|
886
|
+
|
|
887
|
+
ctx = Context(self.session, key, folder)
|
|
888
|
+
units = ("units of the material", "their inverse")
|
|
889
|
+
try:
|
|
890
|
+
elastic_tables(ctx, design.binary_tensor, "of the thresholded design",
|
|
891
|
+
units=units) # fmt: skip
|
|
892
|
+
except np.linalg.LinAlgError: # a design that falls apart: no compliance
|
|
893
|
+
pass
|
|
894
|
+
result["tables"] = ctx.tables
|
|
895
|
+
plane = slice_of(design.density, 2)
|
|
896
|
+
origin = "" if self.source is None else f" from #{self.source[0]['number']}"
|
|
897
|
+
objective = self.optimization.objective.replace("_", " ")
|
|
898
|
+
item = self.session.add(
|
|
899
|
+
key,
|
|
900
|
+
"morphology",
|
|
901
|
+
f"design ({objective}){origin}",
|
|
902
|
+
micro=micro,
|
|
903
|
+
origin="optimize",
|
|
904
|
+
source=None if self.source is None else self.source[0]["key"],
|
|
905
|
+
model=None,
|
|
906
|
+
phases={"0": "void", "1": "solid"},
|
|
907
|
+
thumbnail=png_url(plane, "field", vmin=0.0, vmax=1.0, size=96),
|
|
908
|
+
fraction=design.binary_fraction,
|
|
909
|
+
planar=bool(design.planar),
|
|
910
|
+
info={"objective": self.optimization.objective, **result["properties"]},
|
|
911
|
+
files=files,
|
|
912
|
+
)
|
|
913
|
+
result["files"] = files
|
|
914
|
+
result["item"] = self.session.public(item)
|
|
915
|
+
with self._lock:
|
|
916
|
+
self.image = design.density
|
|
917
|
+
self.result = result
|
|
918
|
+
self.state = "done"
|
|
919
|
+
except Exception as exc: # reported to the page
|
|
920
|
+
with self._lock:
|
|
921
|
+
self.error = str(exc)
|
|
922
|
+
self.state = "error"
|
|
923
|
+
|
|
924
|
+
def status(self, tiles: int = 3) -> dict:
|
|
925
|
+
with self._lock:
|
|
926
|
+
out = {
|
|
927
|
+
"state": self.state,
|
|
928
|
+
"iteration": self.progress["iteration"],
|
|
929
|
+
"objective": list(self.progress["objective"]),
|
|
930
|
+
"volume": list(self.progress["volume"]),
|
|
931
|
+
}
|
|
932
|
+
if self.image is not None:
|
|
933
|
+
plane = slice_of(self.image, 2)
|
|
934
|
+
if self.image.shape[2] == 1:
|
|
935
|
+
plane = np.tile(plane, (tiles, tiles))
|
|
936
|
+
out["png"] = png_url(plane, "field", vmin=0.0, vmax=1.0, size=360)
|
|
937
|
+
if self.result is not None:
|
|
938
|
+
out["result"] = self.result
|
|
939
|
+
if self.error is not None:
|
|
940
|
+
out["error"] = self.error
|
|
941
|
+
return out
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
# -- simulations ------------------------------------------------------------------------------
|
|
945
|
+
|
|
946
|
+
#: The fields and colormaps offered by the interface
|
|
947
|
+
SIM_FIELDS = (
|
|
948
|
+
"von_mises",
|
|
949
|
+
"energy_density",
|
|
950
|
+
"displacement",
|
|
951
|
+
*(f"{n}_{c}" for n in ("stress", "strain") for c in ("11", "22", "33", "23", "31", "12")),
|
|
952
|
+
)
|
|
953
|
+
CMAPS = (
|
|
954
|
+
"viridis",
|
|
955
|
+
"plasma",
|
|
956
|
+
"inferno",
|
|
957
|
+
"magma",
|
|
958
|
+
"cividis",
|
|
959
|
+
"turbo",
|
|
960
|
+
"coolwarm",
|
|
961
|
+
"RdBu_r",
|
|
962
|
+
"jet",
|
|
963
|
+
"gray",
|
|
964
|
+
)
|
|
965
|
+
VIDEO_KINDS = ("field", "orthoslices", "turntable", "sweep", "none")
|
|
966
|
+
MAX_ELEMENTS_HINT = 200_000
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
def _number(request: dict, key: str, default, low: float, high: float) -> float:
|
|
970
|
+
value = request.get(key)
|
|
971
|
+
value = default if value in (None, "") else float(value)
|
|
972
|
+
if not low <= value <= high:
|
|
973
|
+
raise ValueError(f"{key}: between {low:g} and {high:g}")
|
|
974
|
+
return value
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
def _video_format() -> str:
|
|
978
|
+
from morphogen.viz.video import ffmpeg_path
|
|
979
|
+
|
|
980
|
+
return "mp4" if ffmpeg_path() else "gif"
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
def _section(request: dict):
|
|
984
|
+
axis = request.get("section_axis")
|
|
985
|
+
if axis in (None, "", "none"):
|
|
986
|
+
return None
|
|
987
|
+
axis = "xyz".index(axis) if isinstance(axis, str) else int(axis)
|
|
988
|
+
return {"axis": axis, "fraction": _number(request, "section_fraction", 0.5, 0.0, 1.0)}
|
|
989
|
+
|
|
990
|
+
|
|
991
|
+
def _materials(request: dict) -> dict:
|
|
992
|
+
materials = {}
|
|
993
|
+
for key, spec in (request.get("materials") or {}).items():
|
|
994
|
+
if spec in ("void", None) or (isinstance(spec, dict) and spec.get("void")):
|
|
995
|
+
materials[int(key)] = "void"
|
|
996
|
+
else:
|
|
997
|
+
materials[int(key)] = {"young": float(spec["young"]), "poisson": float(spec["poisson"])}
|
|
998
|
+
return materials
|
|
999
|
+
|
|
1000
|
+
|
|
1001
|
+
def simulation_config(request: dict, folder: Path) -> dict:
|
|
1002
|
+
"""The configuration of a simulation from the form of the interface: the model, its
|
|
1003
|
+
conforming mesh from its level set (``method: fe``) or its voxels (``fft``), the
|
|
1004
|
+
apparent ``property`` with its fields; the figures and the video chosen (``video``,
|
|
1005
|
+
"none" by default: the export draws them)."""
|
|
1006
|
+
model = {"type": request["model"], **_clean(request.get("params", {}))}
|
|
1007
|
+
dom = request.get("domain", {})
|
|
1008
|
+
size = dom.get("size", 10.0)
|
|
1009
|
+
periodic = bool(dom.get("periodic", True))
|
|
1010
|
+
method = request.get("method", "fe")
|
|
1011
|
+
if method not in ("fe", "fft"):
|
|
1012
|
+
raise ValueError("method: fe (conforming mesh) or fft (voxels)")
|
|
1013
|
+
prop = request.get("property", "shear_modulus")
|
|
1014
|
+
if prop not in ("bulk_modulus", "shear_modulus"):
|
|
1015
|
+
raise ValueError("property: bulk_modulus or shear_modulus")
|
|
1016
|
+
materials = _materials(request)
|
|
1017
|
+
field = request.get("field") or "von_mises"
|
|
1018
|
+
if field not in SIM_FIELDS:
|
|
1019
|
+
raise ValueError(f"field: one of {', '.join(SIM_FIELDS)}")
|
|
1020
|
+
cmap = request.get("cmap") or "viridis"
|
|
1021
|
+
if cmap not in CMAPS:
|
|
1022
|
+
raise ValueError(f"colormap: one of {', '.join(CMAPS)}")
|
|
1023
|
+
bc = "periodic" if periodic or method == "fft" else "kubc"
|
|
1024
|
+
result = f"{prop}.{bc}"
|
|
1025
|
+
magnification = request.get("magnification")
|
|
1026
|
+
magnification = None if magnification in (None, "", "auto") else float(magnification)
|
|
1027
|
+
fmt = _video_format()
|
|
1028
|
+
view = {"of": result, "color": field}
|
|
1029
|
+
if magnification is not None:
|
|
1030
|
+
view["magnification"] = magnification
|
|
1031
|
+
if method == "fe":
|
|
1032
|
+
if _section(request):
|
|
1033
|
+
view["section"] = _section(request)
|
|
1034
|
+
if request.get("part") == "fluctuation":
|
|
1035
|
+
view["part"] = "fluctuation"
|
|
1036
|
+
if field == "displacement" and method == "fft":
|
|
1037
|
+
raise ValueError("field: the displacement is on the nodes of finite element meshes")
|
|
1038
|
+
# finite elements on the conforming mesh of the level set need no voxels
|
|
1039
|
+
image = {"of": "image", "formats": ["png", "svg", "tex"]}
|
|
1040
|
+
figures = [{"of": "mesh"} if method == "fe" else image, dict(view)]
|
|
1041
|
+
kind = request.get("video") or "none"
|
|
1042
|
+
if kind not in VIDEO_KINDS:
|
|
1043
|
+
raise ValueError(f"video: one of {', '.join(VIDEO_KINDS)}")
|
|
1044
|
+
frames = int(_number(request, "frames", 36, 2, MAX_FRAMES * 4))
|
|
1045
|
+
options = {
|
|
1046
|
+
"formats": [fmt],
|
|
1047
|
+
"mode": request.get("mode") or "bounce",
|
|
1048
|
+
"frames": frames,
|
|
1049
|
+
"fps": _number(request, "fps", 18, 1, 60),
|
|
1050
|
+
}
|
|
1051
|
+
axis = "xyz".index(request.get("axis") or "z")
|
|
1052
|
+
videos = {
|
|
1053
|
+
"field": [{**view, "wave": request.get("wave") or "ramp", **options}],
|
|
1054
|
+
"orthoslices": [{"of": "image", "kind": "orthoslices", **options}],
|
|
1055
|
+
"turntable": [{"of": "mesh", "kind": "turntable", **options}]
|
|
1056
|
+
if method == "fe"
|
|
1057
|
+
else [{"of": "image", "kind": "surface", **options}],
|
|
1058
|
+
"sweep": [{"of": "mesh", "kind": "sweep", "axis": axis, **options}]
|
|
1059
|
+
if method == "fe"
|
|
1060
|
+
else [{"of": "image", "kind": "sections", "axis": axis, **options}],
|
|
1061
|
+
"none": [],
|
|
1062
|
+
}[kind]
|
|
1063
|
+
if kind == "sweep" and method == "fft":
|
|
1064
|
+
del videos[0]["frames"] # one frame per section
|
|
1065
|
+
seed = request.get("seed")
|
|
1066
|
+
shape = _shape(request.get("shape"), MAX_FFT_SHAPE if method == "fft" else MAX_SHAPE) or 48
|
|
1067
|
+
cfg = {
|
|
1068
|
+
"model": model,
|
|
1069
|
+
"domain": {"size": size, "periodic": periodic},
|
|
1070
|
+
"seed": 1 if seed in (None, "") else int(seed),
|
|
1071
|
+
"voxels": {"shape": shape},
|
|
1072
|
+
"homogenization": {
|
|
1073
|
+
"materials": materials,
|
|
1074
|
+
"method": method,
|
|
1075
|
+
"boundary_conditions": [bc],
|
|
1076
|
+
"properties": [prop],
|
|
1077
|
+
"fields": True,
|
|
1078
|
+
},
|
|
1079
|
+
"outputs": {
|
|
1080
|
+
"directory": str(folder),
|
|
1081
|
+
"name": "sample",
|
|
1082
|
+
"geometry": ["json"],
|
|
1083
|
+
"image": [] if method == "fe" else ["vti"],
|
|
1084
|
+
"tables": ["txt", "xlsx"],
|
|
1085
|
+
},
|
|
1086
|
+
"analysis": [] if method == "fe" else ["volume_fraction"],
|
|
1087
|
+
"visualization": {"size": [640, 480], "cmap": cmap, "figures": figures},
|
|
1088
|
+
}
|
|
1089
|
+
if videos:
|
|
1090
|
+
cfg["visualization"]["videos"] = videos
|
|
1091
|
+
device = request.get("device") or "cpu"
|
|
1092
|
+
if device not in ("cpu", "gpu", "auto"):
|
|
1093
|
+
raise ValueError("device: cpu, gpu or auto")
|
|
1094
|
+
if method == "fft" and device != "cpu": # the FFT solver on an NVIDIA GPU (CuPy)
|
|
1095
|
+
cfg["homogenization"]["device"] = device
|
|
1096
|
+
if method == "fe":
|
|
1097
|
+
edge = float(np.max(size)) if np.ndim(size) else float(size)
|
|
1098
|
+
cfg["mesh"] = {"size": _number(request, "element_size", edge / 12, edge / 200, edge)}
|
|
1099
|
+
order = request.get("order")
|
|
1100
|
+
if order not in (None, ""): # 10-node elements by default (the configurations)
|
|
1101
|
+
if str(order) not in ("1", "2"):
|
|
1102
|
+
raise ValueError("order: 1 (4-node tetrahedra) or 2 (10-node tetrahedra)")
|
|
1103
|
+
cfg["mesh"]["order"] = int(order)
|
|
1104
|
+
cfg["outputs"]["conforming_mesh"] = ["vtu"]
|
|
1105
|
+
return cfg
|
|
1106
|
+
|
|
1107
|
+
|
|
1108
|
+
def _files(key: str, folder: Path) -> list[dict]:
|
|
1109
|
+
"""The files of a folder of the session for the page, by kind."""
|
|
1110
|
+
kinds = {
|
|
1111
|
+
".json": "data",
|
|
1112
|
+
".vti": "data",
|
|
1113
|
+
".vtu": "data",
|
|
1114
|
+
".stl": "data",
|
|
1115
|
+
".yaml": "configuration",
|
|
1116
|
+
".csv": "table",
|
|
1117
|
+
".txt": "table",
|
|
1118
|
+
".xlsx": "table",
|
|
1119
|
+
".png": "figure",
|
|
1120
|
+
".svg": "figure",
|
|
1121
|
+
".tex": "figure",
|
|
1122
|
+
".pdf": "figure",
|
|
1123
|
+
".mp4": "video",
|
|
1124
|
+
".gif": "video",
|
|
1125
|
+
".zip": "archive",
|
|
1126
|
+
".md": "report",
|
|
1127
|
+
# the inputs and files of other solvers and formats
|
|
1128
|
+
".inp": "data",
|
|
1129
|
+
".xml": "data",
|
|
1130
|
+
".mfront": "data",
|
|
1131
|
+
".mat": "data", # Z-mat
|
|
1132
|
+
".msh": "data",
|
|
1133
|
+
".mesh": "data",
|
|
1134
|
+
".xdmf": "data",
|
|
1135
|
+
".h5": "data",
|
|
1136
|
+
".vtk": "data",
|
|
1137
|
+
".std": "data",
|
|
1138
|
+
".bin": "data",
|
|
1139
|
+
".tif": "data",
|
|
1140
|
+
".tiff": "data",
|
|
1141
|
+
".mhd": "data",
|
|
1142
|
+
".raw": "data",
|
|
1143
|
+
".npy": "data",
|
|
1144
|
+
".npz": "data",
|
|
1145
|
+
".tess": "data",
|
|
1146
|
+
".sh": "configuration",
|
|
1147
|
+
".bat": "configuration",
|
|
1148
|
+
".rad": "data", # OpenRadioss
|
|
1149
|
+
}
|
|
1150
|
+
out = []
|
|
1151
|
+
for path in sorted(folder.iterdir()):
|
|
1152
|
+
if path.is_file() and path.suffix in kinds:
|
|
1153
|
+
out.append(
|
|
1154
|
+
{"name": path.name, "kind": kinds[path.suffix], "url": f"/files/{key}/{path.name}"}
|
|
1155
|
+
)
|
|
1156
|
+
return out
|
|
1157
|
+
|
|
1158
|
+
|
|
1159
|
+
def _numbers_of(path: Path) -> dict:
|
|
1160
|
+
with path.open(encoding="utf-8", newline="") as f:
|
|
1161
|
+
row = next(csv.DictReader(f), {})
|
|
1162
|
+
out = {}
|
|
1163
|
+
for k, v in row.items():
|
|
1164
|
+
try:
|
|
1165
|
+
x = float(v)
|
|
1166
|
+
except (TypeError, ValueError):
|
|
1167
|
+
continue
|
|
1168
|
+
if np.isfinite(x) and k not in ("realization", "seed"):
|
|
1169
|
+
out[k] = x
|
|
1170
|
+
return out
|
|
1171
|
+
|
|
1172
|
+
|
|
1173
|
+
class SimulationJob:
|
|
1174
|
+
"""A simulation in a thread, with its state: of a morphology of the workspace
|
|
1175
|
+
(``source``: its key), or of a model and seed of the form (the whole chain of a
|
|
1176
|
+
configuration); its result is kept in the workspace, unless it is stopped
|
|
1177
|
+
(:meth:`stop`, at the next iteration of its solver)."""
|
|
1178
|
+
|
|
1179
|
+
def __init__(self, request: dict, session: Session):
|
|
1180
|
+
from morphogen.config import load_config
|
|
1181
|
+
|
|
1182
|
+
self.session = session
|
|
1183
|
+
self.source = None
|
|
1184
|
+
if request.get("source"):
|
|
1185
|
+
self.source = session.item(request["source"], ("morphology",))
|
|
1186
|
+
# a design is not the realization of a model: a stand-in for the configuration,
|
|
1187
|
+
# whose steps run on the morphology itself (and no configuration to rerun)
|
|
1188
|
+
model = self.source.get("model") or {"type": "tpms", "volume_fraction": 0.5}
|
|
1189
|
+
request = {
|
|
1190
|
+
**request,
|
|
1191
|
+
"model": model["type"],
|
|
1192
|
+
"params": {k: v for k, v in model.items() if k != "type"},
|
|
1193
|
+
"domain": self.source.get("domain")
|
|
1194
|
+
or {"size": list(self.source["micro"].domain.lengths), "periodic": True},
|
|
1195
|
+
"seed": self.source.get("seed") or 1,
|
|
1196
|
+
}
|
|
1197
|
+
self.request = request
|
|
1198
|
+
self.key, self.folder = session.folder()
|
|
1199
|
+
self.data = simulation_config(request, self.folder)
|
|
1200
|
+
self.config = load_config(self.data) # errors of the form, before the thread
|
|
1201
|
+
self.started = time.perf_counter()
|
|
1202
|
+
self.state = "running"
|
|
1203
|
+
self.result: dict | None = None
|
|
1204
|
+
self.error: str | None = None
|
|
1205
|
+
self._lock = threading.Lock()
|
|
1206
|
+
self._stop = threading.Event()
|
|
1207
|
+
self.thread = threading.Thread(target=self._run, daemon=True)
|
|
1208
|
+
|
|
1209
|
+
def start(self) -> SimulationJob:
|
|
1210
|
+
self.thread.start()
|
|
1211
|
+
return self
|
|
1212
|
+
|
|
1213
|
+
def stop(self) -> None:
|
|
1214
|
+
"""Stop at the next checkpoint of the solve (:mod:`morphogen.stopping`)."""
|
|
1215
|
+
self._stop.set()
|
|
1216
|
+
|
|
1217
|
+
def _solve(self):
|
|
1218
|
+
"""The steps of the configuration on the morphology of the workspace, else the
|
|
1219
|
+
whole run."""
|
|
1220
|
+
from morphogen import pipeline
|
|
1221
|
+
|
|
1222
|
+
if self.source is None:
|
|
1223
|
+
pipeline.run(self.config)
|
|
1224
|
+
return
|
|
1225
|
+
cfg = self.config
|
|
1226
|
+
cfg.outputs.directory.mkdir(parents=True, exist_ok=True)
|
|
1227
|
+
micro = self.source["micro"]
|
|
1228
|
+
values, fe_rows = pipeline._process(micro, cfg, "sample_0000", self.folder, cfg.analysis)
|
|
1229
|
+
row = {"realization": 0, "seed": self.source.get("seed") or "", **micro.summary()}
|
|
1230
|
+
row.update(values)
|
|
1231
|
+
pipeline._write_results(self.folder, [row], fe_rows, 0, 1, cfg.outputs.tables)
|
|
1232
|
+
|
|
1233
|
+
def _run(self):
|
|
1234
|
+
from morphogen.stopping import Stopped, stoppable
|
|
1235
|
+
|
|
1236
|
+
try:
|
|
1237
|
+
with warnings.catch_warnings(record=True) as caught, stoppable(self._stop):
|
|
1238
|
+
warnings.simplefilter("always")
|
|
1239
|
+
self._solve()
|
|
1240
|
+
reproducible = self.source is None or self.source.get("model") is not None
|
|
1241
|
+
if reproducible:
|
|
1242
|
+
data = dict(self.data)
|
|
1243
|
+
data["outputs"] = {**data["outputs"], "directory": "simulation"}
|
|
1244
|
+
(self.folder / "configuration.yaml").write_text(
|
|
1245
|
+
yaml.safe_dump(data, sort_keys=False), encoding="utf-8"
|
|
1246
|
+
)
|
|
1247
|
+
stem = "sample_0000"
|
|
1248
|
+
figures = sorted(self.folder.glob(f"{stem}_*.png"))
|
|
1249
|
+
videos = sorted(
|
|
1250
|
+
[*self.folder.glob(f"{stem}_*.mp4"), *self.folder.glob(f"{stem}_*.gif")]
|
|
1251
|
+
)
|
|
1252
|
+
values = _numbers_of(self.folder / "results.csv")
|
|
1253
|
+
result = {
|
|
1254
|
+
"values": values,
|
|
1255
|
+
"figures": [
|
|
1256
|
+
{
|
|
1257
|
+
"title": p.stem.removeprefix(stem + "_").replace("_", " "),
|
|
1258
|
+
"url": f"/files/{self.key}/{p.name}",
|
|
1259
|
+
}
|
|
1260
|
+
for p in figures
|
|
1261
|
+
if "-" not in p.stem
|
|
1262
|
+
],
|
|
1263
|
+
"videos": [
|
|
1264
|
+
{
|
|
1265
|
+
"title": p.stem.removeprefix(stem + "_").replace("_", " "),
|
|
1266
|
+
"url": f"/files/{self.key}/{p.name}",
|
|
1267
|
+
"format": p.suffix[1:],
|
|
1268
|
+
}
|
|
1269
|
+
for p in videos
|
|
1270
|
+
],
|
|
1271
|
+
"files": _files(self.key, self.folder),
|
|
1272
|
+
"key": self.key,
|
|
1273
|
+
"time_s": round(time.perf_counter() - self.started, 2),
|
|
1274
|
+
"warnings": shown_warnings(caught),
|
|
1275
|
+
}
|
|
1276
|
+
self._keep(result, values)
|
|
1277
|
+
with self._lock:
|
|
1278
|
+
self.result, self.state = result, "done"
|
|
1279
|
+
except Stopped: # nothing kept
|
|
1280
|
+
with self._lock:
|
|
1281
|
+
self.state = "stopped"
|
|
1282
|
+
except Exception as exc: # reported to the page
|
|
1283
|
+
with self._lock:
|
|
1284
|
+
self.error, self.state = f"{type(exc).__name__}: {exc}", "error"
|
|
1285
|
+
|
|
1286
|
+
def _keep(self, result: dict, values: dict) -> None:
|
|
1287
|
+
"""The simulation in the workspace, with its apparent property."""
|
|
1288
|
+
homog = self.data["homogenization"]
|
|
1289
|
+
prop, method = homog["properties"][0], homog["method"]
|
|
1290
|
+
name = f"{prop}.{homog['boundary_conditions'][0]}"
|
|
1291
|
+
source = self.source
|
|
1292
|
+
of = "" if source is None else f" of #{source['number']}"
|
|
1293
|
+
by = "conforming mesh (FE)" if method == "fe" else "voxels (FFT)"
|
|
1294
|
+
info = {prop: values.get(name)}
|
|
1295
|
+
if "mesh_elements" in values:
|
|
1296
|
+
info["elements"] = int(values["mesh_elements"])
|
|
1297
|
+
materials = {str(k): v for k, v in homog["materials"].items()}
|
|
1298
|
+
item = self.session.add(
|
|
1299
|
+
self.key,
|
|
1300
|
+
"simulation",
|
|
1301
|
+
f"{prop.replace('_', ' ')}{of}, {'FE' if method == 'fe' else 'FFT'}",
|
|
1302
|
+
origin="simulate",
|
|
1303
|
+
source=None if source is None else source["key"],
|
|
1304
|
+
property=prop,
|
|
1305
|
+
method=method,
|
|
1306
|
+
values=values,
|
|
1307
|
+
materials=materials,
|
|
1308
|
+
config=self.data,
|
|
1309
|
+
phases=source.get("phases") if source is not None else None,
|
|
1310
|
+
thumbnail=source.get("thumbnail") if source is not None else None,
|
|
1311
|
+
info={"method": by, **_finite(info)},
|
|
1312
|
+
files={"folder": f"/files/{self.key}/"},
|
|
1313
|
+
)
|
|
1314
|
+
result["item"] = self.session.public(item)
|
|
1315
|
+
|
|
1316
|
+
def status(self) -> dict:
|
|
1317
|
+
with self._lock:
|
|
1318
|
+
out = {"state": self.state, "elapsed_s": round(time.perf_counter() - self.started, 1)}
|
|
1319
|
+
if self.result is not None:
|
|
1320
|
+
out["result"] = self.result
|
|
1321
|
+
if self.error is not None:
|
|
1322
|
+
out["error"] = self.error
|
|
1323
|
+
return out
|
|
1324
|
+
|
|
1325
|
+
|
|
1326
|
+
# -- views and exports -------------------------------------------------------------------------
|
|
1327
|
+
|
|
1328
|
+
|
|
1329
|
+
def _clim(request: dict):
|
|
1330
|
+
if request.get("clim_low") not in (None, "") and request.get("clim_high") not in (None, ""):
|
|
1331
|
+
return (float(request["clim_low"]), float(request["clim_high"]))
|
|
1332
|
+
return None
|
|
1333
|
+
|
|
1334
|
+
|
|
1335
|
+
def _field_files(sim: Path) -> tuple[list[Path], list[Path]]:
|
|
1336
|
+
"""The files of the fields of a simulation: on its mesh (.vtu), on its voxels (.vti)."""
|
|
1337
|
+
meshes = [p for p in sorted(sim.glob("sample_0000_*_*.vtu")) if not p.stem.endswith("_tet")]
|
|
1338
|
+
return meshes, sorted(sim.glob("sample_0000_*_*.vti"))
|
|
1339
|
+
|
|
1340
|
+
|
|
1341
|
+
def field_names(sim: Path) -> list[str]:
|
|
1342
|
+
"""The fields of a simulation that can be drawn (those of its field file: stresses,
|
|
1343
|
+
strains, von Mises, energy density, and the internal variables of nonlinear runs, e.g.
|
|
1344
|
+
the cumulated plastic strain or the porosity), the norm of the displacement for a mesh."""
|
|
1345
|
+
meshes, images = _field_files(sim)
|
|
1346
|
+
if meshes:
|
|
1347
|
+
from morphogen.io.vtk import read_vtu
|
|
1348
|
+
|
|
1349
|
+
data = read_vtu(meshes[0])
|
|
1350
|
+
names = [*data["point_data"], *data["cell_data"]]
|
|
1351
|
+
return [n for n in dict.fromkeys(names) if n not in ("phase", "grain", "fluctuation")]
|
|
1352
|
+
if images:
|
|
1353
|
+
from morphogen.io.vtk import read_vti
|
|
1354
|
+
|
|
1355
|
+
return [img.name for img in read_vti(images[0]) if img.name not in ("phase", "grain")]
|
|
1356
|
+
return []
|
|
1357
|
+
|
|
1358
|
+
|
|
1359
|
+
def simulation_fields(request: dict, session: Session) -> dict:
|
|
1360
|
+
"""The fields of a simulation of the workspace (``key``), the usual ones first."""
|
|
1361
|
+
item = session.item(request.get("key"), ("simulation",))
|
|
1362
|
+
names = field_names(session.file(item["key"], "results.csv").parent)
|
|
1363
|
+
usual = [n for n in SIM_FIELDS if n in names]
|
|
1364
|
+
return {"fields": usual + [n for n in names if n not in usual]}
|
|
1365
|
+
|
|
1366
|
+
|
|
1367
|
+
def _field_view(sim: Path, out: Path, key: str, name: str, request: dict) -> dict:
|
|
1368
|
+
"""A view of the fields of the simulation of folder ``sim`` (field, colormap, range,
|
|
1369
|
+
magnification, cut) written to ``out`` as ``name``.png, and its video (``video``:
|
|
1370
|
+
"field" on the deformed mesh under a growing or oscillating load, "turntable",
|
|
1371
|
+
"sweep" of a cross-section; the sections of an FFT image)."""
|
|
1372
|
+
from PIL import Image
|
|
1373
|
+
|
|
1374
|
+
from morphogen.viz import video as vv
|
|
1375
|
+
from morphogen.viz.export import save_figure
|
|
1376
|
+
from morphogen.viz.figures import field_figure
|
|
1377
|
+
|
|
1378
|
+
field = request.get("field") or "von_mises"
|
|
1379
|
+
available = field_names(sim)
|
|
1380
|
+
if field == "displacement" and not _field_files(sim)[0]:
|
|
1381
|
+
raise ValueError("field: the displacement is on the nodes of finite element meshes")
|
|
1382
|
+
if field not in available:
|
|
1383
|
+
raise ValueError(f"field: one of {', '.join(available) or 'none here'}")
|
|
1384
|
+
cmap = request.get("cmap") or "viridis"
|
|
1385
|
+
if cmap not in CMAPS:
|
|
1386
|
+
raise ValueError(f"colormap: one of {', '.join(CMAPS)}")
|
|
1387
|
+
clim = _clim(request)
|
|
1388
|
+
kind = request.get("video") or "none"
|
|
1389
|
+
if kind not in VIDEO_KINDS:
|
|
1390
|
+
raise ValueError(f"video: one of {', '.join(VIDEO_KINDS)}")
|
|
1391
|
+
frames_n = int(_number(request, "frames", 36, 2, MAX_FRAMES * 4))
|
|
1392
|
+
axis = "xyz".index(request.get("axis") or "z")
|
|
1393
|
+
result: dict = {}
|
|
1394
|
+
meshes, images = _field_files(sim)
|
|
1395
|
+
if meshes:
|
|
1396
|
+
from morphogen.io.vtk import read_vtu
|
|
1397
|
+
|
|
1398
|
+
mesh = io.read_tet_mesh(meshes[0])
|
|
1399
|
+
data = read_vtu(meshes[0])
|
|
1400
|
+
arrays = {**data["point_data"], **data["cell_data"]}
|
|
1401
|
+
u = arrays.get("displacement")
|
|
1402
|
+
values = np.linalg.norm(u, axis=1) if field == "displacement" else arrays[field]
|
|
1403
|
+
magnification = request.get("magnification")
|
|
1404
|
+
magnification = None if magnification in (None, "", "auto") else float(magnification)
|
|
1405
|
+
section = _section(request)
|
|
1406
|
+
cut = None if section is None else (section["axis"], section["fraction"])
|
|
1407
|
+
rgb = vv.deformed_view(
|
|
1408
|
+
mesh, u, values, magnification=magnification, section=cut, cmap=cmap, clim=clim,
|
|
1409
|
+
title=field,
|
|
1410
|
+
) # fmt: skip
|
|
1411
|
+
Image.fromarray(rgb).save(out / f"{name}.png")
|
|
1412
|
+
frames = None
|
|
1413
|
+
if kind == "field":
|
|
1414
|
+
frames = vv.field_frames(
|
|
1415
|
+
mesh, u, values, magnification=magnification, section=cut, cmap=cmap,
|
|
1416
|
+
clim=clim, title=field, wave=request.get("wave") or "ramp", frames=frames_n,
|
|
1417
|
+
scaling=vv.field_scaling(field),
|
|
1418
|
+
) # fmt: skip
|
|
1419
|
+
elif kind == "turntable":
|
|
1420
|
+
frames = vv.turntable_frames(mesh, field=values, frames=frames_n)
|
|
1421
|
+
elif kind == "sweep":
|
|
1422
|
+
frames = vv.section_sweep_frames(
|
|
1423
|
+
mesh, values, axis=axis, frames=frames_n, cmap=cmap, clim=clim, title=field
|
|
1424
|
+
)
|
|
1425
|
+
elif kind == "orthoslices":
|
|
1426
|
+
raise ValueError("video: orthoslices are views of voxel images (FFT simulations)")
|
|
1427
|
+
if frames is not None:
|
|
1428
|
+
result["video"] = _video(frames, out, key, name, request, f"{field} ({kind})")
|
|
1429
|
+
else:
|
|
1430
|
+
if not images:
|
|
1431
|
+
raise ValueError("no fields in this simulation")
|
|
1432
|
+
if field == "displacement":
|
|
1433
|
+
raise ValueError("field: the displacement is on the nodes of finite element meshes")
|
|
1434
|
+
values = io.load_image(images[0], field)
|
|
1435
|
+
formats = [f for f in request.get("formats") or ["png"] if f in ("png", "svg", "tex")]
|
|
1436
|
+
for fmt in formats or ["png"]:
|
|
1437
|
+
save_figure(
|
|
1438
|
+
field_figure(values, cmap=cmap, clim=clim, label=field), out / f"{name}.{fmt}",
|
|
1439
|
+
dpi=120,
|
|
1440
|
+
) # fmt: skip
|
|
1441
|
+
if kind != "none":
|
|
1442
|
+
lo, hi = clim or (None, None)
|
|
1443
|
+
if kind in ("field", "sweep"):
|
|
1444
|
+
frames = vv.section_frames(
|
|
1445
|
+
values, axis, size=480, cmap=cmap, vmin=lo, vmax=hi, labels=False,
|
|
1446
|
+
bar=True, label=field,
|
|
1447
|
+
) # fmt: skip
|
|
1448
|
+
elif kind == "orthoslices":
|
|
1449
|
+
frames = vv.orthoslice_frames(values, frames=frames_n, size=320, cmap=cmap)
|
|
1450
|
+
else:
|
|
1451
|
+
frames = vv.turntable_frames(values, frames=frames_n)
|
|
1452
|
+
result["video"] = _video(frames, out, key, name, request, f"{field} ({kind})")
|
|
1453
|
+
result["figure"] = {"title": field, "url": f"/files/{key}/{name}.png"}
|
|
1454
|
+
return result
|
|
1455
|
+
|
|
1456
|
+
|
|
1457
|
+
def render(request: dict, session: Session) -> dict:
|
|
1458
|
+
"""Another view, and optionally a video, of the fields of a simulation (``key``): a
|
|
1459
|
+
field, colormap, range, magnification, cut, without solving again."""
|
|
1460
|
+
key = str(request["key"])
|
|
1461
|
+
folder = session.file(key, "results.csv").parent
|
|
1462
|
+
n = len(list(folder.glob("render_*.png"))) + 1
|
|
1463
|
+
out = _field_view(folder, folder, key, f"render_{n}", request)
|
|
1464
|
+
out["files"] = _files(key, folder)
|
|
1465
|
+
return out
|
|
1466
|
+
|
|
1467
|
+
|
|
1468
|
+
#: The 3D view: cells along the longest edge of the grids of the surfaces of morphologies
|
|
1469
|
+
SURFACE_RESOLUTION = 96
|
|
1470
|
+
MAX_SURFACE_RESOLUTION = 256
|
|
1471
|
+
|
|
1472
|
+
|
|
1473
|
+
def _surface_resolution(value) -> int:
|
|
1474
|
+
n = SURFACE_RESOLUTION if value in (None, "", 0, "0") else int(value)
|
|
1475
|
+
if not 8 <= n <= MAX_SURFACE_RESOLUTION:
|
|
1476
|
+
raise ValueError(f"resolution: from 8 to {MAX_SURFACE_RESOLUTION} cells per edge")
|
|
1477
|
+
return n
|
|
1478
|
+
|
|
1479
|
+
|
|
1480
|
+
def _budget(value) -> int:
|
|
1481
|
+
from morphogen.viz.surfaces import MAX_TRIANGLES
|
|
1482
|
+
|
|
1483
|
+
n = MAX_TRIANGLES if value in (None, "", 0, "0") else int(value)
|
|
1484
|
+
if not 1000 <= n <= MAX_TRIANGLES:
|
|
1485
|
+
raise ValueError(f"budget: from 1000 to {MAX_TRIANGLES} triangles")
|
|
1486
|
+
return n
|
|
1487
|
+
|
|
1488
|
+
|
|
1489
|
+
def surface(request: dict, session: Session) -> dict:
|
|
1490
|
+
"""The surface of an item of the workspace (``key``) for the 3D view of the page
|
|
1491
|
+
(:mod:`morphogen.viz.surfaces`, as :func:`~morphogen.viz.surfaces.encode` writes it):
|
|
1492
|
+
of a morphology, the interfaces of its phases (or cells) on a grid of ``resolution``
|
|
1493
|
+
cells along its longest edge (:data:`SURFACE_RESOLUTION` by default, at most
|
|
1494
|
+
:data:`MAX_SURFACE_RESOLUTION`); of a simulation, the faces of the mesh or of the
|
|
1495
|
+
voxels of its fields, with ``field`` (by default the von Mises stress) and the
|
|
1496
|
+
displacement of the mesh, its sections on a grid of ``resolution`` cells too. At most
|
|
1497
|
+
``budget`` triangles (300 000 and below): the grids are made coarser, the meshes
|
|
1498
|
+
simplified, to fit."""
|
|
1499
|
+
from morphogen.viz import surfaces
|
|
1500
|
+
|
|
1501
|
+
item = session.item(request.get("key"), ("morphology", "simulation", "result"))
|
|
1502
|
+
resolution = _surface_resolution(request.get("resolution"))
|
|
1503
|
+
budget = _budget(request.get("budget"))
|
|
1504
|
+
started = time.perf_counter()
|
|
1505
|
+
with warnings.catch_warnings(): # those of the libraries, e.g. while Numba compiles
|
|
1506
|
+
warnings.simplefilter("ignore")
|
|
1507
|
+
if item["kind"] == "morphology":
|
|
1508
|
+
micro = item.get("micro")
|
|
1509
|
+
if micro is None:
|
|
1510
|
+
raise ValueError(f"{item['title']}: no microstructure to draw in this session")
|
|
1511
|
+
_voxels(micro.domain, resolution + 2, 24.0, "3D view")
|
|
1512
|
+
shown = surfaces.morphology_surface(micro, resolution, max_triangles=budget)
|
|
1513
|
+
phases = item.get("phases") or {str(k): v for k, v in micro.phase_names.items()}
|
|
1514
|
+
else:
|
|
1515
|
+
folder = session.root / item["key"]
|
|
1516
|
+
if item["kind"] == "result": # the run of a tool: the mesh of its last step
|
|
1517
|
+
from morphogen.gui.tools import meshes_of_result
|
|
1518
|
+
|
|
1519
|
+
meshes, images = meshes_of_result(folder)[::-1], []
|
|
1520
|
+
else:
|
|
1521
|
+
meshes, images = _field_files(folder) if folder.is_dir() else ([], [])
|
|
1522
|
+
field = request.get("field") or None
|
|
1523
|
+
if meshes:
|
|
1524
|
+
shown = surfaces.vtu_surface(
|
|
1525
|
+
meshes[0], field, resolution=resolution, max_triangles=budget
|
|
1526
|
+
)
|
|
1527
|
+
elif images:
|
|
1528
|
+
source = session.items.get(str(item.get("source")))
|
|
1529
|
+
shown = surfaces.vti_surface(
|
|
1530
|
+
images[0],
|
|
1531
|
+
field,
|
|
1532
|
+
phases=_image_phases(folder),
|
|
1533
|
+
morphology=None if source is None else source.get("micro"),
|
|
1534
|
+
max_triangles=budget,
|
|
1535
|
+
)
|
|
1536
|
+
else:
|
|
1537
|
+
raise ValueError(
|
|
1538
|
+
f"{item['title']}: nothing to draw in 3D (no mesh or voxels of fields)"
|
|
1539
|
+
)
|
|
1540
|
+
phases = item.get("phases") or {}
|
|
1541
|
+
out = surfaces.encode(shown)
|
|
1542
|
+
if out["field"] is not None: # the usual fields first, as in the views of the export
|
|
1543
|
+
names = out["field"]["names"]
|
|
1544
|
+
usual = [n for n in SIM_FIELDS if n in names]
|
|
1545
|
+
out["field"]["names"] = usual + [n for n in names if n not in usual]
|
|
1546
|
+
out.update(
|
|
1547
|
+
key=item["key"],
|
|
1548
|
+
kind=item["kind"],
|
|
1549
|
+
title=item["title"],
|
|
1550
|
+
phases={str(k): v for k, v in phases.items()},
|
|
1551
|
+
requested=resolution,
|
|
1552
|
+
budget=budget,
|
|
1553
|
+
time_s=round(time.perf_counter() - started, 3),
|
|
1554
|
+
)
|
|
1555
|
+
return out
|
|
1556
|
+
|
|
1557
|
+
|
|
1558
|
+
def _image_phases(folder: Path):
|
|
1559
|
+
"""The phases of the voxel image of a simulation on voxels (``sample_0000.vti``), if
|
|
1560
|
+
it wrote one."""
|
|
1561
|
+
from morphogen.io.vtk import read_vti
|
|
1562
|
+
|
|
1563
|
+
path = folder / "sample_0000.vti"
|
|
1564
|
+
if not path.is_file():
|
|
1565
|
+
return None
|
|
1566
|
+
images = read_vti(path, names=("phase",))
|
|
1567
|
+
return images[0].data if images else None
|
|
1568
|
+
|
|
1569
|
+
|
|
1570
|
+
def _video(frames, folder: Path, key: str, name: str, request: dict, title: str) -> dict:
|
|
1571
|
+
from morphogen.viz.video import write_video
|
|
1572
|
+
|
|
1573
|
+
fmt = _video_format()
|
|
1574
|
+
path = folder / f"{name}.{fmt}"
|
|
1575
|
+
write_video(
|
|
1576
|
+
frames, path, fps=_number(request, "fps", 18, 1, 60), mode=request.get("mode") or "bounce"
|
|
1577
|
+
)
|
|
1578
|
+
return {"title": title, "url": f"/files/{key}/{path.name}", "format": fmt}
|
|
1579
|
+
|
|
1580
|
+
|
|
1581
|
+
#: What the export writes: of a morphology, of a simulation
|
|
1582
|
+
MORPHOLOGY_EXPORTS = ("geometry", "sections", "level_set", "image", "surface", "mesh")
|
|
1583
|
+
SIMULATION_EXPORTS = ("figure", "tables", "fields", "mesh", "configuration")
|
|
1584
|
+
MORPHOLOGY_VIDEOS = ("none", "sweep", "orthoslices", "turntable", "formation")
|
|
1585
|
+
|
|
1586
|
+
|
|
1587
|
+
def export(request: dict, session: Session) -> dict:
|
|
1588
|
+
"""The files of an item of the workspace (``source``), in a folder of their own with
|
|
1589
|
+
an archive of them all: of a morphology, its geometry, sections of its level set,
|
|
1590
|
+
voxel images of its level set and phases, its surface (STL) and conforming mesh (for
|
|
1591
|
+
a morphology of several phases: the implicit function and the surface of each phase,
|
|
1592
|
+
``level_set_phase<k>.vti`` and ``surface_phase<k>.stl``, and the mesh conforming to
|
|
1593
|
+
all their interfaces), and a video of its sections sweeping it, orthoslices or a
|
|
1594
|
+
turntable; of a simulation, a view of its fields (figure and video), its tables,
|
|
1595
|
+
fields, mesh and configuration."""
|
|
1596
|
+
item = session.item(request.get("source"))
|
|
1597
|
+
key, folder = session.folder()
|
|
1598
|
+
if item["kind"] == "morphology":
|
|
1599
|
+
out = _export_morphology(item, request, key, folder)
|
|
1600
|
+
else:
|
|
1601
|
+
out = _export_simulation(item, request, key, folder, session)
|
|
1602
|
+
files = [p for p in sorted(folder.iterdir()) if p.is_file()]
|
|
1603
|
+
if files:
|
|
1604
|
+
with zipfile.ZipFile(folder / "export.zip", "w", zipfile.ZIP_DEFLATED) as archive:
|
|
1605
|
+
for path in files:
|
|
1606
|
+
archive.write(path, path.name)
|
|
1607
|
+
out["archive"] = f"/files/{key}/export.zip"
|
|
1608
|
+
out["files"] = _files(key, folder)
|
|
1609
|
+
out["source"] = session.public(item)
|
|
1610
|
+
return out
|
|
1611
|
+
|
|
1612
|
+
|
|
1613
|
+
def _chosen(request: dict, allowed) -> list[str]:
|
|
1614
|
+
chosen = list(request.get("outputs") or [])
|
|
1615
|
+
unknown = sorted(set(chosen) - set(allowed))
|
|
1616
|
+
if unknown:
|
|
1617
|
+
raise ValueError(f"outputs: among {', '.join(allowed)} (not {', '.join(unknown)})")
|
|
1618
|
+
return chosen
|
|
1619
|
+
|
|
1620
|
+
|
|
1621
|
+
def _export_morphology(item: dict, request: dict, key: str, folder: Path) -> dict:
|
|
1622
|
+
from morphogen.viz import sections as vs
|
|
1623
|
+
|
|
1624
|
+
micro = item["micro"]
|
|
1625
|
+
chosen = _chosen(request, MORPHOLOGY_EXPORTS)
|
|
1626
|
+
resolution = _resolution(request.get("resolution"))
|
|
1627
|
+
shape = _shape(request.get("shape")) or 128
|
|
1628
|
+
out: dict = {"figures": [], "videos": []}
|
|
1629
|
+
if "geometry" in chosen:
|
|
1630
|
+
io.save_microstructure(micro, folder / "microstructure.json")
|
|
1631
|
+
if "sections" in chosen:
|
|
1632
|
+
for s in vs.sections(micro, resolution):
|
|
1633
|
+
name = f"section_{''.join(s.names)}.png"
|
|
1634
|
+
(folder / name).write_bytes(encode_png(vs.render(s, "phase")))
|
|
1635
|
+
title = f"{s.names[0]}-{s.names[1]} section"
|
|
1636
|
+
out["figures"].append({"title": title, "url": f"/files/{key}/{name}"})
|
|
1637
|
+
if "level_set" in chosen or "surface" in chosen:
|
|
1638
|
+
from morphogen.mesh.surface import surface_mesh
|
|
1639
|
+
from morphogen.models.implicit import implicit_functions
|
|
1640
|
+
|
|
1641
|
+
_voxels(micro.domain, shape, 12.0, "level set")
|
|
1642
|
+
surfaces = "surface" in chosen
|
|
1643
|
+
# one function for two phases; else that of each phase (its surface: but the last,
|
|
1644
|
+
# whose surface is that of the others together)
|
|
1645
|
+
functions = implicit_functions(micro, shape=shape)
|
|
1646
|
+
for k, (suffix, level) in enumerate(functions):
|
|
1647
|
+
if "level_set" in chosen:
|
|
1648
|
+
io.save_image(level, folder / f"level_set{suffix}.vti")
|
|
1649
|
+
if surfaces and (k < len(functions) - 1 or len(functions) == 1):
|
|
1650
|
+
io.save_mesh(surface_mesh(level, closed=True), folder / f"surface{suffix}.stl")
|
|
1651
|
+
if "image" in chosen:
|
|
1652
|
+
_voxels(micro.domain, shape, 6.0, "voxel image")
|
|
1653
|
+
io.save_image(micro.voxelize(shape=shape), folder / "image.vti")
|
|
1654
|
+
if "mesh" in chosen:
|
|
1655
|
+
from morphogen.mesh import conforming_mesh
|
|
1656
|
+
|
|
1657
|
+
edge = float(np.max(micro.domain.lengths))
|
|
1658
|
+
size = _number(request, "element_size", edge / 12, edge / 200, edge)
|
|
1659
|
+
io.save_mesh(conforming_mesh(micro, size=size), folder / "mesh.vtu")
|
|
1660
|
+
kind = request.get("video") or "none"
|
|
1661
|
+
if kind not in MORPHOLOGY_VIDEOS:
|
|
1662
|
+
raise ValueError(f"video: one of {', '.join(MORPHOLOGY_VIDEOS)}")
|
|
1663
|
+
if kind != "none":
|
|
1664
|
+
from morphogen.viz import video as vv
|
|
1665
|
+
|
|
1666
|
+
frames_n = int(_number(request, "frames", 36, 2, MAX_FRAMES * 4))
|
|
1667
|
+
axis = "xyz".index(request.get("axis") or "z")
|
|
1668
|
+
if kind == "sweep": # sections of the level set sweeping the domain
|
|
1669
|
+
n = min(resolution, 720)
|
|
1670
|
+
fractions = (np.arange(frames_n) + 0.5) / frames_n
|
|
1671
|
+
frames = [vs.render(vs.section(micro, axis, float(f), n), "phase") for f in fractions]
|
|
1672
|
+
elif kind == "formation": # the middle section along the formation of the structure
|
|
1673
|
+
model = model_from_config(item["model"]) if item.get("model") else None
|
|
1674
|
+
if model is None or not hasattr(model, "evolution"):
|
|
1675
|
+
raise ValueError(
|
|
1676
|
+
"video: the formation of models grown by a process (automata, growth)"
|
|
1677
|
+
)
|
|
1678
|
+
seed = item.get("seed")
|
|
1679
|
+
states = model.evolution(
|
|
1680
|
+
micro.domain,
|
|
1681
|
+
None if seed is None else derive_seed(int(seed), 0),
|
|
1682
|
+
min(frames_n, MAX_FRAMES),
|
|
1683
|
+
)
|
|
1684
|
+
kind_of = (
|
|
1685
|
+
"labels"
|
|
1686
|
+
if states[-1].dtype == np.int32
|
|
1687
|
+
else ("phase" if states[-1].dtype == np.uint8 else "field")
|
|
1688
|
+
)
|
|
1689
|
+
lo = min(float(s.min()) for s in states)
|
|
1690
|
+
hi = max(float(s.max()) for s in states)
|
|
1691
|
+
frames = []
|
|
1692
|
+
for s in states:
|
|
1693
|
+
rgb = to_rgb(slice_of(s, 2), kind_of, lo, hi)
|
|
1694
|
+
frames.append(upscale(rgb, max(1, 480 // max(rgb.shape[:2]))))
|
|
1695
|
+
else:
|
|
1696
|
+
image = micro.voxelize(shape=min(shape, 160))
|
|
1697
|
+
if kind == "orthoslices":
|
|
1698
|
+
frames = vv.orthoslice_frames(image, frames=frames_n, size=320)
|
|
1699
|
+
else:
|
|
1700
|
+
frames = vv.turntable_frames(image, frames=frames_n)
|
|
1701
|
+
out["videos"].append(_video(frames, folder, key, f"video_{kind}", request, kind))
|
|
1702
|
+
return out
|
|
1703
|
+
|
|
1704
|
+
|
|
1705
|
+
def _export_simulation(item: dict, request: dict, key: str, folder: Path, session) -> dict:
|
|
1706
|
+
from morphogen.io.tables import write_table
|
|
1707
|
+
|
|
1708
|
+
sim = session.file(item["key"], "results.csv").parent
|
|
1709
|
+
chosen = _chosen(request, SIMULATION_EXPORTS)
|
|
1710
|
+
out: dict = {"figures": [], "videos": []}
|
|
1711
|
+
if "figure" in chosen or (request.get("video") or "none") != "none":
|
|
1712
|
+
view = _field_view(sim, folder, key, "view", request)
|
|
1713
|
+
if "figure" in chosen:
|
|
1714
|
+
out["figures"].append(view["figure"])
|
|
1715
|
+
else:
|
|
1716
|
+
for p in folder.glob("view.*"):
|
|
1717
|
+
if p.suffix in (".png", ".svg", ".tex"):
|
|
1718
|
+
p.unlink()
|
|
1719
|
+
if "video" in view:
|
|
1720
|
+
out["videos"].append(view["video"])
|
|
1721
|
+
if "tables" in chosen:
|
|
1722
|
+
for stem in ("results", "homogenization"):
|
|
1723
|
+
path = sim / f"{stem}.csv"
|
|
1724
|
+
if path.exists():
|
|
1725
|
+
shutil.copy2(path, folder / path.name)
|
|
1726
|
+
with path.open(encoding="utf-8", newline="") as f:
|
|
1727
|
+
rows = list(csv.DictReader(f))
|
|
1728
|
+
for fmt in request.get("table_formats") or ["txt", "xlsx"]:
|
|
1729
|
+
if fmt in ("txt", "xlsx"):
|
|
1730
|
+
write_table(folder / f"{stem}.{fmt}", rows)
|
|
1731
|
+
if "fields" in chosen:
|
|
1732
|
+
for path in [*sim.glob("sample_0000_*_*.vtu"), *sim.glob("sample_0000_*_*.vti")]:
|
|
1733
|
+
if not path.stem.endswith("_tet"):
|
|
1734
|
+
shutil.copy2(path, folder / path.name)
|
|
1735
|
+
if "mesh" in chosen:
|
|
1736
|
+
for path in sim.glob("sample_0000_tet.*"):
|
|
1737
|
+
shutil.copy2(path, folder / path.name)
|
|
1738
|
+
if "configuration" in chosen and (sim / "configuration.yaml").exists():
|
|
1739
|
+
shutil.copy2(sim / "configuration.yaml", folder / "configuration.yaml")
|
|
1740
|
+
return out
|
|
1741
|
+
|
|
1742
|
+
|
|
1743
|
+
# -- saving and opening a workspace -------------------------------------------------------------
|
|
1744
|
+
|
|
1745
|
+
#: The manifest of a saved workspace
|
|
1746
|
+
WORKSPACE_FILE = "workspace.json"
|
|
1747
|
+
|
|
1748
|
+
|
|
1749
|
+
def _default_directory() -> Path:
|
|
1750
|
+
return Path.home() / "morphogen" / "workspaces" / time.strftime("%Y%m%d-%H%M%S")
|
|
1751
|
+
|
|
1752
|
+
|
|
1753
|
+
def save_workspace(request: dict, session: Session) -> dict:
|
|
1754
|
+
"""Write the workspace of the session to a folder (``directory``, by default a new one
|
|
1755
|
+
under ``~/morphogen/workspaces``): the folder of each item with its files, the
|
|
1756
|
+
microstructure of each morphology (``micro.json``) and the manifest of the items, so
|
|
1757
|
+
that :func:`open_workspace` restores them in another session."""
|
|
1758
|
+
import json
|
|
1759
|
+
|
|
1760
|
+
from morphogen._utils import to_jsonable
|
|
1761
|
+
|
|
1762
|
+
directory = Path(str(request.get("directory") or "").strip() or _default_directory())
|
|
1763
|
+
directory = directory.expanduser()
|
|
1764
|
+
items = sorted(session.items.values(), key=lambda i: i["number"])
|
|
1765
|
+
if not items:
|
|
1766
|
+
raise ValueError("the workspace is empty: nothing to save")
|
|
1767
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
1768
|
+
manifest = []
|
|
1769
|
+
for item in items:
|
|
1770
|
+
source = session.root / item["key"]
|
|
1771
|
+
target = directory / item["key"]
|
|
1772
|
+
if target.exists():
|
|
1773
|
+
shutil.rmtree(target)
|
|
1774
|
+
shutil.copytree(source, target)
|
|
1775
|
+
if item.get("micro") is not None:
|
|
1776
|
+
io.save_microstructure(item["micro"], target / "micro.json")
|
|
1777
|
+
manifest.append(to_jsonable({k: v for k, v in item.items() if k != "micro"}))
|
|
1778
|
+
(directory / WORKSPACE_FILE).write_text(
|
|
1779
|
+
json.dumps({"morphogen": _version(), "items": manifest}, indent=1), encoding="utf-8"
|
|
1780
|
+
)
|
|
1781
|
+
return {"saved": len(manifest), "directory": str(directory)}
|
|
1782
|
+
|
|
1783
|
+
|
|
1784
|
+
def _version() -> str:
|
|
1785
|
+
from morphogen import __version__
|
|
1786
|
+
|
|
1787
|
+
return __version__
|
|
1788
|
+
|
|
1789
|
+
|
|
1790
|
+
def open_workspace(request: dict, session: Session) -> dict:
|
|
1791
|
+
"""Add the items of a saved workspace (``directory``, see :func:`save_workspace``) to
|
|
1792
|
+
the workspace of the session, under new keys (their links and sources renamed)."""
|
|
1793
|
+
import json
|
|
1794
|
+
import re
|
|
1795
|
+
|
|
1796
|
+
directory = Path(str(request.get("directory") or "").strip()).expanduser()
|
|
1797
|
+
manifest = directory / WORKSPACE_FILE
|
|
1798
|
+
if not manifest.is_file():
|
|
1799
|
+
raise ValueError(f"no saved workspace in {directory} (no {WORKSPACE_FILE})")
|
|
1800
|
+
items = json.loads(manifest.read_text(encoding="utf-8")).get("items", [])
|
|
1801
|
+
keys: dict[str, str] = {}
|
|
1802
|
+
opened = []
|
|
1803
|
+
for item in items: # in their order: the sources come first
|
|
1804
|
+
old = item["key"]
|
|
1805
|
+
new, folder = session.folder()
|
|
1806
|
+
keys[old] = new
|
|
1807
|
+
saved = directory / old
|
|
1808
|
+
if saved.is_dir():
|
|
1809
|
+
shutil.copytree(saved, folder, dirs_exist_ok=True)
|
|
1810
|
+
text = json.dumps(item)
|
|
1811
|
+
for before, after in keys.items(): # its files, sources and the items it took
|
|
1812
|
+
text = text.replace(before, after)
|
|
1813
|
+
data = json.loads(text)
|
|
1814
|
+
for k in ("key", "kind", "number", "title"):
|
|
1815
|
+
data.pop(k, None)
|
|
1816
|
+
if (folder / "micro.json").is_file():
|
|
1817
|
+
data["micro"] = io.load_microstructure(folder / "micro.json")
|
|
1818
|
+
title = re.sub(r"^#\d+ ", "", item.get("title", item["kind"]))
|
|
1819
|
+
opened.append(session.public(session.add(new, item["kind"], title, **data)))
|
|
1820
|
+
return {"opened": len(opened), "items": opened}
|
|
1821
|
+
|
|
1822
|
+
|
|
1823
|
+
def tool_result(key: str, session: Session) -> dict:
|
|
1824
|
+
"""The run of a tool kept in the workspace (a result, or the simulation or behaviour a
|
|
1825
|
+
tool made): its tool and tab, the parameters of its form and its result, to show them
|
|
1826
|
+
again."""
|
|
1827
|
+
item = session.item(key, ("result", "simulation", "behaviour"))
|
|
1828
|
+
if "tool" not in item:
|
|
1829
|
+
raise ValueError(f"{item['title']} is not the run of a tool")
|
|
1830
|
+
return {k: item[k] for k in ("key", "title", "tool", "tab", "params", "result")}
|
|
1831
|
+
|
|
1832
|
+
|
|
1833
|
+
# -- database of results and Ashby charts ----------------------------------------------------
|
|
1834
|
+
|
|
1835
|
+
|
|
1836
|
+
def _database(request: dict):
|
|
1837
|
+
from morphogen.results import ResultsDatabase
|
|
1838
|
+
|
|
1839
|
+
path = str(request.get("database") or "").strip()
|
|
1840
|
+
if not path:
|
|
1841
|
+
raise ValueError("database: the path of a results database (.db)")
|
|
1842
|
+
if request.get("create") is not True and not Path(path).exists():
|
|
1843
|
+
raise ValueError(f"no database {path} (add a run to create it)")
|
|
1844
|
+
return ResultsDatabase(path)
|
|
1845
|
+
|
|
1846
|
+
|
|
1847
|
+
def _conditions(request: dict) -> list[str]:
|
|
1848
|
+
where = request.get("where") or []
|
|
1849
|
+
if isinstance(where, str):
|
|
1850
|
+
where = [w for part in where.splitlines() for w in part.split(";")]
|
|
1851
|
+
return [w.strip() for w in where if w.strip()]
|
|
1852
|
+
|
|
1853
|
+
|
|
1854
|
+
def database_info(request: dict) -> dict:
|
|
1855
|
+
"""Runs of a database and the keys of its records (those matching ``where``)."""
|
|
1856
|
+
with _database(request) as db:
|
|
1857
|
+
conditions = _conditions(request)
|
|
1858
|
+
keys = db.keys(conditions)
|
|
1859
|
+
return {
|
|
1860
|
+
"runs": db.runs(),
|
|
1861
|
+
"records": max((v["count"] for v in keys.values()), default=0),
|
|
1862
|
+
"numeric": [k for k, v in keys.items() if v["numeric"]],
|
|
1863
|
+
"text": [k for k, v in keys.items() if not v["numeric"]],
|
|
1864
|
+
}
|
|
1865
|
+
|
|
1866
|
+
|
|
1867
|
+
def database_add(request: dict) -> dict:
|
|
1868
|
+
"""Add a run directory to a database (created if needed)."""
|
|
1869
|
+
directory = str(request.get("directory") or "").strip()
|
|
1870
|
+
if not directory:
|
|
1871
|
+
raise ValueError("directory: the output directory of a run")
|
|
1872
|
+
with _database({**request, "create": True}) as db:
|
|
1873
|
+
n = db.add_run(directory, name=request.get("name") or None)
|
|
1874
|
+
return {"added": n}
|
|
1875
|
+
|
|
1876
|
+
|
|
1877
|
+
def database_add_session(request: dict, session: Session) -> dict:
|
|
1878
|
+
"""Add the simulations of the workspace (``keys``, by default all) to a database
|
|
1879
|
+
(created if needed), each a run named after its item, for the Ashby charts."""
|
|
1880
|
+
from morphogen import pipeline
|
|
1881
|
+
|
|
1882
|
+
keys = request.get("keys") or [i["key"] for i in session.workspace()]
|
|
1883
|
+
items = [
|
|
1884
|
+
session.item(k, ("simulation",))
|
|
1885
|
+
for k in keys
|
|
1886
|
+
if session.items.get(k, {}).get("kind") == "simulation"
|
|
1887
|
+
]
|
|
1888
|
+
if not items:
|
|
1889
|
+
raise ValueError("no simulation in the workspace: simulate a morphology first")
|
|
1890
|
+
added = 0
|
|
1891
|
+
with _database({**request, "create": True}) as db:
|
|
1892
|
+
for item in items:
|
|
1893
|
+
folder = session.file(item["key"], "results.csv").parent
|
|
1894
|
+
rows = pipeline.collect_results(folder)
|
|
1895
|
+
config = {k: v for k, v in (item.get("config") or {}).items() if k != "outputs"}
|
|
1896
|
+
added += db.add_records(
|
|
1897
|
+
rows, name=item["title"], config=config, path=f"session:{item['key']}"
|
|
1898
|
+
)
|
|
1899
|
+
return {"added": added, "runs": len(items)}
|
|
1900
|
+
|
|
1901
|
+
|
|
1902
|
+
def ashby(request: dict) -> dict:
|
|
1903
|
+
"""Points of an Ashby chart of the records matching ``where``, with the axis labels
|
|
1904
|
+
and the guide lines."""
|
|
1905
|
+
from morphogen.results import ashby_points, axis_label, default_axes
|
|
1906
|
+
|
|
1907
|
+
with _database(request) as db:
|
|
1908
|
+
records = db.records(_conditions(request))
|
|
1909
|
+
if not records:
|
|
1910
|
+
raise ValueError("no record matches the conditions")
|
|
1911
|
+
x, y = request.get("x") or None, request.get("y") or None
|
|
1912
|
+
if x is None or y is None:
|
|
1913
|
+
dx, dy = default_axes(records)
|
|
1914
|
+
x, y = x or dx, y or dy
|
|
1915
|
+
by = request.get("by", "model.type") or None
|
|
1916
|
+
log = bool(request.get("log", True))
|
|
1917
|
+
data = ashby_points(records, x, y, by, log=log, groups=request.get("groups") or None)
|
|
1918
|
+
guides = request.get("guides")
|
|
1919
|
+
if guides is None:
|
|
1920
|
+
guides = [1, 2] if log and x == "solid_fraction" and y.endswith(".relative") else []
|
|
1921
|
+
data.update(
|
|
1922
|
+
x_label=axis_label(x),
|
|
1923
|
+
y_label=axis_label(y),
|
|
1924
|
+
guides=[float(n) for n in guides],
|
|
1925
|
+
matched=len(records),
|
|
1926
|
+
)
|
|
1927
|
+
return data
|