morphogen 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- morphogen/__init__.py +60 -0
- morphogen/__main__.py +7 -0
- morphogen/_platform.py +55 -0
- morphogen/_public.py +153 -0
- morphogen/_utils.py +80 -0
- morphogen/_version.py +1 -0
- morphogen/analysis/__init__.py +174 -0
- morphogen/analysis/anisotropy.py +135 -0
- morphogen/analysis/basic.py +38 -0
- morphogen/analysis/cells.py +54 -0
- morphogen/analysis/connectivity.py +156 -0
- morphogen/analysis/correlation.py +195 -0
- morphogen/analysis/covariance.py +80 -0
- morphogen/analysis/fractal.py +54 -0
- morphogen/analysis/measures.py +188 -0
- morphogen/analysis/morphology.py +265 -0
- morphogen/analysis/particles.py +160 -0
- morphogen/analysis/percolation.py +2034 -0
- morphogen/analysis/power_laws.py +143 -0
- morphogen/analysis/random_sets.py +351 -0
- morphogen/analysis/stereology.py +289 -0
- morphogen/analysis/surface.py +107 -0
- morphogen/analysis/topology.py +92 -0
- morphogen/automata/__init__.py +74 -0
- morphogen/automata/engine.py +211 -0
- morphogen/automata/growth.py +686 -0
- morphogen/automata/lattice.py +143 -0
- morphogen/automata/reaction.py +255 -0
- morphogen/automata/rules.py +353 -0
- morphogen/automata/tilings.py +1715 -0
- morphogen/cli.py +3526 -0
- morphogen/config.py +2167 -0
- morphogen/contact/__init__.py +113 -0
- morphogen/contact/experiments.py +368 -0
- morphogen/contact/hertz.py +104 -0
- morphogen/contact/kernels.py +827 -0
- morphogen/contact/periodic.py +278 -0
- morphogen/contact/problem.py +578 -0
- morphogen/contact/surfaces.py +310 -0
- morphogen/coupling/__init__.py +43 -0
- morphogen/coupling/ageing.py +143 -0
- morphogen/coupling/diffusion.py +226 -0
- morphogen/coupling/fenicsx.py +484 -0
- morphogen/coupling/oxidation.py +447 -0
- morphogen/coupling/plates.py +247 -0
- morphogen/design/__init__.py +51 -0
- morphogen/design/csp.py +616 -0
- morphogen/design/frames.py +277 -0
- morphogen/design/search.py +287 -0
- morphogen/design/tiles.py +336 -0
- morphogen/distributions.py +312 -0
- morphogen/domain.py +203 -0
- morphogen/dynamics/__init__.py +179 -0
- morphogen/dynamics/model.py +638 -0
- morphogen/dynamics/openradioss.py +643 -0
- morphogen/dynamics/results.py +515 -0
- morphogen/fracture/__init__.py +170 -0
- morphogen/fracture/bulk.py +349 -0
- morphogen/fracture/cohesive.py +1614 -0
- morphogen/fracture/ductile.py +557 -0
- morphogen/fracture/lefm.py +1168 -0
- morphogen/fracture/mixed.py +1178 -0
- morphogen/fracture/periodic.py +733 -0
- morphogen/fracture/phasefield.py +714 -0
- morphogen/fracture/phasefield_finite.py +368 -0
- morphogen/fracture/surface.py +572 -0
- morphogen/fracture/toughness.py +566 -0
- morphogen/gpu.py +108 -0
- morphogen/gui/__init__.py +8 -0
- morphogen/gui/api.py +1927 -0
- morphogen/gui/desktop.py +387 -0
- morphogen/gui/icon.png +0 -0
- morphogen/gui/index.html +1909 -0
- morphogen/gui/server.py +229 -0
- morphogen/gui/tools/__init__.py +629 -0
- morphogen/gui/tools/compare.py +149 -0
- morphogen/gui/tools/contact.py +391 -0
- morphogen/gui/tools/couplings.py +1085 -0
- morphogen/gui/tools/crackfront.py +245 -0
- morphogen/gui/tools/design.py +224 -0
- morphogen/gui/tools/dynamics.py +824 -0
- morphogen/gui/tools/fracture.py +2586 -0
- morphogen/gui/tools/interop.py +1654 -0
- morphogen/gui/tools/learning.py +595 -0
- morphogen/gui/tools/mechanics.py +3881 -0
- morphogen/gui/tools/nonlocal_damage.py +1321 -0
- morphogen/gui/tools/phasefield.py +215 -0
- morphogen/gui/tools/physics.py +597 -0
- morphogen/gui/tools/stability.py +1756 -0
- morphogen/gui/tools/statistics.py +1408 -0
- morphogen/gui/viewer.js +1100 -0
- morphogen/homogenization/__init__.py +210 -0
- morphogen/homogenization/acoustics.py +566 -0
- morphogen/homogenization/amg.py +1005 -0
- morphogen/homogenization/apparent.py +1046 -0
- morphogen/homogenization/behaviours.cu +2285 -0
- morphogen/homogenization/behaviours.py +944 -0
- morphogen/homogenization/beremin.py +263 -0
- morphogen/homogenization/bifurcation.py +1085 -0
- morphogen/homogenization/bloch.py +507 -0
- morphogen/homogenization/bounds.py +226 -0
- morphogen/homogenization/core.py +458 -0
- morphogen/homogenization/coupled.py +1135 -0
- morphogen/homogenization/crystal.py +2967 -0
- morphogen/homogenization/dilatation.py +454 -0
- morphogen/homogenization/elements.py +157 -0
- morphogen/homogenization/fatigue.py +768 -0
- morphogen/homogenization/fe.py +1739 -0
- morphogen/homogenization/fenicsx.py +307 -0
- morphogen/homogenization/fft.py +499 -0
- morphogen/homogenization/fft_nonlinear.py +391 -0
- morphogen/homogenization/finite.py +613 -0
- morphogen/homogenization/flow.py +361 -0
- morphogen/homogenization/frames.py +1125 -0
- morphogen/homogenization/gpu.py +1241 -0
- morphogen/homogenization/harmonic.py +427 -0
- morphogen/homogenization/identification.py +579 -0
- morphogen/homogenization/kernels.py +760 -0
- morphogen/homogenization/laws.py +2061 -0
- morphogen/homogenization/materials.py +1080 -0
- morphogen/homogenization/mfront.py +589 -0
- morphogen/homogenization/networks.py +880 -0
- morphogen/homogenization/nonlinear.py +2612 -0
- morphogen/homogenization/ntfa.py +577 -0
- morphogen/homogenization/paths.py +476 -0
- morphogen/homogenization/photonic.py +467 -0
- morphogen/homogenization/poroelastic.py +212 -0
- morphogen/homogenization/porous.py +1120 -0
- morphogen/homogenization/postprocess.py +290 -0
- morphogen/homogenization/solvers.py +1140 -0
- morphogen/homogenization/tensors.py +240 -0
- morphogen/homogenization/voxel_fe.py +457 -0
- morphogen/homogenization/xfem.py +1016 -0
- morphogen/homogenization/zmat.py +1258 -0
- morphogen/iga/__init__.py +48 -0
- morphogen/iga/analysis.py +508 -0
- morphogen/iga/basis.py +214 -0
- morphogen/iga/geometry.py +501 -0
- morphogen/iga/homogenization.py +219 -0
- morphogen/iga/optimization.py +700 -0
- morphogen/iga/shapes.py +331 -0
- morphogen/image.py +128 -0
- morphogen/io/__init__.py +246 -0
- morphogen/io/amitex.py +741 -0
- morphogen/io/ebsd.py +881 -0
- morphogen/io/export.py +196 -0
- morphogen/io/geometry.py +158 -0
- morphogen/io/medit.py +147 -0
- morphogen/io/meshes.py +844 -0
- morphogen/io/metaimage.py +97 -0
- morphogen/io/mfront.py +1104 -0
- morphogen/io/native.py +57 -0
- morphogen/io/radioss.py +764 -0
- morphogen/io/solvers.py +371 -0
- morphogen/io/tables.py +278 -0
- morphogen/io/tiff.py +66 -0
- morphogen/io/vtk.py +701 -0
- morphogen/io/xdmf.py +200 -0
- morphogen/kernels/__init__.py +5 -0
- morphogen/kernels/annealing.py +192 -0
- morphogen/kernels/cells.py +69 -0
- morphogen/kernels/collective.py +87 -0
- morphogen/kernels/force_biased.py +595 -0
- morphogen/kernels/implicit.py +145 -0
- morphogen/kernels/leaves.py +132 -0
- morphogen/kernels/packing.py +304 -0
- morphogen/kernels/raster.py +279 -0
- morphogen/kernels/rsa.py +371 -0
- morphogen/kernels/union.py +135 -0
- morphogen/kernels/watershed.py +190 -0
- morphogen/laser/__init__.py +234 -0
- morphogen/laser/architectures.py +375 -0
- morphogen/laser/bending.py +216 -0
- morphogen/laser/cells.py +1694 -0
- morphogen/laser/design.py +940 -0
- morphogen/laser/figures.py +227 -0
- morphogen/laser/heat.py +804 -0
- morphogen/laser/materials.py +691 -0
- morphogen/laser/mechanics.py +1670 -0
- morphogen/laser/metallurgy.py +615 -0
- morphogen/laser/patterns.py +828 -0
- morphogen/laser/periodic.py +392 -0
- morphogen/laser/process.py +362 -0
- morphogen/laser/run.py +534 -0
- morphogen/laser/solid.py +216 -0
- morphogen/laser/specimen.py +200 -0
- morphogen/laser/structures.py +708 -0
- morphogen/learning/__init__.py +81 -0
- morphogen/learning/behaviour.py +398 -0
- morphogen/learning/data.py +328 -0
- morphogen/learning/learned.cpp +668 -0
- morphogen/learning/logarithmic.py +202 -0
- morphogen/learning/mfront.py +409 -0
- morphogen/learning/networks.py +767 -0
- morphogen/learning/run.py +212 -0
- morphogen/learning/standard.py +814 -0
- morphogen/learning/training.py +235 -0
- morphogen/mesh/__init__.py +29 -0
- morphogen/mesh/conforming.py +1423 -0
- morphogen/mesh/curved.py +600 -0
- morphogen/mesh/exact.py +1717 -0
- morphogen/mesh/octree.py +350 -0
- morphogen/mesh/polycrystal.py +1041 -0
- morphogen/mesh/polyhedra.py +677 -0
- morphogen/mesh/regularize.py +570 -0
- morphogen/mesh/surface.py +97 -0
- morphogen/mesh/tetra.py +512 -0
- morphogen/mesh/voxel.py +124 -0
- morphogen/micromorphic/__init__.py +31 -0
- morphogen/micromorphic/damage.py +359 -0
- morphogen/micromorphic/ductile.py +534 -0
- morphogen/micromorphic/finite.py +220 -0
- morphogen/micromorphic/microfoam.py +787 -0
- morphogen/micromorphic/space.py +341 -0
- morphogen/models/__init__.py +195 -0
- morphogen/models/affine.py +384 -0
- morphogen/models/automata.py +592 -0
- morphogen/models/base.py +500 -0
- morphogen/models/boolean.py +310 -0
- morphogen/models/bouligand.py +331 -0
- morphogen/models/branching.py +241 -0
- morphogen/models/combination.py +430 -0
- morphogen/models/deadleaves.py +766 -0
- morphogen/models/design.py +289 -0
- morphogen/models/ebsd.py +206 -0
- morphogen/models/fibers.py +1476 -0
- morphogen/models/foam.py +594 -0
- morphogen/models/gaussian.py +314 -0
- morphogen/models/growth.py +459 -0
- morphogen/models/hardcore.py +317 -0
- morphogen/models/hierarchical.py +269 -0
- morphogen/models/honeycomb.py +749 -0
- morphogen/models/implicit.py +177 -0
- morphogen/models/laminate.py +470 -0
- morphogen/models/lattice.py +351 -0
- morphogen/models/lattice_field.py +345 -0
- morphogen/models/levelset_foam.py +563 -0
- morphogen/models/nacre.py +411 -0
- morphogen/models/nested.py +924 -0
- morphogen/models/osteons.py +374 -0
- morphogen/models/pieces.py +167 -0
- morphogen/models/planar.py +126 -0
- morphogen/models/reconstruction.py +203 -0
- morphogen/models/scale_rich.py +1409 -0
- morphogen/models/scale_rich_3d.py +1616 -0
- morphogen/models/tessellation.py +735 -0
- morphogen/models/tiling_field.py +302 -0
- morphogen/models/tpms.py +197 -0
- morphogen/models/transparent.py +406 -0
- morphogen/models/union.py +141 -0
- morphogen/optimization/__init__.py +43 -0
- morphogen/optimization/cell.py +295 -0
- morphogen/optimization/filters.py +115 -0
- morphogen/optimization/mma.py +226 -0
- morphogen/optimization/run.py +219 -0
- morphogen/optimization/topology.py +632 -0
- morphogen/orientations.py +568 -0
- morphogen/parallel.py +599 -0
- morphogen/pipeline.py +978 -0
- morphogen/primitives.py +188 -0
- morphogen/results.py +564 -0
- morphogen/rve/__init__.py +73 -0
- morphogen/rve/report.py +627 -0
- morphogen/rve/scaling.py +363 -0
- morphogen/rve/study.py +1054 -0
- morphogen/rve/windows.py +345 -0
- morphogen/seeding.py +51 -0
- morphogen/settings.py +118 -0
- morphogen/stopping.py +48 -0
- morphogen/symmetry.py +384 -0
- morphogen/templates/activator_inhibitor.yaml +22 -0
- morphogen/templates/aggregation.yaml +23 -0
- morphogen/templates/boolean_cylinders.yaml +20 -0
- morphogen/templates/boolean_spheres.yaml +22 -0
- morphogen/templates/bouligand.yaml +28 -0
- morphogen/templates/cellular_automaton.yaml +25 -0
- morphogen/templates/coated_spheres.yaml +26 -0
- morphogen/templates/contact_fibers.yaml +27 -0
- morphogen/templates/cox_nanocomposite.yaml +22 -0
- morphogen/templates/cross_linked_fibers.yaml +26 -0
- morphogen/templates/curved_arcs.yaml +28 -0
- morphogen/templates/curved_fibers.yaml +24 -0
- morphogen/templates/dead_leaves.yaml +22 -0
- morphogen/templates/delaunay_network.yaml +22 -0
- morphogen/templates/dense_packing.yaml +22 -0
- morphogen/templates/diffusion.yaml +33 -0
- morphogen/templates/ebsd.yaml +34 -0
- morphogen/templates/ebsd_map.ctf +3087 -0
- morphogen/templates/fracture_composite.yaml +42 -0
- morphogen/templates/fracture_rubber.yaml +47 -0
- morphogen/templates/gaussian_excursion.yaml +17 -0
- morphogen/templates/graded_lattice.yaml +24 -0
- morphogen/templates/hardcore_fibers.yaml +22 -0
- morphogen/templates/hardcore_spheres.yaml +22 -0
- morphogen/templates/hierarchical_lattice.yaml +22 -0
- morphogen/templates/homogenization_acoustic_foam.yaml +36 -0
- morphogen/templates/homogenization_beremin.yaml +50 -0
- morphogen/templates/homogenization_cleavage.yaml +51 -0
- morphogen/templates/homogenization_cleavage_band.yaml +55 -0
- morphogen/templates/homogenization_contact.yaml +43 -0
- morphogen/templates/homogenization_crack_closure.yaml +49 -0
- morphogen/templates/homogenization_crystal_plasticity.yaml +50 -0
- morphogen/templates/homogenization_crystal_plasticity_fft.yaml +52 -0
- morphogen/templates/homogenization_crystallization.yaml +30 -0
- morphogen/templates/homogenization_debonding.yaml +43 -0
- morphogen/templates/homogenization_detwinning.yaml +58 -0
- morphogen/templates/homogenization_ductile_damage.yaml +47 -0
- morphogen/templates/homogenization_fatigue.yaml +40 -0
- morphogen/templates/homogenization_grain_fracture.yaml +56 -0
- morphogen/templates/homogenization_gyroid.yaml +30 -0
- morphogen/templates/homogenization_intergranular.yaml +43 -0
- morphogen/templates/homogenization_interphase.yaml +42 -0
- morphogen/templates/homogenization_mixed_loading.yaml +33 -0
- morphogen/templates/homogenization_ntfa.yaml +56 -0
- morphogen/templates/homogenization_piezoelectric.yaml +27 -0
- morphogen/templates/homogenization_polycrystal.yaml +30 -0
- morphogen/templates/homogenization_polycrystal_inclusions.yaml +30 -0
- morphogen/templates/homogenization_poroelastic.yaml +26 -0
- morphogen/templates/homogenization_rubber.yaml +40 -0
- morphogen/templates/homogenization_slip_cleavage.yaml +50 -0
- morphogen/templates/homogenization_spheres.yaml +31 -0
- morphogen/templates/homogenization_transport.yaml +29 -0
- morphogen/templates/homogenization_twinning.yaml +54 -0
- morphogen/templates/homogenization_viscoelastic.yaml +34 -0
- morphogen/templates/homogenization_viscoplastic.yaml +42 -0
- morphogen/templates/homogenization_voronoi.yaml +26 -0
- morphogen/templates/homogenization_xfem.yaml +23 -0
- morphogen/templates/hyperuniform_cells.yaml +24 -0
- morphogen/templates/laguerre.yaml +18 -0
- morphogen/templates/laser_bending.yaml +35 -0
- morphogen/templates/laser_cells.yaml +38 -0
- morphogen/templates/laser_corrugated.yaml +36 -0
- morphogen/templates/level_set_foam.yaml +29 -0
- morphogen/templates/menger_sponge.yaml +17 -0
- morphogen/templates/nacre.yaml +25 -0
- morphogen/templates/nucleation_growth.yaml +25 -0
- morphogen/templates/optimize_auxetic.yaml +29 -0
- morphogen/templates/optimize_auxetic_3d.yaml +27 -0
- morphogen/templates/optimize_bulk.yaml +23 -0
- morphogen/templates/optimize_conductivity.yaml +20 -0
- morphogen/templates/osteons.yaml +28 -0
- morphogen/templates/penetrable_spheres.yaml +21 -0
- morphogen/templates/poisson_fibers.yaml +21 -0
- morphogen/templates/random_laminate.yaml +26 -0
- morphogen/templates/random_lattice.yaml +27 -0
- morphogen/templates/random_walk_fibers.yaml +26 -0
- morphogen/templates/reaction_diffusion.yaml +22 -0
- morphogen/templates/reconstruction.yaml +22 -0
- morphogen/templates/rve_cellular_automaton.yaml +23 -0
- morphogen/templates/rve_crystal_plasticity_fft.yaml +51 -0
- morphogen/templates/rve_multiphysics.yaml +43 -0
- morphogen/templates/rve_poisson_fibers.yaml +22 -0
- morphogen/templates/rve_poisson_fibers_fe.yaml +33 -0
- morphogen/templates/rve_voronoi_windows.yaml +20 -0
- morphogen/templates/scale_rich_network.yaml +29 -0
- morphogen/templates/scale_rich_plates.yaml +30 -0
- morphogen/templates/sequential_dead_leaves.yaml +25 -0
- morphogen/templates/strut_lattice.yaml +21 -0
- morphogen/templates/tile_assembly.yaml +28 -0
- morphogen/templates/tpms.yaml +19 -0
- morphogen/templates/trabecular_bone.yaml +29 -0
- morphogen/templates/transparent_dead_leaves.yaml +23 -0
- morphogen/templates/vascular_tree.yaml +23 -0
- morphogen/templates/voronoi.yaml +20 -0
- morphogen/templates/wood.yaml +34 -0
- morphogen/templates/workflow.yaml +56 -0
- morphogen/texture.py +665 -0
- morphogen/theory.py +162 -0
- morphogen/viz/__init__.py +12 -0
- morphogen/viz/export.py +244 -0
- morphogen/viz/figures.py +707 -0
- morphogen/viz/png.py +148 -0
- morphogen/viz/sections.py +696 -0
- morphogen/viz/surfaces.py +1352 -0
- morphogen/viz/video.py +904 -0
- morphogen/viz/workflow.py +488 -0
- morphogen-1.0.0.dist-info/METADATA +2316 -0
- morphogen-1.0.0.dist-info/RECORD +381 -0
- morphogen-1.0.0.dist-info/WHEEL +4 -0
- morphogen-1.0.0.dist-info/entry_points.txt +5 -0
- morphogen-1.0.0.dist-info/licenses/LICENSE +674 -0
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"""Periodic pin-jointed frameworks: strut lattices with defects, and their rigidity.
|
|
2
|
+
|
|
3
|
+
A framework is a set of nodes in a periodic box and of bars joining pairs of nodes, the
|
|
4
|
+
second end possibly in a neighbouring copy of the box (``shift``). Lattices are built
|
|
5
|
+
from the unit cells of :mod:`morphogen.models.lattice`; defects are struts removed at
|
|
6
|
+
random (dilution) and nodes displaced at random (perturbation).
|
|
7
|
+
|
|
8
|
+
Rigidity (Maxwell 1864, Calladine 1978, Pellegrino and Calladine 1986; periodic
|
|
9
|
+
frameworks: Guest and Hutchinson 2003). The compatibility matrix ``A`` maps periodic
|
|
10
|
+
node displacements to bar extensions, and ``B`` maps a macroscopic strain ``E`` to the
|
|
11
|
+
extensions ``n . E L`` it imposes on the bars. Then
|
|
12
|
+
|
|
13
|
+
* mechanisms (periodic displacement modes extending no bar, rigid translations
|
|
14
|
+
excluded): ``m = 3 j - 3 - rank(A)``;
|
|
15
|
+
* states of self-stress (bar tensions in equilibrium without load):
|
|
16
|
+
``s = b - rank(A)``, so that ``m - s = 3 j - 3 - b`` (Maxwell-Calladine);
|
|
17
|
+
* floppy macroscopic strains (accommodated by some displacement without extending any
|
|
18
|
+
bar): ``6 - rank([A B]) + rank(A)``.
|
|
19
|
+
|
|
20
|
+
A lattice whose macroscopic strains all stretch bars is stretching-dominated: its
|
|
21
|
+
stiffness scales with the relative density, against its square for bending-dominated
|
|
22
|
+
lattices (Deshpande, Ashby and Fleck 2001). Maxwell's count requires a mean coordination
|
|
23
|
+
of at least 6 in 3D for large frameworks.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
from scipy.sparse import coo_matrix
|
|
32
|
+
from scipy.sparse.csgraph import connected_components
|
|
33
|
+
|
|
34
|
+
from morphogen.primitives import Segments
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class Framework:
|
|
39
|
+
"""Nodes in a periodic box and bars from ``nodes[p]`` to ``nodes[q] + shift * box``."""
|
|
40
|
+
|
|
41
|
+
nodes: np.ndarray
|
|
42
|
+
bars: np.ndarray
|
|
43
|
+
shifts: np.ndarray
|
|
44
|
+
box: np.ndarray
|
|
45
|
+
|
|
46
|
+
def __post_init__(self) -> None:
|
|
47
|
+
self.nodes = np.asarray(self.nodes, dtype=float).reshape(-1, 3)
|
|
48
|
+
self.bars = np.asarray(self.bars, dtype=np.int64).reshape(-1, 2)
|
|
49
|
+
self.shifts = np.asarray(self.shifts, dtype=np.int64).reshape(-1, 3)
|
|
50
|
+
self.box = np.asarray(self.box, dtype=float).reshape(3)
|
|
51
|
+
if len(self.bars) != len(self.shifts):
|
|
52
|
+
raise ValueError("bars and shifts: same length")
|
|
53
|
+
if len(self.bars) and (self.bars.min() < 0 or self.bars.max() >= len(self.nodes)):
|
|
54
|
+
raise ValueError("bars: node indices out of range")
|
|
55
|
+
|
|
56
|
+
# -- construction --------------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def lattice(cls, cell: str, n_cells=1, cell_size: float = 1.0) -> Framework:
|
|
60
|
+
"""The periodic lattice of ``n_cells`` unit cells (cubic, bcc, fcc, octet, kelvin,
|
|
61
|
+
diamond or pyrochlore: :data:`morphogen.models.lattice.CELLS`)."""
|
|
62
|
+
from morphogen.models.lattice import CELLS, unit_cell_struts # (models import us)
|
|
63
|
+
|
|
64
|
+
if cell not in CELLS:
|
|
65
|
+
raise ValueError(f"cell: one of {CELLS}")
|
|
66
|
+
n = np.broadcast_to(np.asarray(n_cells, dtype=int), (3,))
|
|
67
|
+
if np.any(n < 1):
|
|
68
|
+
raise ValueError("n_cells: at least one cell along each axis")
|
|
69
|
+
unit = unit_cell_struts(cell) # fractional coordinates, (s, 2, 3)
|
|
70
|
+
offsets = np.stack(np.meshgrid(*[np.arange(k) for k in n], indexing="ij"), -1)
|
|
71
|
+
ends = (offsets.reshape(-1, 1, 1, 3) + unit[None]).reshape(-1, 2, 3)
|
|
72
|
+
# the nodes of the cells are multiples of 1/8 of their edge (1/2 for the cubic
|
|
73
|
+
# lattices, 1/4 for the Kelvin and diamond cells, 1/8 for the pyrochlore)
|
|
74
|
+
keys = np.mod(np.rint(ends * 8).astype(np.int64), 8 * n)
|
|
75
|
+
wrapped = keys / 8.0
|
|
76
|
+
flat = keys.reshape(-1, 3)
|
|
77
|
+
uniq, inverse = np.unique(flat, axis=0, return_inverse=True)
|
|
78
|
+
ids = inverse.reshape(-1, 2)
|
|
79
|
+
shifts = np.rint((ends[:, 1] - wrapped[:, 1]) / n).astype(np.int64) - np.rint(
|
|
80
|
+
(ends[:, 0] - wrapped[:, 0]) / n
|
|
81
|
+
).astype(np.int64)
|
|
82
|
+
frame = cls(uniq / 8.0 * cell_size, ids, shifts, n * float(cell_size))
|
|
83
|
+
return frame._deduplicated()
|
|
84
|
+
|
|
85
|
+
def _deduplicated(self) -> Framework:
|
|
86
|
+
"""Remove repeated bars (a bar p-q with shift s is the bar q-p with shift -s)."""
|
|
87
|
+
p, q = self.bars[:, 0], self.bars[:, 1]
|
|
88
|
+
s = self.shifts
|
|
89
|
+
# orient each bar canonically: p < q, or p == q with a positive first non-zero shift
|
|
90
|
+
first = np.argmax(s != 0, axis=1)
|
|
91
|
+
neg = s[np.arange(len(s)), first] < 0
|
|
92
|
+
flip = (p > q) | ((p == q) & neg)
|
|
93
|
+
pp = np.where(flip, q, p)
|
|
94
|
+
qq = np.where(flip, p, q)
|
|
95
|
+
ss = np.where(flip[:, None], -s, s)
|
|
96
|
+
key = np.column_stack([pp, qq, ss])
|
|
97
|
+
_, idx = np.unique(key, axis=0, return_index=True)
|
|
98
|
+
idx.sort()
|
|
99
|
+
keep = idx[~((pp[idx] == qq[idx]) & np.all(ss[idx] == 0, axis=1))] # no zero bars
|
|
100
|
+
return Framework(self.nodes, np.column_stack([pp, qq])[keep], ss[keep], self.box)
|
|
101
|
+
|
|
102
|
+
# -- description ---------------------------------------------------------------------
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def n_nodes(self) -> int:
|
|
106
|
+
return len(self.nodes)
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def n_bars(self) -> int:
|
|
110
|
+
return len(self.bars)
|
|
111
|
+
|
|
112
|
+
def degrees(self) -> np.ndarray:
|
|
113
|
+
return np.bincount(self.bars.ravel(), minlength=self.n_nodes)
|
|
114
|
+
|
|
115
|
+
def coordination(self) -> float:
|
|
116
|
+
"""Mean number of bars per node, ``Z = 2 b / j``."""
|
|
117
|
+
return 2.0 * self.n_bars / self.n_nodes if self.n_nodes else 0.0
|
|
118
|
+
|
|
119
|
+
def vectors(self) -> np.ndarray:
|
|
120
|
+
"""Bar vectors ``(b, 3)``."""
|
|
121
|
+
p, q = self.bars[:, 0], self.bars[:, 1]
|
|
122
|
+
return self.nodes[q] + self.shifts * self.box - self.nodes[p]
|
|
123
|
+
|
|
124
|
+
def components(self) -> np.ndarray:
|
|
125
|
+
"""Connected component of every node (through the periodic boundaries)."""
|
|
126
|
+
p, q = self.bars[:, 0], self.bars[:, 1]
|
|
127
|
+
graph = coo_matrix((np.ones(len(p)), (p, q)), shape=(self.n_nodes, self.n_nodes))
|
|
128
|
+
return connected_components(graph, directed=False)[1]
|
|
129
|
+
|
|
130
|
+
# -- transformations -----------------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
def with_bars(self, keep) -> Framework:
|
|
133
|
+
"""The framework with the selected bars only (same nodes)."""
|
|
134
|
+
keep = np.asarray(keep)
|
|
135
|
+
return Framework(self.nodes, self.bars[keep], self.shifts[keep], self.box)
|
|
136
|
+
|
|
137
|
+
def without_isolated_nodes(self) -> Framework:
|
|
138
|
+
used = np.zeros(self.n_nodes, dtype=bool)
|
|
139
|
+
used[self.bars.ravel()] = True
|
|
140
|
+
index = np.cumsum(used) - 1
|
|
141
|
+
return Framework(self.nodes[used], index[self.bars], self.shifts, self.box)
|
|
142
|
+
|
|
143
|
+
def pruned(self, min_degree: int = 2) -> Framework:
|
|
144
|
+
"""Remove, repeatedly, the bars at nodes of fewer than ``min_degree`` bars."""
|
|
145
|
+
frame = self
|
|
146
|
+
while frame.n_bars:
|
|
147
|
+
deg = frame.degrees()
|
|
148
|
+
weak = deg < min_degree
|
|
149
|
+
bad = weak[frame.bars[:, 0]] | weak[frame.bars[:, 1]]
|
|
150
|
+
if not bad.any():
|
|
151
|
+
break
|
|
152
|
+
frame = frame.with_bars(~bad)
|
|
153
|
+
return frame.without_isolated_nodes()
|
|
154
|
+
|
|
155
|
+
def largest_component(self) -> Framework:
|
|
156
|
+
if self.n_bars == 0:
|
|
157
|
+
return self.without_isolated_nodes()
|
|
158
|
+
comp = self.components()
|
|
159
|
+
sizes = np.bincount(comp[self.bars[:, 0]], minlength=comp.max() + 1)
|
|
160
|
+
keep = comp[self.bars[:, 0]] == np.argmax(sizes)
|
|
161
|
+
return self.with_bars(keep).without_isolated_nodes()
|
|
162
|
+
|
|
163
|
+
def diluted(
|
|
164
|
+
self,
|
|
165
|
+
rng: np.random.Generator,
|
|
166
|
+
*,
|
|
167
|
+
coordination: float | None = None,
|
|
168
|
+
fraction: float | None = None,
|
|
169
|
+
min_degree: int = 3,
|
|
170
|
+
) -> Framework:
|
|
171
|
+
"""Struts removed at random.
|
|
172
|
+
|
|
173
|
+
With ``coordination``: until the mean coordination reaches the target, never
|
|
174
|
+
below ``min_degree`` bars at a node (the target may not be reached). With
|
|
175
|
+
``fraction``: that fraction of the bars, then dangling bars are pruned. The
|
|
176
|
+
largest connected component is kept.
|
|
177
|
+
"""
|
|
178
|
+
if (coordination is None) == (fraction is None):
|
|
179
|
+
raise ValueError("give exactly one of 'coordination' and 'fraction'")
|
|
180
|
+
if fraction is not None:
|
|
181
|
+
if not 0.0 <= fraction < 1.0:
|
|
182
|
+
raise ValueError("fraction: in [0, 1)")
|
|
183
|
+
keep = np.ones(self.n_bars, dtype=bool)
|
|
184
|
+
keep[rng.permutation(self.n_bars)[: round(fraction * self.n_bars)]] = False
|
|
185
|
+
return self.with_bars(keep).pruned(2).largest_component()
|
|
186
|
+
target = round(float(coordination) * self.n_nodes / 2.0)
|
|
187
|
+
deg = self.degrees().copy()
|
|
188
|
+
keep = np.ones(self.n_bars, dtype=bool)
|
|
189
|
+
n_bars = self.n_bars
|
|
190
|
+
for k in rng.permutation(self.n_bars):
|
|
191
|
+
if n_bars <= target:
|
|
192
|
+
break
|
|
193
|
+
p, q = self.bars[k]
|
|
194
|
+
need = 2 if p == q else 1 # a self-bar counts twice at its node
|
|
195
|
+
if deg[p] - need >= min_degree and deg[q] - need >= min_degree:
|
|
196
|
+
keep[k] = False
|
|
197
|
+
deg[p] -= 1
|
|
198
|
+
deg[q] -= 1
|
|
199
|
+
n_bars -= 1
|
|
200
|
+
return self.with_bars(keep).largest_component()
|
|
201
|
+
|
|
202
|
+
def perturbed(self, rng: np.random.Generator, amplitude: float) -> Framework:
|
|
203
|
+
"""Nodes displaced uniformly in balls of radius ``amplitude``."""
|
|
204
|
+
v = rng.standard_normal((self.n_nodes, 3))
|
|
205
|
+
v /= np.linalg.norm(v, axis=1, keepdims=True)
|
|
206
|
+
r = amplitude * rng.random(self.n_nodes) ** (1.0 / 3.0)
|
|
207
|
+
return Framework(self.nodes + v * r[:, None], self.bars, self.shifts, self.box)
|
|
208
|
+
|
|
209
|
+
def segments(self, radius: float, origin=(0.0, 0.0, 0.0)) -> Segments:
|
|
210
|
+
"""Struts as round-capped cylinders (periodic images are added when needed)."""
|
|
211
|
+
start = self.nodes[self.bars[:, 0]] + np.asarray(origin, dtype=float)
|
|
212
|
+
return Segments(
|
|
213
|
+
start, start + self.vectors(), np.full(self.n_bars, float(radius)), round_caps=True
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
# -- rigidity ------------------------------------------------------------------------
|
|
217
|
+
|
|
218
|
+
def compatibility(self) -> tuple[np.ndarray, np.ndarray]:
|
|
219
|
+
"""Dense matrices ``A (b, 3 j)`` and ``B (b, 6)`` (strains 11, 22, 33, 23, 13, 12,
|
|
220
|
+
shear components counted twice)."""
|
|
221
|
+
v = self.vectors()
|
|
222
|
+
length = np.linalg.norm(v, axis=1)
|
|
223
|
+
if np.any(length <= 0):
|
|
224
|
+
raise ValueError("bars of zero length")
|
|
225
|
+
n = v / length[:, None]
|
|
226
|
+
a = np.zeros((self.n_bars, 3 * self.n_nodes))
|
|
227
|
+
rows = np.arange(self.n_bars)
|
|
228
|
+
for d in range(3):
|
|
229
|
+
np.add.at(a, (rows, 3 * self.bars[:, 1] + d), n[:, d])
|
|
230
|
+
np.add.at(a, (rows, 3 * self.bars[:, 0] + d), -n[:, d])
|
|
231
|
+
b = np.column_stack(
|
|
232
|
+
[
|
|
233
|
+
n[:, 0] * v[:, 0],
|
|
234
|
+
n[:, 1] * v[:, 1],
|
|
235
|
+
n[:, 2] * v[:, 2],
|
|
236
|
+
n[:, 1] * v[:, 2] + n[:, 2] * v[:, 1],
|
|
237
|
+
n[:, 0] * v[:, 2] + n[:, 2] * v[:, 0],
|
|
238
|
+
n[:, 0] * v[:, 1] + n[:, 1] * v[:, 0],
|
|
239
|
+
]
|
|
240
|
+
)
|
|
241
|
+
return a, b / np.mean(length)
|
|
242
|
+
|
|
243
|
+
def rigidity(self, tol: float = 1e-9) -> dict:
|
|
244
|
+
"""Mechanisms, states of self-stress and floppy macroscopic strains (SVD ranks)."""
|
|
245
|
+
a, b = self.compatibility()
|
|
246
|
+
|
|
247
|
+
def rank(m):
|
|
248
|
+
if m.size == 0:
|
|
249
|
+
return 0
|
|
250
|
+
s = np.linalg.svd(m, compute_uv=False)
|
|
251
|
+
return int(np.sum(s > tol * max(1.0, s[0])))
|
|
252
|
+
|
|
253
|
+
ra = rank(a)
|
|
254
|
+
rab = rank(np.hstack([a, b]))
|
|
255
|
+
mechanisms = 3 * self.n_nodes - 3 - ra
|
|
256
|
+
floppy = 6 - (rab - ra)
|
|
257
|
+
return {
|
|
258
|
+
"n_nodes": self.n_nodes,
|
|
259
|
+
"n_bars": self.n_bars,
|
|
260
|
+
"coordination": self.coordination(),
|
|
261
|
+
"mechanisms": int(mechanisms),
|
|
262
|
+
"self_stresses": int(self.n_bars - ra),
|
|
263
|
+
"floppy_strains": int(floppy),
|
|
264
|
+
"stretching_dominated": bool(floppy == 0),
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
def to_dict(self) -> dict:
|
|
268
|
+
return {
|
|
269
|
+
"nodes": self.nodes.tolist(),
|
|
270
|
+
"bars": self.bars.tolist(),
|
|
271
|
+
"shifts": self.shifts.tolist(),
|
|
272
|
+
"box": self.box.tolist(),
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
@classmethod
|
|
276
|
+
def from_dict(cls, data: dict) -> Framework:
|
|
277
|
+
return cls(data["nodes"], data["bars"], data["shifts"], data["box"])
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""Search algorithms for discrete design problems, and the inverse design of automata.
|
|
2
|
+
|
|
3
|
+
``simulated_annealing`` and ``genetic_algorithm`` minimize a cost over any
|
|
4
|
+
representation (bit strings, tile weights, rule tables...), given the moves.
|
|
5
|
+
``fit_rule`` searches the outer-totalistic rules (birth and survival sets) of a cellular
|
|
6
|
+
automaton whose structures, grown from noise, match target morphological descriptors:
|
|
7
|
+
volume fraction, interface density and two-point correlation function, measured on an
|
|
8
|
+
image (e.g. a real microstructure, at the resolution of the automaton's cells) or given.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import math
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
from morphogen.automata.engine import CellularAutomaton, interface_density
|
|
21
|
+
from morphogen.automata.lattice import offsets
|
|
22
|
+
from morphogen.automata.rules import LifeRule
|
|
23
|
+
from morphogen.automata.tilings import QUASIPERIODIC, TilingContext, make_tiling
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class SearchResult:
|
|
28
|
+
"""Best solution found, its cost and the history of the search."""
|
|
29
|
+
|
|
30
|
+
best: Any
|
|
31
|
+
cost: float
|
|
32
|
+
evaluations: int
|
|
33
|
+
history: dict[str, list] = field(default_factory=dict)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def simulated_annealing(
|
|
37
|
+
x0,
|
|
38
|
+
cost: Callable[[Any], float],
|
|
39
|
+
neighbour: Callable[[Any, np.random.Generator], Any],
|
|
40
|
+
rng: np.random.Generator,
|
|
41
|
+
*,
|
|
42
|
+
steps: int = 1000,
|
|
43
|
+
t_start: float | None = None,
|
|
44
|
+
t_end: float | None = None,
|
|
45
|
+
callback=None,
|
|
46
|
+
) -> SearchResult:
|
|
47
|
+
"""Minimize ``cost`` by Metropolis moves ``x -> neighbour(x, rng)`` with a geometric
|
|
48
|
+
cooling from ``t_start`` to ``t_end`` (default: from the spread of the costs of 20
|
|
49
|
+
random moves, down to a thousandth of it)."""
|
|
50
|
+
x, c = x0, float(cost(x0))
|
|
51
|
+
evaluations = 1
|
|
52
|
+
if t_start is None:
|
|
53
|
+
diffs = []
|
|
54
|
+
for _ in range(20):
|
|
55
|
+
diffs.append(abs(float(cost(neighbour(x0, rng))) - c))
|
|
56
|
+
evaluations += 1
|
|
57
|
+
t_start = max(float(np.mean(diffs)), 1e-12)
|
|
58
|
+
if t_end is None:
|
|
59
|
+
t_end = 1e-3 * t_start
|
|
60
|
+
if not 0 < t_end <= t_start:
|
|
61
|
+
raise ValueError("temperatures: 0 < t_end <= t_start")
|
|
62
|
+
best, best_c = x, c
|
|
63
|
+
hist: dict[str, list] = {"step": [], "cost": [], "best": [], "temperature": []}
|
|
64
|
+
ratio = (t_end / t_start) ** (1.0 / max(1, steps - 1))
|
|
65
|
+
t = t_start
|
|
66
|
+
for k in range(int(steps)):
|
|
67
|
+
y = neighbour(x, rng)
|
|
68
|
+
cy = float(cost(y))
|
|
69
|
+
evaluations += 1
|
|
70
|
+
if cy <= c or rng.random() < math.exp(-(cy - c) / t):
|
|
71
|
+
x, c = y, cy
|
|
72
|
+
if c < best_c:
|
|
73
|
+
best, best_c = x, c
|
|
74
|
+
hist["step"].append(k)
|
|
75
|
+
hist["cost"].append(c)
|
|
76
|
+
hist["best"].append(best_c)
|
|
77
|
+
hist["temperature"].append(t)
|
|
78
|
+
if callback is not None:
|
|
79
|
+
callback(k, x, c)
|
|
80
|
+
t *= ratio
|
|
81
|
+
return SearchResult(best, best_c, evaluations, hist)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def genetic_algorithm(
|
|
85
|
+
population: list,
|
|
86
|
+
cost: Callable[[Any], float],
|
|
87
|
+
rng: np.random.Generator,
|
|
88
|
+
*,
|
|
89
|
+
mutate: Callable[[Any, np.random.Generator], Any],
|
|
90
|
+
crossover: Callable[[Any, Any, np.random.Generator], Any] | None = None,
|
|
91
|
+
generations: int = 50,
|
|
92
|
+
elite: int = 2,
|
|
93
|
+
tournament: int = 3,
|
|
94
|
+
callback=None,
|
|
95
|
+
) -> SearchResult:
|
|
96
|
+
"""Minimize ``cost`` with a generational genetic algorithm: the ``elite`` best
|
|
97
|
+
individuals are kept, the others are children of parents chosen by tournaments of
|
|
98
|
+
``tournament`` individuals, by ``crossover`` (if given) then ``mutate``."""
|
|
99
|
+
pop = list(population)
|
|
100
|
+
if len(pop) < 2:
|
|
101
|
+
raise ValueError("population: at least two individuals")
|
|
102
|
+
if not 0 <= elite < len(pop):
|
|
103
|
+
raise ValueError("elite: fewer than the population")
|
|
104
|
+
costs = [float(cost(x)) for x in pop]
|
|
105
|
+
evaluations = len(pop)
|
|
106
|
+
hist: dict[str, list] = {"generation": [], "best": [], "mean": []}
|
|
107
|
+
|
|
108
|
+
def pick():
|
|
109
|
+
idx = rng.choice(len(pop), size=min(tournament, len(pop)), replace=False)
|
|
110
|
+
return pop[min(idx, key=lambda i: costs[i])]
|
|
111
|
+
|
|
112
|
+
for g in range(int(generations) + 1):
|
|
113
|
+
order = np.argsort(costs)
|
|
114
|
+
hist["generation"].append(g)
|
|
115
|
+
hist["best"].append(costs[order[0]])
|
|
116
|
+
hist["mean"].append(float(np.mean(costs)))
|
|
117
|
+
if callback is not None:
|
|
118
|
+
callback(g, pop[order[0]], costs[order[0]])
|
|
119
|
+
if g == generations:
|
|
120
|
+
break
|
|
121
|
+
children = [pop[i] for i in order[:elite]]
|
|
122
|
+
child_costs = [costs[i] for i in order[:elite]]
|
|
123
|
+
while len(children) < len(pop):
|
|
124
|
+
a = pick()
|
|
125
|
+
child = crossover(a, pick(), rng) if crossover is not None else a
|
|
126
|
+
child = mutate(child, rng)
|
|
127
|
+
children.append(child)
|
|
128
|
+
child_costs.append(float(cost(child)))
|
|
129
|
+
evaluations += 1
|
|
130
|
+
pop, costs = children, child_costs
|
|
131
|
+
best = int(np.argmin(costs))
|
|
132
|
+
return SearchResult(pop[best], costs[best], evaluations, hist)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# -- inverse design of cellular automata ---------------------------------------------------
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def structure_descriptors(state, max_lag: int = 4, periodic: bool = True) -> np.ndarray:
|
|
139
|
+
"""Volume fraction, interface density (fraction of unlike neighbour pairs) and
|
|
140
|
+
two-point correlation ``rho(h) = (C(h) - f^2) / (f - f^2)`` at lags 1..max_lag
|
|
141
|
+
(mean over the axes of more than one cell)."""
|
|
142
|
+
s = np.asarray(state.data if hasattr(state, "data") else state) == 1
|
|
143
|
+
if s.ndim != 3:
|
|
144
|
+
raise ValueError("descriptors of 3D arrays ((nx, ny, 1) in 2D)")
|
|
145
|
+
f = float(s.mean())
|
|
146
|
+
out = [f, interface_density(s.astype(np.uint8), periodic)]
|
|
147
|
+
axes = [a for a in range(3) if s.shape[a] > max_lag]
|
|
148
|
+
for h in range(1, max_lag + 1):
|
|
149
|
+
if f <= 0.0 or f >= 1.0 or not axes:
|
|
150
|
+
out.append(0.0)
|
|
151
|
+
continue
|
|
152
|
+
c = np.mean([np.mean(s & np.roll(s, h, axis=a)) for a in axes])
|
|
153
|
+
out.append((c - f * f) / (f - f * f))
|
|
154
|
+
return np.array(out)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def descriptor_cost(d: np.ndarray, target: np.ndarray) -> float:
|
|
158
|
+
"""Squared errors: relative for the volume fraction and the interface density,
|
|
159
|
+
absolute for the correlation function."""
|
|
160
|
+
e_f = (d[0] - target[0]) / max(target[0], 0.05)
|
|
161
|
+
e_s = (d[1] - target[1]) / max(target[1], 0.01)
|
|
162
|
+
return float(e_f**2 + e_s**2 + np.sum((d[2:] - target[2:]) ** 2))
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@dataclass
|
|
166
|
+
class RuleFit:
|
|
167
|
+
"""Result of :func:`fit_rule`."""
|
|
168
|
+
|
|
169
|
+
rule: str
|
|
170
|
+
initial_fraction: float
|
|
171
|
+
cost: float
|
|
172
|
+
descriptors: np.ndarray
|
|
173
|
+
target: np.ndarray
|
|
174
|
+
evaluations: int
|
|
175
|
+
history: dict[str, list]
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def fit_rule(
|
|
179
|
+
target,
|
|
180
|
+
*,
|
|
181
|
+
neighbourhood: str = "moore",
|
|
182
|
+
radius: float = 1,
|
|
183
|
+
dims: int = 3,
|
|
184
|
+
lattice: str = "square",
|
|
185
|
+
shape=(24, 24, 24),
|
|
186
|
+
steps: int = 15,
|
|
187
|
+
initial_fraction: float | None = None,
|
|
188
|
+
population: int = 24,
|
|
189
|
+
generations: int = 15,
|
|
190
|
+
max_lag: int = 4,
|
|
191
|
+
rng: np.random.Generator | None = None,
|
|
192
|
+
callback=None,
|
|
193
|
+
) -> RuleFit:
|
|
194
|
+
"""Rule ``B.../S...`` (and initial noise density) whose structures best match
|
|
195
|
+
``target``.
|
|
196
|
+
|
|
197
|
+
``target`` is a phase image (phase 1 is the automaton's state 1) or an array of
|
|
198
|
+
descriptors (see :func:`structure_descriptors`). Each candidate rule is run for
|
|
199
|
+
``steps`` synchronous updates from noise of density ``initial_fraction`` (searched
|
|
200
|
+
too when not given) on a periodic lattice of ``shape`` cells, and scored by
|
|
201
|
+
:func:`descriptor_cost`; a genetic algorithm searches the birth and survival sets.
|
|
202
|
+
All candidates start from the same noise (common random numbers). Other ``lattice``
|
|
203
|
+
values than ``square`` run the candidates on a tiling of the box of ``shape`` cell
|
|
204
|
+
sizes (:mod:`morphogen.automata.tilings`; a free patch for quasi-periodic tilings),
|
|
205
|
+
rasterized at one voxel per cell size before their descriptors are measured.
|
|
206
|
+
"""
|
|
207
|
+
rng = np.random.default_rng() if rng is None else rng
|
|
208
|
+
if isinstance(target, np.ndarray) and target.ndim == 1:
|
|
209
|
+
goal = np.asarray(target, dtype=float)
|
|
210
|
+
max_lag = len(goal) - 2
|
|
211
|
+
else:
|
|
212
|
+
goal = structure_descriptors(target, max_lag)
|
|
213
|
+
if initial_fraction is not None and not 0.0 < initial_fraction < 1.0:
|
|
214
|
+
raise ValueError("initial_fraction: must lie in (0, 1)")
|
|
215
|
+
shape = tuple(int(n) for n in shape)
|
|
216
|
+
tiling = pixels = None
|
|
217
|
+
if lattice == "square":
|
|
218
|
+
k = len(offsets(neighbourhood, radius, dims=dims))
|
|
219
|
+
noise = rng.random(shape)
|
|
220
|
+
else:
|
|
221
|
+
from morphogen.domain import Domain, Grid
|
|
222
|
+
|
|
223
|
+
periodic = lattice not in QUASIPERIODIC
|
|
224
|
+
tiling = make_tiling(lattice, shape, 1.0, dims=dims, periodic=periodic, rng=rng)
|
|
225
|
+
pixels = tiling.cell_index(Grid(Domain(size=shape, periodic=periodic), shape))
|
|
226
|
+
k = int(np.max(TilingContext(tiling, neighbourhood, radius).n_neighbours))
|
|
227
|
+
noise = rng.random(tiling.n_cells)
|
|
228
|
+
|
|
229
|
+
def rule_of(genome) -> LifeRule:
|
|
230
|
+
bits = genome[0]
|
|
231
|
+
return LifeRule(np.flatnonzero(bits[: k + 1]), np.flatnonzero(bits[k + 1 :]))
|
|
232
|
+
|
|
233
|
+
def describe(genome):
|
|
234
|
+
ca = CellularAutomaton(
|
|
235
|
+
rule_of(genome), neighbourhood=neighbourhood, radius=radius, dims=dims, tiling=tiling
|
|
236
|
+
)
|
|
237
|
+
state = (noise < genome[1]).astype(np.uint8)
|
|
238
|
+
evo = ca.run(state, steps, rng, record=False)
|
|
239
|
+
return structure_descriptors(evo.state if tiling is None else evo.state[pixels], max_lag)
|
|
240
|
+
|
|
241
|
+
def cost(genome) -> float:
|
|
242
|
+
return descriptor_cost(describe(genome), goal)
|
|
243
|
+
|
|
244
|
+
def random_genome():
|
|
245
|
+
# threshold rules: birth above b neighbours, survival from s neighbours
|
|
246
|
+
b, s = rng.integers(k // 4, 3 * k // 4 + 1, size=2)
|
|
247
|
+
bits = np.zeros(2 * (k + 1), dtype=bool)
|
|
248
|
+
bits[b + 1 : k + 1] = True
|
|
249
|
+
bits[k + 1 + s :] = True
|
|
250
|
+
p0 = initial_fraction if initial_fraction is not None else rng.uniform(0.2, 0.8)
|
|
251
|
+
return bits, float(p0)
|
|
252
|
+
|
|
253
|
+
def mutate(genome, rng):
|
|
254
|
+
bits, p0 = genome
|
|
255
|
+
out = bits.copy()
|
|
256
|
+
flips = rng.random(out.size) < 1.5 / out.size
|
|
257
|
+
if not flips.any() and (initial_fraction is not None or rng.random() < 0.7):
|
|
258
|
+
flips[rng.integers(out.size)] = True
|
|
259
|
+
out[flips] = ~out[flips]
|
|
260
|
+
if initial_fraction is None and rng.random() < 0.3:
|
|
261
|
+
p0 = float(np.clip(p0 + 0.05 * rng.standard_normal(), 0.02, 0.98))
|
|
262
|
+
return out, p0
|
|
263
|
+
|
|
264
|
+
def crossover(a, b, rng):
|
|
265
|
+
mask = rng.random(a[0].size) < 0.5
|
|
266
|
+
return np.where(mask, a[0], b[0]), (a[1] if rng.random() < 0.5 else b[1])
|
|
267
|
+
|
|
268
|
+
init = [mutate(random_genome(), rng) for _ in range(int(population))]
|
|
269
|
+
res = genetic_algorithm(
|
|
270
|
+
init,
|
|
271
|
+
cost,
|
|
272
|
+
rng,
|
|
273
|
+
mutate=mutate,
|
|
274
|
+
crossover=crossover,
|
|
275
|
+
generations=generations,
|
|
276
|
+
callback=callback,
|
|
277
|
+
)
|
|
278
|
+
best = res.best
|
|
279
|
+
return RuleFit(
|
|
280
|
+
rule_of(best).describe(),
|
|
281
|
+
best[1],
|
|
282
|
+
res.cost,
|
|
283
|
+
describe(best),
|
|
284
|
+
goal,
|
|
285
|
+
res.evaluations,
|
|
286
|
+
res.history,
|
|
287
|
+
)
|