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.
Files changed (381) hide show
  1. morphogen/__init__.py +60 -0
  2. morphogen/__main__.py +7 -0
  3. morphogen/_platform.py +55 -0
  4. morphogen/_public.py +153 -0
  5. morphogen/_utils.py +80 -0
  6. morphogen/_version.py +1 -0
  7. morphogen/analysis/__init__.py +174 -0
  8. morphogen/analysis/anisotropy.py +135 -0
  9. morphogen/analysis/basic.py +38 -0
  10. morphogen/analysis/cells.py +54 -0
  11. morphogen/analysis/connectivity.py +156 -0
  12. morphogen/analysis/correlation.py +195 -0
  13. morphogen/analysis/covariance.py +80 -0
  14. morphogen/analysis/fractal.py +54 -0
  15. morphogen/analysis/measures.py +188 -0
  16. morphogen/analysis/morphology.py +265 -0
  17. morphogen/analysis/particles.py +160 -0
  18. morphogen/analysis/percolation.py +2034 -0
  19. morphogen/analysis/power_laws.py +143 -0
  20. morphogen/analysis/random_sets.py +351 -0
  21. morphogen/analysis/stereology.py +289 -0
  22. morphogen/analysis/surface.py +107 -0
  23. morphogen/analysis/topology.py +92 -0
  24. morphogen/automata/__init__.py +74 -0
  25. morphogen/automata/engine.py +211 -0
  26. morphogen/automata/growth.py +686 -0
  27. morphogen/automata/lattice.py +143 -0
  28. morphogen/automata/reaction.py +255 -0
  29. morphogen/automata/rules.py +353 -0
  30. morphogen/automata/tilings.py +1715 -0
  31. morphogen/cli.py +3526 -0
  32. morphogen/config.py +2167 -0
  33. morphogen/contact/__init__.py +113 -0
  34. morphogen/contact/experiments.py +368 -0
  35. morphogen/contact/hertz.py +104 -0
  36. morphogen/contact/kernels.py +827 -0
  37. morphogen/contact/periodic.py +278 -0
  38. morphogen/contact/problem.py +578 -0
  39. morphogen/contact/surfaces.py +310 -0
  40. morphogen/coupling/__init__.py +43 -0
  41. morphogen/coupling/ageing.py +143 -0
  42. morphogen/coupling/diffusion.py +226 -0
  43. morphogen/coupling/fenicsx.py +484 -0
  44. morphogen/coupling/oxidation.py +447 -0
  45. morphogen/coupling/plates.py +247 -0
  46. morphogen/design/__init__.py +51 -0
  47. morphogen/design/csp.py +616 -0
  48. morphogen/design/frames.py +277 -0
  49. morphogen/design/search.py +287 -0
  50. morphogen/design/tiles.py +336 -0
  51. morphogen/distributions.py +312 -0
  52. morphogen/domain.py +203 -0
  53. morphogen/dynamics/__init__.py +179 -0
  54. morphogen/dynamics/model.py +638 -0
  55. morphogen/dynamics/openradioss.py +643 -0
  56. morphogen/dynamics/results.py +515 -0
  57. morphogen/fracture/__init__.py +170 -0
  58. morphogen/fracture/bulk.py +349 -0
  59. morphogen/fracture/cohesive.py +1614 -0
  60. morphogen/fracture/ductile.py +557 -0
  61. morphogen/fracture/lefm.py +1168 -0
  62. morphogen/fracture/mixed.py +1178 -0
  63. morphogen/fracture/periodic.py +733 -0
  64. morphogen/fracture/phasefield.py +714 -0
  65. morphogen/fracture/phasefield_finite.py +368 -0
  66. morphogen/fracture/surface.py +572 -0
  67. morphogen/fracture/toughness.py +566 -0
  68. morphogen/gpu.py +108 -0
  69. morphogen/gui/__init__.py +8 -0
  70. morphogen/gui/api.py +1927 -0
  71. morphogen/gui/desktop.py +387 -0
  72. morphogen/gui/icon.png +0 -0
  73. morphogen/gui/index.html +1909 -0
  74. morphogen/gui/server.py +229 -0
  75. morphogen/gui/tools/__init__.py +629 -0
  76. morphogen/gui/tools/compare.py +149 -0
  77. morphogen/gui/tools/contact.py +391 -0
  78. morphogen/gui/tools/couplings.py +1085 -0
  79. morphogen/gui/tools/crackfront.py +245 -0
  80. morphogen/gui/tools/design.py +224 -0
  81. morphogen/gui/tools/dynamics.py +824 -0
  82. morphogen/gui/tools/fracture.py +2586 -0
  83. morphogen/gui/tools/interop.py +1654 -0
  84. morphogen/gui/tools/learning.py +595 -0
  85. morphogen/gui/tools/mechanics.py +3881 -0
  86. morphogen/gui/tools/nonlocal_damage.py +1321 -0
  87. morphogen/gui/tools/phasefield.py +215 -0
  88. morphogen/gui/tools/physics.py +597 -0
  89. morphogen/gui/tools/stability.py +1756 -0
  90. morphogen/gui/tools/statistics.py +1408 -0
  91. morphogen/gui/viewer.js +1100 -0
  92. morphogen/homogenization/__init__.py +210 -0
  93. morphogen/homogenization/acoustics.py +566 -0
  94. morphogen/homogenization/amg.py +1005 -0
  95. morphogen/homogenization/apparent.py +1046 -0
  96. morphogen/homogenization/behaviours.cu +2285 -0
  97. morphogen/homogenization/behaviours.py +944 -0
  98. morphogen/homogenization/beremin.py +263 -0
  99. morphogen/homogenization/bifurcation.py +1085 -0
  100. morphogen/homogenization/bloch.py +507 -0
  101. morphogen/homogenization/bounds.py +226 -0
  102. morphogen/homogenization/core.py +458 -0
  103. morphogen/homogenization/coupled.py +1135 -0
  104. morphogen/homogenization/crystal.py +2967 -0
  105. morphogen/homogenization/dilatation.py +454 -0
  106. morphogen/homogenization/elements.py +157 -0
  107. morphogen/homogenization/fatigue.py +768 -0
  108. morphogen/homogenization/fe.py +1739 -0
  109. morphogen/homogenization/fenicsx.py +307 -0
  110. morphogen/homogenization/fft.py +499 -0
  111. morphogen/homogenization/fft_nonlinear.py +391 -0
  112. morphogen/homogenization/finite.py +613 -0
  113. morphogen/homogenization/flow.py +361 -0
  114. morphogen/homogenization/frames.py +1125 -0
  115. morphogen/homogenization/gpu.py +1241 -0
  116. morphogen/homogenization/harmonic.py +427 -0
  117. morphogen/homogenization/identification.py +579 -0
  118. morphogen/homogenization/kernels.py +760 -0
  119. morphogen/homogenization/laws.py +2061 -0
  120. morphogen/homogenization/materials.py +1080 -0
  121. morphogen/homogenization/mfront.py +589 -0
  122. morphogen/homogenization/networks.py +880 -0
  123. morphogen/homogenization/nonlinear.py +2612 -0
  124. morphogen/homogenization/ntfa.py +577 -0
  125. morphogen/homogenization/paths.py +476 -0
  126. morphogen/homogenization/photonic.py +467 -0
  127. morphogen/homogenization/poroelastic.py +212 -0
  128. morphogen/homogenization/porous.py +1120 -0
  129. morphogen/homogenization/postprocess.py +290 -0
  130. morphogen/homogenization/solvers.py +1140 -0
  131. morphogen/homogenization/tensors.py +240 -0
  132. morphogen/homogenization/voxel_fe.py +457 -0
  133. morphogen/homogenization/xfem.py +1016 -0
  134. morphogen/homogenization/zmat.py +1258 -0
  135. morphogen/iga/__init__.py +48 -0
  136. morphogen/iga/analysis.py +508 -0
  137. morphogen/iga/basis.py +214 -0
  138. morphogen/iga/geometry.py +501 -0
  139. morphogen/iga/homogenization.py +219 -0
  140. morphogen/iga/optimization.py +700 -0
  141. morphogen/iga/shapes.py +331 -0
  142. morphogen/image.py +128 -0
  143. morphogen/io/__init__.py +246 -0
  144. morphogen/io/amitex.py +741 -0
  145. morphogen/io/ebsd.py +881 -0
  146. morphogen/io/export.py +196 -0
  147. morphogen/io/geometry.py +158 -0
  148. morphogen/io/medit.py +147 -0
  149. morphogen/io/meshes.py +844 -0
  150. morphogen/io/metaimage.py +97 -0
  151. morphogen/io/mfront.py +1104 -0
  152. morphogen/io/native.py +57 -0
  153. morphogen/io/radioss.py +764 -0
  154. morphogen/io/solvers.py +371 -0
  155. morphogen/io/tables.py +278 -0
  156. morphogen/io/tiff.py +66 -0
  157. morphogen/io/vtk.py +701 -0
  158. morphogen/io/xdmf.py +200 -0
  159. morphogen/kernels/__init__.py +5 -0
  160. morphogen/kernels/annealing.py +192 -0
  161. morphogen/kernels/cells.py +69 -0
  162. morphogen/kernels/collective.py +87 -0
  163. morphogen/kernels/force_biased.py +595 -0
  164. morphogen/kernels/implicit.py +145 -0
  165. morphogen/kernels/leaves.py +132 -0
  166. morphogen/kernels/packing.py +304 -0
  167. morphogen/kernels/raster.py +279 -0
  168. morphogen/kernels/rsa.py +371 -0
  169. morphogen/kernels/union.py +135 -0
  170. morphogen/kernels/watershed.py +190 -0
  171. morphogen/laser/__init__.py +234 -0
  172. morphogen/laser/architectures.py +375 -0
  173. morphogen/laser/bending.py +216 -0
  174. morphogen/laser/cells.py +1694 -0
  175. morphogen/laser/design.py +940 -0
  176. morphogen/laser/figures.py +227 -0
  177. morphogen/laser/heat.py +804 -0
  178. morphogen/laser/materials.py +691 -0
  179. morphogen/laser/mechanics.py +1670 -0
  180. morphogen/laser/metallurgy.py +615 -0
  181. morphogen/laser/patterns.py +828 -0
  182. morphogen/laser/periodic.py +392 -0
  183. morphogen/laser/process.py +362 -0
  184. morphogen/laser/run.py +534 -0
  185. morphogen/laser/solid.py +216 -0
  186. morphogen/laser/specimen.py +200 -0
  187. morphogen/laser/structures.py +708 -0
  188. morphogen/learning/__init__.py +81 -0
  189. morphogen/learning/behaviour.py +398 -0
  190. morphogen/learning/data.py +328 -0
  191. morphogen/learning/learned.cpp +668 -0
  192. morphogen/learning/logarithmic.py +202 -0
  193. morphogen/learning/mfront.py +409 -0
  194. morphogen/learning/networks.py +767 -0
  195. morphogen/learning/run.py +212 -0
  196. morphogen/learning/standard.py +814 -0
  197. morphogen/learning/training.py +235 -0
  198. morphogen/mesh/__init__.py +29 -0
  199. morphogen/mesh/conforming.py +1423 -0
  200. morphogen/mesh/curved.py +600 -0
  201. morphogen/mesh/exact.py +1717 -0
  202. morphogen/mesh/octree.py +350 -0
  203. morphogen/mesh/polycrystal.py +1041 -0
  204. morphogen/mesh/polyhedra.py +677 -0
  205. morphogen/mesh/regularize.py +570 -0
  206. morphogen/mesh/surface.py +97 -0
  207. morphogen/mesh/tetra.py +512 -0
  208. morphogen/mesh/voxel.py +124 -0
  209. morphogen/micromorphic/__init__.py +31 -0
  210. morphogen/micromorphic/damage.py +359 -0
  211. morphogen/micromorphic/ductile.py +534 -0
  212. morphogen/micromorphic/finite.py +220 -0
  213. morphogen/micromorphic/microfoam.py +787 -0
  214. morphogen/micromorphic/space.py +341 -0
  215. morphogen/models/__init__.py +195 -0
  216. morphogen/models/affine.py +384 -0
  217. morphogen/models/automata.py +592 -0
  218. morphogen/models/base.py +500 -0
  219. morphogen/models/boolean.py +310 -0
  220. morphogen/models/bouligand.py +331 -0
  221. morphogen/models/branching.py +241 -0
  222. morphogen/models/combination.py +430 -0
  223. morphogen/models/deadleaves.py +766 -0
  224. morphogen/models/design.py +289 -0
  225. morphogen/models/ebsd.py +206 -0
  226. morphogen/models/fibers.py +1476 -0
  227. morphogen/models/foam.py +594 -0
  228. morphogen/models/gaussian.py +314 -0
  229. morphogen/models/growth.py +459 -0
  230. morphogen/models/hardcore.py +317 -0
  231. morphogen/models/hierarchical.py +269 -0
  232. morphogen/models/honeycomb.py +749 -0
  233. morphogen/models/implicit.py +177 -0
  234. morphogen/models/laminate.py +470 -0
  235. morphogen/models/lattice.py +351 -0
  236. morphogen/models/lattice_field.py +345 -0
  237. morphogen/models/levelset_foam.py +563 -0
  238. morphogen/models/nacre.py +411 -0
  239. morphogen/models/nested.py +924 -0
  240. morphogen/models/osteons.py +374 -0
  241. morphogen/models/pieces.py +167 -0
  242. morphogen/models/planar.py +126 -0
  243. morphogen/models/reconstruction.py +203 -0
  244. morphogen/models/scale_rich.py +1409 -0
  245. morphogen/models/scale_rich_3d.py +1616 -0
  246. morphogen/models/tessellation.py +735 -0
  247. morphogen/models/tiling_field.py +302 -0
  248. morphogen/models/tpms.py +197 -0
  249. morphogen/models/transparent.py +406 -0
  250. morphogen/models/union.py +141 -0
  251. morphogen/optimization/__init__.py +43 -0
  252. morphogen/optimization/cell.py +295 -0
  253. morphogen/optimization/filters.py +115 -0
  254. morphogen/optimization/mma.py +226 -0
  255. morphogen/optimization/run.py +219 -0
  256. morphogen/optimization/topology.py +632 -0
  257. morphogen/orientations.py +568 -0
  258. morphogen/parallel.py +599 -0
  259. morphogen/pipeline.py +978 -0
  260. morphogen/primitives.py +188 -0
  261. morphogen/results.py +564 -0
  262. morphogen/rve/__init__.py +73 -0
  263. morphogen/rve/report.py +627 -0
  264. morphogen/rve/scaling.py +363 -0
  265. morphogen/rve/study.py +1054 -0
  266. morphogen/rve/windows.py +345 -0
  267. morphogen/seeding.py +51 -0
  268. morphogen/settings.py +118 -0
  269. morphogen/stopping.py +48 -0
  270. morphogen/symmetry.py +384 -0
  271. morphogen/templates/activator_inhibitor.yaml +22 -0
  272. morphogen/templates/aggregation.yaml +23 -0
  273. morphogen/templates/boolean_cylinders.yaml +20 -0
  274. morphogen/templates/boolean_spheres.yaml +22 -0
  275. morphogen/templates/bouligand.yaml +28 -0
  276. morphogen/templates/cellular_automaton.yaml +25 -0
  277. morphogen/templates/coated_spheres.yaml +26 -0
  278. morphogen/templates/contact_fibers.yaml +27 -0
  279. morphogen/templates/cox_nanocomposite.yaml +22 -0
  280. morphogen/templates/cross_linked_fibers.yaml +26 -0
  281. morphogen/templates/curved_arcs.yaml +28 -0
  282. morphogen/templates/curved_fibers.yaml +24 -0
  283. morphogen/templates/dead_leaves.yaml +22 -0
  284. morphogen/templates/delaunay_network.yaml +22 -0
  285. morphogen/templates/dense_packing.yaml +22 -0
  286. morphogen/templates/diffusion.yaml +33 -0
  287. morphogen/templates/ebsd.yaml +34 -0
  288. morphogen/templates/ebsd_map.ctf +3087 -0
  289. morphogen/templates/fracture_composite.yaml +42 -0
  290. morphogen/templates/fracture_rubber.yaml +47 -0
  291. morphogen/templates/gaussian_excursion.yaml +17 -0
  292. morphogen/templates/graded_lattice.yaml +24 -0
  293. morphogen/templates/hardcore_fibers.yaml +22 -0
  294. morphogen/templates/hardcore_spheres.yaml +22 -0
  295. morphogen/templates/hierarchical_lattice.yaml +22 -0
  296. morphogen/templates/homogenization_acoustic_foam.yaml +36 -0
  297. morphogen/templates/homogenization_beremin.yaml +50 -0
  298. morphogen/templates/homogenization_cleavage.yaml +51 -0
  299. morphogen/templates/homogenization_cleavage_band.yaml +55 -0
  300. morphogen/templates/homogenization_contact.yaml +43 -0
  301. morphogen/templates/homogenization_crack_closure.yaml +49 -0
  302. morphogen/templates/homogenization_crystal_plasticity.yaml +50 -0
  303. morphogen/templates/homogenization_crystal_plasticity_fft.yaml +52 -0
  304. morphogen/templates/homogenization_crystallization.yaml +30 -0
  305. morphogen/templates/homogenization_debonding.yaml +43 -0
  306. morphogen/templates/homogenization_detwinning.yaml +58 -0
  307. morphogen/templates/homogenization_ductile_damage.yaml +47 -0
  308. morphogen/templates/homogenization_fatigue.yaml +40 -0
  309. morphogen/templates/homogenization_grain_fracture.yaml +56 -0
  310. morphogen/templates/homogenization_gyroid.yaml +30 -0
  311. morphogen/templates/homogenization_intergranular.yaml +43 -0
  312. morphogen/templates/homogenization_interphase.yaml +42 -0
  313. morphogen/templates/homogenization_mixed_loading.yaml +33 -0
  314. morphogen/templates/homogenization_ntfa.yaml +56 -0
  315. morphogen/templates/homogenization_piezoelectric.yaml +27 -0
  316. morphogen/templates/homogenization_polycrystal.yaml +30 -0
  317. morphogen/templates/homogenization_polycrystal_inclusions.yaml +30 -0
  318. morphogen/templates/homogenization_poroelastic.yaml +26 -0
  319. morphogen/templates/homogenization_rubber.yaml +40 -0
  320. morphogen/templates/homogenization_slip_cleavage.yaml +50 -0
  321. morphogen/templates/homogenization_spheres.yaml +31 -0
  322. morphogen/templates/homogenization_transport.yaml +29 -0
  323. morphogen/templates/homogenization_twinning.yaml +54 -0
  324. morphogen/templates/homogenization_viscoelastic.yaml +34 -0
  325. morphogen/templates/homogenization_viscoplastic.yaml +42 -0
  326. morphogen/templates/homogenization_voronoi.yaml +26 -0
  327. morphogen/templates/homogenization_xfem.yaml +23 -0
  328. morphogen/templates/hyperuniform_cells.yaml +24 -0
  329. morphogen/templates/laguerre.yaml +18 -0
  330. morphogen/templates/laser_bending.yaml +35 -0
  331. morphogen/templates/laser_cells.yaml +38 -0
  332. morphogen/templates/laser_corrugated.yaml +36 -0
  333. morphogen/templates/level_set_foam.yaml +29 -0
  334. morphogen/templates/menger_sponge.yaml +17 -0
  335. morphogen/templates/nacre.yaml +25 -0
  336. morphogen/templates/nucleation_growth.yaml +25 -0
  337. morphogen/templates/optimize_auxetic.yaml +29 -0
  338. morphogen/templates/optimize_auxetic_3d.yaml +27 -0
  339. morphogen/templates/optimize_bulk.yaml +23 -0
  340. morphogen/templates/optimize_conductivity.yaml +20 -0
  341. morphogen/templates/osteons.yaml +28 -0
  342. morphogen/templates/penetrable_spheres.yaml +21 -0
  343. morphogen/templates/poisson_fibers.yaml +21 -0
  344. morphogen/templates/random_laminate.yaml +26 -0
  345. morphogen/templates/random_lattice.yaml +27 -0
  346. morphogen/templates/random_walk_fibers.yaml +26 -0
  347. morphogen/templates/reaction_diffusion.yaml +22 -0
  348. morphogen/templates/reconstruction.yaml +22 -0
  349. morphogen/templates/rve_cellular_automaton.yaml +23 -0
  350. morphogen/templates/rve_crystal_plasticity_fft.yaml +51 -0
  351. morphogen/templates/rve_multiphysics.yaml +43 -0
  352. morphogen/templates/rve_poisson_fibers.yaml +22 -0
  353. morphogen/templates/rve_poisson_fibers_fe.yaml +33 -0
  354. morphogen/templates/rve_voronoi_windows.yaml +20 -0
  355. morphogen/templates/scale_rich_network.yaml +29 -0
  356. morphogen/templates/scale_rich_plates.yaml +30 -0
  357. morphogen/templates/sequential_dead_leaves.yaml +25 -0
  358. morphogen/templates/strut_lattice.yaml +21 -0
  359. morphogen/templates/tile_assembly.yaml +28 -0
  360. morphogen/templates/tpms.yaml +19 -0
  361. morphogen/templates/trabecular_bone.yaml +29 -0
  362. morphogen/templates/transparent_dead_leaves.yaml +23 -0
  363. morphogen/templates/vascular_tree.yaml +23 -0
  364. morphogen/templates/voronoi.yaml +20 -0
  365. morphogen/templates/wood.yaml +34 -0
  366. morphogen/templates/workflow.yaml +56 -0
  367. morphogen/texture.py +665 -0
  368. morphogen/theory.py +162 -0
  369. morphogen/viz/__init__.py +12 -0
  370. morphogen/viz/export.py +244 -0
  371. morphogen/viz/figures.py +707 -0
  372. morphogen/viz/png.py +148 -0
  373. morphogen/viz/sections.py +696 -0
  374. morphogen/viz/surfaces.py +1352 -0
  375. morphogen/viz/video.py +904 -0
  376. morphogen/viz/workflow.py +488 -0
  377. morphogen-1.0.0.dist-info/METADATA +2316 -0
  378. morphogen-1.0.0.dist-info/RECORD +381 -0
  379. morphogen-1.0.0.dist-info/WHEEL +4 -0
  380. morphogen-1.0.0.dist-info/entry_points.txt +5 -0
  381. 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,5 @@
1
+ """Compiled (Numba) kernels.
2
+
3
+ Kernels take and return plain NumPy arrays so that they can be replaced by other
4
+ implementations (GPU, Rust...) without changing the rest of the package.
5
+ """
@@ -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