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/io/xdmf.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""XDMF images and voxel images written slab by slab (volumes larger than memory).
|
|
2
|
+
|
|
3
|
+
An XDMF image is an XML header (``.xdmf``, read by ParaView and VisIt) referring to raw
|
|
4
|
+
little-endian binary files, one per array, with the x index varying fastest. The
|
|
5
|
+
MetaImage format (``.mhd`` + ``.raw``) has the same layout. :func:`voxelize_to_file`
|
|
6
|
+
samples a microstructure slab by slab along z into a memory-mapped raw file, so that the
|
|
7
|
+
volume never needs to fit in memory.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from morphogen.domain import Domain, Grid
|
|
17
|
+
from morphogen.image import VoxelImage
|
|
18
|
+
|
|
19
|
+
_TYPES = {
|
|
20
|
+
"uint8": ("UChar", 1),
|
|
21
|
+
"int8": ("Char", 1),
|
|
22
|
+
"uint16": ("UInt", 2),
|
|
23
|
+
"int16": ("Int", 2),
|
|
24
|
+
"uint32": ("UInt", 4),
|
|
25
|
+
"int32": ("Int", 4),
|
|
26
|
+
"uint64": ("UInt", 8),
|
|
27
|
+
"int64": ("Int", 8),
|
|
28
|
+
"float32": ("Float", 4),
|
|
29
|
+
"float64": ("Float", 8),
|
|
30
|
+
}
|
|
31
|
+
_MET = {
|
|
32
|
+
"uint8": "MET_UCHAR",
|
|
33
|
+
"int8": "MET_CHAR",
|
|
34
|
+
"uint16": "MET_USHORT",
|
|
35
|
+
"int16": "MET_SHORT",
|
|
36
|
+
"uint32": "MET_UINT",
|
|
37
|
+
"int32": "MET_INT",
|
|
38
|
+
"uint64": "MET_ULONG_LONG",
|
|
39
|
+
"int64": "MET_LONG_LONG",
|
|
40
|
+
"float32": "MET_FLOAT",
|
|
41
|
+
"float64": "MET_DOUBLE",
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _dtype(dtype) -> np.dtype:
|
|
46
|
+
dtype = np.dtype(np.uint8 if np.dtype(dtype) == np.bool_ else dtype)
|
|
47
|
+
if dtype.name not in _TYPES:
|
|
48
|
+
raise ValueError(f"unsupported data type for raw images: {dtype}")
|
|
49
|
+
return dtype
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _xdmf_header(shape, spacing, origin, arrays) -> str:
|
|
53
|
+
"""``arrays``: (name, raw file name, dtype)."""
|
|
54
|
+
nx, ny, nz = shape
|
|
55
|
+
attrs = []
|
|
56
|
+
for name, raw, dtype in arrays:
|
|
57
|
+
number, precision = _TYPES[dtype.name]
|
|
58
|
+
attrs.append(
|
|
59
|
+
f' <Attribute Name="{name}" AttributeType="Scalar" Center="Cell">\n'
|
|
60
|
+
f' <DataItem Dimensions="{nz} {ny} {nx}" NumberType="{number}" '
|
|
61
|
+
f'Precision="{precision}" Format="Binary" Endian="Little">{raw}</DataItem>\n'
|
|
62
|
+
" </Attribute>"
|
|
63
|
+
)
|
|
64
|
+
z = " ".join(repr(float(v)) for v in origin[::-1])
|
|
65
|
+
h = " ".join(repr(float(v)) for v in spacing[::-1])
|
|
66
|
+
return (
|
|
67
|
+
'<?xml version="1.0" ?>\n'
|
|
68
|
+
'<Xdmf Version="3.0">\n'
|
|
69
|
+
" <Domain>\n"
|
|
70
|
+
' <Grid Name="image" GridType="Uniform">\n'
|
|
71
|
+
f' <Topology TopologyType="3DCoRectMesh" Dimensions="{nz + 1} {ny + 1} {nx + 1}"/>\n'
|
|
72
|
+
' <Geometry GeometryType="ORIGIN_DXDYDZ">\n'
|
|
73
|
+
f' <DataItem Dimensions="3" NumberType="Float" Precision="8" Format="XML">{z}'
|
|
74
|
+
"</DataItem>\n"
|
|
75
|
+
f' <DataItem Dimensions="3" NumberType="Float" Precision="8" Format="XML">{h}'
|
|
76
|
+
"</DataItem>\n"
|
|
77
|
+
" </Geometry>\n" + "\n".join(attrs) + "\n"
|
|
78
|
+
" </Grid>\n"
|
|
79
|
+
" </Domain>\n"
|
|
80
|
+
"</Xdmf>\n"
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def write_xdmf(path, images) -> Path:
|
|
85
|
+
"""XDMF header ``path`` and one raw file per image (same grid): ``<stem>_<name>.raw``."""
|
|
86
|
+
path = Path(path)
|
|
87
|
+
images = [images] if isinstance(images, VoxelImage) else list(images)
|
|
88
|
+
if not images:
|
|
89
|
+
raise ValueError("no image to write")
|
|
90
|
+
first = images[0]
|
|
91
|
+
arrays = []
|
|
92
|
+
for img in images:
|
|
93
|
+
if img.shape != first.shape:
|
|
94
|
+
raise ValueError("the images of an XDMF file share their grid")
|
|
95
|
+
dtype = _dtype(img.data.dtype)
|
|
96
|
+
raw = path.parent / f"{path.stem}_{img.name}.raw"
|
|
97
|
+
data = np.ascontiguousarray(img.data.astype(dtype).transpose(2, 1, 0))
|
|
98
|
+
raw.write_bytes(data.astype(dtype.newbyteorder("<"), copy=False).tobytes())
|
|
99
|
+
arrays.append((img.name, raw.name, dtype))
|
|
100
|
+
path.write_text(_xdmf_header(first.shape, first.spacing, first.origin, arrays), "ascii")
|
|
101
|
+
return path
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def read_xdmf(path, name: str | None = None) -> VoxelImage:
|
|
105
|
+
"""Image (array ``name``, or the first one) of an XDMF file written by morphoGen."""
|
|
106
|
+
import re
|
|
107
|
+
|
|
108
|
+
path = Path(path)
|
|
109
|
+
text = path.read_text(encoding="ascii")
|
|
110
|
+
dims = [int(v) for v in re.search(r'Dimensions="(\d+) (\d+) (\d+)"/>', text).groups()]
|
|
111
|
+
nz, ny, nx = (d - 1 for d in dims)
|
|
112
|
+
geo = re.findall(r'Format="XML">([^<]+)</DataItem>', text)
|
|
113
|
+
origin = tuple(float(v) for v in geo[0].split()[::-1])
|
|
114
|
+
spacing = tuple(float(v) for v in geo[1].split()[::-1])
|
|
115
|
+
for match in re.finditer(
|
|
116
|
+
r'<Attribute Name="([^"]+)".*?NumberType="(\w+)" Precision="(\d)".*?>([^<]+)</DataItem>',
|
|
117
|
+
text,
|
|
118
|
+
re.S,
|
|
119
|
+
):
|
|
120
|
+
array, number, precision, raw = match.groups()
|
|
121
|
+
if name is not None and array != name:
|
|
122
|
+
continue
|
|
123
|
+
dtype = next(np.dtype(k) for k, v in _TYPES.items() if v == (number, int(precision)))
|
|
124
|
+
data = np.fromfile(path.parent / raw, dtype=dtype.newbyteorder("<")).astype(dtype)
|
|
125
|
+
data = data.reshape(nz, ny, nx).transpose(2, 1, 0)
|
|
126
|
+
return VoxelImage(np.ascontiguousarray(data), spacing=spacing, origin=origin, name=array)
|
|
127
|
+
raise ValueError(f"{path}: no array {name!r}")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _slab_grid(grid: Grid, k0: int, k1: int) -> Grid:
|
|
131
|
+
"""Voxels ``[:, :, k0:k1]`` of a grid, as a grid of their own."""
|
|
132
|
+
h = np.asarray(grid.spacing, dtype=float)
|
|
133
|
+
lower = np.asarray(grid.domain.lower, dtype=float)
|
|
134
|
+
size = (grid.domain.lengths[0], grid.domain.lengths[1], h[2] * (k1 - k0))
|
|
135
|
+
origin = (lower[0], lower[1], lower[2] + h[2] * k0)
|
|
136
|
+
return Grid(
|
|
137
|
+
Domain(size=size, origin=origin, periodic=False), (grid.shape[0], grid.shape[1], k1 - k0)
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def voxelize_to_file(
|
|
142
|
+
micro,
|
|
143
|
+
path,
|
|
144
|
+
shape=None,
|
|
145
|
+
*,
|
|
146
|
+
voxel_size=None,
|
|
147
|
+
labels: bool = False,
|
|
148
|
+
slab: int | None = None,
|
|
149
|
+
max_voxels: int = 2**24,
|
|
150
|
+
) -> Path:
|
|
151
|
+
"""Phase (or with ``labels``, cell label) image of a microstructure written to an
|
|
152
|
+
``.xdmf`` or ``.mhd`` file slab by slab along z: memory holds one slab (about
|
|
153
|
+
``max_voxels`` voxels, or ``slab`` layers), whatever the size of the image. The
|
|
154
|
+
models whose images are computed pointwise give the same voxels as at once."""
|
|
155
|
+
path = Path(path)
|
|
156
|
+
ext = path.suffix.lower()
|
|
157
|
+
if ext not in (".xdmf", ".mhd"):
|
|
158
|
+
raise ValueError("chunked images are written to .xdmf or .mhd files")
|
|
159
|
+
grid = micro.grid(shape, voxel_size=voxel_size)
|
|
160
|
+
nx, ny, nz = grid.shape
|
|
161
|
+
step = int(slab) if slab else max(1, int(max_voxels) // (nx * ny))
|
|
162
|
+
name = "cell" if labels else "phase"
|
|
163
|
+
raw = path.parent / (f"{path.stem}_{name}.raw" if ext == ".xdmf" else f"{path.stem}.raw")
|
|
164
|
+
out = None
|
|
165
|
+
for k0 in range(0, nz, step):
|
|
166
|
+
k1 = min(nz, k0 + step)
|
|
167
|
+
sub = _slab_grid(grid, k0, k1)
|
|
168
|
+
img = micro.labels(grid=sub) if labels else micro.voxelize(grid=sub)
|
|
169
|
+
dtype = _dtype(img.data.dtype)
|
|
170
|
+
if out is None:
|
|
171
|
+
out = np.memmap(raw, dtype=dtype.newbyteorder("<"), mode="w+", shape=(nz, ny, nx))
|
|
172
|
+
first = dtype
|
|
173
|
+
if dtype != first:
|
|
174
|
+
raise ValueError("the slabs of the image have different data types")
|
|
175
|
+
out[k0:k1] = img.data.astype(dtype).transpose(2, 1, 0)
|
|
176
|
+
out.flush()
|
|
177
|
+
del out
|
|
178
|
+
if ext == ".xdmf":
|
|
179
|
+
header = _xdmf_header(
|
|
180
|
+
grid.shape, grid.spacing, grid.domain.lower, [(name, raw.name, first)]
|
|
181
|
+
)
|
|
182
|
+
path.write_text(header, encoding="ascii")
|
|
183
|
+
else:
|
|
184
|
+
centre = np.asarray(grid.domain.lower, dtype=float) + 0.5 * np.asarray(grid.spacing)
|
|
185
|
+
lines = [
|
|
186
|
+
"ObjectType = Image",
|
|
187
|
+
"NDims = 3",
|
|
188
|
+
"BinaryData = True",
|
|
189
|
+
"BinaryDataByteOrderMSB = False",
|
|
190
|
+
"CompressedData = False",
|
|
191
|
+
"TransformMatrix = 1 0 0 0 1 0 0 0 1",
|
|
192
|
+
f"Offset = {' '.join(repr(float(v)) for v in centre)}",
|
|
193
|
+
"CenterOfRotation = 0 0 0",
|
|
194
|
+
f"ElementSpacing = {' '.join(repr(float(v)) for v in grid.spacing)}",
|
|
195
|
+
f"DimSize = {nx} {ny} {nz}",
|
|
196
|
+
f"ElementType = {_MET[first.name]}",
|
|
197
|
+
f"ElementDataFile = {raw.name}",
|
|
198
|
+
]
|
|
199
|
+
path.write_text("\n".join(lines) + "\n", encoding="ascii")
|
|
200
|
+
return path
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Stochastic reconstruction of two-phase media by simulated annealing (Yeong & Torquato
|
|
2
|
+
1998): swaps of a cell of phase 1 and a cell of phase 0, which keep the volume fraction,
|
|
3
|
+
accepted by Metropolis' rule for the energy ``E = Σ_a Σ_r (S_a(r) - S*_a(r))^2 + w Σ_a
|
|
4
|
+
Σ_r (L_a(r) - L*_a(r))^2``: the two-point probability ``S`` and the lineal-path function
|
|
5
|
+
``L`` of phase 1 along the axes of a periodic lattice, against their targets.
|
|
6
|
+
|
|
7
|
+
A swap changes the counts of the pairs and segments of the lines through its two cells
|
|
8
|
+
only: removing phase 1 at the position ``i`` of a line removes the pairs ``(i, i ± r)``
|
|
9
|
+
of phase 1, ``I(i + r) + I(i - r)`` at the lag ``r``; along a line, a run of ``l`` cells
|
|
10
|
+
of phase 1 holds ``(l - r)_+`` segments of ``r + 1`` cells, so that splitting or merging
|
|
11
|
+
runs changes them by the runs on both sides of the cell (a line full of phase 1 holds a
|
|
12
|
+
segment at each of its cells). The energy of a swap is thus evaluated in ``O(R)`` per
|
|
13
|
+
axis.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import math
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
from numba import njit
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@njit(cache=True, inline="always")
|
|
25
|
+
def _at(img, idx, axis, d, n):
|
|
26
|
+
"""The cell at the offset ``d`` along ``axis`` from ``idx`` (periodic)."""
|
|
27
|
+
if axis == 0:
|
|
28
|
+
return img[(idx[0] + d) % n, idx[1], idx[2]]
|
|
29
|
+
if axis == 1:
|
|
30
|
+
return img[idx[0], (idx[1] + d) % n, idx[2]]
|
|
31
|
+
return img[idx[0], idx[1], (idx[2] + d) % n]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@njit(cache=True)
|
|
35
|
+
def _pairs(img, idx, axis, n, sign, rmax, out):
|
|
36
|
+
"""Add ``sign * (I(i + r) + I(i - r))`` to ``out[r]`` along ``axis``, r = 1..rmax."""
|
|
37
|
+
for r in range(1, rmax + 1):
|
|
38
|
+
out[r] += sign * (_at(img, idx, axis, r, n) + _at(img, idx, axis, -r, n))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@njit(cache=True)
|
|
42
|
+
def _segments(img, idx, axis, n, sign, rmax, out):
|
|
43
|
+
"""The change (``sign`` 1: the cell ``idx`` turns to phase 1; -1: to phase 0) of the
|
|
44
|
+
segments of phase 1 along ``axis``, the other cells as in ``img``, into ``out[r]``."""
|
|
45
|
+
left = 0
|
|
46
|
+
while left < n - 1 and _at(img, idx, axis, -(left + 1), n) == 1:
|
|
47
|
+
left += 1
|
|
48
|
+
right = 0
|
|
49
|
+
while right < n - 1 - left and _at(img, idx, axis, right + 1, n) == 1:
|
|
50
|
+
right += 1
|
|
51
|
+
whole = left + right == n - 1 # the other cells of the line are all of phase 1
|
|
52
|
+
for r in range(1, rmax + 1):
|
|
53
|
+
if whole: # a full line (n segments) against one run of n - 1 cells
|
|
54
|
+
change = n - max(n - 1 - r, 0)
|
|
55
|
+
else:
|
|
56
|
+
change = max(left + right + 1 - r, 0) - max(left - r, 0) - max(right - r, 0)
|
|
57
|
+
out[r] += sign * change
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@njit(cache=True)
|
|
61
|
+
def _change(img, p, q, sizes, n_axes, rmax, weight, cs, cl, target_s, target_l, total, ds, dl):
|
|
62
|
+
"""The energy change of swapping the cells ``p`` (phase 1) and ``q`` (phase 0), with
|
|
63
|
+
the changes of the counts in ``ds`` and ``dl``; on return ``p`` is of phase 0 and
|
|
64
|
+
``q`` still of phase 0."""
|
|
65
|
+
ds[:, :] = 0.0
|
|
66
|
+
dl[:, :] = 0.0
|
|
67
|
+
for a in range(n_axes):
|
|
68
|
+
_pairs(img, p, a, sizes[a], -1.0, rmax, ds[a])
|
|
69
|
+
if weight > 0.0:
|
|
70
|
+
_segments(img, p, a, sizes[a], -1.0, rmax, dl[a])
|
|
71
|
+
img[p[0], p[1], p[2]] = 0
|
|
72
|
+
for a in range(n_axes):
|
|
73
|
+
_pairs(img, q, a, sizes[a], 1.0, rmax, ds[a])
|
|
74
|
+
if weight > 0.0:
|
|
75
|
+
_segments(img, q, a, sizes[a], 1.0, rmax, dl[a])
|
|
76
|
+
change = 0.0
|
|
77
|
+
for a in range(n_axes):
|
|
78
|
+
for r in range(1, rmax + 1):
|
|
79
|
+
if ds[a, r] != 0.0:
|
|
80
|
+
old = cs[a, r] / total - target_s[a, r]
|
|
81
|
+
new = (cs[a, r] + ds[a, r]) / total - target_s[a, r]
|
|
82
|
+
change += new * new - old * old
|
|
83
|
+
if weight > 0.0 and dl[a, r] != 0.0:
|
|
84
|
+
old = cl[a, r] / total - target_l[a, r]
|
|
85
|
+
new = (cl[a, r] + dl[a, r]) / total - target_l[a, r]
|
|
86
|
+
change += weight * (new * new - old * old)
|
|
87
|
+
return change
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@njit(cache=True, inline="always")
|
|
91
|
+
def _unflat(c, ny, nz, out):
|
|
92
|
+
out[0] = c // (ny * nz)
|
|
93
|
+
out[1] = (c // nz) % ny
|
|
94
|
+
out[2] = c % nz
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@njit(cache=True)
|
|
98
|
+
def anneal(img, target_s, target_l, weight, n_axes, rmax, trials, cooling, stage, tolerance,
|
|
99
|
+
seed): # fmt: skip
|
|
100
|
+
"""Anneal the periodic phase image ``img`` (uint8, 0 and 1) in place towards the
|
|
101
|
+
targets (``target_s[a, r]``, ``target_l[a, r]``, r = 0..rmax, for the first ``n_axes``
|
|
102
|
+
axes; the lineal path with ``weight > 0`` only): at most ``trials`` swaps, the
|
|
103
|
+
temperature multiplied by ``cooling`` after every ``stage`` trials, from a temperature
|
|
104
|
+
at which half the swaps that raise the energy are accepted (the mean of their
|
|
105
|
+
changes over 2000 trials, divided by ln 2); stops once the energy is below
|
|
106
|
+
``tolerance``, or once ten stages (a sweep) pass without an accepted swap. Returns
|
|
107
|
+
the initial and final energies, the number of trials and of accepted swaps."""
|
|
108
|
+
np.random.seed(seed) # noqa: NPY002 (the generator of Numba)
|
|
109
|
+
nx, ny, nz = img.shape
|
|
110
|
+
sizes = np.array([nx, ny, nz], dtype=np.int64)
|
|
111
|
+
total = nx * ny * nz
|
|
112
|
+
ones = np.empty(total, dtype=np.int64)
|
|
113
|
+
zeros = np.empty(total, dtype=np.int64)
|
|
114
|
+
n1, n0 = 0, 0
|
|
115
|
+
for i in range(nx):
|
|
116
|
+
for j in range(ny):
|
|
117
|
+
for k in range(nz):
|
|
118
|
+
if img[i, j, k] == 1:
|
|
119
|
+
ones[n1] = (i * ny + j) * nz + k
|
|
120
|
+
n1 += 1
|
|
121
|
+
else:
|
|
122
|
+
zeros[n0] = (i * ny + j) * nz + k
|
|
123
|
+
n0 += 1
|
|
124
|
+
cs = np.zeros((3, rmax + 1))
|
|
125
|
+
cl = np.zeros((3, rmax + 1))
|
|
126
|
+
if n1 == 0 or n0 == 0:
|
|
127
|
+
return 0.0, 0.0, 0, 0
|
|
128
|
+
idx = np.empty(3, dtype=np.int64)
|
|
129
|
+
for a in range(n_axes): # the pairs and the segments along the axes
|
|
130
|
+
n = sizes[a]
|
|
131
|
+
for f in range(n1):
|
|
132
|
+
_unflat(ones[f], ny, nz, idx)
|
|
133
|
+
run = 1
|
|
134
|
+
for r in range(rmax + 1):
|
|
135
|
+
cs[a, r] += _at(img, idx, a, r, n)
|
|
136
|
+
if weight > 0.0 and run == 1:
|
|
137
|
+
if r > 0 and _at(img, idx, a, r, n) == 0:
|
|
138
|
+
run = 0
|
|
139
|
+
else:
|
|
140
|
+
cl[a, r] += 1
|
|
141
|
+
energy = 0.0
|
|
142
|
+
for a in range(n_axes):
|
|
143
|
+
for r in range(1, rmax + 1):
|
|
144
|
+
energy += (cs[a, r] / total - target_s[a, r]) ** 2
|
|
145
|
+
if weight > 0.0:
|
|
146
|
+
energy += weight * (cl[a, r] / total - target_l[a, r]) ** 2
|
|
147
|
+
initial = energy
|
|
148
|
+
ds = np.zeros((3, rmax + 1))
|
|
149
|
+
dl = np.zeros((3, rmax + 1))
|
|
150
|
+
p = np.empty(3, dtype=np.int64)
|
|
151
|
+
q = np.empty(3, dtype=np.int64)
|
|
152
|
+
up, n_up = 0.0, 0
|
|
153
|
+
for _ in range(2000): # the scale of the energy changes
|
|
154
|
+
_unflat(ones[np.random.randint(n1)], ny, nz, p) # noqa: NPY002
|
|
155
|
+
_unflat(zeros[np.random.randint(n0)], ny, nz, q) # noqa: NPY002
|
|
156
|
+
change = _change(img, p, q, sizes, n_axes, rmax, weight, cs, cl, target_s, target_l,
|
|
157
|
+
total, ds, dl) # fmt: skip
|
|
158
|
+
img[p[0], p[1], p[2]] = 1
|
|
159
|
+
if change > 0.0:
|
|
160
|
+
up += change
|
|
161
|
+
n_up += 1
|
|
162
|
+
temperature = up / n_up / math.log(2.0) if n_up else 1e-300
|
|
163
|
+
accepted, done = 0, 0
|
|
164
|
+
quiet, before = 0, 0 # stages without an accepted swap
|
|
165
|
+
while done < trials and energy > tolerance:
|
|
166
|
+
done += 1
|
|
167
|
+
a1 = np.random.randint(n1) # noqa: NPY002
|
|
168
|
+
a0 = np.random.randint(n0) # noqa: NPY002
|
|
169
|
+
_unflat(ones[a1], ny, nz, p)
|
|
170
|
+
_unflat(zeros[a0], ny, nz, q)
|
|
171
|
+
change = _change(img, p, q, sizes, n_axes, rmax, weight, cs, cl, target_s, target_l,
|
|
172
|
+
total, ds, dl) # fmt: skip
|
|
173
|
+
draw = np.random.random() # noqa: NPY002
|
|
174
|
+
accept = change <= 0.0 or draw < math.exp(-change / temperature)
|
|
175
|
+
if accept:
|
|
176
|
+
img[q[0], q[1], q[2]] = 1
|
|
177
|
+
ones[a1], zeros[a0] = zeros[a0], ones[a1]
|
|
178
|
+
for a in range(n_axes):
|
|
179
|
+
for r in range(1, rmax + 1):
|
|
180
|
+
cs[a, r] += ds[a, r]
|
|
181
|
+
cl[a, r] += dl[a, r]
|
|
182
|
+
energy += change
|
|
183
|
+
accepted += 1
|
|
184
|
+
else:
|
|
185
|
+
img[p[0], p[1], p[2]] = 1
|
|
186
|
+
if done % stage == 0:
|
|
187
|
+
temperature *= cooling
|
|
188
|
+
quiet = quiet + 1 if accepted == before else 0
|
|
189
|
+
before = accepted
|
|
190
|
+
if quiet >= 10: # frozen: a sweep without an accepted swap
|
|
191
|
+
break
|
|
192
|
+
return initial, energy, done, accepted
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Implicit functions of unions of convex cells: the cells of a tiling that have a phase,
|
|
2
|
+
each given by the planes of its faces."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
from numba import njit, prange
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@njit(parallel=True, cache=True)
|
|
11
|
+
def cells_implicit(
|
|
12
|
+
points,
|
|
13
|
+
cell,
|
|
14
|
+
indptr,
|
|
15
|
+
indices,
|
|
16
|
+
centres,
|
|
17
|
+
kind,
|
|
18
|
+
planes,
|
|
19
|
+
counts,
|
|
20
|
+
inside,
|
|
21
|
+
lengths,
|
|
22
|
+
dims,
|
|
23
|
+
band,
|
|
24
|
+
out,
|
|
25
|
+
):
|
|
26
|
+
"""The implicit function of the union of the cells that are ``inside`` at ``points``
|
|
27
|
+
(n, 3), each in the cell ``cell`` of a tiling whose cells around each (``indptr``,
|
|
28
|
+
``indices``: those sharing a vertex with it) are convex: ``planes[kind[c]]`` holds
|
|
29
|
+
``counts[kind[c]]`` planes ``(n, h)`` of the faces of the cell ``c`` from its centre
|
|
30
|
+
(``n . x <= h`` inside; ``dims``: the coordinates that count, 2 for the prisms through
|
|
31
|
+
a plate). The gauge of a cell at a point is its largest distance to these planes,
|
|
32
|
+
negative inside the cell; the function is the smallest gauge of the cells inside
|
|
33
|
+
minus the smallest of the others, among the cell of the point and those around it:
|
|
34
|
+
it vanishes on the faces between a cell inside and a cell outside, near which half of
|
|
35
|
+
it is the distance to the face; that half is returned, clipped to ``band``.
|
|
36
|
+
``lengths``: the periods of a
|
|
37
|
+
periodic tiling along the axes (0: not periodic), for the nearest image of the
|
|
38
|
+
cells."""
|
|
39
|
+
for p in prange(points.shape[0]):
|
|
40
|
+
c0 = cell[p]
|
|
41
|
+
g_in = band
|
|
42
|
+
g_out = band
|
|
43
|
+
for q in range(indptr[c0] - 1, indptr[c0 + 1]):
|
|
44
|
+
c = c0 if q < indptr[c0] else indices[q]
|
|
45
|
+
rel = np.empty(3)
|
|
46
|
+
for a in range(3):
|
|
47
|
+
d = points[p, a] - centres[c, a]
|
|
48
|
+
if lengths[a] > 0.0:
|
|
49
|
+
d -= lengths[a] * np.floor(d / lengths[a] + 0.5)
|
|
50
|
+
rel[a] = d
|
|
51
|
+
t = kind[c]
|
|
52
|
+
g = -np.inf
|
|
53
|
+
for f in range(counts[t]):
|
|
54
|
+
v = -planes[t, f, 3]
|
|
55
|
+
for a in range(dims):
|
|
56
|
+
v += planes[t, f, a] * rel[a]
|
|
57
|
+
if v > g:
|
|
58
|
+
g = v
|
|
59
|
+
if inside[c]:
|
|
60
|
+
if g < g_in:
|
|
61
|
+
g_in = g
|
|
62
|
+
elif g < g_out:
|
|
63
|
+
g_out = g
|
|
64
|
+
value = 0.5 * (g_in - g_out)
|
|
65
|
+
if value > band:
|
|
66
|
+
value = band
|
|
67
|
+
elif value < -band:
|
|
68
|
+
value = -band
|
|
69
|
+
out[p] = value
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Stealthy hyperuniform point patterns by the collective-coordinate method (Uche,
|
|
2
|
+
Stillinger & Torquato 2004; Batten, Stillinger & Torquato 2008).
|
|
3
|
+
|
|
4
|
+
``n`` points in a periodic box are moved, from uniform random positions, to a ground
|
|
5
|
+
state of the energy ``Φ = Σ_{k ∈ Q} |ρ(k)|^2``, ``ρ(k) = Σ_j e^{i k·x_j}`` the collective
|
|
6
|
+
coordinates on the wave vectors ``k = 2π m / L`` of the box (``m`` integer) with ``0 < |k|
|
|
7
|
+
<= K``, one of each pair ``±k`` (``ρ(-k)`` is the conjugate of ``ρ(k)``). At ``Φ = 0`` the
|
|
8
|
+
structure factor ``S(k) = |ρ(k)|^2 / n`` vanishes on the ball of radius ``K``: the pattern
|
|
9
|
+
is stealthy (it scatters no wave of those wave vectors) and hyperuniform. The ratio of
|
|
10
|
+
the constrained wave vectors to the degrees of freedom, ``χ = M / (3 (n - 1))``, sets the
|
|
11
|
+
order: ground states are disordered below ``χ = 1/2`` and crystallize beyond. ``Φ`` and
|
|
12
|
+
its gradient ``∂Φ/∂x_j = 2 Σ_k k (Im ρ(k) cos(k·x_j) - Re ρ(k) sin(k·x_j))`` are
|
|
13
|
+
minimized by L-BFGS.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import math
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
from scipy.optimize import minimize
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def stealthy_wave_vectors(n: int, box, chi: float) -> np.ndarray:
|
|
25
|
+
"""The wave vectors ``k`` (rows) of the half space whose number is the largest up to
|
|
26
|
+
``χ · 3 (n - 1)`` over the complete shells of ``|k|``."""
|
|
27
|
+
box = np.asarray(box, dtype=float)
|
|
28
|
+
target = chi * 3.0 * (n - 1)
|
|
29
|
+
k0 = 2.0 * math.pi / box
|
|
30
|
+
# enough integer vectors: a ball holding twice the target in its half
|
|
31
|
+
radius = (3.0 * 2.0 * target / (2.0 * math.pi) * np.prod(k0)) ** (1.0 / 3.0) + k0.max()
|
|
32
|
+
span = np.ceil(radius / k0).astype(int)
|
|
33
|
+
m = np.stack(np.meshgrid(*[np.arange(-s, s + 1) for s in span], indexing="ij"), -1)
|
|
34
|
+
m = m.reshape(-1, 3)
|
|
35
|
+
half = (
|
|
36
|
+
(m[:, 0] > 0)
|
|
37
|
+
| ((m[:, 0] == 0) & (m[:, 1] > 0))
|
|
38
|
+
| ((m[:, 0] == 0) & (m[:, 1] == 0) & (m[:, 2] > 0))
|
|
39
|
+
)
|
|
40
|
+
k = m[half] * k0
|
|
41
|
+
size = np.linalg.norm(k, axis=1)
|
|
42
|
+
order = np.argsort(size, kind="stable")
|
|
43
|
+
k, size = k[order], size[order]
|
|
44
|
+
shells = np.flatnonzero(np.diff(np.round(size, 9)) > 0) + 1 # ends of complete shells
|
|
45
|
+
ends = np.concatenate([shells, [len(size)]])
|
|
46
|
+
keep = ends[ends <= target]
|
|
47
|
+
if not len(keep):
|
|
48
|
+
raise ValueError(f"stealthy: no complete shell of wave vectors for chi = {chi} and {n} "
|
|
49
|
+
"points (raise chi or the number of points)") # fmt: skip
|
|
50
|
+
return k[: int(keep[-1])]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _energy(x, k):
|
|
54
|
+
"""``Φ`` and its gradient for the positions ``x`` (flattened) and wave vectors ``k``."""
|
|
55
|
+
phase = x.reshape(-1, 3) @ k.T
|
|
56
|
+
c, s = np.cos(phase), np.sin(phase)
|
|
57
|
+
re, im = c.sum(axis=0), s.sum(axis=0)
|
|
58
|
+
grad = 2.0 * ((c * im - s * re) @ k)
|
|
59
|
+
return float(np.sum(re * re + im * im)), grad.ravel()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def stealthy_points(n: int, box, chi: float, rng, *, tries: int = 3, tolerance: float = 1e-10):
|
|
63
|
+
"""``n`` points of a stealthy hyperuniform ground state in the periodic box of edges
|
|
64
|
+
``box`` (see the module), their ``S(k)`` below ``tolerance`` on the constrained wave
|
|
65
|
+
vectors; returns the points (in ``[0, box)``), the wave vectors and the ``χ`` reached.
|
|
66
|
+
Raises ``RuntimeError`` when ``tries`` runs from random positions miss it."""
|
|
67
|
+
if not 0.0 < chi < 0.5:
|
|
68
|
+
raise ValueError("stealthy: chi in (0, 0.5), the disordered ground states")
|
|
69
|
+
box = np.asarray(box, dtype=float)
|
|
70
|
+
k = stealthy_wave_vectors(n, box, chi)
|
|
71
|
+
worst = math.inf
|
|
72
|
+
for _ in range(tries):
|
|
73
|
+
x0 = rng.random((n, 3)) * box
|
|
74
|
+
options = {"maxiter": 20_000, "maxcor": 30, "ftol": 0.0, "gtol": 0.0}
|
|
75
|
+
res = minimize(_energy, x0.ravel(), args=(k,), jac=True, method="L-BFGS-B",
|
|
76
|
+
options=options) # fmt: skip
|
|
77
|
+
energy, _ = _energy(res.x, k)
|
|
78
|
+
worst = min(worst, energy / n)
|
|
79
|
+
if energy / n <= tolerance * len(k):
|
|
80
|
+
pts = np.mod(res.x.reshape(n, 3), box)
|
|
81
|
+
pts[pts >= box] = 0.0
|
|
82
|
+
phase = pts @ k.T
|
|
83
|
+
s = (np.cos(phase).sum(0) ** 2 + np.sin(phase).sum(0) ** 2) / n
|
|
84
|
+
if s.max() <= tolerance:
|
|
85
|
+
return pts, k, len(k) / (3.0 * (n - 1))
|
|
86
|
+
raise RuntimeError(f"stealthy: the ground state was not reached (S(k) up to {worst:.2e}); "
|
|
87
|
+
"lower chi, or raise the number of points") # fmt: skip
|