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
@@ -0,0 +1,345 @@
1
+ """The window method for tensors: the stiffness and the conductivity of the windows of one
2
+ large periodic realization.
3
+
4
+ The realization is solved once per unit macroscopic load by the FFT solver
5
+ (:mod:`morphogen.homogenization.fft`): the six unit strains ``E^(k)`` (Voigt order 11 22 33
6
+ 23 31 12, engineering shears); the three in-plane ones ``E_11, E_22, E_12`` of a planar
7
+ image (``nz = 1``: the plane stiffness, Voigt order 11 22 12); the three unit gradients of
8
+ the conductivity. The tensor of a window ``w`` is the matrix of the window means of the
9
+ mutual energy densities of these solutions,
10
+
11
+ C^w_kl = <eps^(k) : C : eps^(l)>_w (K^w_kl = <grad T^(k) . K grad T^(l)>_w),
12
+
13
+ integrated over the Gauss points of its voxels as the solver integrates the energy. It is
14
+ symmetric, to the bit (its upper triangle is computed, then mirrored), and positive
15
+ semi-definite: ``a . C^w a`` is the mean energy over the window of the solution
16
+ ``sum_k a_k u^(k)``. Over windows tiling the box, its mean is the box's mean energy to
17
+ round-off, which Hill's lemma ``<sigma : eps> = Sigma : E`` makes the box's apparent
18
+ stiffness ``C_kl = E^(k) . <sigma^(l)>`` (that of
19
+ :func:`~morphogen.homogenization.stiffness_tensor`; the conductivity of
20
+ :func:`~morphogen.homogenization.conductivity_tensor`), to the tolerance of the solver: the
21
+ energy is stationary at the solution, its error of the second order in that of the fields,
22
+ that of the mean stresses of the first. Its diagonal is the energy estimate of the apparent
23
+ moduli (Dirrenberger et al. 2014, eqs. 64 and 66).
24
+
25
+ This definition rather than the window means of the stresses under the unit strains,
26
+ ``<sigma^(l)>_w`` (Kanit et al. 2003): those tile the box as exactly, but are neither
27
+ symmetric (``C A`` at a point, ``A`` the concentration of the strains: 16 % off on random
28
+ voxels of a contrast of 10) nor positive (their symmetric part indefinite at voxels of that
29
+ contrast, in windows of 2 voxels at a contrast of 1000), and in a laminate their components
30
+ across the layers are those of the box in every window, the tractions being continuous: no
31
+ scatter, whatever the window. ``<sigma>_w <eps>_w^-1``, the
32
+ window's own apparent tensor, is neither symmetric nor tiling, and is undefined where the
33
+ mean strain of a window is singular (a rigid inclusion). In a laminate, whose strains are
34
+ uniform in each layer (``eps = A_p E``), the window tensor is ``sum_p f_p^w A_p^T C_p A_p``,
35
+ ``f_p^w`` the fraction of the layers ``p`` in the window.
36
+
37
+ The windows are the cubes of ``w`` voxels that tile the image from its origin, the
38
+ remainder left out, as in :func:`morphogen.rve.scaling.window_statistics` (squares of ``w``
39
+ pixels across a planar image, whose measure is then their area). Their statistics per size
40
+ are those of the ensemble method, the windows as realizations
41
+ (:class:`~morphogen.rve.study.TensorStatistics`, ``method="windows"``): the mean ``Cbar``
42
+ and the standard deviation of each component, ``S = Cbar^-1`` and the mean of the
43
+ compliances of the windows, the RVE size of each component. A window without stiffness in
44
+ some direction (within a pore) has no compliance (NaN, as a singular realization).
45
+
46
+ Shifted tilings (``shifts > 1``, as in :func:`~morphogen.rve.scaling.window_statistics`):
47
+ the tilings shifted by the offsets ``k w // shifts`` voxels along each axis, all their
48
+ combinations, wrapping around the periodic image. They take the fields already solved,
49
+ each tiling one more pass of the kernel over the image (a few percent of a solve). Each is
50
+ a translate of the first on the periodic image, its windows of the law of the unshifted
51
+ ones: the statistics of a size are the means over all the windows of all its tilings (over
52
+ each tiling of the box, the box's tensor), the variances pooled within the tilings and the
53
+ counts of one tiling, the independent windows (:mod:`morphogen.rve.scaling`).
54
+ """
55
+
56
+ from __future__ import annotations
57
+
58
+ from dataclasses import dataclass
59
+
60
+ import numpy as np
61
+ from numba import njit, prange
62
+
63
+ from morphogen.homogenization.kernels import CORNERS
64
+ from morphogen.rve.scaling import _offsets, _shift_count
65
+ from morphogen.rve.study import (
66
+ TRANSPORT_TENSORS,
67
+ StudyOptions,
68
+ TensorStatistics,
69
+ _tensor_statistics,
70
+ tensor_notation,
71
+ )
72
+
73
+ #: The tensors of the window method and the physics of their problems: the stiffness, and
74
+ #: the tensor of each transport phenomenon (``conductivity_tensor``,
75
+ #: ``electrical_conductivity_tensor``, ``permittivity_tensor``, ``permeability_tensor``,
76
+ #: ``diffusivity_tensor``)
77
+ WINDOW_TENSORS = {"stiffness": "elastic", **TRANSPORT_TENSORS}
78
+ #: The tasks of one call of the kernel (windows times their planes along x): its memory
79
+ _TASKS = 1 << 16
80
+
81
+
82
+ @njit(parallel=True, cache=True)
83
+ def _window_sums(
84
+ nx, ny, nz, nd, mat, dmat, w, u_loc, b_gauss, weight, ext, counts, offset, first, out
85
+ ):
86
+ """``out[t, p]``: the integral over the plane ``i`` (along x) of the window ``m`` (``t =
87
+ (m - first) ext[0] + i``) of the mutual energy density ``eps_s . D eps_u`` of the loads
88
+ ``(s, u)``, ``s <= u``, row by row (``p``). The windows of ``ext`` voxels are numbered
89
+ ``m = (a counts[1] + b) counts[2] + c`` on the grid of ``counts`` shifted by ``offset``
90
+ voxels, wrapping around the periodic image; ``w[s]`` holds the periodic nodal
91
+ fluctuation of the load ``s`` (``nd`` per node), ``u_loc[s]`` its affine part at the
92
+ corners of a voxel, ``b_gauss`` the measures (strains, gradients) of the Gauss points,
93
+ ``dmat[mat_e]`` the matrix of voxel ``e`` (-1: a void, no energy)."""
94
+ n_load = w.shape[0]
95
+ n_rows = b_gauss.shape[1]
96
+ n_cols = b_gauss.shape[2]
97
+ ex, ey, ez = ext[0], ext[1], ext[2]
98
+ cy, cz = counts[1], counts[2]
99
+ for t in prange(out.shape[0]):
100
+ m = first + t // ex
101
+ i = (offset[0] + (m // (cy * cz)) * ex + t % ex) % nx
102
+ j0 = offset[1] + ((m // cz) % cy) * ey
103
+ k0 = offset[2] + (m % cz) * ez
104
+ nodes = np.empty(8, dtype=np.int64)
105
+ ue = np.empty((n_load, n_cols))
106
+ eps = np.empty((n_load, n_rows))
107
+ sig = np.empty((n_load, n_rows))
108
+ acc = np.zeros(out.shape[1])
109
+ for jj in range(j0, j0 + ey):
110
+ j = jj % ny
111
+ for kk in range(k0, k0 + ez):
112
+ k = kk % nz
113
+ e = (i * ny + j) * nz + k
114
+ g = mat[e]
115
+ if g < 0:
116
+ continue
117
+ for q in range(8):
118
+ a = (i + CORNERS[q, 0]) % nx
119
+ b = (j + CORNERS[q, 1]) % ny
120
+ c = (k + CORNERS[q, 2]) % nz
121
+ nodes[q] = (a * ny + b) * nz + c
122
+ for s in range(n_load):
123
+ for q in range(8):
124
+ for r in range(nd):
125
+ ue[s, nd * q + r] = u_loc[s, nd * q + r] + w[s, nd * nodes[q] + r]
126
+ d = dmat[g]
127
+ for gp in range(8):
128
+ for s in range(n_load):
129
+ for r in range(n_rows):
130
+ v = 0.0
131
+ for col in range(n_cols):
132
+ v += b_gauss[gp, r, col] * ue[s, col]
133
+ eps[s, r] = v
134
+ for r in range(n_rows):
135
+ v = 0.0
136
+ for col in range(n_rows):
137
+ v += d[r, col] * eps[s, col]
138
+ sig[s, r] = v
139
+ p = 0
140
+ for s in range(n_load):
141
+ for u in range(s, n_load):
142
+ v = 0.0
143
+ for r in range(n_rows):
144
+ v += eps[s, r] * sig[u, r]
145
+ acc[p] += v
146
+ p += 1
147
+ for p in range(out.shape[1]):
148
+ out[t, p] = weight * acc[p]
149
+
150
+
151
+ @dataclass
152
+ class WindowTensors:
153
+ """The tensors of the windows of one realization (see the module documentation).
154
+
155
+ ``property``: ``stiffness`` or ``conductivity_tensor``; ``edges``: the window edges
156
+ (voxels), ``volumes`` their measures (their areas across a planar image, ``dimension``
157
+ 2) and ``tensors[k]`` the tensors of the windows of edge ``edges[k]``, ``(n_k, d, d)``:
158
+ in morphoGen's Voigt order 11 22 33 23 31 12 with engineering shears (11 22 12 in the
159
+ plane), the axes 1 2 3 for the conductivity (:attr:`notation`). ``box``: the tensor of
160
+ the whole realization by the same definition, the mean of the windows that tile it;
161
+ ``apparent``: its apparent tensor from its mean stresses (fluxes), symmetrized, as
162
+ :func:`~morphogen.homogenization.homogenize` gives it: ``box`` to the tolerance of the
163
+ solver. ``offsets[k]``: with shifted tilings, the offsets (voxels, ``(t_k, 3)``) of the
164
+ ``t_k`` tilings of the size ``k``, the unshifted one first, ``tensors[k]`` then the
165
+ windows of all of them, tiling by tiling; None: one tiling of each size.
166
+ """
167
+
168
+ property: str
169
+ edges: np.ndarray
170
+ volumes: np.ndarray
171
+ tensors: list[np.ndarray]
172
+ box: np.ndarray
173
+ apparent: np.ndarray
174
+ bc: str = "periodic"
175
+ dimension: int = 3
176
+ offsets: list[np.ndarray] | None = None
177
+
178
+ @property
179
+ def key(self) -> str:
180
+ return f"{self.property}.{self.bc}"
181
+
182
+ @property
183
+ def notation(self) -> str:
184
+ """The notation of the tensors (:func:`~morphogen.rve.study.tensor_notation`)."""
185
+ return tensor_notation(self.property, self.box)
186
+
187
+ @property
188
+ def tilings(self) -> np.ndarray:
189
+ """The number of tilings of each size (1 without shifts)."""
190
+ if self.offsets is None:
191
+ return np.ones(len(self.edges), dtype=int)
192
+ return np.array([len(o) for o in self.offsets])
193
+
194
+ def statistics(self, options: StudyOptions | None = None) -> TensorStatistics:
195
+ """Their statistics per size, the windows as realizations: the mean tensor and the
196
+ standard deviation of each component, its inverse and the mean of the inverses of
197
+ the windows, the RVE size of each component (``options``: those of the study,
198
+ without bootstrap; the windows of non-finite tensors left out, as the realizations
199
+ of :func:`~morphogen.rve.study.tensor_statistics`); with shifted tilings, the means
200
+ over all their windows, the variances pooled within the tilings, the counts of one
201
+ (see the module)."""
202
+ groups = []
203
+ for k, (v, t) in enumerate(zip(self.volumes, self.tensors, strict=True)):
204
+ finite = np.isfinite(t).all(axis=(1, 2))
205
+ if self.offsets is None:
206
+ groups.append((v, t[finite]))
207
+ else: # the tiling of each window, the windows tiling by tiling
208
+ count = len(self.offsets[k])
209
+ tiles = np.repeat(np.arange(count), len(t) // count)
210
+ groups.append((v, t[finite], tiles[finite]))
211
+ groups = [g for g in groups if len(g[1])]
212
+ if not groups:
213
+ raise ValueError(f"{self.key}: no finite tensor of a window")
214
+ return _tensor_statistics(self.property, self.bc, groups, options, method="windows",
215
+ dimension=self.dimension) # fmt: skip
216
+
217
+
218
+ def _loads(prop: str, planar: bool) -> tuple[int, ...]:
219
+ """The unit macroscopic loads solved: the components of the strain (Voigt) or of the
220
+ gradient."""
221
+ if prop in TRANSPORT_TENSORS:
222
+ return (0, 1, 2)
223
+ return (0, 1, 5) if planar else tuple(range(6))
224
+
225
+
226
+ def _apparent(problem, prop: str, loads) -> np.ndarray:
227
+ """The apparent tensor of the sample from its mean stresses (fluxes) under the loads,
228
+ symmetrized (the unit solutions cached by the problem)."""
229
+ from morphogen.homogenization import Loading, conductivity_tensor
230
+ from morphogen.homogenization.elements import tensor_to_voigt
231
+
232
+ if prop in TRANSPORT_TENSORS:
233
+ return conductivity_tensor(problem)[0]
234
+ c = np.zeros((len(loads), len(loads)))
235
+ for col, j in enumerate(loads):
236
+ unit = np.zeros(6)
237
+ unit[j] = 1.0
238
+ stress = tensor_to_voigt(problem.solve(Loading.strain(unit)).stress, strain=False)
239
+ c[:, col] = stress[list(loads)]
240
+ return 0.5 * (c + c.T)
241
+
242
+
243
+ def _means(problem, fields, u_loc, b_gauss, ext, offset=(0, 0, 0)) -> np.ndarray:
244
+ """The window means of the mutual energies of the loads, ``(n_windows, n_pairs)``, over
245
+ the windows of ``ext`` voxels that tile the image from its origin, or from the voxel
246
+ ``offset`` around the periodic image (by chunks of windows: the memory of ``_TASKS``
247
+ rows)."""
248
+ nx, ny, nz = problem.shape
249
+ counts = np.array([nx // ext[0], ny // ext[1], nz // ext[2]], dtype=np.int64)
250
+ n_windows = int(np.prod(counts))
251
+ n_pairs = len(fields) * (len(fields) + 1) // 2
252
+ dmat = np.ascontiguousarray(problem.table.matrices, dtype=np.float64)
253
+ weight = float(problem.element.weight)
254
+ sums = np.empty((n_windows, n_pairs))
255
+ step = max(1, _TASKS // ext[0])
256
+ shift = np.asarray(offset, dtype=np.int64)
257
+ for first in range(0, n_windows, step):
258
+ stop = min(n_windows, first + step)
259
+ out = np.zeros(((stop - first) * ext[0], n_pairs))
260
+ _window_sums(nx, ny, nz, problem.nd, problem.mat, dmat, fields, u_loc, b_gauss, weight,
261
+ np.asarray(ext, dtype=np.int64), counts, shift, first, out) # fmt: skip
262
+ sums[first:stop] = out.reshape(stop - first, ext[0], n_pairs).sum(axis=1)
263
+ return sums / (float(np.prod(ext)) * problem.element.volume)
264
+
265
+
266
+ def _symmetric(means: np.ndarray, d: int) -> np.ndarray:
267
+ """The symmetric matrices ``(n, d, d)`` of their upper triangles, row by row."""
268
+ out = np.empty((len(means), d, d))
269
+ rows, cols = np.triu_indices(d)
270
+ out[:, rows, cols] = means
271
+ out[:, cols, rows] = means
272
+ return out
273
+
274
+
275
+ def window_tensors(
276
+ image,
277
+ materials,
278
+ window_sizes,
279
+ *,
280
+ property: str = "stiffness",
281
+ tol: float = 1e-8,
282
+ maxiter: int | None = None,
283
+ grains=None,
284
+ orientations=None,
285
+ device: str = "cpu",
286
+ shifts: int = 1,
287
+ ) -> WindowTensors:
288
+ """The tensors of the windows of a periodic voxel image (see the module documentation):
289
+ ``property`` ``stiffness`` (six unit strains; three in the plane of a planar image) or
290
+ ``conductivity_tensor`` (three unit gradients), solved once each by the FFT solver
291
+ (``tol``, ``maxiter``, ``device``; crystals turned by the orientations of their
292
+ ``grains``, see :func:`~morphogen.homogenization.make_problem`), then averaged over the
293
+ windows of each edge of ``window_sizes`` (voxels): of the tiling from the origin, or
294
+ with ``shifts > 1`` of the tilings shifted by ``k w // shifts`` voxels along each axis
295
+ (``k < shifts``, all their combinations, wrapping around the image), from the same
296
+ solutions. :meth:`WindowTensors.statistics` gives their statistics per size."""
297
+ from morphogen.homogenization import make_problem
298
+ from morphogen.image import VoxelImage
299
+
300
+ if property not in WINDOW_TENSORS:
301
+ raise ValueError(f"property: one of {list(WINDOW_TENSORS)}, got {property!r}")
302
+ if not isinstance(image, VoxelImage):
303
+ raise TypeError(f"window_tensors: a VoxelImage (FFT solver), got {type(image).__name__}")
304
+ shifts = _shift_count(shifts, image.periodic)
305
+ problem = make_problem(image, materials, WINDOW_TENSORS[property], "periodic", tol=tol,
306
+ maxiter=maxiter, grains=grains, orientations=orientations,
307
+ device=device) # fmt: skip
308
+ shape = problem.shape
309
+ planar = shape[2] == 1
310
+ edges = sorted({int(w) for w in window_sizes})
311
+ for w in edges:
312
+ if w < 1 or w > min(shape[:2] if planar else shape):
313
+ raise ValueError(f"window size {w} does not fit in the image {shape}")
314
+ loads = _loads(property, planar)
315
+ element = problem.element
316
+ if WINDOW_TENSORS[property] == "elastic":
317
+ units = np.eye(6)[list(loads)]
318
+ u_loc = np.array([element.affine_displacement(e) for e in units])
319
+ b_gauss = element.b_gauss
320
+ else:
321
+ u_loc = np.array([element.affine_temperature(e) for e in np.eye(3)])
322
+ b_gauss = element.g_gauss
323
+ fields = np.ascontiguousarray(np.stack([problem._unit(j)[0] for j in loads]))
324
+ u_loc = np.ascontiguousarray(u_loc)
325
+ d = len(loads)
326
+ tensors, volumes, offsets = [], [], []
327
+ h = element.spacing
328
+ for w in edges:
329
+ ext = (w, w, 1 if planar else w)
330
+ tiles = _offsets(w, shifts, planar) # (0, 0, 0) first
331
+ means = [_means(problem, fields, u_loc, b_gauss, ext, o) for o in tiles]
332
+ tensors.append(_symmetric(np.concatenate(means), d))
333
+ volumes.append(w * w * h[0] * h[1] * (1.0 if planar else w * h[2]))
334
+ offsets.append(tiles)
335
+ (box,) = _symmetric(_means(problem, fields, u_loc, b_gauss, shape), d)
336
+ return WindowTensors(
337
+ property=property,
338
+ edges=np.array(edges),
339
+ volumes=np.array(volumes),
340
+ tensors=tensors,
341
+ box=box,
342
+ apparent=_apparent(problem, property, loads),
343
+ dimension=2 if planar else 3,
344
+ offsets=offsets if shifts > 1 else None,
345
+ )
morphogen/seeding.py ADDED
@@ -0,0 +1,51 @@
1
+ """Reproducible random number generation.
2
+
3
+ Every random draw in morphoGen goes through a :class:`numpy.random.Generator` built
4
+ from a seed. The realizations of a study get seeds derived from the study seed and
5
+ their indices (``SeedSequence(seed, spawn_key=(size_index, realization_index))``), so
6
+ a result does not depend on how the study was split across processes or cluster jobs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import numpy as np
12
+
13
+ SeedLike = int | np.random.SeedSequence | np.random.Generator | None
14
+
15
+
16
+ def derive_seed(base: int | None, *key: int) -> np.random.SeedSequence:
17
+ """Seed of the item ``key`` (e.g. ``(size_index, realization_index)``) of a study."""
18
+ return np.random.SeedSequence(entropy=base, spawn_key=tuple(int(k) for k in key))
19
+
20
+
21
+ def make_rng(seed: SeedLike = None) -> tuple[np.random.Generator, dict | None]:
22
+ """Return a generator and a JSON-able description that reproduces it.
23
+
24
+ ``seed`` may be an integer, a :class:`~numpy.random.SeedSequence`, an existing
25
+ generator (used as is, not reproducible from the description) or ``None`` (fresh
26
+ entropy, recorded so that the realization can be regenerated).
27
+ """
28
+ if isinstance(seed, np.random.Generator):
29
+ return seed, None
30
+ if isinstance(seed, np.random.SeedSequence):
31
+ ss = seed
32
+ elif seed is None:
33
+ ss = np.random.SeedSequence()
34
+ else:
35
+ if isinstance(seed, bool) or int(seed) != seed or int(seed) < 0:
36
+ raise ValueError(f"seed: expected a non-negative integer, got {seed!r}")
37
+ ss = np.random.SeedSequence(int(seed))
38
+ return np.random.default_rng(ss), describe_seed(ss)
39
+
40
+
41
+ def describe_seed(ss: np.random.SeedSequence) -> dict:
42
+ """The entropy and spawn key of a seed sequence, which recreate it (recorded with the
43
+ results)."""
44
+ return {"entropy": ss.entropy, "spawn_key": list(ss.spawn_key)}
45
+
46
+
47
+ def seed_from_description(desc: dict | int | None) -> np.random.SeedSequence | int | None:
48
+ """Inverse of :func:`describe_seed` (also accepts a plain integer)."""
49
+ if desc is None or isinstance(desc, int):
50
+ return desc
51
+ return np.random.SeedSequence(entropy=desc["entropy"], spawn_key=tuple(desc["spawn_key"]))
morphogen/settings.py ADDED
@@ -0,0 +1,118 @@
1
+ """Global run-time settings (number of threads)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import sys
7
+ from collections.abc import Iterator
8
+ from contextlib import contextmanager
9
+
10
+ _threads: int | None = None
11
+ #: The functions that read and set the number of threads of the OpenBLAS libraries of the
12
+ #: process (found once; see :func:`blas_on_one_thread`)
13
+ _openblas_threads: list | None = None
14
+
15
+
16
+ def set_num_threads(n: int | None) -> None:
17
+ """Number of threads used by compiled kernels and SciPy (``None``: all cores)."""
18
+ global _threads
19
+ import numba
20
+
21
+ if n is None:
22
+ _threads = None
23
+ numba.set_num_threads(numba.config.NUMBA_NUM_THREADS)
24
+ return
25
+ n = int(n)
26
+ if n < 1:
27
+ raise ValueError("number of threads must be positive")
28
+ numba.set_num_threads(min(n, numba.config.NUMBA_NUM_THREADS))
29
+ _threads = n
30
+
31
+
32
+ def workers() -> int:
33
+ """``workers`` argument for SciPy routines."""
34
+ return -1 if _threads is None else _threads
35
+
36
+
37
+ def _openblas() -> list:
38
+ """The functions ``(get, set)`` of the number of threads of each OpenBLAS library
39
+ that NumPy and SciPy have loaded (their wheels carry one each; an installation may
40
+ share one): the libraries mapped by the process on Linux, those of the folders of
41
+ the wheels elsewhere. Empty with another BLAS, or where none is found."""
42
+ global _openblas_threads
43
+ if _openblas_threads is not None:
44
+ return _openblas_threads
45
+ import ctypes
46
+ import glob
47
+ import os
48
+
49
+ import numpy
50
+ import numpy.linalg # (the libraries are loaded with the modules that call them)
51
+ import scipy
52
+ import scipy.linalg
53
+
54
+ paths: list[str] = []
55
+ if sys.platform.startswith("linux"):
56
+ try:
57
+ with open("/proc/self/maps") as maps: # (the path: what follows five fields)
58
+ mapped = [line.split(None, 5) for line in maps if "openblas" in line.lower()]
59
+ paths = sorted({fields[5].strip() for fields in mapped if len(fields) == 6})
60
+ except OSError:
61
+ paths = []
62
+ else:
63
+ for package in (numpy, scipy):
64
+ name = package.__name__
65
+ root = os.path.dirname(os.path.dirname(os.path.abspath(package.__file__)))
66
+ for folder in (f"{name}.libs", os.path.join(name, ".dylibs")):
67
+ paths += sorted(glob.glob(os.path.join(root, folder, "*openblas*")))
68
+ found = []
69
+ for path in paths:
70
+ try:
71
+ library = ctypes.CDLL(path)
72
+ except OSError:
73
+ continue
74
+ for prefix, suffix in (("scipy_", "64_"), ("scipy_", ""), ("", "64_"), ("", "")):
75
+ get = getattr(library, f"{prefix}openblas_get_num_threads{suffix}", None)
76
+ put = getattr(library, f"{prefix}openblas_set_num_threads{suffix}", None)
77
+ if get is not None and put is not None:
78
+ get.restype = ctypes.c_int
79
+ put.argtypes = [ctypes.c_int]
80
+ put.restype = None
81
+ found.append((get, put))
82
+ break
83
+ _openblas_threads = found
84
+ return found
85
+
86
+
87
+ @contextmanager
88
+ def blas_on_one_thread() -> Iterator[None]:
89
+ """Within the block, the BLAS of NumPy and SciPy (OpenBLAS) on one thread; the
90
+ number of its threads is restored after it.
91
+
92
+ The compiled kernels run on their own threads. A product of BLAS between two of
93
+ them (a norm, a small factorization) wakes the threads of OpenBLAS, which then stay
94
+ busy for a tenth of a second, waiting for the next product, and take the cores of the
95
+ kernels that follow: a loading path or a Krylov iteration is slowed by a third to a
96
+ half. The dense algebra within those loops is small (6 x 6 systems, the Hessenberg
97
+ matrices of GMRES): one thread serves it as well. Without OpenBLAS (another BLAS, or
98
+ none found), the block runs as it is."""
99
+ libraries = _openblas()
100
+ before = [get() for get, _ in libraries]
101
+ for _, put in libraries:
102
+ put(1)
103
+ try:
104
+ yield
105
+ finally:
106
+ for (_, put), count in zip(libraries, before, strict=True):
107
+ put(count)
108
+
109
+
110
+ def without_blas_threads(function):
111
+ """Decorator: the function runs within :func:`blas_on_one_thread`."""
112
+
113
+ @functools.wraps(function)
114
+ def wrapped(*args, **kwargs):
115
+ with blas_on_one_thread():
116
+ return function(*args, **kwargs)
117
+
118
+ return wrapped
morphogen/stopping.py ADDED
@@ -0,0 +1,48 @@
1
+ """Cooperative stops of long computations.
2
+
3
+ A thread that runs a computation it may have to stop (a job of the interface) runs it
4
+ under :func:`stoppable` with an event; the long loops of morphoGen (the iterations of the
5
+ conjugate gradients, the realizations of a run, the steps the tools of the interface
6
+ report) call :func:`checkpoint`, which raises :class:`Stopped` once the event is set. A
7
+ stop thus takes effect at the next checkpoint, never in the middle of a step; elsewhere
8
+ (no event, another thread) :func:`checkpoint` does nothing.
9
+
10
+ :class:`Stopped` derives from :class:`BaseException`, as :class:`KeyboardInterrupt` does,
11
+ so that the handlers of :class:`Exception` that fall back on another method (a GPU on the
12
+ CPU, a solver on another) let it through."""
13
+
14
+ from __future__ import annotations
15
+
16
+ import threading
17
+ from collections.abc import Iterator
18
+ from contextlib import contextmanager
19
+
20
+ _local = threading.local()
21
+
22
+
23
+ class Stopped(BaseException):
24
+ """A computation asked to stop (raised by :func:`checkpoint`)."""
25
+
26
+
27
+ @contextmanager
28
+ def stoppable(event: threading.Event) -> Iterator[threading.Event]:
29
+ """Run the block with ``event`` as the stop of the computations of this thread (the
30
+ innermost when nested)."""
31
+ previous = getattr(_local, "event", None)
32
+ _local.event = event
33
+ try:
34
+ yield event
35
+ finally:
36
+ _local.event = previous
37
+
38
+
39
+ def requested() -> bool:
40
+ """Whether the computation of this thread was asked to stop."""
41
+ event = getattr(_local, "event", None)
42
+ return event is not None and event.is_set()
43
+
44
+
45
+ def checkpoint() -> None:
46
+ """Raise :class:`Stopped` if the computation of this thread was asked to stop."""
47
+ if requested():
48
+ raise Stopped("stopped on request")